diff --git a/OpenMetaverse/AgentManager.cs b/OpenMetaverse/AgentManager.cs index 7092efe5..996030f0 100644 --- a/OpenMetaverse/AgentManager.cs +++ b/OpenMetaverse/AgentManager.cs @@ -26,10 +26,8 @@ using System; using System.Net; -using System.Text; using System.Text.RegularExpressions; using System.Threading; -using System.Reflection; using System.Collections.Generic; using OpenMetaverse.StructuredData; using OpenMetaverse.Http; @@ -773,8 +771,7 @@ namespace OpenMetaverse protected virtual void OnChat(ChatEventArgs e) { EventHandler handler = m_Chat; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -796,8 +793,7 @@ namespace OpenMetaverse protected virtual void OnScriptDialog(ScriptDialogEventArgs e) { EventHandler handler = m_ScriptDialog; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -819,8 +815,7 @@ namespace OpenMetaverse protected virtual void OnScriptQuestion(ScriptQuestionEventArgs e) { EventHandler handler = m_ScriptQuestion; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -841,8 +836,7 @@ namespace OpenMetaverse protected virtual void OnLoadURL(LoadUrlEventArgs e) { EventHandler handler = m_LoadURL; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -863,8 +857,7 @@ namespace OpenMetaverse protected virtual void OnBalance(BalanceEventArgs e) { EventHandler handler = m_Balance; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -886,8 +879,7 @@ namespace OpenMetaverse protected virtual void OnMoneyBalanceReply(MoneyBalanceReplyEventArgs e) { EventHandler handler = m_MoneyBalance; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -909,8 +901,7 @@ namespace OpenMetaverse protected virtual void OnInstantMessage(InstantMessageEventArgs e) { EventHandler handler = m_InstantMessage; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -932,8 +923,7 @@ namespace OpenMetaverse protected virtual void OnTeleport(TeleportEventArgs e) { EventHandler handler = m_Teleport; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -955,8 +945,7 @@ namespace OpenMetaverse protected virtual void OnAgentData(AgentDataReplyEventArgs e) { EventHandler handler = m_AgentData; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -978,8 +967,7 @@ namespace OpenMetaverse protected virtual void OnAnimationsChanged(AnimationsChangedEventArgs e) { EventHandler handler = m_AnimationsChanged; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -1001,8 +989,7 @@ namespace OpenMetaverse protected virtual void OnMeanCollision(MeanCollisionEventArgs e) { EventHandler handler = m_MeanCollision; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -1024,8 +1011,7 @@ namespace OpenMetaverse protected virtual void OnRegionCrossed(RegionCrossedEventArgs e) { EventHandler handler = m_RegionCrossed; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -1047,8 +1033,7 @@ namespace OpenMetaverse protected virtual void OnGroupChatJoined(GroupChatJoinedEventArgs e) { EventHandler handler = m_GroupChatJoined; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -1070,8 +1055,7 @@ namespace OpenMetaverse protected virtual void OnAlertMessage(AlertMessageEventArgs e) { EventHandler handler = m_AlertMessage; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -1094,8 +1078,7 @@ namespace OpenMetaverse protected virtual void OnScriptControlChange(ScriptControlEventArgs e) { EventHandler handler = m_ScriptControl; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object diff --git a/OpenMetaverse/AgentManagerCamera.cs b/OpenMetaverse/AgentManagerCamera.cs index 886bfa8f..f328fde4 100644 --- a/OpenMetaverse/AgentManagerCamera.cs +++ b/OpenMetaverse/AgentManagerCamera.cs @@ -24,8 +24,6 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using System; - namespace OpenMetaverse { public partial class AgentManager diff --git a/OpenMetaverse/AgentManagerMovement.cs b/OpenMetaverse/AgentManagerMovement.cs index 4bff3441..fa4dbdc7 100644 --- a/OpenMetaverse/AgentManagerMovement.cs +++ b/OpenMetaverse/AgentManagerMovement.cs @@ -26,7 +26,6 @@ using System; using System.Threading; -using OpenMetaverse; using OpenMetaverse.Packets; namespace OpenMetaverse diff --git a/OpenMetaverse/AssemblyInfo.cs b/OpenMetaverse/AssemblyInfo.cs index 70fb0783..7f851bab 100644 --- a/OpenMetaverse/AssemblyInfo.cs +++ b/OpenMetaverse/AssemblyInfo.cs @@ -10,7 +10,7 @@ using System.Runtime.CompilerServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("openmetaverse.co")] [assembly: AssemblyProduct("OpenMetaverse")] -[assembly: AssemblyCopyright("Copyright © openmetaverse.co 2006-2015")] +[assembly: AssemblyCopyright("Copyright � openmetaverse.co 2006-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/OpenMetaverse/AssetManager.cs b/OpenMetaverse/AssetManager.cs index e7c62656..b69a26c9 100644 --- a/OpenMetaverse/AssetManager.cs +++ b/OpenMetaverse/AssetManager.cs @@ -27,9 +27,7 @@ using System; using System.Collections.Generic; using System.Threading; -using System.IO; using System.Net; -using OpenMetaverse; using OpenMetaverse.Packets; using OpenMetaverse.Assets; using OpenMetaverse.Http; diff --git a/OpenMetaverse/Avatar.cs b/OpenMetaverse/Avatar.cs index ae2ad6c4..21430353 100644 --- a/OpenMetaverse/Avatar.cs +++ b/OpenMetaverse/Avatar.cs @@ -25,10 +25,7 @@ */ using System; -using System.Net; using System.Collections.Generic; -using System.Threading; -using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using System.Reflection; diff --git a/OpenMetaverse/BVHDecoder.cs b/OpenMetaverse/BVHDecoder.cs index a1509f5f..7ae7dca9 100644 --- a/OpenMetaverse/BVHDecoder.cs +++ b/OpenMetaverse/BVHDecoder.cs @@ -23,6 +23,7 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ + using System; namespace OpenMetaverse diff --git a/OpenMetaverse/Caps.cs b/OpenMetaverse/Caps.cs index 209320ca..5fb66d14 100644 --- a/OpenMetaverse/Caps.cs +++ b/OpenMetaverse/Caps.cs @@ -27,8 +27,6 @@ using System; using System.Collections.Generic; using System.Net; -using System.Text; -using System.Threading; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using OpenMetaverse.Interfaces; diff --git a/OpenMetaverse/CapsToPacket.cs b/OpenMetaverse/CapsToPacket.cs index 6907e1b1..b6129424 100644 --- a/OpenMetaverse/CapsToPacket.cs +++ b/OpenMetaverse/CapsToPacket.cs @@ -26,7 +26,6 @@ using System; using System.Collections; -using System.Collections.Generic; using System.Reflection; using OpenMetaverse.StructuredData; diff --git a/OpenMetaverse/DownloadManager.cs b/OpenMetaverse/DownloadManager.cs index d3daec3f..d9981a2d 100644 --- a/OpenMetaverse/DownloadManager.cs +++ b/OpenMetaverse/DownloadManager.cs @@ -25,8 +25,6 @@ */ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Net; using System.Security.Cryptography.X509Certificates; using OpenMetaverse.Http; diff --git a/OpenMetaverse/EventDictionary.cs b/OpenMetaverse/EventDictionary.cs index df2fe4e3..b38b6112 100644 --- a/OpenMetaverse/EventDictionary.cs +++ b/OpenMetaverse/EventDictionary.cs @@ -26,10 +26,8 @@ using System; using System.Collections.Generic; -using System.Text; using System.Threading; using OpenMetaverse.Packets; -using OpenMetaverse.Messages.Linden; using OpenMetaverse.Interfaces; namespace OpenMetaverse diff --git a/OpenMetaverse/FriendsManager.cs b/OpenMetaverse/FriendsManager.cs index 2e5e8f59..2ecf0d3f 100644 --- a/OpenMetaverse/FriendsManager.cs +++ b/OpenMetaverse/FriendsManager.cs @@ -24,7 +24,6 @@ */ using System; -using System.Text; using System.Collections.Generic; using OpenMetaverse.Packets; @@ -905,7 +904,7 @@ namespace OpenMetaverse foreach (BuddyListEntry buddy in replyData.BuddyList) { UUID bubid; - string id = buddy.buddy_id.Length > uuidLength ? buddy.buddy_id.Substring(0, uuidLength) : buddy.buddy_id; + string id = buddy.BuddyId.Length > uuidLength ? buddy.BuddyId.Substring(0, uuidLength) : buddy.BuddyId; if (UUID.TryParse(id, out bubid)) { lock (FriendList.Dictionary) @@ -913,8 +912,8 @@ namespace OpenMetaverse if (!FriendList.ContainsKey(bubid)) { FriendList[bubid] = new FriendInfo(bubid, - (FriendRights)buddy.buddy_rights_given, - (FriendRights)buddy.buddy_rights_has); + (FriendRights)buddy.BuddyRightsGiven, + (FriendRights)buddy.BuddyRightsHas); } } } diff --git a/OpenMetaverse/GridManager.cs b/OpenMetaverse/GridManager.cs index 19f9efe9..e79bd9e8 100644 --- a/OpenMetaverse/GridManager.cs +++ b/OpenMetaverse/GridManager.cs @@ -25,8 +25,6 @@ */ using System; -using System.Text; -using System.Collections; using System.Collections.Generic; using System.Threading; using OpenMetaverse.StructuredData; diff --git a/OpenMetaverse/Helpers.cs b/OpenMetaverse/Helpers.cs index 1c5f8970..39a4a100 100644 --- a/OpenMetaverse/Helpers.cs +++ b/OpenMetaverse/Helpers.cs @@ -27,7 +27,6 @@ using System; using System.Collections.Generic; using System.Text; -using OpenMetaverse.Packets; using System.IO; using System.Reflection; using OpenMetaverse.StructuredData; diff --git a/OpenMetaverse/Inventory.cs b/OpenMetaverse/Inventory.cs index ac3cdc88..05ef680a 100644 --- a/OpenMetaverse/Inventory.cs +++ b/OpenMetaverse/Inventory.cs @@ -28,7 +28,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; -using System.Runtime.Serialization; namespace OpenMetaverse { diff --git a/OpenMetaverse/InventoryNode.cs b/OpenMetaverse/InventoryNode.cs index c35235b0..e8a92660 100644 --- a/OpenMetaverse/InventoryNode.cs +++ b/OpenMetaverse/InventoryNode.cs @@ -25,8 +25,6 @@ */ using System; -using System.Collections.Generic; -using System.Text; using System.Runtime.Serialization; namespace OpenMetaverse diff --git a/OpenMetaverse/InventoryNodeDictionary.cs b/OpenMetaverse/InventoryNodeDictionary.cs index 696accb0..73c32cfd 100644 --- a/OpenMetaverse/InventoryNodeDictionary.cs +++ b/OpenMetaverse/InventoryNodeDictionary.cs @@ -26,7 +26,6 @@ using System; using System.Collections.Generic; -using System.Text; namespace OpenMetaverse { diff --git a/OpenMetaverse/Logger.cs b/OpenMetaverse/Logger.cs index f45716d9..a0c1b8b4 100644 --- a/OpenMetaverse/Logger.cs +++ b/OpenMetaverse/Logger.cs @@ -28,7 +28,7 @@ using System; using log4net; using log4net.Config; -[assembly: log4net.Config.XmlConfigurator(Watch = true)] +[assembly: XmlConfigurator(Watch = true)] namespace OpenMetaverse { @@ -63,8 +63,10 @@ namespace OpenMetaverse // ConsoleAppender if (!LogInstance.Logger.IsEnabledFor(log4net.Core.Level.Error)) { - log4net.Appender.ConsoleAppender appender = new log4net.Appender.ConsoleAppender(); - appender.Layout = new log4net.Layout.PatternLayout("%timestamp [%thread] %-5level - %message%newline"); + log4net.Appender.ConsoleAppender appender = new log4net.Appender.ConsoleAppender + { + Layout = new log4net.Layout.PatternLayout("%timestamp [%thread] %-5level - %message%newline") + }; BasicConfigurator.Configure(appender); if(Settings.LOG_LEVEL != Helpers.LogLevel.None) @@ -114,10 +116,9 @@ namespace OpenMetaverse public static void Log(object message, Helpers.LogLevel level, GridClient client, Exception exception) { if (client != null && client.Settings.LOG_NAMES) - message = String.Format("<{0}>: {1}", client.Self.Name, message); + message = $"<{client.Self.Name}>: {message}"; - if (OnLogMessage != null) - OnLogMessage(message, level); + OnLogMessage?.Invoke(message, level); switch (level) { @@ -172,16 +173,14 @@ namespace OpenMetaverse [System.Diagnostics.Conditional("DEBUG")] public static void DebugLog(object message, GridClient client) { - if (Settings.LOG_LEVEL == Helpers.LogLevel.Debug) - { - if (client != null && client.Settings.LOG_NAMES) - message = String.Format("<{0}>: {1}", client.Self.Name, message); + if (Settings.LOG_LEVEL != Helpers.LogLevel.Debug) return; - if (OnLogMessage != null) - OnLogMessage(message, Helpers.LogLevel.Debug); + if (client != null && client.Settings.LOG_NAMES) + message = $"<{client.Self.Name}>: {message}"; - LogInstance.Debug(message); - } + OnLogMessage?.Invoke(message, Helpers.LogLevel.Debug); + + LogInstance.Debug(message); } } } diff --git a/OpenMetaverse/Login.cs b/OpenMetaverse/Login.cs index ccf9dbcb..48f65f2e 100644 --- a/OpenMetaverse/Login.cs +++ b/OpenMetaverse/Login.cs @@ -28,10 +28,8 @@ using System; using System.Collections; using System.Collections.Generic; using System.Threading; -using System.IO; using System.Net; -using System.Xml; -using System.Security.Cryptography.X509Certificates; +using System.Net.NetworkInformation; using Nwc.XmlRpc; using OpenMetaverse.StructuredData; using OpenMetaverse.Http; @@ -152,35 +150,37 @@ namespace OpenMetaverse /// public LoginParams() { - List options = new List(16); - options.Add("inventory-root"); - options.Add("inventory-skeleton"); - options.Add("inventory-lib-root"); - options.Add("inventory-lib-owner"); - options.Add("inventory-skel-lib"); - options.Add("initial-outfit"); - options.Add("gestures"); - options.Add("event_categories"); - options.Add("event_notifications"); - options.Add("classified_categories"); - options.Add("buddy-list"); - options.Add("ui-config"); - options.Add("tutorial_settings"); - options.Add("login-flags"); - options.Add("global-textures"); - options.Add("adult_compliant"); + var options = new List(16) + { + "inventory-root", + "inventory-skeleton", + "inventory-lib-root", + "inventory-lib-owner", + "inventory-skel-lib", + "initial-outfit", + "gestures", + "event_categories", + "event_notifications", + "classified_categories", + "buddy-list", + "ui-config", + "tutorial_settings", + "login-flags", + "global-textures", + "adult_compliant" + }; - this.Options = options.ToArray(); - this.MethodName = "login_to_simulator"; - this.Start = "last"; - this.Platform = NetworkManager.GetPlatform(); - this.PlatformVersion = NetworkManager.GetPlatformVersion(); - this.MAC = NetworkManager.GetMAC(); - this.ViewerDigest = String.Empty; - this.ID0 = NetworkManager.GetMAC(); - this.AgreeToTos = true; - this.ReadCritical = true; - this.LastExecEvent = LastExecStatus.Normal; + Options = options.ToArray(); + MethodName = "login_to_simulator"; + Start = "last"; + Platform = NetworkManager.GetPlatform(); + PlatformVersion = NetworkManager.GetPlatformVersion(); + MAC = NetworkManager.GetMAC(); + ViewerDigest = String.Empty; + ID0 = NetworkManager.GetMAC(); + AgreeToTos = true; + ReadCritical = true; + LastExecEvent = LastExecStatus.Normal; } /// @@ -195,13 +195,13 @@ namespace OpenMetaverse public LoginParams(GridClient client, string firstName, string lastName, string password, string channel, string version) : this() { - this.URI = client.Settings.LOGIN_SERVER; - this.Timeout = client.Settings.LOGIN_TIMEOUT; - this.FirstName = firstName; - this.LastName = lastName; - this.Password = password; - this.Channel = channel; - this.Version = version; + URI = client.Settings.LOGIN_SERVER; + Timeout = client.Settings.LOGIN_TIMEOUT; + FirstName = firstName; + LastName = lastName; + Password = password; + Channel = channel; + Version = version; } /// @@ -217,15 +217,15 @@ namespace OpenMetaverse public LoginParams(GridClient client, string firstName, string lastName, string password, string channel, string version, string loginURI) : this(client, firstName, lastName, password, channel, version) { - this.URI = loginURI; + URI = loginURI; } } public struct BuddyListEntry { - public int buddy_rights_given; - public string buddy_id; - public int buddy_rights_has; + public int BuddyRightsGiven; + public string BuddyId; + public int BuddyRightsHas; } /// @@ -324,21 +324,19 @@ namespace OpenMetaverse } // Home - OSDMap home = null; OSD osdHome = OSDParser.DeserializeLLSDNotation(reply["home"].AsString()); if (osdHome.Type == OSDType.Map) { - home = (OSDMap)osdHome; + var home = (OSDMap)osdHome; OSD homeRegion; if (home.TryGetValue("region_handle", out homeRegion) && homeRegion.Type == OSDType.Array) { OSDArray homeArray = (OSDArray)homeRegion; - if (homeArray.Count == 2) - HomeRegion = Utils.UIntsToLong((uint)homeArray[0].AsInteger(), (uint)homeArray[1].AsInteger()); - else - HomeRegion = 0; + HomeRegion = homeArray.Count == 2 + ? Utils.UIntsToLong((uint)homeArray[0].AsInteger(), (uint)homeArray[1].AsInteger()) + : 0; } HomePosition = ParseVector3("position", home); @@ -365,16 +363,16 @@ namespace OpenMetaverse { List buddys = new List(); OSDArray buddyArray = (OSDArray)buddyLLSD; - for (int i = 0; i < buddyArray.Count; i++) + foreach (OSD t in buddyArray) { - if (buddyArray[i].Type == OSDType.Map) + if (t.Type == OSDType.Map) { BuddyListEntry bud = new BuddyListEntry(); - OSDMap buddy = (OSDMap)buddyArray[i]; + OSDMap buddy = (OSDMap)t; - bud.buddy_id = buddy["buddy_id"].AsString(); - bud.buddy_rights_given = (int)ParseUInt("buddy_rights_given", buddy); - bud.buddy_rights_has = (int)ParseUInt("buddy_rights_has", buddy); + bud.BuddyId = buddy["buddy_id"].AsString(); + bud.BuddyRightsGiven = (int)ParseUInt("buddy_rights_given", buddy); + bud.BuddyRightsHas = (int)ParseUInt("buddy_rights_has", buddy); buddys.Add(bud); } @@ -431,14 +429,13 @@ namespace OpenMetaverse return; // Home - OSDMap home = null; if (reply.ContainsKey("home")) { OSD osdHome = OSDParser.DeserializeLLSDNotation(reply["home"].ToString()); if (osdHome.Type == OSDType.Map) { - home = (OSDMap)osdHome; + var home = (OSDMap)osdHome; OSD homeRegion; if (home.TryGetValue("region_handle", out homeRegion) && homeRegion.Type == OSDType.Array) @@ -476,19 +473,18 @@ namespace OpenMetaverse List buddys = new List(); ArrayList buddyArray = (ArrayList)reply["buddy-list"]; - for (int i = 0; i < buddyArray.Count; i++) + foreach (object t in buddyArray) { - if (buddyArray[i] is Hashtable) - { - BuddyListEntry bud = new BuddyListEntry(); - Hashtable buddy = (Hashtable)buddyArray[i]; + if (!(t is Hashtable)) continue; - bud.buddy_id = ParseString("buddy_id", buddy); - bud.buddy_rights_given = (int)ParseUInt("buddy_rights_given", buddy); - bud.buddy_rights_has = (int)ParseUInt("buddy_rights_has", buddy); + BuddyListEntry bud = new BuddyListEntry(); + Hashtable buddy = (Hashtable)t; - buddys.Add(bud); - } + bud.BuddyId = ParseString("buddy_id", buddy); + bud.BuddyRightsGiven = (int)ParseUInt("buddy_rights_given", buddy); + bud.BuddyRightsHas = (int)ParseUInt("buddy_rights_has", buddy); + + buddys.Add(bud); } BuddyList = buddys.ToArray(); @@ -538,13 +534,12 @@ namespace OpenMetaverse if (reply.ContainsKey("initial-outfit") && reply["initial-outfit"] is ArrayList) { ArrayList array = (ArrayList)reply["initial-outfit"]; - for (int i = 0; i < array.Count; i++) + foreach (object t in array) { - if (array[i] is Hashtable) - { - Hashtable map = (Hashtable)array[i]; - InitialOutfit = ParseString("folder_name", map); - } + if (!(t is Hashtable)) continue; + + Hashtable map = (Hashtable)t; + InitialOutfit = ParseString("folder_name", map); } } @@ -552,13 +547,12 @@ namespace OpenMetaverse if (reply.ContainsKey("login-flags") && reply["login-flags"] is ArrayList) { ArrayList array = (ArrayList)reply["login-flags"]; - for (int i = 0; i < array.Count; i++) + foreach (object t in array) { - if (array[i] is Hashtable) - { - Hashtable map = (Hashtable)array[i]; - FirstLogin = ParseString("ever_logged_in", map) == "N"; - } + if (!(t is Hashtable)) continue; + + Hashtable map = (Hashtable)t; + FirstLogin = ParseString("ever_logged_in", map) == "N"; } } @@ -570,20 +564,16 @@ namespace OpenMetaverse public static uint ParseUInt(string key, OSDMap reply) { OSD osd; - if (reply.TryGetValue(key, out osd)) - return osd.AsUInteger(); - else - return 0; + return reply.TryGetValue(key, out osd) ? osd.AsUInteger() : 0; } public static uint ParseUInt(string key, Hashtable reply) { - if (reply.ContainsKey(key)) - { - object value = reply[key]; - if (value is int) - return (uint)(int)value; - } + if (!reply.ContainsKey(key)) return 0; + + var value = reply[key]; + if (value is int) + return (uint)(int)value; return 0; } @@ -591,55 +581,40 @@ namespace OpenMetaverse public static UUID ParseUUID(string key, OSDMap reply) { OSD osd; - if (reply.TryGetValue(key, out osd)) - return osd.AsUUID(); - else - return UUID.Zero; + return reply.TryGetValue(key, out osd) ? osd.AsUUID() : UUID.Zero; } public static UUID ParseUUID(string key, Hashtable reply) { - if (reply.ContainsKey(key)) - { - UUID value; - if (UUID.TryParse((string)reply[key], out value)) - return value; - } + if (!reply.ContainsKey(key)) return UUID.Zero; - return UUID.Zero; + UUID value; + return UUID.TryParse((string)reply[key], out value) ? value : UUID.Zero; } public static string ParseString(string key, OSDMap reply) { OSD osd; - if (reply.TryGetValue(key, out osd)) - return osd.AsString(); - else - return String.Empty; + return reply.TryGetValue(key, out osd) ? osd.AsString() : String.Empty; } public static string ParseString(string key, Hashtable reply) { - if (reply.ContainsKey(key)) - return String.Format("{0}", reply[key]); - - return String.Empty; + return reply.ContainsKey(key) ? $"{reply[key]}" : String.Empty; } public static Vector3 ParseVector3(string key, OSDMap reply) { OSD osd; - if (reply.TryGetValue(key, out osd)) + if (!reply.TryGetValue(key, out osd)) return Vector3.Zero; + + switch (osd.Type) { - if (osd.Type == OSDType.Array) - { - return ((OSDArray)osd).AsVector3(); - } - else if (osd.Type == OSDType.String) - { - OSDArray array = (OSDArray)OSDParser.DeserializeLLSDNotation(osd.AsString()); + case OSDType.Array: + return ((OSDArray) osd).AsVector3(); + case OSDType.String: + OSDArray array = (OSDArray) OSDParser.DeserializeLLSDNotation(osd.AsString()); return array.AsVector3(); - } } return Vector3.Zero; @@ -647,29 +622,28 @@ namespace OpenMetaverse public static Vector3 ParseVector3(string key, Hashtable reply) { - if (reply.ContainsKey(key)) + if (!reply.ContainsKey(key)) return Vector3.Zero; + var value = reply[key]; + + var list1 = value as IList; + if (list1 != null) { - object value = reply[key]; - - if (value is IList) + IList list = list1; + if (list.Count == 3) { - IList list = (IList)value; - if (list.Count == 3) - { - float x, y, z; - Single.TryParse((string)list[0], out x); - Single.TryParse((string)list[1], out y); - Single.TryParse((string)list[2], out z); + float x, y, z; + Single.TryParse((string)list[0], out x); + Single.TryParse((string)list[1], out y); + Single.TryParse((string)list[2], out z); - return new Vector3(x, y, z); - } - } - else if (value is string) - { - OSDArray array = (OSDArray)OSDParser.DeserializeLLSDNotation((string)value); - return array.AsVector3(); + return new Vector3(x, y, z); } } + else if (value is string) + { + OSDArray array = (OSDArray)OSDParser.DeserializeLLSDNotation((string)value); + return array.AsVector3(); + } return Vector3.Zero; } @@ -694,14 +668,13 @@ namespace OpenMetaverse public static UUID ParseMappedUUID(string key, string key2, Hashtable reply) { - if (reply.ContainsKey(key) && reply[key] is ArrayList) + if (!reply.ContainsKey(key) || !(reply[key] is ArrayList)) return UUID.Zero; + + ArrayList array = (ArrayList)reply[key]; + if (array.Count == 1 && array[0] is Hashtable) { - ArrayList array = (ArrayList)reply[key]; - if (array.Count == 1 && array[0] is Hashtable) - { - Hashtable map = (Hashtable)array[0]; - return ParseUUID(key2, map); - } + Hashtable map = (Hashtable)array[0]; + return ParseUUID(key2, map); } return UUID.Zero; @@ -716,17 +689,19 @@ namespace OpenMetaverse { OSDArray array = (OSDArray)skeleton; - for (int i = 0; i < array.Count; i++) + foreach (OSD t in array) { - if (array[i].Type == OSDType.Map) + if (t.Type == OSDType.Map) { - OSDMap map = (OSDMap)array[i]; - InventoryFolder folder = new InventoryFolder(map["folder_id"].AsUUID()); - folder.PreferredType = (FolderType)map["type_default"].AsInteger(); - folder.Version = map["version"].AsInteger(); - folder.OwnerID = owner; - folder.ParentUUID = map["parent_id"].AsUUID(); - folder.Name = map["name"].AsString(); + OSDMap map = (OSDMap)t; + InventoryFolder folder = new InventoryFolder(map["folder_id"].AsUUID()) + { + PreferredType = (FolderType) map["type_default"].AsInteger(), + Version = map["version"].AsInteger(), + OwnerID = owner, + ParentUUID = map["parent_id"].AsUUID(), + Name = map["name"].AsString() + }; folders.Add(folder); } @@ -744,16 +719,18 @@ namespace OpenMetaverse if (reply.TryGetValue(key, out skeleton) && skeleton.Type == OSDType.Array) { OSDArray array = (OSDArray)skeleton; - for (int i = 0; i < array.Count; i++) + foreach (OSD t in array) { - if (array[i].Type == OSDType.Map) + if (t.Type == OSDType.Map) { - OSDMap map = (OSDMap)array[i]; - InventoryFolder folder = new InventoryFolder(map["folder_id"].AsUUID()); - folder.Name = map["name"].AsString(); - folder.ParentUUID = map["parent_id"].AsUUID(); - folder.PreferredType = (FolderType)map["type_default"].AsInteger(); - folder.Version = map["version"].AsInteger(); + OSDMap map = (OSDMap)t; + InventoryFolder folder = new InventoryFolder(map["folder_id"].AsUUID()) + { + Name = map["name"].AsString(), + ParentUUID = map["parent_id"].AsUUID(), + PreferredType = (FolderType) map["type_default"].AsInteger(), + Version = map["version"].AsInteger() + }; folders.Add(folder); } } @@ -764,27 +741,26 @@ namespace OpenMetaverse public InventoryFolder[] ParseInventorySkeleton(string key, Hashtable reply) { UUID ownerID; - if (key.Equals("inventory-skel-lib")) - ownerID = LibraryOwner; - else - ownerID = AgentID; + ownerID = key.Equals("inventory-skel-lib") ? LibraryOwner : AgentID; List folders = new List(); if (reply.ContainsKey(key) && reply[key] is ArrayList) { ArrayList array = (ArrayList)reply[key]; - for (int i = 0; i < array.Count; i++) + foreach (object t in array) { - if (array[i] is Hashtable) + if (t is Hashtable) { - Hashtable map = (Hashtable)array[i]; - InventoryFolder folder = new InventoryFolder(ParseUUID("folder_id", map)); - folder.Name = ParseString("name", map); - folder.ParentUUID = ParseUUID("parent_id", map); - folder.PreferredType = (FolderType)ParseUInt("type_default", map); - folder.Version = (int)ParseUInt("version", map); - folder.OwnerID = ownerID; + Hashtable map = (Hashtable)t; + InventoryFolder folder = new InventoryFolder(ParseUUID("folder_id", map)) + { + Name = ParseString("name", map), + ParentUUID = ParseUUID("parent_id", map), + PreferredType = (FolderType) ParseUInt("type_default", map), + Version = (int) ParseUInt("version", map), + OwnerID = ownerID + }; folders.Add(folder); } @@ -818,8 +794,7 @@ namespace OpenMetaverse protected virtual void OnLoginProgress(LoginProgressEventArgs e) { EventHandler handler = m_LoginProgress; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -884,15 +859,18 @@ namespace OpenMetaverse public LoginStatus LoginStatusCode { get { return InternalStatusCode; } } /// Upon login failure, contains a short string key for the /// type of login error that occurred - public string LoginErrorKey { get { return InternalErrorKey; } } + public string LoginErrorKey => InternalErrorKey; + /// The raw XML-RPC reply from the login server, exactly as it /// was received (minus the HTTP header) - public string RawLoginReply { get { return InternalRawLoginReply; } } + public string RawLoginReply => InternalRawLoginReply; + /// During login this contains a descriptive version of /// LoginStatusCode. After a successful login this will contain the /// message of the day, and after a failed login a descriptive error /// message will be returned - public string LoginMessage { get { return InternalLoginMessage; } } + public string LoginMessage => InternalLoginMessage; + /// Maximum number of groups an agent can belong to, -1 for unlimited public int MaxAgentGroups = -1; /// Server side baking service URL @@ -1122,36 +1100,36 @@ namespace OpenMetaverse #region LLSD Based Login // Create the CAPS login structure - OSDMap loginLLSD = new OSDMap(); - loginLLSD["first"] = OSD.FromString(loginParams.FirstName); - loginLLSD["last"] = OSD.FromString(loginParams.LastName); - loginLLSD["passwd"] = OSD.FromString(loginParams.Password); - loginLLSD["start"] = OSD.FromString(loginParams.Start); - loginLLSD["channel"] = OSD.FromString(loginParams.Channel); - loginLLSD["version"] = OSD.FromString(loginParams.Version); - loginLLSD["platform"] = OSD.FromString(loginParams.Platform); - loginLLSD["platform_version"] = OSD.FromString(loginParams.PlatformVersion); - loginLLSD["mac"] = OSD.FromString(loginParams.MAC); - loginLLSD["agree_to_tos"] = OSD.FromBoolean(loginParams.AgreeToTos); - loginLLSD["read_critical"] = OSD.FromBoolean(loginParams.ReadCritical); - loginLLSD["viewer_digest"] = OSD.FromString(loginParams.ViewerDigest); - loginLLSD["id0"] = OSD.FromString(loginParams.ID0); - loginLLSD["last_exec_event"] = OSD.FromInteger((int)loginParams.LastExecEvent); + OSDMap loginLLSD = new OSDMap + { + ["first"] = OSD.FromString(loginParams.FirstName), + ["last"] = OSD.FromString(loginParams.LastName), + ["passwd"] = OSD.FromString(loginParams.Password), + ["start"] = OSD.FromString(loginParams.Start), + ["channel"] = OSD.FromString(loginParams.Channel), + ["version"] = OSD.FromString(loginParams.Version), + ["platform"] = OSD.FromString(loginParams.Platform), + ["platform_version"] = OSD.FromString(loginParams.PlatformVersion), + ["mac"] = OSD.FromString(loginParams.MAC), + ["agree_to_tos"] = OSD.FromBoolean(loginParams.AgreeToTos), + ["read_critical"] = OSD.FromBoolean(loginParams.ReadCritical), + ["viewer_digest"] = OSD.FromString(loginParams.ViewerDigest), + ["id0"] = OSD.FromString(loginParams.ID0), + ["last_exec_event"] = OSD.FromInteger((int) loginParams.LastExecEvent) + }; // Create the options LLSD array OSDArray optionsOSD = new OSDArray(); - for (int i = 0; i < loginParams.Options.Length; i++) - optionsOSD.Add(OSD.FromString(loginParams.Options[i])); + foreach (string t in loginParams.Options) + optionsOSD.Add(OSD.FromString(t)); foreach (string[] callbackOpts in CallbackOptions.Values) { - if (callbackOpts != null) + if (callbackOpts == null) continue; + foreach (string t in callbackOpts) { - for (int i = 0; i < callbackOpts.Length; i++) - { - if (!optionsOSD.Contains(callbackOpts[i])) - optionsOSD.Add(callbackOpts[i]); - } + if (!optionsOSD.Contains(t)) + optionsOSD.Add(t); } } loginLLSD["options"] = optionsOSD; @@ -1164,7 +1142,7 @@ namespace OpenMetaverse } catch (Exception ex) { - Logger.Log(String.Format("Failed to parse login URI {0}, {1}", loginParams.URI, ex.Message), + Logger.Log($"Failed to parse login URI {loginParams.URI}, {ex.Message}", Helpers.LogLevel.Error, Client); return; } @@ -1172,7 +1150,8 @@ namespace OpenMetaverse CapsClient loginRequest = new CapsClient(loginUri); loginRequest.OnComplete += new CapsClient.CompleteCallback(LoginReplyLLSDHandler); loginRequest.UserData = CurrentContext; - UpdateLoginStatus(LoginStatus.ConnectingToLogin, String.Format("Logging in as {0} {1}...", loginParams.FirstName, loginParams.LastName)); + UpdateLoginStatus(LoginStatus.ConnectingToLogin, + $"Logging in as {loginParams.FirstName} {loginParams.LastName}..."); loginRequest.BeginGetResponse(loginLLSD, OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); #endregion @@ -1182,16 +1161,18 @@ namespace OpenMetaverse #region XML-RPC Based Login Code // Create the Hashtable for XmlRpcCs - Hashtable loginXmlRpc = new Hashtable(); - loginXmlRpc["first"] = loginParams.FirstName; - loginXmlRpc["last"] = loginParams.LastName; - loginXmlRpc["passwd"] = loginParams.Password; - loginXmlRpc["start"] = loginParams.Start; - loginXmlRpc["channel"] = loginParams.Channel; - loginXmlRpc["version"] = loginParams.Version; - loginXmlRpc["platform"] = loginParams.Platform; - loginXmlRpc["platform_version"] = loginParams.PlatformVersion; - loginXmlRpc["mac"] = loginParams.MAC; + Hashtable loginXmlRpc = new Hashtable + { + ["first"] = loginParams.FirstName, + ["last"] = loginParams.LastName, + ["passwd"] = loginParams.Password, + ["start"] = loginParams.Start, + ["channel"] = loginParams.Channel, + ["version"] = loginParams.Version, + ["platform"] = loginParams.Platform, + ["platform_version"] = loginParams.PlatformVersion, + ["mac"] = loginParams.MAC + }; if (loginParams.AgreeToTos) loginXmlRpc["agree_to_tos"] = "true"; if (loginParams.ReadCritical) @@ -1201,18 +1182,16 @@ namespace OpenMetaverse // Create the options array ArrayList options = new ArrayList(); - for (int i = 0; i < loginParams.Options.Length; i++) - options.Add(loginParams.Options[i]); + foreach (string t in loginParams.Options) + options.Add(t); foreach (string[] callbackOpts in CallbackOptions.Values) { - if (callbackOpts != null) + if (callbackOpts == null) continue; + foreach (string t in callbackOpts) { - for (int i = 0; i < callbackOpts.Length; i++) - { - if (!options.Contains(callbackOpts[i])) - options.Add(callbackOpts[i]); - } + if (!options.Contains(t)) + options.Add(t); } } loginXmlRpc["options"] = options; @@ -1235,10 +1214,10 @@ namespace OpenMetaverse } catch (Exception e) { - UpdateLoginStatus(LoginStatus.Failed, "Error opening the login server connection: " + e.Message); + UpdateLoginStatus(LoginStatus.Failed, + "Error opening the login server connection: " + e.Message); } - }); - requestThread.Name = "XML-RPC Login"; + }) {Name = "XML-RPC Login"}; requestThread.Start(); } catch (Exception e) @@ -1437,10 +1416,7 @@ namespace OpenMetaverse { // Make sure a usable error key is set - if (!String.IsNullOrEmpty(reason)) - InternalErrorKey = reason; - else - InternalErrorKey = "unknown"; + InternalErrorKey = !String.IsNullOrEmpty(reason) ? reason : "unknown"; UpdateLoginStatus(LoginStatus.Failed, message); } @@ -1608,9 +1584,9 @@ namespace OpenMetaverse if (nics != null && nics.Length > 0) { - for (int i = 0; i < nics.Length; i++) + foreach (NetworkInterface t in nics) { - string adapterMac = nics[i].GetPhysicalAddress().ToString().ToUpper(); + string adapterMac = t.GetPhysicalAddress().ToString().ToUpper(); if (adapterMac.Length == 12 && adapterMac != "000000000000") { mac = adapterMac; @@ -1643,15 +1619,15 @@ namespace OpenMetaverse private readonly String m_Message; private readonly String m_FailReason; - public LoginStatus Status { get { return m_Status; } } - public String Message { get { return m_Message; } } - public string FailReason { get { return m_FailReason; } } + public LoginStatus Status => m_Status; + public String Message => m_Message; + public string FailReason => m_FailReason; - public LoginProgressEventArgs(LoginStatus login, String message, String failReason) + public LoginProgressEventArgs(LoginStatus login, string message, string failReason) { - this.m_Status = login; - this.m_Message = message; - this.m_FailReason = failReason; + m_Status = login; + m_Message = message; + m_FailReason = failReason; } } diff --git a/OpenMetaverse/NameValue.cs b/OpenMetaverse/NameValue.cs index 08891fa8..45b8509b 100644 --- a/OpenMetaverse/NameValue.cs +++ b/OpenMetaverse/NameValue.cs @@ -25,7 +25,6 @@ */ using System; -using System.Collections.Generic; using System.Text; namespace OpenMetaverse @@ -163,10 +162,8 @@ namespace OpenMetaverse /// public NameValue(string data) { - int i; - // Name - i = data.IndexOfAny(Separators); + var i = data.IndexOfAny(Separators); if (i < 1) { Name = String.Empty; diff --git a/OpenMetaverse/NetworkManager.cs b/OpenMetaverse/NetworkManager.cs index 6fff7947..dbf3b1b6 100644 --- a/OpenMetaverse/NetworkManager.cs +++ b/OpenMetaverse/NetworkManager.cs @@ -26,14 +26,10 @@ using System; using System.Threading; -using System.Collections; using System.Collections.Generic; +using System.Linq; using System.Net; -using System.Net.Sockets; -using System.Globalization; -using System.IO; using OpenMetaverse.Packets; -using OpenMetaverse.StructuredData; using OpenMetaverse.Interfaces; using OpenMetaverse.Messages.Linden; @@ -367,7 +363,7 @@ namespace OpenMetaverse CapsEvents = new CapsEventDictionary(client); // Register internal CAPS callbacks - RegisterEventCallback("EnableSimulator", new Caps.EventQueueCallback(EnableSimulatorHandler)); + RegisterEventCallback("EnableSimulator", EnableSimulatorHandler); // Register the internal callbacks RegisterCallback(PacketType.RegionHandshake, RegionHandshakeHandler); @@ -510,7 +506,7 @@ namespace OpenMetaverse /// A Simulator object on success, otherwise null public Simulator Connect(IPAddress ip, ushort port, ulong handle, bool setDefault, string seedcaps) { - IPEndPoint endPoint = new IPEndPoint(ip, (int)port); + IPEndPoint endPoint = new IPEndPoint(ip, port); return Connect(endPoint, handle, setDefault, seedcaps); } @@ -552,14 +548,18 @@ namespace OpenMetaverse PacketOutbox.Open(); // Start the packet decoding thread - Thread decodeThread = new Thread(new ThreadStart(IncomingPacketHandler)); - decodeThread.Name = "Incoming UDP packet dispatcher"; + Thread decodeThread = new Thread(IncomingPacketHandler) + { + Name = "Incoming UDP packet dispatcher" + }; decodeThread.Start(); // Start the packet sending thread - Thread sendThread = new Thread(new ThreadStart(OutgoingPacketHandler)); - sendThread.Name = "Outgoing UDP packet dispatcher"; - sendThread.Start(); + Thread sendThread = new Thread(OutgoingPacketHandler) + { + Name = "Outgoing UDP packet dispatcher" + }; + sendThread.Start(); } // raise the SimConnecting event and allow any event @@ -586,7 +586,7 @@ namespace OpenMetaverse if (DisconnectTimer == null) { // Start a timer that checks if we've been disconnected - DisconnectTimer = new Timer(new TimerCallback(DisconnectTimer_Elapsed), null, + DisconnectTimer = new Timer(DisconnectTimer_Elapsed, null, Client.Settings.SIMULATOR_TIMEOUT, Client.Settings.SIMULATOR_TIMEOUT); } @@ -658,7 +658,8 @@ namespace OpenMetaverse // Otherwise we fire it manually with a NetworkTimeout type after LOGOUT_TIMEOUT System.Timers.Timer timeout = new System.Timers.Timer(); - EventHandler callback = delegate(object sender, LoggedOutEventArgs e) { + EventHandler callback = delegate + { Shutdown(DisconnectType.ClientInitiated); timeout.Stop(); }; @@ -666,7 +667,8 @@ namespace OpenMetaverse LoggedOut += callback; timeout.Interval = Client.Settings.LOGOUT_TIMEOUT; - timeout.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) { + timeout.Elapsed += delegate + { timeout.Stop(); Shutdown(DisconnectType.NetworkTimeout); OnLoggedOut(new LoggedOutEventArgs(new List())); @@ -687,7 +689,7 @@ namespace OpenMetaverse public void Logout() { AutoResetEvent logoutEvent = new AutoResetEvent(false); - EventHandler callback = delegate(object sender, LoggedOutEventArgs e) { logoutEvent.Set(); }; + EventHandler callback = delegate { logoutEvent.Set(); }; LoggedOut += callback; @@ -726,9 +728,14 @@ namespace OpenMetaverse Logger.Log("Logging out", Helpers.LogLevel.Info, Client); // Send a logout request to the current sim - LogoutRequestPacket logout = new LogoutRequestPacket(); - logout.AgentData.AgentID = Client.Self.AgentID; - logout.AgentData.SessionID = Client.Self.SessionID; + LogoutRequestPacket logout = new LogoutRequestPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + } + }; SendPacket(logout); } @@ -788,16 +795,16 @@ namespace OpenMetaverse lock (Simulators) { // Disconnect all simulators except the current one - for (int i = 0; i < Simulators.Count; i++) + foreach (Simulator t in Simulators) { - if (Simulators[i] != null && Simulators[i] != CurrentSim) + if (t != null && t != CurrentSim) { - Simulators[i].Disconnect(sendCloseCircuit); + t.Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (m_SimDisconnected != null) { - OnSimDisconnected(new SimDisconnectedEventArgs(Simulators[i], type)); + OnSimDisconnected(new SimDisconnectedEventArgs(t, type)); } } } @@ -840,10 +847,10 @@ namespace OpenMetaverse { lock (Simulators) { - for (int i = 0; i < Simulators.Count; i++) + foreach (Simulator t in Simulators) { - if (Simulators[i].IPEndPoint.Equals(endPoint)) - return Simulators[i]; + if (t.IPEndPoint.Equals(endPoint)) + return t; } } @@ -873,78 +880,70 @@ namespace OpenMetaverse private void OutgoingPacketHandler() { OutgoingPacket outgoingPacket = null; - Simulator simulator; // FIXME: This is kind of ridiculous. Port the HTB code from Simian over ASAP! System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); while (connected) { - if (PacketOutbox.Dequeue(100, ref outgoingPacket)) + if (!PacketOutbox.Dequeue(100, ref outgoingPacket)) continue; + + var simulator = outgoingPacket.Simulator; + + // Very primitive rate limiting, keeps a fixed buffer of time between each packet + stopwatch.Stop(); + if (stopwatch.ElapsedMilliseconds < 10) { - simulator = outgoingPacket.Simulator; - - // Very primitive rate limiting, keeps a fixed buffer of time between each packet - stopwatch.Stop(); - if (stopwatch.ElapsedMilliseconds < 10) - { - //Logger.DebugLog(String.Format("Rate limiting, last packet was {0}ms ago", ms)); - Thread.Sleep(10 - (int)stopwatch.ElapsedMilliseconds); - } - - simulator.SendPacketFinal(outgoingPacket); - stopwatch.Start(); + //Logger.DebugLog(String.Format("Rate limiting, last packet was {0}ms ago", ms)); + Thread.Sleep(10 - (int)stopwatch.ElapsedMilliseconds); } + + simulator.SendPacketFinal(outgoingPacket); + stopwatch.Start(); } } private void IncomingPacketHandler() { IncomingPacket incomingPacket = new IncomingPacket(); - Packet packet = null; - Simulator simulator = null; while (connected) { // Reset packet to null for the check below - packet = null; - if (PacketInbox.Dequeue(100, ref incomingPacket)) + if (!PacketInbox.Dequeue(100, ref incomingPacket)) continue; + var packet = incomingPacket.Packet; + var simulator = incomingPacket.Simulator; + + if (packet != null) { - packet = incomingPacket.Packet; - simulator = incomingPacket.Simulator; - - if (packet != null) + // Skip blacklisted packets + if (UDPBlacklist.Contains(packet.Type.ToString())) { - // Skip blacklisted packets - if (UDPBlacklist.Contains(packet.Type.ToString())) - { - Logger.Log(String.Format("Discarding Blacklisted packet {0} from {1}", - packet.Type, simulator.IPEndPoint), Helpers.LogLevel.Warning); - return; - } - - // Fire the callback(s), if any - PacketEvents.RaiseEvent(packet.Type, packet, simulator); + Logger.Log($"Discarding Blacklisted packet {packet.Type} from {simulator.IPEndPoint}", + Helpers.LogLevel.Warning); + return; } + + // Fire the callback(s), if any + PacketEvents.RaiseEvent(packet.Type, packet, simulator); } } } private void SetCurrentSim(Simulator simulator, string seedcaps) { - if (simulator != CurrentSim) + if (simulator == CurrentSim) return; + + Simulator oldSim = CurrentSim; + lock (Simulators) CurrentSim = simulator; // CurrentSim is synchronized against Simulators + + simulator.SetSeedCaps(seedcaps); + + // If the current simulator changed fire the callback + if (m_SimChanged != null && simulator != oldSim) { - Simulator oldSim = CurrentSim; - lock (Simulators) CurrentSim = simulator; // CurrentSim is synchronized against Simulators - - simulator.SetSeedCaps(seedcaps); - - // If the current simulator changed fire the callback - if (m_SimChanged != null && simulator != oldSim) - { - OnSimChanged(new SimChangedEventArgs(oldSim)); - } + OnSimChanged(new SimChangedEventArgs(oldSim)); } } @@ -1005,12 +1004,7 @@ namespace OpenMetaverse // Deal with callbacks, if any if (m_LoggedOut != null) { - List itemIDs = new List(); - - foreach (LogoutReplyPacket.InventoryDataBlock InventoryData in logout.InventoryData) - { - itemIDs.Add(InventoryData.ItemID); - } + var itemIDs = logout.InventoryData.Select(InventoryData => InventoryData.ItemID).ToList(); OnLoggedOut(new LoggedOutEventArgs(itemIDs)); } @@ -1065,9 +1059,8 @@ namespace OpenMetaverse return; } SimStatsPacket stats = (SimStatsPacket)e.Packet; - for (int i = 0; i < stats.Stat.Length; i++) + foreach (SimStatsPacket.StatBlock s in stats.Stat) { - SimStatsPacket.StatBlock s = stats.Stat[i]; switch (s.StatID) { case 0: @@ -1215,11 +1208,11 @@ namespace OpenMetaverse EnableSimulatorMessage msg = (EnableSimulatorMessage)message; - for (int i = 0; i < msg.Simulators.Length; i++) + foreach (EnableSimulatorMessage.SimulatorInfoBlock t in msg.Simulators) { - IPAddress ip = msg.Simulators[i].IP; - ushort port = (ushort)msg.Simulators[i].Port; - ulong handle = msg.Simulators[i].RegionHandle; + IPAddress ip = t.IP; + ushort port = (ushort)t.Port; + ulong handle = t.RegionHandle; IPEndPoint endPoint = new IPEndPoint(ip, port); @@ -1258,16 +1251,14 @@ namespace OpenMetaverse public class PacketReceivedEventArgs : EventArgs { - private readonly Packet m_Packet; - private readonly Simulator m_Simulator; + public Packet Packet { get; } - public Packet Packet { get { return m_Packet; } } - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator { get; } public PacketReceivedEventArgs(Packet packet, Simulator simulator) { - this.m_Packet = packet; - this.m_Simulator = simulator; + Packet = packet; + Simulator = simulator; } } @@ -1284,65 +1275,51 @@ namespace OpenMetaverse public class PacketSentEventArgs : EventArgs { - private readonly byte[] m_Data; - private readonly int m_SentBytes; - private readonly Simulator m_Simulator; - - public byte[] Data { get { return m_Data; } } - public int SentBytes { get { return m_SentBytes; } } - public Simulator Simulator { get { return m_Simulator; } } + public byte[] Data { get; } + public int SentBytes { get; } + public Simulator Simulator { get; } public PacketSentEventArgs(byte[] data, int bytesSent, Simulator simulator) { - this.m_Data = data; - this.m_SentBytes = bytesSent; - this.m_Simulator = simulator; + Data = data; + SentBytes = bytesSent; + Simulator = simulator; } } public class SimConnectingEventArgs : EventArgs { - private readonly Simulator m_Simulator; - private bool m_Cancel; + public Simulator Simulator { get; } - public Simulator Simulator { get { return m_Simulator; } } - - public bool Cancel - { - get { return m_Cancel; } - set { m_Cancel = value; } - } + public bool Cancel { get; set; } public SimConnectingEventArgs(Simulator simulator) { - this.m_Simulator = simulator; - this.m_Cancel = false; + Simulator = simulator; + Cancel = false; } } public class SimConnectedEventArgs : EventArgs { - private readonly Simulator m_Simulator; - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator { get; } public SimConnectedEventArgs(Simulator simulator) { - this.m_Simulator = simulator; + Simulator = simulator; } } public class SimDisconnectedEventArgs : EventArgs { - private readonly Simulator m_Simulator; - private readonly NetworkManager.DisconnectType m_Reason; + public Simulator Simulator { get; } - public Simulator Simulator { get { return m_Simulator; } } - public NetworkManager.DisconnectType Reason { get { return m_Reason; } } + public NetworkManager.DisconnectType Reason { get; } public SimDisconnectedEventArgs(Simulator simulator, NetworkManager.DisconnectType reason) { - this.m_Simulator = simulator; - this.m_Reason = reason; + Simulator = simulator; + Reason = reason; } } @@ -1351,37 +1328,33 @@ namespace OpenMetaverse private readonly NetworkManager.DisconnectType m_Reason; private readonly String m_Message; - public NetworkManager.DisconnectType Reason { get { return m_Reason; } } - public String Message { get { return m_Message; } } + public NetworkManager.DisconnectType Reason => m_Reason; + public String Message => m_Message; - public DisconnectedEventArgs(NetworkManager.DisconnectType reason, String message) + public DisconnectedEventArgs(NetworkManager.DisconnectType reason, string message) { - this.m_Reason = reason; - this.m_Message = message; + m_Reason = reason; + m_Message = message; } } public class SimChangedEventArgs : EventArgs { - private readonly Simulator m_PreviousSimulator; - - public Simulator PreviousSimulator { get { return m_PreviousSimulator; } } + public Simulator PreviousSimulator { get; } public SimChangedEventArgs(Simulator previousSimulator) { - this.m_PreviousSimulator = previousSimulator; + PreviousSimulator = previousSimulator; } } public class EventQueueRunningEventArgs : EventArgs { - private readonly Simulator m_Simulator; - - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator { get; } public EventQueueRunningEventArgs(Simulator simulator) { - this.m_Simulator = simulator; + Simulator = simulator; } } #endregion diff --git a/OpenMetaverse/ObjectPool.cs b/OpenMetaverse/ObjectPool.cs index ded1d486..b69799b3 100644 --- a/OpenMetaverse/ObjectPool.cs +++ b/OpenMetaverse/ObjectPool.cs @@ -9,7 +9,7 @@ namespace OpenMetaverse public class UDPPacketBuffer { /// Size of the byte array used to store raw packet data - public const int BUFFER_SIZE = 4096; + public const int BufferSize = 4096; /// Raw packet data buffer public readonly byte[] Data; /// Length of the data to transmit @@ -26,7 +26,7 @@ namespace OpenMetaverse /// public UDPPacketBuffer() { - Data = new byte[UDPPacketBuffer.BUFFER_SIZE]; + Data = new byte[BufferSize]; // Will be modified later by BeginReceiveFrom() RemoteEndPoint = new IPEndPoint(Settings.BIND_ADDR, 0); } @@ -37,7 +37,7 @@ namespace OpenMetaverse /// EndPoint of the remote host public UDPPacketBuffer(IPEndPoint endPoint) { - Data = new byte[UDPPacketBuffer.BUFFER_SIZE]; + Data = new byte[BufferSize]; RemoteEndPoint = endPoint; } @@ -64,7 +64,7 @@ namespace OpenMetaverse /// public class PacketBufferPool : ObjectPoolBase { - private IPEndPoint EndPoint; + private IPEndPoint _endPoint; /// /// Initialize the object pool in client mode @@ -75,7 +75,7 @@ namespace OpenMetaverse public PacketBufferPool(IPEndPoint endPoint, int itemsPerSegment, int minSegments) : base() { - EndPoint = endPoint; + _endPoint = endPoint; Initialize(itemsPerSegment, minSegments, true, 1000 * 60 * 5); } @@ -85,9 +85,8 @@ namespace OpenMetaverse /// /// public PacketBufferPool(int itemsPerSegment, int minSegments) - : base() { - EndPoint = null; + _endPoint = null; Initialize(itemsPerSegment, minSegments, true, 1000 * 60 * 5); } @@ -98,12 +97,7 @@ namespace OpenMetaverse /// Initialized UDPPacketBuffer object protected override UDPPacketBuffer GetObjectInstance() { - if (EndPoint != null) - // Client mode - return new UDPPacketBuffer(EndPoint); - else - // Server mode - return new UDPPacketBuffer(); + return _endPoint != null ? new UDPPacketBuffer(_endPoint) : new UDPPacketBuffer(); } } diff --git a/OpenMetaverse/ObjectPoolBase.cs b/OpenMetaverse/ObjectPoolBase.cs index 1534e0c0..cc935e01 100644 --- a/OpenMetaverse/ObjectPoolBase.cs +++ b/OpenMetaverse/ObjectPoolBase.cs @@ -25,7 +25,6 @@ */ using System; -using System.Collections; using System.Collections.Generic; using System.Threading; @@ -34,14 +33,14 @@ namespace OpenMetaverse public sealed class WrappedObject : IDisposable where T : class { private T _instance; - internal readonly ObjectPoolSegment _owningSegment; - internal readonly ObjectPoolBase _owningObjectPool; + internal readonly ObjectPoolSegment OwningSegment; + internal readonly ObjectPoolBase OwningObjectPool; private bool _disposed = false; internal WrappedObject(ObjectPoolBase owningPool, ObjectPoolSegment ownerSegment, T activeInstance) { - _owningObjectPool = owningPool; - _owningSegment = ownerSegment; + OwningObjectPool = owningPool; + OwningSegment = ownerSegment; _instance = activeInstance; } @@ -58,7 +57,7 @@ namespace OpenMetaverse GC.ReRegisterForFinalize(this); // Return this instance back to the owning queue - _owningObjectPool.CheckIn(_owningSegment, _instance); + OwningObjectPool.CheckIn(OwningSegment, _instance); } /// @@ -83,7 +82,7 @@ namespace OpenMetaverse return; _disposed = true; - _owningObjectPool.CheckIn(_owningSegment, _instance); + OwningObjectPool.CheckIn(OwningSegment, _instance); GC.SuppressFinalize(this); } } @@ -152,7 +151,7 @@ namespace OpenMetaverse { while (_segments.Count < this.MinimumSegmentCount) { - ObjectPoolSegment segment = CreateSegment(false); + var segment = CreateSegment(false); _segments.Add(segment.SegmentNumber, segment); } } @@ -160,7 +159,7 @@ namespace OpenMetaverse // This forces a compact, to make sure our objects fill in any holes in the heap. if (_gc) { - System.GC.Collect(); + GC.Collect(); } _timer = new Timer(CleanupThreadCallback, null, cleanupFrequenceMS, cleanupFrequenceMS); @@ -233,7 +232,7 @@ namespace OpenMetaverse int segmentToAdd = _activeSegment; _activeSegment++; - Queue buffers = new Queue(); + var buffers = new Queue(); for (int i = 1; i <= this._itemsPerSegment; i++) { T obj = GetObjectInstance(); @@ -241,7 +240,7 @@ namespace OpenMetaverse } // certain segments we don't want to ever be cleaned up (the initial segments) - DateTime cleanupTime = (allowSegmentToBeCleanedUp) ? DateTime.Now.Add(this._minimumAgeToCleanup) : DateTime.MaxValue; + DateTime cleanupTime = (allowSegmentToBeCleanedUp) ? DateTime.Now.Add(_minimumAgeToCleanup) : DateTime.MaxValue; ObjectPoolSegment segment = new ObjectPoolSegment(segmentToAdd, buffers, cleanupTime); return segment; @@ -429,27 +428,25 @@ namespace OpenMetaverse protected virtual void Dispose(bool disposing) { - if (disposing) + if (!disposing) return; + lock (_syncRoot) { - lock (_syncRoot) + if (_disposed) + return; + + _timer.Dispose(); + _disposed = true; + + foreach (var kvp in _segments) { - if (_disposed) - return; - - _timer.Dispose(); - _disposed = true; - - foreach (KeyValuePair> kvp in _segments) + try { - try - { - kvp.Value.Dispose(); - } - catch (Exception) { } + kvp.Value.Dispose(); } - - _segments.Clear(); + catch (Exception) { } // TODO: Investigate, this is smelly. } + + _segments.Clear(); } } @@ -461,12 +458,12 @@ namespace OpenMetaverse private Queue _liveInstances = new Queue(); private int _segmentNumber; private int _originalCount; - private bool _isDisposed = false; + private bool _isDisposed; private DateTime _eligibleForDeletionAt; - public int SegmentNumber { get { return _segmentNumber; } } - public int AvailableItems { get { return _liveInstances.Count; } } - public DateTime DateEligibleForDeletion { get { return _eligibleForDeletionAt; } } + public int SegmentNumber => _segmentNumber; + public int AvailableItems => _liveInstances.Count; + public DateTime DateEligibleForDeletion => _eligibleForDeletionAt; public ObjectPoolSegment(int segmentNumber, Queue liveInstances, DateTime eligibleForDeletionAt) { @@ -478,7 +475,7 @@ namespace OpenMetaverse public bool CanBeCleanedUp() { - if (_isDisposed == true) + if (_isDisposed) throw new ObjectDisposedException("ObjectPoolSegment"); return ((_originalCount == _liveInstances.Count) && (DateTime.Now > _eligibleForDeletionAt)); @@ -494,7 +491,7 @@ namespace OpenMetaverse bool shouldDispose = (typeof(T) is IDisposable); while (_liveInstances.Count != 0) { - T instance = _liveInstances.Dequeue(); + var instance = _liveInstances.Dequeue(); if (shouldDispose) { try @@ -508,7 +505,7 @@ namespace OpenMetaverse internal void CheckInObject(T o) { - if (_isDisposed == true) + if (_isDisposed) throw new ObjectDisposedException("ObjectPoolSegment"); _liveInstances.Enqueue(o); @@ -516,13 +513,13 @@ namespace OpenMetaverse internal T CheckOutObject() { - if (_isDisposed == true) + if (_isDisposed) throw new ObjectDisposedException("ObjectPoolSegment"); if (0 == _liveInstances.Count) throw new InvalidOperationException("No Objects Available for Checkout"); - T o = _liveInstances.Dequeue(); + var o = _liveInstances.Dequeue(); return o; } } diff --git a/OpenMetaverse/PacketDecoder.cs b/OpenMetaverse/PacketDecoder.cs index 91208240..2c7ebc45 100644 --- a/OpenMetaverse/PacketDecoder.cs +++ b/OpenMetaverse/PacketDecoder.cs @@ -1546,27 +1546,27 @@ namespace OpenMetaverse.Packets { FieldInfo[] fields = nestedArrayRecord.GetType().GetFields(); - for (int i = 0; i < fields.Length; i++) + foreach (FieldInfo t in fields) { String special; - if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + fields[i].Name, - fields[i].GetValue(nestedArrayRecord), out special)) + if (SpecialDecoder(packet.GetType().Name + "." + fieldInfo.Name + "." + t.Name, + t.GetValue(nestedArrayRecord), out special)) { result.AppendLine(special); } - else if (fields[i].FieldType.IsArray) // default for an array (probably a byte[]) + else if (t.FieldType.IsArray) // default for an array (probably a byte[]) { result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - fields[i].Name, - Utils.BytesToString((byte[])fields[i].GetValue(nestedArrayRecord)), + t.Name, + Utils.BytesToString((byte[])t.GetValue(nestedArrayRecord)), /*fields[i].GetValue(nestedArrayRecord).GetType().Name*/ "String"); } else // default for a field { result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, - fields[i].Name, - fields[i].GetValue(nestedArrayRecord), - fields[i].GetValue(nestedArrayRecord).GetType().Name); + t.Name, + t.GetValue(nestedArrayRecord), + t.GetValue(nestedArrayRecord).GetType().Name); } } diff --git a/OpenMetaverse/Parallel.cs b/OpenMetaverse/Parallel.cs index 39f730ba..914c4cc7 100644 --- a/OpenMetaverse/Parallel.cs +++ b/OpenMetaverse/Parallel.cs @@ -101,7 +101,7 @@ namespace OpenMetaverse /// Method body to run for each object in the collection public static void ForEach(IEnumerable enumerable, Action body) { - ForEach(processorCount, enumerable, body); + ForEach(processorCount, enumerable, body); } /// @@ -123,8 +123,6 @@ namespace OpenMetaverse WorkPool.QueueUserWorkItem( delegate(object o) { - int threadIndex = (int)o; - while (exception == null) { T entry; @@ -133,7 +131,7 @@ namespace OpenMetaverse { if (!enumerator.MoveNext()) break; - entry = (T)enumerator.Current; // Explicit typecast for Mono's sake + entry = enumerator.Current; // Explicit typecast for Mono's sake } try { body(entry); } diff --git a/OpenMetaverse/ParcelManager.cs b/OpenMetaverse/ParcelManager.cs index b30d371a..afb44c02 100644 --- a/OpenMetaverse/ParcelManager.cs +++ b/OpenMetaverse/ParcelManager.cs @@ -28,6 +28,7 @@ using System; using System.Threading; using System.Reflection; using System.Collections.Generic; +using System.Linq; using OpenMetaverse.Http; using OpenMetaverse.Packets; using OpenMetaverse.Interfaces; @@ -576,14 +577,9 @@ namespace OpenMetaverse /// string containing key=value pairs of a parcel object public override string ToString() { - string result = ""; Type parcelType = this.GetType(); FieldInfo[] fields = parcelType.GetFields(); - foreach (FieldInfo field in fields) - { - result += (field.Name + " = " + field.GetValue(this) + " "); - } - return result; + return fields.Aggregate("", (current, field) => current + (field.Name + " = " + field.GetValue(this) + " ")); } /// /// Defalt constructor @@ -614,33 +610,35 @@ namespace OpenMetaverse if (url != null) { - ParcelPropertiesUpdateMessage req = new ParcelPropertiesUpdateMessage(); - req.AuthBuyerID = this.AuthBuyerID; - req.Category = this.Category; - req.Desc = this.Desc; - req.GroupID = this.GroupID; - req.Landing = this.Landing; - req.LocalID = this.LocalID; - req.MediaAutoScale = this.Media.MediaAutoScale; - req.MediaDesc = this.Media.MediaDesc; - req.MediaHeight = this.Media.MediaHeight; - req.MediaID = this.Media.MediaID; - req.MediaLoop = this.Media.MediaLoop; - req.MediaType = this.Media.MediaType; - req.MediaURL = this.Media.MediaURL; - req.MediaWidth = this.Media.MediaWidth; - req.MusicURL = this.MusicURL; - req.Name = this.Name; - req.ObscureMedia = this.ObscureMedia; - req.ObscureMusic = this.ObscureMusic; - req.ParcelFlags = this.Flags; - req.PassHours = this.PassHours; - req.PassPrice = (uint)this.PassPrice; - req.SalePrice = (uint)this.SalePrice; - req.SnapshotID = this.SnapshotID; - req.UserLocation = this.UserLocation; - req.UserLookAt = this.UserLookAt; - + ParcelPropertiesUpdateMessage req = new ParcelPropertiesUpdateMessage + { + AuthBuyerID = AuthBuyerID, + Category = Category, + Desc = Desc, + GroupID = GroupID, + Landing = Landing, + LocalID = LocalID, + MediaAutoScale = Media.MediaAutoScale, + MediaDesc = Media.MediaDesc, + MediaHeight = Media.MediaHeight, + MediaID = Media.MediaID, + MediaLoop = Media.MediaLoop, + MediaType = Media.MediaType, + MediaURL = Media.MediaURL, + MediaWidth = Media.MediaWidth, + MusicURL = MusicURL, + Name = Name, + ObscureMedia = ObscureMedia, + ObscureMusic = ObscureMusic, + ParcelFlags = Flags, + PassHours = PassHours, + PassPrice = (uint) PassPrice, + SalePrice = (uint) SalePrice, + SnapshotID = SnapshotID, + UserLocation = UserLocation, + UserLookAt = UserLookAt + }; + OSDMap body = req.Serialize(); CapsClient capsPost = new CapsClient(url); @@ -648,31 +646,39 @@ namespace OpenMetaverse } else { - ParcelPropertiesUpdatePacket request = new ParcelPropertiesUpdatePacket(); + ParcelPropertiesUpdatePacket request = new ParcelPropertiesUpdatePacket + { + AgentData = + { + AgentID = simulator.Client.Self.AgentID, + SessionID = simulator.Client.Self.SessionID + }, + ParcelData = + { + LocalID = LocalID, + AuthBuyerID = AuthBuyerID, + Category = (byte) Category, + Desc = Utils.StringToBytes(Desc), + GroupID = GroupID, + LandingType = (byte) Landing, + MediaAutoScale = (Media.MediaAutoScale) ? (byte) 0x1 : (byte) 0x0, + MediaID = Media.MediaID, + MediaURL = Utils.StringToBytes(Media.MediaURL), + MusicURL = Utils.StringToBytes(MusicURL), + Name = Utils.StringToBytes(Name) + } + }; - request.AgentData.AgentID = simulator.Client.Self.AgentID; - request.AgentData.SessionID = simulator.Client.Self.SessionID; - request.ParcelData.LocalID = this.LocalID; - request.ParcelData.AuthBuyerID = this.AuthBuyerID; - request.ParcelData.Category = (byte)this.Category; - request.ParcelData.Desc = Utils.StringToBytes(this.Desc); - request.ParcelData.GroupID = this.GroupID; - request.ParcelData.LandingType = (byte)this.Landing; - request.ParcelData.MediaAutoScale = (this.Media.MediaAutoScale) ? (byte)0x1 : (byte)0x0; - request.ParcelData.MediaID = this.Media.MediaID; - request.ParcelData.MediaURL = Utils.StringToBytes(this.Media.MediaURL.ToString()); - request.ParcelData.MusicURL = Utils.StringToBytes(this.MusicURL.ToString()); - request.ParcelData.Name = Utils.StringToBytes(this.Name); if (wantReply) request.ParcelData.Flags = 1; - request.ParcelData.ParcelFlags = (uint)this.Flags; - request.ParcelData.PassHours = this.PassHours; - request.ParcelData.PassPrice = this.PassPrice; - request.ParcelData.SalePrice = this.SalePrice; - request.ParcelData.SnapshotID = this.SnapshotID; - request.ParcelData.UserLocation = this.UserLocation; - request.ParcelData.UserLookAt = this.UserLookAt; + request.ParcelData.ParcelFlags = (uint)Flags; + request.ParcelData.PassHours = PassHours; + request.ParcelData.PassPrice = PassPrice; + request.ParcelData.SalePrice = SalePrice; + request.ParcelData.SnapshotID = SnapshotID; + request.ParcelData.UserLocation = UserLocation; + request.ParcelData.UserLookAt = UserLookAt; simulator.SendPacket(request); } @@ -687,11 +693,19 @@ namespace OpenMetaverse /// Simulator to send the update to public void UpdateOtherCleanTime(Simulator simulator) { - ParcelSetOtherCleanTimePacket request = new ParcelSetOtherCleanTimePacket(); - request.AgentData.AgentID = simulator.Client.Self.AgentID; - request.AgentData.SessionID = simulator.Client.Self.SessionID; - request.ParcelData.LocalID = this.LocalID; - request.ParcelData.OtherCleanTime = this.OtherCleanTime; + ParcelSetOtherCleanTimePacket request = new ParcelSetOtherCleanTimePacket + { + AgentData = + { + AgentID = simulator.Client.Self.AgentID, + SessionID = simulator.Client.Self.SessionID + }, + ParcelData = + { + LocalID = LocalID, + OtherCleanTime = OtherCleanTime + } + }; simulator.SendPacket(request); } @@ -755,8 +769,7 @@ namespace OpenMetaverse protected virtual void OnParcelDwellReply(ParcelDwellReplyEventArgs e) { EventHandler handler = m_DwellReply; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -778,8 +791,7 @@ namespace OpenMetaverse protected virtual void OnParcelInfoReply(ParcelInfoReplyEventArgs e) { EventHandler handler = m_ParcelInfo; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -801,8 +813,7 @@ namespace OpenMetaverse protected virtual void OnParcelProperties(ParcelPropertiesEventArgs e) { EventHandler handler = m_ParcelProperties; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -824,8 +835,7 @@ namespace OpenMetaverse protected virtual void OnParcelAccessListReply(ParcelAccessListReplyEventArgs e) { EventHandler handler = m_ParcelACL; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -847,8 +857,7 @@ namespace OpenMetaverse protected virtual void OnParcelObjectOwnersReply(ParcelObjectOwnersReplyEventArgs e) { EventHandler handler = m_ParcelObjectOwnersReply; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -870,8 +879,7 @@ namespace OpenMetaverse protected virtual void OnSimParcelsDownloaded(SimParcelsDownloadedEventArgs e) { EventHandler handler = m_SimParcelsDownloaded; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -893,8 +901,7 @@ namespace OpenMetaverse protected virtual void OnForceSelectObjectsReply(ForceSelectObjectsReplyEventArgs e) { EventHandler handler = m_ForceSelectObjects; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -916,8 +923,7 @@ namespace OpenMetaverse protected virtual void OnParcelMediaUpdateReply(ParcelMediaUpdateReplyEventArgs e) { EventHandler handler = m_ParcelMediaUpdateReply; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -939,8 +945,7 @@ namespace OpenMetaverse protected virtual void OnParcelMediaCommand(ParcelMediaCommandEventArgs e) { EventHandler handler = m_ParcelMediaCommand; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -969,9 +974,9 @@ namespace OpenMetaverse // Setup the callbacks Client.Network.RegisterCallback(PacketType.ParcelInfoReply, ParcelInfoReplyHandler); - Client.Network.RegisterEventCallback("ParcelObjectOwnersReply", new Caps.EventQueueCallback(ParcelObjectOwnersReplyHandler)); + Client.Network.RegisterEventCallback("ParcelObjectOwnersReply", ParcelObjectOwnersReplyHandler); // CAPS packet handler, to allow for Media Data not contained in the message template - Client.Network.RegisterEventCallback("ParcelProperties", new Caps.EventQueueCallback(ParcelPropertiesReplyHandler)); + Client.Network.RegisterEventCallback("ParcelProperties", ParcelPropertiesReplyHandler); Client.Network.RegisterCallback(PacketType.ParcelDwellReply, ParcelDwellReplyHandler); Client.Network.RegisterCallback(PacketType.ParcelAccessListReply, ParcelAccessListReplyHandler); Client.Network.RegisterCallback(PacketType.ForceObjectSelect, SelectParcelObjectsReplyHandler); @@ -986,10 +991,15 @@ namespace OpenMetaverse /// Simulator-local ID of the parcel public void RequestParcelInfo(UUID parcelID) { - ParcelInfoRequestPacket request = new ParcelInfoRequestPacket(); - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; - request.Data.ParcelID = parcelID; + ParcelInfoRequestPacket request = new ParcelInfoRequestPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = {ParcelID = parcelID} + }; Client.Network.SendPacket(request); } @@ -1004,13 +1014,19 @@ namespace OpenMetaverse /// multiple simultaneous requests public void RequestParcelProperties(Simulator simulator, int localID, int sequenceID) { - ParcelPropertiesRequestByIDPacket request = new ParcelPropertiesRequestByIDPacket(); - - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; - - request.ParcelData.LocalID = localID; - request.ParcelData.SequenceID = sequenceID; + ParcelPropertiesRequestByIDPacket request = new ParcelPropertiesRequestByIDPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + ParcelData = + { + LocalID = localID, + SequenceID = sequenceID + } + }; Client.Network.SendPacket(request, simulator); } @@ -1026,13 +1042,20 @@ namespace OpenMetaverse /// public void RequestParcelAccessList(Simulator simulator, int localID, AccessList flags, int sequenceID) { - ParcelAccessListRequestPacket request = new ParcelAccessListRequestPacket(); - - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; - request.Data.LocalID = localID; - request.Data.Flags = (uint)flags; - request.Data.SequenceID = sequenceID; + ParcelAccessListRequestPacket request = new ParcelAccessListRequestPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = + { + LocalID = localID, + Flags = (uint) flags, + SequenceID = sequenceID + } + }; Client.Network.SendPacket(request, simulator); } @@ -1054,16 +1077,23 @@ namespace OpenMetaverse public void RequestParcelProperties(Simulator simulator, float north, float east, float south, float west, int sequenceID, bool snapSelection) { - ParcelPropertiesRequestPacket request = new ParcelPropertiesRequestPacket(); - - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; - request.ParcelData.North = north; - request.ParcelData.East = east; - request.ParcelData.South = south; - request.ParcelData.West = west; - request.ParcelData.SequenceID = sequenceID; - request.ParcelData.SnapSelection = snapSelection; + ParcelPropertiesRequestPacket request = new ParcelPropertiesRequestPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + ParcelData = + { + North = north, + East = east, + South = south, + West = west, + SequenceID = sequenceID, + SnapSelection = snapSelection + } + }; Client.Network.SendPacket(request, simulator); } @@ -1148,11 +1178,20 @@ namespace OpenMetaverse /// Simulator-local ID of the parcel public void RequestDwell(Simulator simulator, int localID) { - ParcelDwellRequestPacket request = new ParcelDwellRequestPacket(); - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; - request.Data.LocalID = localID; - request.Data.ParcelID = UUID.Zero; // Not used by clients + ParcelDwellRequestPacket request = new ParcelDwellRequestPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = + { + LocalID = localID, + ParcelID = UUID.Zero + } + }; + // Not used by clients Client.Network.SendPacket(request, simulator); } @@ -1171,19 +1210,30 @@ namespace OpenMetaverse public void Buy(Simulator simulator, int localID, bool forGroup, UUID groupID, bool removeContribution, int parcelArea, int parcelPrice) { - ParcelBuyPacket request = new ParcelBuyPacket(); + ParcelBuyPacket request = new ParcelBuyPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = + { + Final = true, + GroupID = groupID, + LocalID = localID, + IsGroupOwned = forGroup, + RemoveContribution = removeContribution + }, + ParcelData = + { + Area = parcelArea, + Price = parcelPrice + } + }; - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; - request.Data.Final = true; - request.Data.GroupID = groupID; - request.Data.LocalID = localID; - request.Data.IsGroupOwned = forGroup; - request.Data.RemoveContribution = removeContribution; - request.ParcelData.Area = parcelArea; - request.ParcelData.Price = parcelPrice; Client.Network.SendPacket(request, simulator); } @@ -1195,11 +1245,16 @@ namespace OpenMetaverse /// The parcels region specific local ID public void Reclaim(Simulator simulator, int localID) { - ParcelReclaimPacket request = new ParcelReclaimPacket(); - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; + ParcelReclaimPacket request = new ParcelReclaimPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = {LocalID = localID} + }; - request.Data.LocalID = localID; Client.Network.SendPacket(request, simulator); } @@ -1212,12 +1267,20 @@ namespace OpenMetaverse /// The groups public void DeedToGroup(Simulator simulator, int localID, UUID groupID) { - ParcelDeedToGroupPacket request = new ParcelDeedToGroupPacket(); - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; + ParcelDeedToGroupPacket request = new ParcelDeedToGroupPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = + { + LocalID = localID, + GroupID = groupID + } + }; - request.Data.LocalID = localID; - request.Data.GroupID = groupID; Client.Network.SendPacket(request, simulator); } @@ -1229,12 +1292,17 @@ namespace OpenMetaverse /// The parcels region specific local ID public void RequestObjectOwners(Simulator simulator, int localID) { - ParcelObjectOwnersRequestPacket request = new ParcelObjectOwnersRequestPacket(); + ParcelObjectOwnersRequestPacket request = new ParcelObjectOwnersRequestPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + ParcelData = {LocalID = localID} + }; - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; - request.ParcelData.LocalID = localID; Client.Network.SendPacket(request, simulator); } @@ -1247,17 +1315,24 @@ namespace OpenMetaverse /// A list containing object owners s to return public void ReturnObjects(Simulator simulator, int localID, ObjectReturnType type, List ownerIDs) { - ParcelReturnObjectsPacket request = new ParcelReturnObjectsPacket(); - request.AgentData.AgentID = Client.Self.AgentID; - request.AgentData.SessionID = Client.Self.SessionID; + ParcelReturnObjectsPacket request = new ParcelReturnObjectsPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + ParcelData = + { + LocalID = localID, + ReturnType = (uint) type + }, + TaskIDs = new ParcelReturnObjectsPacket.TaskIDsBlock[1] + }; - request.ParcelData.LocalID = localID; - request.ParcelData.ReturnType = (uint)type; // A single null TaskID is (not) used for parcel object returns - request.TaskIDs = new ParcelReturnObjectsPacket.TaskIDsBlock[1]; - request.TaskIDs[0] = new ParcelReturnObjectsPacket.TaskIDsBlock(); - request.TaskIDs[0].TaskID = UUID.Zero; + request.TaskIDs[0] = new ParcelReturnObjectsPacket.TaskIDsBlock {TaskID = UUID.Zero}; // Convert the list of owner UUIDs to packet blocks if a list is given if (ownerIDs != null) @@ -1266,8 +1341,7 @@ namespace OpenMetaverse for (int i = 0; i < ownerIDs.Count; i++) { - request.OwnerIDs[i] = new ParcelReturnObjectsPacket.OwnerIDsBlock(); - request.OwnerIDs[i].OwnerID = ownerIDs[i]; + request.OwnerIDs[i] = new ParcelReturnObjectsPacket.OwnerIDsBlock {OwnerID = ownerIDs[i]}; } } else @@ -1288,13 +1362,21 @@ namespace OpenMetaverse /// public void ParcelSubdivide(Simulator simulator, float west, float south, float east, float north) { - ParcelDividePacket divide = new ParcelDividePacket(); - divide.AgentData.AgentID = Client.Self.AgentID; - divide.AgentData.SessionID = Client.Self.SessionID; - divide.ParcelData.East = east; - divide.ParcelData.North = north; - divide.ParcelData.South = south; - divide.ParcelData.West = west; + ParcelDividePacket divide = new ParcelDividePacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + ParcelData = + { + East = east, + North = north, + South = south, + West = west + } + }; Client.Network.SendPacket(divide, simulator); } @@ -1440,26 +1522,35 @@ namespace OpenMetaverse public void Terraform(Simulator simulator, int localID, float west, float south, float east, float north, TerraformAction action, TerraformBrushSize brushSize, int seconds, float height) { - ModifyLandPacket land = new ModifyLandPacket(); - land.AgentData.AgentID = Client.Self.AgentID; - land.AgentData.SessionID = Client.Self.SessionID; + ModifyLandPacket land = new ModifyLandPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + ModifyBlock = + { + Action = (byte) action, + BrushSize = (byte) brushSize, + Seconds = seconds, + Height = height + }, + ParcelData = new ModifyLandPacket.ParcelDataBlock[1] + }; - land.ModifyBlock.Action = (byte)action; - land.ModifyBlock.BrushSize = (byte)brushSize; - land.ModifyBlock.Seconds = seconds; - land.ModifyBlock.Height = height; - land.ParcelData = new ModifyLandPacket.ParcelDataBlock[1]; - land.ParcelData[0] = new ModifyLandPacket.ParcelDataBlock(); - land.ParcelData[0].LocalID = localID; - land.ParcelData[0].West = west; - land.ParcelData[0].South = south; - land.ParcelData[0].East = east; - land.ParcelData[0].North = north; + land.ParcelData[0] = new ModifyLandPacket.ParcelDataBlock + { + LocalID = localID, + West = west, + South = south, + East = east, + North = north + }; land.ModifyBlockExtended = new ModifyLandPacket.ModifyBlockExtendedBlock[1]; - land.ModifyBlockExtended[0] = new ModifyLandPacket.ModifyBlockExtendedBlock(); - land.ModifyBlockExtended[0].BrushSize = (float)brushSize; + land.ModifyBlockExtended[0] = new ModifyLandPacket.ModifyBlockExtendedBlock {BrushSize = (float) brushSize}; Client.Network.SendPacket(land, simulator); } @@ -1482,8 +1573,7 @@ namespace OpenMetaverse select.ParcelData.ReturnType = (uint)selectType; select.ReturnIDs = new ParcelSelectObjectsPacket.ReturnIDsBlock[1]; - select.ReturnIDs[0] = new ParcelSelectObjectsPacket.ReturnIDsBlock(); - select.ReturnIDs[0].ReturnID = ownerID; + select.ReturnIDs[0] = new ParcelSelectObjectsPacket.ReturnIDsBlock {ReturnID = ownerID}; Client.Network.SendPacket(select); } @@ -1495,12 +1585,16 @@ namespace OpenMetaverse /// true to also ban target public void EjectUser(UUID targetID, bool ban) { - EjectUserPacket eject = new EjectUserPacket(); - eject.AgentData.AgentID = Client.Self.AgentID; - eject.AgentData.SessionID = Client.Self.SessionID; - eject.Data.TargetID = targetID; - if (ban) eject.Data.Flags = 1; - else eject.Data.Flags = 0; + EjectUserPacket eject = new EjectUserPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = {TargetID = targetID} + }; + eject.Data.Flags = ban ? (uint)1 : 0; Client.Network.SendPacket(eject); } @@ -1512,12 +1606,16 @@ namespace OpenMetaverse /// true to freeze, false to unfreeze public void FreezeUser(UUID targetID, bool freeze) { - FreezeUserPacket frz = new FreezeUserPacket(); - frz.AgentData.AgentID = Client.Self.AgentID; - frz.AgentData.SessionID = Client.Self.SessionID; - frz.Data.TargetID = targetID; - if (freeze) frz.Data.Flags = 0; - else frz.Data.Flags = 1; + FreezeUserPacket frz = new FreezeUserPacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = {TargetID = targetID} + }; + frz.Data.Flags = freeze ? (uint)0 : 1; Client.Network.SendPacket(frz); } @@ -1529,10 +1627,15 @@ namespace OpenMetaverse /// Simulator local ID of parcel public void ReleaseParcel(Simulator simulator, int localID) { - ParcelReleasePacket abandon = new ParcelReleasePacket(); - abandon.AgentData.AgentID = Client.Self.AgentID; - abandon.AgentData.SessionID = Client.Self.SessionID; - abandon.Data.LocalID = localID; + ParcelReleasePacket abandon = new ParcelReleasePacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + }, + Data = {LocalID = localID} + }; Client.Network.SendPacket(abandon, simulator); } @@ -1553,10 +1656,12 @@ namespace OpenMetaverse if (url != null) { - RemoteParcelRequestRequest msg = new RemoteParcelRequestRequest(); - msg.Location = location; - msg.RegionHandle = regionHandle; - msg.RegionID = regionID; + RemoteParcelRequestRequest msg = new RemoteParcelRequestRequest + { + Location = location, + RegionHandle = regionHandle, + RegionID = regionID + }; try { @@ -1621,8 +1726,7 @@ namespace OpenMetaverse } }; - LandResourcesRequest param = new LandResourcesRequest(); - param.ParcelID = parcelID; + LandResourcesRequest param = new LandResourcesRequest {ParcelID = parcelID}; request.BeginGetResponse(param.Serialize(), OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); } @@ -1672,150 +1776,154 @@ namespace OpenMetaverse /// The EventArgs object containing the packet data /// Raises the event protected void ParcelInfoReplyHandler(object sender, PacketReceivedEventArgs e) - { - if (m_ParcelInfo != null) + { + if (m_ParcelInfo == null) return; + + Packet packet = e.Packet; + ParcelInfoReplyPacket info = (ParcelInfoReplyPacket)packet; + + ParcelInfo parcelInfo = new ParcelInfo { - Packet packet = e.Packet; - ParcelInfoReplyPacket info = (ParcelInfoReplyPacket)packet; + ActualArea = info.Data.ActualArea, + AuctionID = info.Data.AuctionID, + BillableArea = info.Data.BillableArea, + Description = Utils.BytesToString(info.Data.Desc), + Dwell = info.Data.Dwell, + GlobalX = info.Data.GlobalX, + GlobalY = info.Data.GlobalY, + GlobalZ = info.Data.GlobalZ, + ID = info.Data.ParcelID, + Mature = ((info.Data.Flags & 1) != 0) ? true : false, + Name = Utils.BytesToString(info.Data.Name), + OwnerID = info.Data.OwnerID, + SalePrice = info.Data.SalePrice, + SimName = Utils.BytesToString(info.Data.SimName), + SnapshotID = info.Data.SnapshotID + }; - ParcelInfo parcelInfo = new ParcelInfo(); - parcelInfo.ActualArea = info.Data.ActualArea; - parcelInfo.AuctionID = info.Data.AuctionID; - parcelInfo.BillableArea = info.Data.BillableArea; - parcelInfo.Description = Utils.BytesToString(info.Data.Desc); - parcelInfo.Dwell = info.Data.Dwell; - parcelInfo.GlobalX = info.Data.GlobalX; - parcelInfo.GlobalY = info.Data.GlobalY; - parcelInfo.GlobalZ = info.Data.GlobalZ; - parcelInfo.ID = info.Data.ParcelID; - parcelInfo.Mature = ((info.Data.Flags & 1) != 0) ? true : false; - parcelInfo.Name = Utils.BytesToString(info.Data.Name); - parcelInfo.OwnerID = info.Data.OwnerID; - parcelInfo.SalePrice = info.Data.SalePrice; - parcelInfo.SimName = Utils.BytesToString(info.Data.SimName); - parcelInfo.SnapshotID = info.Data.SnapshotID; - - OnParcelInfoReply(new ParcelInfoReplyEventArgs(parcelInfo)); - } + OnParcelInfoReply(new ParcelInfoReplyEventArgs(parcelInfo)); } protected void ParcelPropertiesReplyHandler(string capsKey, IMessage message, Simulator simulator) - { - if (m_ParcelProperties != null || Client.Settings.PARCEL_TRACKING == true) + { + if (m_ParcelProperties == null && Client.Settings.PARCEL_TRACKING != true) return; + ParcelPropertiesMessage msg = (ParcelPropertiesMessage)message; + + Parcel parcel = new Parcel(msg.LocalID) { - ParcelPropertiesMessage msg = (ParcelPropertiesMessage)message; - - Parcel parcel = new Parcel(msg.LocalID); - - parcel.AABBMax = msg.AABBMax; - parcel.AABBMin = msg.AABBMin; - parcel.Area = msg.Area; - parcel.AuctionID = msg.AuctionID; - parcel.AuthBuyerID = msg.AuthBuyerID; - parcel.Bitmap = msg.Bitmap; - parcel.Category = msg.Category; - parcel.ClaimDate = msg.ClaimDate; - parcel.ClaimPrice = msg.ClaimPrice; - parcel.Desc = msg.Desc; - parcel.Flags = msg.ParcelFlags; - parcel.GroupID = msg.GroupID; - parcel.GroupPrims = msg.GroupPrims; - parcel.IsGroupOwned = msg.IsGroupOwned; - parcel.Landing = msg.LandingType; - parcel.MaxPrims = msg.MaxPrims; - parcel.Media.MediaAutoScale = msg.MediaAutoScale; - parcel.Media.MediaID = msg.MediaID; - parcel.Media.MediaURL = msg.MediaURL; - parcel.MusicURL = msg.MusicURL; - parcel.Name = msg.Name; - parcel.OtherCleanTime = msg.OtherCleanTime; - parcel.OtherCount = msg.OtherCount; - parcel.OtherPrims = msg.OtherPrims; - parcel.OwnerID = msg.OwnerID; - parcel.OwnerPrims = msg.OwnerPrims; - parcel.ParcelPrimBonus = msg.ParcelPrimBonus; - parcel.PassHours = msg.PassHours; - parcel.PassPrice = msg.PassPrice; - parcel.PublicCount = msg.PublicCount; - parcel.RegionDenyAgeUnverified = msg.RegionDenyAgeUnverified; - parcel.RegionDenyAnonymous = msg.RegionDenyAnonymous; - parcel.RegionPushOverride = msg.RegionPushOverride; - parcel.RentPrice = msg.RentPrice; - ParcelResult result = msg.RequestResult; - parcel.SalePrice = msg.SalePrice; - int selectedPrims = msg.SelectedPrims; - parcel.SelfCount = msg.SelfCount; - int sequenceID = msg.SequenceID; - parcel.SimWideMaxPrims = msg.SimWideMaxPrims; - parcel.SimWideTotalPrims = msg.SimWideTotalPrims; - bool snapSelection = msg.SnapSelection; - parcel.SnapshotID = msg.SnapshotID; - parcel.Status = msg.Status; - parcel.TotalPrims = msg.TotalPrims; - parcel.UserLocation = msg.UserLocation; - parcel.UserLookAt = msg.UserLookAt; - parcel.Media.MediaDesc = msg.MediaDesc; - parcel.Media.MediaHeight = msg.MediaHeight; - parcel.Media.MediaWidth = msg.MediaWidth; - parcel.Media.MediaLoop = msg.MediaLoop; - parcel.Media.MediaType = msg.MediaType; - parcel.ObscureMedia = msg.ObscureMedia; - parcel.ObscureMusic = msg.ObscureMusic; - - if (Client.Settings.PARCEL_TRACKING) + AABBMax = msg.AABBMax, + AABBMin = msg.AABBMin, + Area = msg.Area, + AuctionID = msg.AuctionID, + AuthBuyerID = msg.AuthBuyerID, + Bitmap = msg.Bitmap, + Category = msg.Category, + ClaimDate = msg.ClaimDate, + ClaimPrice = msg.ClaimPrice, + Desc = msg.Desc, + Flags = msg.ParcelFlags, + GroupID = msg.GroupID, + GroupPrims = msg.GroupPrims, + IsGroupOwned = msg.IsGroupOwned, + Landing = msg.LandingType, + MaxPrims = msg.MaxPrims, + Media = { - lock (simulator.Parcels.Dictionary) - simulator.Parcels.Dictionary[parcel.LocalID] = parcel; + MediaAutoScale = msg.MediaAutoScale, + MediaID = msg.MediaID, + MediaURL = msg.MediaURL + }, + MusicURL = msg.MusicURL, + Name = msg.Name, + OtherCleanTime = msg.OtherCleanTime, + OtherCount = msg.OtherCount, + OtherPrims = msg.OtherPrims, + OwnerID = msg.OwnerID, + OwnerPrims = msg.OwnerPrims, + ParcelPrimBonus = msg.ParcelPrimBonus, + PassHours = msg.PassHours, + PassPrice = msg.PassPrice, + PublicCount = msg.PublicCount, + RegionDenyAgeUnverified = msg.RegionDenyAgeUnverified, + RegionDenyAnonymous = msg.RegionDenyAnonymous, + RegionPushOverride = msg.RegionPushOverride, + RentPrice = msg.RentPrice + }; - bool set = false; - int y, x, index, bit; - for (y = 0; y < 64; y++) + ParcelResult result = msg.RequestResult; + parcel.SalePrice = msg.SalePrice; + int selectedPrims = msg.SelectedPrims; + parcel.SelfCount = msg.SelfCount; + int sequenceID = msg.SequenceID; + parcel.SimWideMaxPrims = msg.SimWideMaxPrims; + parcel.SimWideTotalPrims = msg.SimWideTotalPrims; + bool snapSelection = msg.SnapSelection; + parcel.SnapshotID = msg.SnapshotID; + parcel.Status = msg.Status; + parcel.TotalPrims = msg.TotalPrims; + parcel.UserLocation = msg.UserLocation; + parcel.UserLookAt = msg.UserLookAt; + parcel.Media.MediaDesc = msg.MediaDesc; + parcel.Media.MediaHeight = msg.MediaHeight; + parcel.Media.MediaWidth = msg.MediaWidth; + parcel.Media.MediaLoop = msg.MediaLoop; + parcel.Media.MediaType = msg.MediaType; + parcel.ObscureMedia = msg.ObscureMedia; + parcel.ObscureMusic = msg.ObscureMusic; + + if (Client.Settings.PARCEL_TRACKING) + { + lock (simulator.Parcels.Dictionary) + simulator.Parcels.Dictionary[parcel.LocalID] = parcel; + + bool set = false; + int y, x, index, bit; + for (y = 0; y < 64; y++) + { + for (x = 0; x < 64; x++) { - for (x = 0; x < 64; x++) - { - index = (y * 64) + x; - bit = index % 8; - index >>= 3; + index = (y * 64) + x; + bit = index % 8; + index >>= 3; - if ((parcel.Bitmap[index] & (1 << bit)) != 0) - { - simulator.ParcelMap[y, x] = parcel.LocalID; - set = true; - } + if ((parcel.Bitmap[index] & (1 << bit)) != 0) + { + simulator.ParcelMap[y, x] = parcel.LocalID; + set = true; } } - - if (!set) - { - Logger.Log("Received a parcel with a bitmap that did not map to any locations", - Helpers.LogLevel.Warning); - } } - if (sequenceID.Equals(int.MaxValue) && WaitForSimParcel != null) - WaitForSimParcel.Set(); - - // auto request acl, will be stored in parcel tracking dictionary if enabled - if (Client.Settings.ALWAYS_REQUEST_PARCEL_ACL) - Client.Parcels.RequestParcelAccessList(simulator, parcel.LocalID, - AccessList.Both, sequenceID); - - // auto request dwell, will be stored in parcel tracking dictionary if enables - if (Client.Settings.ALWAYS_REQUEST_PARCEL_DWELL) - Client.Parcels.RequestDwell(simulator, parcel.LocalID); - - // Fire the callback for parcel properties being received - if (m_ParcelProperties != null) + if (!set) { - OnParcelProperties(new ParcelPropertiesEventArgs(simulator, parcel, result, selectedPrims, sequenceID, snapSelection)); + Logger.Log("Received a parcel with a bitmap that did not map to any locations", + Helpers.LogLevel.Warning); } + } - // Check if all of the simulator parcels have been retrieved, if so fire another callback - if (simulator.IsParcelMapFull() && m_SimParcelsDownloaded != null) - { - OnSimParcelsDownloaded(new SimParcelsDownloadedEventArgs(simulator, simulator.Parcels, simulator.ParcelMap)); - } + if (sequenceID.Equals(int.MaxValue)) + WaitForSimParcel?.Set(); + + // auto request acl, will be stored in parcel tracking dictionary if enabled + if (Client.Settings.ALWAYS_REQUEST_PARCEL_ACL) + Client.Parcels.RequestParcelAccessList(simulator, parcel.LocalID, + AccessList.Both, sequenceID); + + // auto request dwell, will be stored in parcel tracking dictionary if enables + if (Client.Settings.ALWAYS_REQUEST_PARCEL_DWELL) + Client.Parcels.RequestDwell(simulator, parcel.LocalID); + + // Fire the callback for parcel properties being received + if (m_ParcelProperties != null) + { + OnParcelProperties(new ParcelPropertiesEventArgs(simulator, parcel, result, selectedPrims, sequenceID, snapSelection)); + } + + // Check if all of the simulator parcels have been retrieved, if so fire another callback + if (simulator.IsParcelMapFull() && m_SimParcelsDownloaded != null) + { + OnSimParcelsDownloaded(new SimParcelsDownloadedEventArgs(simulator, simulator.Parcels, simulator.ParcelMap)); } } @@ -1834,12 +1942,14 @@ namespace OpenMetaverse List accessList = new List(reply.List.Length); - for (int i = 0; i < reply.List.Length; i++) + foreach (ParcelAccessListReplyPacket.ListBlock t in reply.List) { - ParcelAccessEntry pae = new ParcelAccessEntry(); - pae.AgentID = reply.List[i].ID; - pae.Time = Utils.UnixTimeToDateTime((uint)reply.List[i].Time); - pae.Flags = (AccessList)reply.List[i].Flags; + ParcelAccessEntry pae = new ParcelAccessEntry + { + AgentID = t.ID, + Time = Utils.UnixTimeToDateTime((uint) t.Time), + Flags = (AccessList) t.Flags + }; accessList.Add(pae); } @@ -1875,14 +1985,16 @@ namespace OpenMetaverse ParcelObjectOwnersReplyMessage msg = (ParcelObjectOwnersReplyMessage)message; - for (int i = 0; i < msg.PrimOwnersBlock.Length; i++) + foreach (ParcelObjectOwnersReplyMessage.PrimOwner t in msg.PrimOwnersBlock) { - ParcelPrimOwners primOwner = new ParcelPrimOwners(); - primOwner.OwnerID = msg.PrimOwnersBlock[i].OwnerID; - primOwner.Count = msg.PrimOwnersBlock[i].Count; - primOwner.IsGroupOwned = msg.PrimOwnersBlock[i].IsGroupOwned; - primOwner.OnlineStatus = msg.PrimOwnersBlock[i].OnlineStatus; - primOwner.NewestPrim = msg.PrimOwnersBlock[i].TimeStamp; + ParcelPrimOwners primOwner = new ParcelPrimOwners + { + OwnerID = t.OwnerID, + Count = t.Count, + IsGroupOwned = t.IsGroupOwned, + OnlineStatus = t.OnlineStatus, + NewestPrim = t.TimeStamp + }; primOwners.Add(primOwner); } @@ -1897,21 +2009,16 @@ namespace OpenMetaverse /// Raises the event protected void SelectParcelObjectsReplyHandler(object sender, PacketReceivedEventArgs e) { - if (m_ForceSelectObjects != null) - { - Packet packet = e.Packet; - Simulator simulator = e.Simulator; + if (m_ForceSelectObjects == null) return; - ForceObjectSelectPacket reply = (ForceObjectSelectPacket)packet; - List objectIDs = new List(reply.Data.Length); + Packet packet = e.Packet; + Simulator simulator = e.Simulator; - for (int i = 0; i < reply.Data.Length; i++) - { - objectIDs.Add(reply.Data[i].LocalID); - } + ForceObjectSelectPacket reply = (ForceObjectSelectPacket)packet; + List objectIDs = new List(reply.Data.Length); + objectIDs.AddRange(reply.Data.Select(t => t.LocalID)); - OnForceSelectObjectsReply(new ForceSelectObjectsReplyEventArgs(simulator, objectIDs, reply._Header.ResetList)); - } + OnForceSelectObjectsReply(new ForceSelectObjectsReplyEventArgs(simulator, objectIDs, reply._Header.ResetList)); } /// Process an incoming packet and raise the appropriate events @@ -1920,25 +2027,26 @@ namespace OpenMetaverse /// Raises the event protected void ParcelMediaUpdateHandler(object sender, PacketReceivedEventArgs e) { - if (m_ParcelMediaUpdateReply != null) + if (m_ParcelMediaUpdateReply == null) return; + + Packet packet = e.Packet; + Simulator simulator = e.Simulator; + + ParcelMediaUpdatePacket reply = (ParcelMediaUpdatePacket)packet; + ParcelMedia media = new ParcelMedia { - Packet packet = e.Packet; - Simulator simulator = e.Simulator; + MediaAutoScale = (reply.DataBlock.MediaAutoScale == (byte) 0x1) ? true : false, + MediaID = reply.DataBlock.MediaID, + MediaDesc = Utils.BytesToString(reply.DataBlockExtended.MediaDesc), + MediaHeight = reply.DataBlockExtended.MediaHeight, + MediaLoop = ((reply.DataBlockExtended.MediaLoop & 1) != 0) ? true : false, + MediaType = Utils.BytesToString(reply.DataBlockExtended.MediaType), + MediaWidth = reply.DataBlockExtended.MediaWidth, + MediaURL = Utils.BytesToString(reply.DataBlock.MediaURL) + }; - ParcelMediaUpdatePacket reply = (ParcelMediaUpdatePacket)packet; - ParcelMedia media = new ParcelMedia(); - media.MediaAutoScale = (reply.DataBlock.MediaAutoScale == (byte)0x1) ? true : false; - media.MediaID = reply.DataBlock.MediaID; - media.MediaDesc = Utils.BytesToString(reply.DataBlockExtended.MediaDesc); - media.MediaHeight = reply.DataBlockExtended.MediaHeight; - media.MediaLoop = ((reply.DataBlockExtended.MediaLoop & 1) != 0) ? true : false; - media.MediaType = Utils.BytesToString(reply.DataBlockExtended.MediaType); - media.MediaWidth = reply.DataBlockExtended.MediaWidth; - media.MediaURL = Utils.BytesToString(reply.DataBlock.MediaURL); - - OnParcelMediaUpdateReply(new ParcelMediaUpdateReplyEventArgs(simulator, media)); - } + OnParcelMediaUpdateReply(new ParcelMediaUpdateReplyEventArgs(simulator, media)); } /// Process an incoming packet and raise the appropriate events @@ -1979,17 +2087,16 @@ namespace OpenMetaverse /// Raises the event protected void ParcelMediaCommandMessagePacketHandler(object sender, PacketReceivedEventArgs e) { - if (m_ParcelMediaCommand != null) - { - Packet packet = e.Packet; - Simulator simulator = e.Simulator; + if (m_ParcelMediaCommand == null) return; - ParcelMediaCommandMessagePacket pmc = (ParcelMediaCommandMessagePacket)packet; - ParcelMediaCommandMessagePacket.CommandBlockBlock block = pmc.CommandBlock; + Packet packet = e.Packet; + Simulator simulator = e.Simulator; - OnParcelMediaCommand(new ParcelMediaCommandEventArgs(simulator, pmc.Header.Sequence, (ParcelFlags)block.Flags, - (ParcelMediaCommand)block.Command, block.Time)); - } + ParcelMediaCommandMessagePacket pmc = (ParcelMediaCommandMessagePacket)packet; + ParcelMediaCommandMessagePacket.CommandBlockBlock block = pmc.CommandBlock; + + OnParcelMediaCommand(new ParcelMediaCommandEventArgs(simulator, pmc.Header.Sequence, (ParcelFlags)block.Flags, + (ParcelMediaCommand)block.Command, block.Time)); } #endregion Packet Handlers @@ -2004,11 +2111,13 @@ namespace OpenMetaverse private readonly float m_Dwell; /// Get the global ID of the parcel - public UUID ParcelID { get { return m_ParcelID; } } + public UUID ParcelID => m_ParcelID; + /// Get the simulator specific ID of the parcel - public int LocalID { get { return m_LocalID; } } + public int LocalID => m_LocalID; + /// Get the calculated dwell - public float Dwell { get { return m_Dwell; } } + public float Dwell => m_Dwell; /// /// Construct a new instance of the ParcelDwellReplyEventArgs class @@ -2018,9 +2127,9 @@ namespace OpenMetaverse /// The calculated dwell for the parcel public ParcelDwellReplyEventArgs(UUID parcelID, int localID, float dwell) { - this.m_ParcelID = parcelID; - this.m_LocalID = localID; - this.m_Dwell = dwell; + m_ParcelID = parcelID; + m_LocalID = localID; + m_Dwell = dwell; } } @@ -2031,7 +2140,7 @@ namespace OpenMetaverse private readonly ParcelInfo m_Parcel; /// Get the object containing basic parcel info - public ParcelInfo Parcel { get { return m_Parcel; } } + public ParcelInfo Parcel => m_Parcel; /// /// Construct a new instance of the ParcelInfoReplyEventArgs class @@ -2039,7 +2148,7 @@ namespace OpenMetaverse /// The object containing basic parcel info public ParcelInfoReplyEventArgs(ParcelInfo parcel) { - this.m_Parcel = parcel; + m_Parcel = parcel; } } @@ -2054,20 +2163,25 @@ namespace OpenMetaverse private readonly bool m_SnapSelection; /// Get the simulator the parcel is located in - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the object containing the details /// If Result is NoData, this object will not contain valid data - public Parcel Parcel { get { return m_Parcel; } } + public Parcel Parcel => m_Parcel; + /// Get the result of the request - public ParcelResult Result { get { return m_Result; } } + public ParcelResult Result => m_Result; + /// Get the number of primitieves your agent is /// currently selecting and or sitting on in this parcel - public int SelectedPrims { get { return m_SelectedPrims; } } + public int SelectedPrims => m_SelectedPrims; + /// Get the user assigned ID used to correlate a request with /// these results - public int SequenceID { get { return m_SequenceID; } } + public int SequenceID => m_SequenceID; + /// TODO: - public bool SnapSelection { get { return m_SnapSelection; } } + public bool SnapSelection => m_SnapSelection; /// /// Construct a new instance of the ParcelPropertiesEventArgs class @@ -2083,12 +2197,12 @@ namespace OpenMetaverse public ParcelPropertiesEventArgs(Simulator simulator, Parcel parcel, ParcelResult result, int selectedPrims, int sequenceID, bool snapSelection) { - this.m_Simulator = simulator; - this.m_Parcel = parcel; - this.m_Result = result; - this.m_SelectedPrims = selectedPrims; - this.m_SequenceID = sequenceID; - this.m_SnapSelection = snapSelection; + m_Simulator = simulator; + m_Parcel = parcel; + m_Result = result; + m_SelectedPrims = selectedPrims; + m_SequenceID = sequenceID; + m_SnapSelection = snapSelection; } } @@ -2102,16 +2216,20 @@ namespace OpenMetaverse private readonly List m_AccessList; /// Get the simulator the parcel is located in - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the user assigned ID used to correlate a request with /// these results - public int SequenceID { get { return m_SequenceID; } } + public int SequenceID => m_SequenceID; + /// Get the simulator specific ID of the parcel - public int LocalID { get { return m_LocalID; } } - /// TODO: - public uint Flags { get { return m_Flags; } } + public int LocalID => m_LocalID; + + /// TODO + public uint Flags => m_Flags; + /// Get the list containing the white/blacklisted agents for the parcel - public List AccessList { get { return m_AccessList; } } + public List AccessList => m_AccessList; /// /// Construct a new instance of the ParcelAccessListReplyEventArgs class @@ -2124,11 +2242,11 @@ namespace OpenMetaverse /// The list containing the white/blacklisted agents for the parcel public ParcelAccessListReplyEventArgs(Simulator simulator, int sequenceID, int localID, uint flags, List accessEntries) { - this.m_Simulator = simulator; - this.m_SequenceID = sequenceID; - this.m_LocalID = localID; - this.m_Flags = flags; - this.m_AccessList = accessEntries; + m_Simulator = simulator; + m_SequenceID = sequenceID; + m_LocalID = localID; + m_Flags = flags; + m_AccessList = accessEntries; } } @@ -2140,9 +2258,10 @@ namespace OpenMetaverse private readonly List m_Owners; /// Get the simulator the parcel is located in - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the list containing prim ownership counts - public List PrimOwners { get { return m_Owners; } } + public List PrimOwners => m_Owners; /// /// Construct a new instance of the ParcelObjectOwnersReplyEventArgs class @@ -2151,8 +2270,8 @@ namespace OpenMetaverse /// The list containing prim ownership counts public ParcelObjectOwnersReplyEventArgs(Simulator simulator, List primOwners) { - this.m_Simulator = simulator; - this.m_Owners = primOwners; + m_Simulator = simulator; + m_Owners = primOwners; } } @@ -2164,12 +2283,14 @@ namespace OpenMetaverse private readonly int[,] m_ParcelMap; /// Get the simulator the parcel data was retrieved from - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// A dictionary containing the parcel data where the key correlates to the ParcelMap entry - public InternalDictionary Parcels { get { return m_Parcels; } } + public InternalDictionary Parcels => m_Parcels; + /// Get the multidimensional array containing a x,y grid mapped /// to each 64x64 parcel's LocalID. - public int[,] ParcelMap { get { return m_ParcelMap; } } + public int[,] ParcelMap => m_ParcelMap; /// /// Construct a new instance of the SimParcelsDownloadedEventArgs class @@ -2180,9 +2301,9 @@ namespace OpenMetaverse /// to each 64x64 parcel's LocalID. public SimParcelsDownloadedEventArgs(Simulator simulator, InternalDictionary simParcels, int[,] parcelMap) { - this.m_Simulator = simulator; - this.m_Parcels = simParcels; - this.m_ParcelMap = parcelMap; + m_Simulator = simulator; + m_Parcels = simParcels; + m_ParcelMap = parcelMap; } } @@ -2194,12 +2315,14 @@ namespace OpenMetaverse private readonly bool m_ResetList; /// Get the simulator the parcel data was retrieved from - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the list of primitive IDs - public List ObjectIDs { get { return m_ObjectIDs; } } + public List ObjectIDs => m_ObjectIDs; + /// true if the list is clean and contains the information /// only for a given request - public bool ResetList { get { return m_ResetList; } } + public bool ResetList => m_ResetList; /// /// Construct a new instance of the ForceSelectObjectsReplyEventArgs class @@ -2223,10 +2346,11 @@ namespace OpenMetaverse private readonly ParcelMedia m_ParcelMedia; /// Get the simulator the parcel media data was updated in - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the updated media information - public ParcelMedia Media { get { return m_ParcelMedia; } } - + public ParcelMedia Media => m_ParcelMedia; + /// /// Construct a new instance of the ParcelMediaUpdateReplyEventArgs class /// @@ -2249,15 +2373,19 @@ namespace OpenMetaverse private readonly float m_Time; /// Get the simulator the parcel media command was issued in - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// - public uint Sequence { get { return m_Sequence; } } + public uint Sequence => m_Sequence; + /// - public ParcelFlags ParcelFlags { get { return m_ParcelFlags; } } + public ParcelFlags ParcelFlags => m_ParcelFlags; + /// Get the media command that was sent - public ParcelMediaCommand MediaCommand { get { return m_MediaCommand; } } + public ParcelMediaCommand MediaCommand => m_MediaCommand; + /// - public float Time { get { return m_Time; } } + public float Time => m_Time; /// /// Construct a new instance of the ParcelMediaCommandEventArgs class @@ -2269,11 +2397,11 @@ namespace OpenMetaverse /// public ParcelMediaCommandEventArgs(Simulator simulator, uint sequence, ParcelFlags flags, ParcelMediaCommand command, float time) { - this.m_Simulator = simulator; - this.m_Sequence = sequence; - this.m_ParcelFlags = flags; - this.m_MediaCommand = command; - this.m_Time = time; + m_Simulator = simulator; + m_Sequence = sequence; + m_ParcelFlags = flags; + m_MediaCommand = command; + m_Time = time; } } #endregion diff --git a/OpenMetaverse/Permissions.cs b/OpenMetaverse/Permissions.cs index 952a76ff..aadfe35d 100644 --- a/OpenMetaverse/Permissions.cs +++ b/OpenMetaverse/Permissions.cs @@ -103,12 +103,14 @@ namespace OpenMetaverse public OSD GetOSD() { - OSDMap permissions = new OSDMap(5); - permissions["base_mask"] = OSD.FromInteger((uint)BaseMask); - permissions["everyone_mask"] = OSD.FromInteger((uint)EveryoneMask); - permissions["group_mask"] = OSD.FromInteger((uint)GroupMask); - permissions["next_owner_mask"] = OSD.FromInteger((uint)NextOwnerMask); - permissions["owner_mask"] = OSD.FromInteger((uint)OwnerMask); + OSDMap permissions = new OSDMap(5) + { + ["base_mask"] = OSD.FromInteger((uint) BaseMask), + ["everyone_mask"] = OSD.FromInteger((uint) EveryoneMask), + ["group_mask"] = OSD.FromInteger((uint) GroupMask), + ["next_owner_mask"] = OSD.FromInteger((uint) NextOwnerMask), + ["owner_mask"] = OSD.FromInteger((uint) OwnerMask) + }; return permissions; } @@ -143,7 +145,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Permissions) ? this == (Permissions)obj : false; + return (obj is Permissions) && this == (Permissions)obj; } public bool Equals(Permissions other) diff --git a/OpenMetaverse/ProtocolManager.cs b/OpenMetaverse/ProtocolManager.cs index cd761d32..f0991521 100644 --- a/OpenMetaverse/ProtocolManager.cs +++ b/OpenMetaverse/ProtocolManager.cs @@ -27,7 +27,6 @@ using System; using System.Collections.Generic; using System.IO; -using OpenMetaverse; namespace OpenMetaverse { @@ -103,21 +102,16 @@ namespace OpenMetaverse { MapField temp = (MapField)obj; - if (this.KeywordPosition > temp.KeywordPosition) + if (KeywordPosition > temp.KeywordPosition) { return 1; } - else - { - if(temp.KeywordPosition == this.KeywordPosition) - { - return 0; - } - else - { - return -1; - } - } + + if(temp.KeywordPosition == KeywordPosition) + { + return 0; + } + return -1; } } @@ -144,21 +138,15 @@ namespace OpenMetaverse { MapBlock temp = (MapBlock)obj; - if (this.KeywordPosition > temp.KeywordPosition) + if (KeywordPosition > temp.KeywordPosition) { return 1; } - else - { - if(temp.KeywordPosition == this.KeywordPosition) - { - return 0; - } - else - { - return -1; - } - } + if(temp.KeywordPosition == KeywordPosition) + { + return 0; + } + return -1; } } @@ -214,28 +202,30 @@ namespace OpenMetaverse HighMaps = new MapPacket[256]; // Build the type size hash table - TypeSizes = new Dictionary(); - TypeSizes.Add(FieldType.U8, 1); - TypeSizes.Add(FieldType.U16, 2); - TypeSizes.Add(FieldType.U32, 4); - TypeSizes.Add(FieldType.U64, 8); - TypeSizes.Add(FieldType.S8, 1); - TypeSizes.Add(FieldType.S16, 2); - TypeSizes.Add(FieldType.S32, 4); - TypeSizes.Add(FieldType.F32, 4); - TypeSizes.Add(FieldType.F64, 8); - TypeSizes.Add(FieldType.UUID, 16); - TypeSizes.Add(FieldType.BOOL, 1); - TypeSizes.Add(FieldType.Vector3, 12); - TypeSizes.Add(FieldType.Vector3d, 24); - TypeSizes.Add(FieldType.Vector4, 16); - TypeSizes.Add(FieldType.Quaternion, 16); - TypeSizes.Add(FieldType.IPADDR, 4); - TypeSizes.Add(FieldType.IPPORT, 2); - TypeSizes.Add(FieldType.Variable, -1); - TypeSizes.Add(FieldType.Fixed, -2); + TypeSizes = new Dictionary + { + {FieldType.U8, 1}, + {FieldType.U16, 2}, + {FieldType.U32, 4}, + {FieldType.U64, 8}, + {FieldType.S8, 1}, + {FieldType.S16, 2}, + {FieldType.S32, 4}, + {FieldType.F32, 4}, + {FieldType.F64, 8}, + {FieldType.UUID, 16}, + {FieldType.BOOL, 1}, + {FieldType.Vector3, 12}, + {FieldType.Vector3d, 24}, + {FieldType.Vector4, 16}, + {FieldType.Quaternion, 16}, + {FieldType.IPADDR, 4}, + {FieldType.IPPORT, 2}, + {FieldType.Variable, -1}, + {FieldType.Fixed, -2} + }; - KeywordPositions = new Dictionary(); + KeywordPositions = new Dictionary(); LoadMapFile(mapFile); } @@ -248,35 +238,32 @@ namespace OpenMetaverse { foreach (MapPacket map in HighMaps) { - if (map != null) - { - if (command == map.Name) - { - return map; - } - } + if (map == null) continue; + + if (command == map.Name) + { + return map; + } } foreach (MapPacket map in MediumMaps) { - if (map != null) - { - if (command == map.Name) - { - return map; - } - } + if (map == null) continue; + + if (command == map.Name) + { + return map; + } } foreach (MapPacket map in LowMaps) { - if (map != null) - { - if (command == map.Name) - { - return map; - } - } + if (map == null) continue; + + if (command == map.Name) + { + return map; + } } throw new Exception("Cannot find map for command \"" + command + "\""); @@ -396,14 +383,14 @@ namespace OpenMetaverse { byte magicKey = 0; byte[] buffer = new byte[2048]; - int nread; - try + try { using (BinaryReader map = new BinaryReader(new FileStream(mapFile, FileMode.Open))) { using (BinaryWriter output = new BinaryWriter(new FileStream(outputFile, FileMode.CreateNew))) { + int nread; while ((nread = map.Read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) @@ -441,8 +428,6 @@ namespace OpenMetaverse using (StreamReader r = new StreamReader(map)) { r.BaseStream.Seek(0, SeekOrigin.Begin); - string newline; - string trimmedline; bool inPacket = false; bool inBlock = false; MapPacket currentPacket = null; @@ -454,8 +439,8 @@ namespace OpenMetaverse { #region ParseMap - newline = r.ReadLine(); - trimmedline = System.Text.RegularExpressions.Regex.Replace(newline, @"\s+", " "); + var newline = r.ReadLine(); + var trimmedline = System.Text.RegularExpressions.Regex.Replace(newline, @"\s+", " "); trimmedline = trimmedline.Trim(trimArray); if (!inPacket) @@ -493,78 +478,85 @@ namespace OpenMetaverse // Splice the string in to tokens string[] tokens = trimmedline.Split(new char[] { ' ', '\t' }); - if (tokens.Length > 3) + if (tokens.Length <= 3) continue; + + //Hash packet name to insure correct keyword ordering + KeywordPosition(tokens[0]); + + if (tokens[1] == "Fixed") { - //Hash packet name to insure correct keyword ordering - KeywordPosition(tokens[0]); - - if (tokens[1] == "Fixed") + // Remove the leading "0x" + if (tokens[2].Substring(0, 2) == "0x") { - // Remove the leading "0x" - if (tokens[2].Substring(0, 2) == "0x") - { - tokens[2] = tokens[2].Substring(2, tokens[2].Length - 2); - } - - uint fixedID = UInt32.Parse(tokens[2], System.Globalization.NumberStyles.HexNumber); - // Truncate the id to a short - fixedID ^= 0xFFFF0000; - LowMaps[fixedID] = new MapPacket(); - LowMaps[fixedID].ID = (ushort)fixedID; - LowMaps[fixedID].Frequency = PacketFrequency.Low; - LowMaps[fixedID].Name = tokens[0]; - LowMaps[fixedID].Trusted = (tokens[3] == "Trusted"); - LowMaps[fixedID].Encoded = (tokens[4] == "Zerocoded"); - LowMaps[fixedID].Blocks = new List(); - - currentPacket = LowMaps[fixedID]; + tokens[2] = tokens[2].Substring(2, tokens[2].Length - 2); } - else if (tokens[1] == "Low") + + uint fixedID = UInt32.Parse(tokens[2], System.Globalization.NumberStyles.HexNumber); + // Truncate the id to a short + fixedID ^= 0xFFFF0000; + LowMaps[fixedID] = new MapPacket { - LowMaps[low] = new MapPacket(); - LowMaps[low].ID = low; - LowMaps[low].Frequency = PacketFrequency.Low; - LowMaps[low].Name = tokens[0]; - LowMaps[low].Trusted = (tokens[2] == "Trusted"); - LowMaps[low].Encoded = (tokens[3] == "Zerocoded"); - LowMaps[low].Blocks = new List(); + ID = (ushort) fixedID, + Frequency = PacketFrequency.Low, + Name = tokens[0], + Trusted = (tokens[3] == "Trusted"), + Encoded = (tokens[4] == "Zerocoded"), + Blocks = new List() + }; - currentPacket = LowMaps[low]; - - low++; - } - else if (tokens[1] == "Medium") + currentPacket = LowMaps[fixedID]; + } + else if (tokens[1] == "Low") + { + LowMaps[low] = new MapPacket { - MediumMaps[medium] = new MapPacket(); - MediumMaps[medium].ID = medium; - MediumMaps[medium].Frequency = PacketFrequency.Medium; - MediumMaps[medium].Name = tokens[0]; - MediumMaps[medium].Trusted = (tokens[2] == "Trusted"); - MediumMaps[medium].Encoded = (tokens[3] == "Zerocoded"); - MediumMaps[medium].Blocks = new List(); + ID = low, + Frequency = PacketFrequency.Low, + Name = tokens[0], + Trusted = (tokens[2] == "Trusted"), + Encoded = (tokens[3] == "Zerocoded"), + Blocks = new List() + }; - currentPacket = MediumMaps[medium]; + currentPacket = LowMaps[low]; - medium++; - } - else if (tokens[1] == "High") + low++; + } + else if (tokens[1] == "Medium") + { + MediumMaps[medium] = new MapPacket { - HighMaps[high] = new MapPacket(); - HighMaps[high].ID = high; - HighMaps[high].Frequency = PacketFrequency.High; - HighMaps[high].Name = tokens[0]; - HighMaps[high].Trusted = (tokens[2] == "Trusted"); - HighMaps[high].Encoded = (tokens[3] == "Zerocoded"); - HighMaps[high].Blocks = new List(); + ID = medium, + Frequency = PacketFrequency.Medium, + Name = tokens[0], + Trusted = (tokens[2] == "Trusted"), + Encoded = (tokens[3] == "Zerocoded"), + Blocks = new List() + }; - currentPacket = HighMaps[high]; + currentPacket = MediumMaps[medium]; - high++; - } - else + medium++; + } + else if (tokens[1] == "High") + { + HighMaps[high] = new MapPacket { - Logger.Log("Unknown packet frequency", Helpers.LogLevel.Error, Client); - } + ID = high, + Frequency = PacketFrequency.High, + Name = tokens[0], + Trusted = (tokens[2] == "Trusted"), + Encoded = (tokens[3] == "Zerocoded"), + Blocks = new List() + }; + + currentPacket = HighMaps[high]; + + high++; + } + else + { + Logger.Log("Unknown packet frequency", Helpers.LogLevel.Error, Client); } #endregion @@ -588,7 +580,7 @@ namespace OpenMetaverse if (tokens[3] != "}") { - field.Count = Int32.Parse(tokens[3]); + field.Count = int.Parse(tokens[3]); } else { diff --git a/OpenMetaverse/Settings.cs b/OpenMetaverse/Settings.cs index f65d5372..3b2ec3ba 100644 --- a/OpenMetaverse/Settings.cs +++ b/OpenMetaverse/Settings.cs @@ -24,8 +24,6 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using System; -using System.Collections.Generic; using OpenMetaverse.Packets; namespace OpenMetaverse @@ -307,7 +305,7 @@ namespace OpenMetaverse /// Cost of uploading an asset /// Read-only since this value is dynamically fetched at login - public int UPLOAD_COST { get { return priceUpload; } } + public int UPLOAD_COST => priceUpload; /// Maximum number of times to resend a failed packet public int MAX_RESEND_COUNT = 3; @@ -375,7 +373,7 @@ namespace OpenMetaverse public Settings(GridClient client) { Client = client; - Client.Network.RegisterCallback(Packets.PacketType.EconomyData, EconomyDataHandler); + Client.Network.RegisterCallback(PacketType.EconomyData, EconomyDataHandler); } #endregion diff --git a/OpenMetaverse/Simulator.cs b/OpenMetaverse/Simulator.cs index 24ce0aa1..e5b1950f 100644 --- a/OpenMetaverse/Simulator.cs +++ b/OpenMetaverse/Simulator.cs @@ -26,9 +26,9 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Net; -using System.Net.Sockets; using OpenMetaverse.Packets; namespace OpenMetaverse @@ -256,7 +256,7 @@ namespace OpenMetaverse /// A Unique Cache identifier for this simulator public UUID ID = UUID.Zero; /// The capabilities for this simulator - public Caps Caps = null; + public Caps Caps; /// public ulong Handle; /// The current version of software this simulator is running @@ -396,8 +396,7 @@ namespace OpenMetaverse { return DataPool.Parcels; } - if (_Parcels == null) _Parcels = new InternalDictionary(); - return _Parcels; + return _Parcels ?? (_Parcels = new InternalDictionary()); } } private InternalDictionary _Parcels; @@ -416,8 +415,7 @@ namespace OpenMetaverse { return DataPool.ParcelMap; } - if (_ParcelMap == null) _ParcelMap = new int[64, 64]; - return _ParcelMap; + return _parcelMap ?? (_parcelMap = new int[64, 64]); } } } @@ -432,7 +430,7 @@ namespace OpenMetaverse { for (int x = 0; x < 64; x++) { - if (this.ParcelMap[y, x] == 0) + if (ParcelMap[y, x] == 0) return false; } } @@ -494,7 +492,7 @@ namespace OpenMetaverse private Timer PingTimer; private Timer StatsTimer; // simulator <> parcel LocalID Map - private int[,] _ParcelMap; + private int[,] _parcelMap; public readonly SimulatorDataPool DataPool; internal bool DownloadingParcelMap { @@ -555,21 +553,15 @@ namespace OpenMetaverse public virtual void Dispose(bool disposing) { - if (disposing) - { - if (AckTimer != null) - AckTimer.Dispose(); - if (PingTimer != null) - PingTimer.Dispose(); - if (StatsTimer != null) - StatsTimer.Dispose(); - if (ConnectedEvent != null) - ConnectedEvent.Close(); + if (!disposing) return; - // Force all the CAPS connections closed for this simulator - if (Caps != null) - Caps.Disconnect(true); - } + AckTimer?.Dispose(); + PingTimer?.Dispose(); + StatsTimer?.Dispose(); + ConnectedEvent?.Close(); + + // Force all the CAPS connections closed for this simulator + Caps?.Disconnect(true); } /// @@ -585,7 +577,10 @@ namespace OpenMetaverse if (connected) { UseCircuitCode(true); - if (moveToSim) Client.Self.CompleteAgentMovement(this); + if (moveToSim) + { + Client.Self.CompleteAgentMovement(this); + } return true; } @@ -605,7 +600,7 @@ namespace OpenMetaverse #endregion Start Timers - Logger.Log("Connecting to " + this.ToString(), Helpers.LogLevel.Info, Client); + Logger.Log("Connecting to " + this, Helpers.LogLevel.Info, Client); try { @@ -625,7 +620,7 @@ namespace OpenMetaverse if (!ConnectedEvent.WaitOne(Client.Settings.LOGIN_TIMEOUT, false)) { - Logger.Log("Giving up on waiting for RegionHandshake for " + this.ToString(), + Logger.Log("Giving up on waiting for RegionHandshake for " + this, Helpers.LogLevel.Warning, Client); //Remove the simulator from the list, not useful if we haven't recieved the RegionHandshake lock (Client.Network.Simulators) { @@ -656,10 +651,15 @@ namespace OpenMetaverse public void UseCircuitCode(bool waitForAck) { // Send the UseCircuitCode packet to initiate the connection - UseCircuitCodePacket use = new UseCircuitCodePacket(); - use.CircuitCode.Code = Network.CircuitCode; - use.CircuitCode.ID = Client.Self.AgentID; - use.CircuitCode.SessionID = Client.Self.SessionID; + UseCircuitCodePacket use = new UseCircuitCodePacket + { + CircuitCode = + { + Code = Network.CircuitCode, + ID = Client.Self.AgentID, + SessionID = Client.Self.SessionID + } + }; if (waitForAck) { @@ -705,46 +705,44 @@ namespace OpenMetaverse /// public void Disconnect(bool sendCloseCircuit) { - if (connected) + if (!connected) return; + + connected = false; + // Destroy the timers + AckTimer?.Dispose(); + StatsTimer?.Dispose(); + PingTimer?.Dispose(); + + AckTimer = null; + StatsTimer = null; + PingTimer = null; + + // Kill the current CAPS system + if (Caps != null) { - connected = false; - - // Destroy the timers - if (AckTimer != null) AckTimer.Dispose(); - if (StatsTimer != null) StatsTimer.Dispose(); - if (PingTimer != null) PingTimer.Dispose(); - - AckTimer = null; - StatsTimer = null; - PingTimer = null; - - // Kill the current CAPS system - if (Caps != null) - { - Caps.Disconnect(true); - Caps = null; - } - - if (sendCloseCircuit) - { - // Try to send the CloseCircuit notice - CloseCircuitPacket close = new CloseCircuitPacket(); - UDPPacketBuffer buf = new UDPPacketBuffer(remoteEndPoint); - byte[] data = close.ToBytes(); - Buffer.BlockCopy(data, 0, buf.Data, 0, data.Length); - buf.DataLength = data.Length; - - AsyncBeginSend(buf); - } - - if (Client.Settings.POOL_PARCEL_DATA || Client.Settings.CACHE_PRIMITIVES) - { - SimulatorDataPool.SimulatorRelease(this); - } - - // Shut the socket communication down - Stop(); + Caps.Disconnect(true); + Caps = null; } + + if (sendCloseCircuit) + { + // Try to send the CloseCircuit notice + CloseCircuitPacket close = new CloseCircuitPacket(); + UDPPacketBuffer buf = new UDPPacketBuffer(remoteEndPoint); + byte[] data = close.ToBytes(); + Buffer.BlockCopy(data, 0, buf.Data, 0, data.Length); + buf.DataLength = data.Length; + + AsyncBeginSend(buf); + } + + if (Client.Settings.POOL_PARCEL_DATA || Client.Settings.CACHE_PRIMITIVES) + { + SimulatorDataPool.SimulatorRelease(this); + } + + // Shut the socket communication down + Stop(); } /// @@ -752,10 +750,15 @@ namespace OpenMetaverse /// public void Pause() { - AgentPausePacket pause = new AgentPausePacket(); - pause.AgentData.AgentID = Client.Self.AgentID; - pause.AgentData.SessionID = Client.Self.SessionID; - pause.AgentData.SerialNum = (uint)Interlocked.Exchange(ref pauseSerial, pauseSerial + 1); + AgentPausePacket pause = new AgentPausePacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID, + SerialNum = (uint) Interlocked.Exchange(ref pauseSerial, pauseSerial + 1) + } + }; Client.Network.SendPacket(pause, this); } @@ -765,10 +768,15 @@ namespace OpenMetaverse /// public void Resume() { - AgentResumePacket resume = new AgentResumePacket(); - resume.AgentData.AgentID = Client.Self.AgentID; - resume.AgentData.SessionID = Client.Self.SessionID; - resume.AgentData.SerialNum = (uint)Interlocked.Exchange(ref pauseSerial, pauseSerial + 1); + AgentResumePacket resume = new AgentResumePacket + { + AgentData = + { + AgentID = Client.Self.AgentID, + SessionID = Client.Self.SessionID, + SerialNum = (uint) Interlocked.Exchange(ref pauseSerial, pauseSerial + 1) + } + }; Client.Network.SendPacket(resume, this); } @@ -849,7 +857,10 @@ namespace OpenMetaverse // Zerocode if needed if (doZerocode) { - try { dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data); } + try + { + dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data); + } catch (IndexOutOfRangeException) { // The packet grew larger than Packet.MTU bytes while zerocoding. @@ -958,19 +969,26 @@ namespace OpenMetaverse { if (NeedAck.Count > 0) { - SortedDictionary.KeyCollection.Enumerator en = NeedAck.Keys.GetEnumerator(); - en.MoveNext(); - oldestUnacked = en.Current; + using (var en = NeedAck.Keys.GetEnumerator()) + { + en.MoveNext(); + oldestUnacked = en.Current; + } } } //if (oldestUnacked != 0) // Logger.DebugLog("Sending ping with oldestUnacked=" + oldestUnacked); - StartPingCheckPacket ping = new StartPingCheckPacket(); - ping.PingID.PingID = Stats.LastPingID++; - ping.PingID.OldestUnacked = oldestUnacked; - ping.Header.Reliable = false; + StartPingCheckPacket ping = new StartPingCheckPacket + { + PingID = + { + PingID = Stats.LastPingID++, + OldestUnacked = oldestUnacked + }, + Header = {Reliable = false} + }; SendPacket(ping); Stats.LastPingSent = Environment.TickCount; } @@ -983,10 +1001,9 @@ namespace OpenMetaverse /// public override string ToString() { - if (!String.IsNullOrEmpty(Name)) - return String.Format("{0} ({1})", Name, remoteEndPoint); - else - return String.Format("({0})", remoteEndPoint); + return !String.IsNullOrEmpty(Name) + ? $"{Name} ({remoteEndPoint})" + : $"({remoteEndPoint})"; } /// @@ -1006,15 +1023,13 @@ namespace OpenMetaverse public override bool Equals(object obj) { Simulator sim = obj as Simulator; - if (sim == null) - return false; - return (remoteEndPoint.Equals(sim.remoteEndPoint)); + return sim != null && (remoteEndPoint.Equals(sim.remoteEndPoint)); } public static bool operator ==(Simulator lhs, Simulator rhs) { // If both are null, or both are same instance, return true - if (System.Object.ReferenceEquals(lhs, rhs)) + if (ReferenceEquals(lhs, rhs)) { return true; } @@ -1041,7 +1056,7 @@ namespace OpenMetaverse if (!remoteEndPoint.Address.Equals(((IPEndPoint)buffer.RemoteEndPoint).Address)) { Logger.Log("Received " + buffer.DataLength + " bytes of data from unrecognized source " + - ((IPEndPoint)buffer.RemoteEndPoint).ToString(), Helpers.LogLevel.Warning, Client); + ((IPEndPoint)buffer.RemoteEndPoint), Helpers.LogLevel.Warning, Client); return; } @@ -1086,13 +1101,13 @@ namespace OpenMetaverse { lock (NeedAck) { - for (int i = 0; i < packet.Header.AckList.Length; i++) + foreach (var t in packet.Header.AckList) { - if (NeedAck.ContainsKey(packet.Header.AckList[i]) && NeedAck[packet.Header.AckList[i]].Type == PacketType.UseCircuitCode) + if (NeedAck.ContainsKey(t) && NeedAck[t].Type == PacketType.UseCircuitCode) { GotUseCircuitCodeAck.Set(); } - NeedAck.Remove(packet.Header.AckList[i]); + NeedAck.Remove(t); } } } @@ -1104,13 +1119,13 @@ namespace OpenMetaverse lock (NeedAck) { - for (int i = 0; i < ackPacket.Packets.Length; i++) + foreach (var t in ackPacket.Packets) { - if (NeedAck.ContainsKey(ackPacket.Packets[i].ID) && NeedAck[ackPacket.Packets[i].ID].Type == PacketType.UseCircuitCode) + if (NeedAck.ContainsKey(t.ID) && NeedAck[t.ID].Type == PacketType.UseCircuitCode) { GotUseCircuitCodeAck.Set(); } - NeedAck.Remove(ackPacket.Packets[i].ID); + NeedAck.Remove(t.ID); } } } @@ -1122,7 +1137,7 @@ namespace OpenMetaverse #region ACK Sending // Add this packet to the list of ACKs that need to be sent out - uint sequence = (uint)packet.Header.Sequence; + var sequence = packet.Header.Sequence; PendingAcks.Enqueue(sequence); // Send out ACKs if we have a lot of them @@ -1191,20 +1206,20 @@ namespace OpenMetaverse if (PendingAcks.TryDequeue(out ack)) { List blocks = new List(); - PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock(); - block.ID = ack; + PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock {ID = ack}; blocks.Add(block); while (PendingAcks.TryDequeue(out ack)) { - block = new PacketAckPacket.PacketsBlock(); - block.ID = ack; + block = new PacketAckPacket.PacketsBlock {ID = ack}; blocks.Add(block); } - PacketAckPacket packet = new PacketAckPacket(); - packet.Header.Reliable = false; - packet.Packets = blocks.ToArray(); + PacketAckPacket packet = new PacketAckPacket + { + Header = {Reliable = false}, + Packets = blocks.ToArray() + }; ackCount = blocks.Count; SendPacket(packet); @@ -1218,55 +1233,51 @@ namespace OpenMetaverse /// private void ResendUnacked() { - if (NeedAck.Count > 0) + if (NeedAck.Count <= 0) return; + + NetworkManager.OutgoingPacket[] array; + + lock (NeedAck) { - NetworkManager.OutgoingPacket[] array; + // Create a temporary copy of the outgoing packets array to iterate over + array = new NetworkManager.OutgoingPacket[NeedAck.Count]; + NeedAck.Values.CopyTo(array, 0); + } - lock (NeedAck) + int now = Environment.TickCount; + + // Resend packets + foreach (NetworkManager.OutgoingPacket outgoing in array) + { + if (outgoing.TickCount == 0 || now - outgoing.TickCount <= Client.Settings.RESEND_TIMEOUT) continue; + + if (outgoing.ResendCount < Client.Settings.MAX_RESEND_COUNT) { - // Create a temporary copy of the outgoing packets array to iterate over - array = new NetworkManager.OutgoingPacket[NeedAck.Count]; - NeedAck.Values.CopyTo(array, 0); - } - - int now = Environment.TickCount; - - // Resend packets - for (int i = 0; i < array.Length; i++) - { - NetworkManager.OutgoingPacket outgoing = array[i]; - - if (outgoing.TickCount != 0 && now - outgoing.TickCount > Client.Settings.RESEND_TIMEOUT) + if (Client.Settings.LOG_RESENDS) { - if (outgoing.ResendCount < Client.Settings.MAX_RESEND_COUNT) - { - if (Client.Settings.LOG_RESENDS) - { - Logger.DebugLog(String.Format("Resending {2} packet #{0}, {1}ms have passed", - outgoing.SequenceNumber, now - outgoing.TickCount, outgoing.Type), Client); - } - - // The TickCount will be set to the current time when the packet - // is actually sent out again - outgoing.TickCount = 0; - - // Set the resent flag - outgoing.Buffer.Data[0] = (byte)(outgoing.Buffer.Data[0] | Helpers.MSG_RESENT); - - // Stats tracking - Interlocked.Increment(ref outgoing.ResendCount); - Interlocked.Increment(ref Stats.ResentPackets); - - SendPacketFinal(outgoing); - } - else - { - Logger.DebugLog(String.Format("Dropping packet #{0} after {1} failed attempts", - outgoing.SequenceNumber, outgoing.ResendCount)); - - lock (NeedAck) NeedAck.Remove(outgoing.SequenceNumber); - } + Logger.DebugLog(String.Format("Resending {2} packet #{0}, {1}ms have passed", + outgoing.SequenceNumber, now - outgoing.TickCount, outgoing.Type), Client); } + + // The TickCount will be set to the current time when the packet + // is actually sent out again + outgoing.TickCount = 0; + + // Set the resent flag + outgoing.Buffer.Data[0] = (byte)(outgoing.Buffer.Data[0] | Helpers.MSG_RESENT); + + // Stats tracking + Interlocked.Increment(ref outgoing.ResendCount); + Interlocked.Increment(ref Stats.ResentPackets); + + SendPacketFinal(outgoing); + } + else + { + Logger.DebugLog(String.Format("Dropping packet #{0} after {1} failed attempts", + outgoing.SequenceNumber, outgoing.ResendCount)); + + lock (NeedAck) NeedAck.Remove(outgoing.SequenceNumber); } } } @@ -1278,15 +1289,19 @@ namespace OpenMetaverse // Start the ACK handling functions again after NETWORK_TICK_INTERVAL milliseconds if (null == AckTimer) return; - try { AckTimer.Change(Settings.NETWORK_TICK_INTERVAL, Timeout.Infinite); } - catch (Exception) { } + try + { + AckTimer.Change(Settings.NETWORK_TICK_INTERVAL, Timeout.Infinite); + } + catch (Exception) + { } // *TODO: Review catch all code smell } private void StatsTimer_Elapsed(object obj) { long old_in = 0, old_out = 0; - long recv = Stats.RecvBytes; - long sent = Stats.SentBytes; + var recv = Stats.RecvBytes; + var sent = Stats.SentBytes; if (InBytes.Count >= Client.Settings.STATS_QUEUE_SIZE) old_in = InBytes.Dequeue(); @@ -1315,7 +1330,7 @@ namespace OpenMetaverse public sealed class IncomingPacketIDCollection { - readonly uint[] Items; + readonly uint[] _items; HashSet hashSet; int first; int next; @@ -1324,7 +1339,7 @@ namespace OpenMetaverse public IncomingPacketIDCollection(int capacity) { this.capacity = capacity; - Items = new uint[capacity]; + _items = new uint[capacity]; hashSet = new HashSet(); } @@ -1334,11 +1349,11 @@ namespace OpenMetaverse { if (hashSet.Add(ack)) { - Items[next] = ack; + _items[next] = ack; next = (next + 1) % capacity; if (next == first) { - hashSet.Remove(Items[first]); + hashSet.Remove(_items[first]); first = (first + 1) % capacity; } @@ -1358,15 +1373,11 @@ namespace OpenMetaverse { lock (SimulatorDataPools) { - int SimTimeout = Settings.SIMULATOR_POOL_TIMEOUT; - List reap = new List(); - foreach (var pool in SimulatorDataPools.Values) - { - if (pool.InactiveSince != DateTime.MaxValue && pool.InactiveSince.AddMilliseconds(SimTimeout) < DateTime.Now) - { - reap.Add(pool.Handle); - } - } + int simTimeout = Settings.SIMULATOR_POOL_TIMEOUT; + var reap = (from pool in SimulatorDataPools.Values + where pool.InactiveSince != DateTime.MaxValue + && pool.InactiveSince.AddMilliseconds(simTimeout) < DateTime.Now + select pool.Handle).ToList(); foreach (var hndl in reap) { SimulatorDataPools.Remove(hndl); @@ -1382,14 +1393,14 @@ namespace OpenMetaverse { InactiveSimReaper = new Timer(RemoveOldSims, null, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(3)); } - SimulatorDataPool pool = GetSimulatorData(sim.Handle); + var pool = GetSimulatorData(sim.Handle); if (pool.ActiveClients < 1) pool.ActiveClients = 1; else pool.ActiveClients++; pool.InactiveSince = DateTime.MaxValue; } } public static void SimulatorRelease(Simulator sim) { - ulong hndl = sim.Handle; + var hndl = sim.Handle; lock (SimulatorDataPools) { SimulatorDataPool dataPool = GetSimulatorData(hndl); @@ -1401,12 +1412,12 @@ namespace OpenMetaverse } } - static public Dictionary SimulatorDataPools = new Dictionary(); + public static Dictionary SimulatorDataPools = new Dictionary(); /// /// Simulator handle /// - readonly public ulong Handle; + public readonly ulong Handle; /// /// Number of GridClients using this datapool /// @@ -1474,7 +1485,7 @@ namespace OpenMetaverse { lock (PrimCache) { - foreach (uint u in removePrims) + foreach (var u in removePrims) { Primitive prim; if (PrimCache.TryGetValue(u, out prim)) prim.ActiveClients--; diff --git a/OpenMetaverse/SoundManager.cs b/OpenMetaverse/SoundManager.cs index 74e9013e..48b20492 100644 --- a/OpenMetaverse/SoundManager.cs +++ b/OpenMetaverse/SoundManager.cs @@ -25,7 +25,6 @@ */ using System; -using System.Collections.Generic; using OpenMetaverse.Packets; namespace OpenMetaverse @@ -36,32 +35,31 @@ namespace OpenMetaverse public class SoundManager { #region Private Members - private readonly GridClient Client; + private readonly GridClient _client; #endregion #region Event Handling /// The event subscribers, null of no subscribers - private EventHandler m_AttachedSound; + private EventHandler _mAttachedSound; ///Raises the AttachedSound Event /// A AttachedSoundEventArgs object containing /// the data sent from the simulator protected virtual void OnAttachedSound(AttachedSoundEventArgs e) { - EventHandler handler = m_AttachedSound; - if (handler != null) - handler(this, e); + EventHandler handler = _mAttachedSound; + handler?.Invoke(this, e); } /// Thread sync lock object - private readonly object m_AttachedSoundLock = new object(); + private readonly object _mAttachedSoundLock = new object(); /// Raised when the simulator sends us data containing /// sound public event EventHandler AttachedSound { - add { lock (m_AttachedSoundLock) { m_AttachedSound += value; } } - remove { lock (m_AttachedSoundLock) { m_AttachedSound -= value; } } + add { lock (_mAttachedSoundLock) { _mAttachedSound += value; } } + remove { lock (_mAttachedSoundLock) { _mAttachedSound -= value; } } } /// The event subscribers, null of no subscribers @@ -73,8 +71,7 @@ namespace OpenMetaverse protected virtual void OnAttachedSoundGainChange(AttachedSoundGainChangeEventArgs e) { EventHandler handler = m_AttachedSoundGainChange; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -97,8 +94,7 @@ namespace OpenMetaverse protected virtual void OnSoundTrigger(SoundTriggerEventArgs e) { EventHandler handler = m_SoundTrigger; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -121,8 +117,7 @@ namespace OpenMetaverse protected virtual void OnPreloadSound(PreloadSoundEventArgs e) { EventHandler handler = m_PreloadSound; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -145,12 +140,12 @@ namespace OpenMetaverse /// A reference to the current GridClient instance public SoundManager(GridClient client) { - Client = client; + _client = client; - Client.Network.RegisterCallback(PacketType.AttachedSound, AttachedSoundHandler); - Client.Network.RegisterCallback(PacketType.AttachedSoundGainChange, AttachedSoundGainChangeHandler); - Client.Network.RegisterCallback(PacketType.PreloadSound, PreloadSoundHandler); - Client.Network.RegisterCallback(PacketType.SoundTrigger, SoundTriggerHandler); + _client.Network.RegisterCallback(PacketType.AttachedSound, AttachedSoundHandler); + _client.Network.RegisterCallback(PacketType.AttachedSoundGainChange, AttachedSoundGainChangeHandler); + _client.Network.RegisterCallback(PacketType.PreloadSound, PreloadSoundHandler); + _client.Network.RegisterCallback(PacketType.SoundTrigger, SoundTriggerHandler); } #region public methods @@ -161,7 +156,7 @@ namespace OpenMetaverse /// UUID of the sound to be played public void PlaySound(UUID soundID) { - SendSoundTrigger(soundID, Client.Self.SimPosition, 1.0f); + SendSoundTrigger(soundID, _client.Self.SimPosition, 1.0f); } /// @@ -171,7 +166,7 @@ namespace OpenMetaverse /// position for the sound to be played at. Normally the avatar. public void SendSoundTrigger(UUID soundID, Vector3 position) { - SendSoundTrigger(soundID, Client.Self.SimPosition, 1.0f); + SendSoundTrigger(soundID, _client.Self.SimPosition, 1.0f); } /// @@ -182,7 +177,7 @@ namespace OpenMetaverse /// volume of the sound, from 0.0 to 1.0 public void SendSoundTrigger(UUID soundID, Vector3 position, float gain) { - SendSoundTrigger(soundID, Client.Network.CurrentSim.Handle, position, gain); + SendSoundTrigger(soundID, _client.Network.CurrentSim.Handle, position, gain); } /// /// Plays a sound in the specified sim @@ -205,17 +200,21 @@ namespace OpenMetaverse /// volume of the sound, from 0.0 to 1.0 public void SendSoundTrigger(UUID soundID, ulong handle, Vector3 position, float gain) { - SoundTriggerPacket soundtrigger = new SoundTriggerPacket(); - soundtrigger.SoundData = new SoundTriggerPacket.SoundDataBlock(); - soundtrigger.SoundData.SoundID = soundID; - soundtrigger.SoundData.ObjectID = UUID.Zero; - soundtrigger.SoundData.OwnerID = UUID.Zero; - soundtrigger.SoundData.ParentID = UUID.Zero; - soundtrigger.SoundData.Handle = handle; - soundtrigger.SoundData.Position = position; - soundtrigger.SoundData.Gain = gain; + SoundTriggerPacket soundtrigger = new SoundTriggerPacket + { + SoundData = new SoundTriggerPacket.SoundDataBlock + { + SoundID = soundID, + ObjectID = UUID.Zero, + OwnerID = UUID.Zero, + ParentID = UUID.Zero, + Handle = handle, + Position = position, + Gain = gain + } + }; - Client.Network.SendPacket(soundtrigger); + _client.Network.SendPacket(soundtrigger); } #endregion @@ -226,41 +225,37 @@ namespace OpenMetaverse /// The sender /// The EventArgs object containing the packet data protected void AttachedSoundHandler(object sender, PacketReceivedEventArgs e) - { - if (m_AttachedSound != null) - { - AttachedSoundPacket sound = (AttachedSoundPacket)e.Packet; + { + if (_mAttachedSound == null) return; - OnAttachedSound(new AttachedSoundEventArgs(e.Simulator, sound.DataBlock.SoundID, sound.DataBlock.OwnerID, sound.DataBlock.ObjectID, - sound.DataBlock.Gain, (SoundFlags)sound.DataBlock.Flags)); - } + AttachedSoundPacket sound = (AttachedSoundPacket)e.Packet; + OnAttachedSound(new AttachedSoundEventArgs(e.Simulator, sound.DataBlock.SoundID, sound.DataBlock.OwnerID, + sound.DataBlock.ObjectID, sound.DataBlock.Gain, (SoundFlags)sound.DataBlock.Flags)); } /// Process an incoming packet and raise the appropriate events /// The sender /// The EventArgs object containing the packet data protected void AttachedSoundGainChangeHandler(object sender, PacketReceivedEventArgs e) - { - if (m_AttachedSoundGainChange != null) - { - AttachedSoundGainChangePacket change = (AttachedSoundGainChangePacket)e.Packet; - OnAttachedSoundGainChange(new AttachedSoundGainChangeEventArgs(e.Simulator, change.DataBlock.ObjectID, change.DataBlock.Gain)); - } + { + if (m_AttachedSoundGainChange == null) return; + + AttachedSoundGainChangePacket change = (AttachedSoundGainChangePacket)e.Packet; + OnAttachedSoundGainChange(new AttachedSoundGainChangeEventArgs(e.Simulator, change.DataBlock.ObjectID, + change.DataBlock.Gain)); } /// Process an incoming packet and raise the appropriate events /// The sender /// The EventArgs object containing the packet data protected void PreloadSoundHandler(object sender, PacketReceivedEventArgs e) - { - if (m_PreloadSound != null) - { - PreloadSoundPacket preload = (PreloadSoundPacket)e.Packet; + { + if (m_PreloadSound == null) return; - foreach (PreloadSoundPacket.DataBlockBlock data in preload.DataBlock) - { - OnPreloadSound(new PreloadSoundEventArgs(e.Simulator, data.SoundID, data.OwnerID, data.ObjectID)); - } + PreloadSoundPacket preload = (PreloadSoundPacket)e.Packet; + foreach (var data in preload.DataBlock) + { + OnPreloadSound(new PreloadSoundEventArgs(e.Simulator, data.SoundID, data.OwnerID, data.ObjectID)); } } @@ -268,19 +263,18 @@ namespace OpenMetaverse /// The sender /// The EventArgs object containing the packet data protected void SoundTriggerHandler(object sender, PacketReceivedEventArgs e) - { - if (m_SoundTrigger != null) - { - SoundTriggerPacket trigger = (SoundTriggerPacket)e.Packet; - OnSoundTrigger(new SoundTriggerEventArgs(e.Simulator, - trigger.SoundData.SoundID, - trigger.SoundData.OwnerID, - trigger.SoundData.ObjectID, - trigger.SoundData.ParentID, - trigger.SoundData.Gain, - trigger.SoundData.Handle, - trigger.SoundData.Position)); - } + { + if (m_SoundTrigger == null) return; + + SoundTriggerPacket trigger = (SoundTriggerPacket)e.Packet; + OnSoundTrigger(new SoundTriggerEventArgs(e.Simulator, + trigger.SoundData.SoundID, + trigger.SoundData.OwnerID, + trigger.SoundData.ObjectID, + trigger.SoundData.ParentID, + trigger.SoundData.Gain, + trigger.SoundData.Handle, + trigger.SoundData.Position)); } #endregion @@ -306,25 +300,23 @@ namespace OpenMetaverse /// public class AttachedSoundEventArgs : EventArgs { - private readonly Simulator m_Simulator; - private readonly UUID m_SoundID; - private readonly UUID m_OwnerID; - private readonly UUID m_ObjectID; - private readonly float m_Gain; - private readonly SoundFlags m_Flags; - /// Simulator where the event originated - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator { get; } + /// Get the sound asset id - public UUID SoundID { get { return m_SoundID; } } + public UUID SoundID { get; } + /// Get the ID of the owner - public UUID OwnerID { get { return m_OwnerID; } } + public UUID OwnerID { get; } + /// Get the ID of the Object - public UUID ObjectID { get { return m_ObjectID; } } + public UUID ObjectID { get; } + /// Get the volume level - public float Gain { get { return m_Gain; } } + public float Gain { get; } + /// Get the - public SoundFlags Flags { get { return m_Flags; } } + public SoundFlags Flags { get; } /// /// Construct a new instance of the SoundTriggerEventArgs class @@ -337,12 +329,12 @@ namespace OpenMetaverse /// The public AttachedSoundEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID, float gain, SoundFlags flags) { - this.m_Simulator = sim; - this.m_SoundID = soundID; - this.m_OwnerID = ownerID; - this.m_ObjectID = objectID; - this.m_Gain = gain; - this.m_Flags = flags; + Simulator = sim; + SoundID = soundID; + OwnerID = ownerID; + ObjectID = objectID; + Gain = gain; + Flags = flags; } } @@ -356,11 +348,13 @@ namespace OpenMetaverse private readonly float m_Gain; /// Simulator where the event originated - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the ID of the Object - public UUID ObjectID { get { return m_ObjectID; } } + public UUID ObjectID => m_ObjectID; + /// Get the volume level - public float Gain { get { return m_Gain; } } + public float Gain => m_Gain; /// /// Construct a new instance of the AttachedSoundGainChangedEventArgs class @@ -370,9 +364,9 @@ namespace OpenMetaverse /// The new volume level public AttachedSoundGainChangeEventArgs(Simulator sim, UUID objectID, float gain) { - this.m_Simulator = sim; - this.m_ObjectID = objectID; - this.m_Gain = gain; + m_Simulator = sim; + m_ObjectID = objectID; + m_Gain = gain; } } @@ -414,21 +408,28 @@ namespace OpenMetaverse private readonly Vector3 m_Position; /// Simulator where the event originated - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the sound asset id - public UUID SoundID { get { return m_SoundID; } } + public UUID SoundID => m_SoundID; + /// Get the ID of the owner - public UUID OwnerID { get { return m_OwnerID; } } + public UUID OwnerID => m_OwnerID; + /// Get the ID of the Object - public UUID ObjectID { get { return m_ObjectID; } } + public UUID ObjectID => m_ObjectID; + /// Get the ID of the objects parent - public UUID ParentID { get { return m_ParentID; } } + public UUID ParentID => m_ParentID; + /// Get the volume level - public float Gain { get { return m_Gain; } } + public float Gain => m_Gain; + /// Get the regionhandle - public ulong RegionHandle { get { return m_RegionHandle; } } + public ulong RegionHandle => m_RegionHandle; + /// Get the source position - public Vector3 Position { get { return m_Position; } } + public Vector3 Position => m_Position; /// /// Construct a new instance of the SoundTriggerEventArgs class @@ -443,14 +444,14 @@ namespace OpenMetaverse /// The source position public SoundTriggerEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID, UUID parentID, float gain, ulong regionHandle, Vector3 position) { - this.m_Simulator = sim; - this.m_SoundID = soundID; - this.m_OwnerID = ownerID; - this.m_ObjectID = objectID; - this.m_ParentID = parentID; - this.m_Gain = gain; - this.m_RegionHandle = regionHandle; - this.m_Position = position; + m_Simulator = sim; + m_SoundID = soundID; + m_OwnerID = ownerID; + m_ObjectID = objectID; + m_ParentID = parentID; + m_Gain = gain; + m_RegionHandle = regionHandle; + m_Position = position; } } @@ -479,13 +480,16 @@ namespace OpenMetaverse private readonly UUID m_ObjectID; /// Simulator where the event originated - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Get the sound asset id - public UUID SoundID { get { return m_SoundID; } } + public UUID SoundID => m_SoundID; + /// Get the ID of the owner - public UUID OwnerID { get { return m_OwnerID; } } + public UUID OwnerID => m_OwnerID; + /// Get the ID of the Object - public UUID ObjectID { get { return m_ObjectID; } } + public UUID ObjectID => m_ObjectID; /// /// Construct a new instance of the PreloadSoundEventArgs class @@ -496,10 +500,10 @@ namespace OpenMetaverse /// The ID of the object public PreloadSoundEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID) { - this.m_Simulator = sim; - this.m_SoundID = soundID; - this.m_OwnerID = ownerID; - this.m_ObjectID = objectID; + m_Simulator = sim; + m_SoundID = soundID; + m_OwnerID = ownerID; + m_ObjectID = objectID; } } #endregion diff --git a/OpenMetaverse/Sounds.cs b/OpenMetaverse/Sounds.cs index 8fd954bc..4117ed29 100644 --- a/OpenMetaverse/Sounds.cs +++ b/OpenMetaverse/Sounds.cs @@ -37,112 +37,112 @@ namespace OpenMetaverse public static class Sounds { /// - public readonly static UUID BELL_TING = new UUID(" ed124764-705d-d497-167a-182cd9fa2e6c"); + public static readonly UUID BELL_TING = new UUID(" ed124764-705d-d497-167a-182cd9fa2e6c"); /// - public readonly static UUID CLICK = new UUID("4c8c3c77-de8d-bde2-b9b8-32635e0fd4a6"); + public static readonly UUID CLICK = new UUID("4c8c3c77-de8d-bde2-b9b8-32635e0fd4a6"); /// - public readonly static UUID HEALTH_REDUCTION_FEMALE = new UUID("219c5d93-6c09-31c5-fb3f-c5fe7495c115"); + public static readonly UUID HEALTH_REDUCTION_FEMALE = new UUID("219c5d93-6c09-31c5-fb3f-c5fe7495c115"); /// - public readonly static UUID HEALTH_REDUCTION_MALE = new UUID("e057c244-5768-1056-c37e-1537454eeb62"); + public static readonly UUID HEALTH_REDUCTION_MALE = new UUID("e057c244-5768-1056-c37e-1537454eeb62"); /// - public readonly static UUID IM_START = new UUID("c825dfbc-9827-7e02-6507-3713d18916c1"); + public static readonly UUID IM_START = new UUID("c825dfbc-9827-7e02-6507-3713d18916c1"); /// - public readonly static UUID INSTANT_MESSAGE_NOTIFICATION = new UUID("67cc2844-00f3-2b3c-b991-6418d01e1bb7"); + public static readonly UUID INSTANT_MESSAGE_NOTIFICATION = new UUID("67cc2844-00f3-2b3c-b991-6418d01e1bb7"); /// - public readonly static UUID INVALID_OPERATION = new UUID("4174f859-0d3d-c517-c424-72923dc21f65"); + public static readonly UUID INVALID_OPERATION = new UUID("4174f859-0d3d-c517-c424-72923dc21f65"); /// - public readonly static UUID KEYBOARD_LOOP = new UUID("5e191c7b-8996-9ced-a177-b2ac32bfea06"); + public static readonly UUID KEYBOARD_LOOP = new UUID("5e191c7b-8996-9ced-a177-b2ac32bfea06"); /// coins - public readonly static UUID MONEY_REDUCTION_COINS = new UUID("77a018af-098e-c037-51a6-178f05877c6f"); + public static readonly UUID MONEY_REDUCTION_COINS = new UUID("77a018af-098e-c037-51a6-178f05877c6f"); /// cash register bell - public readonly static UUID MONEY_INCREASE_CASH_REGISTER_BELL = new UUID("104974e3-dfda-428b-99ee-b0d4e748d3a3"); + public static readonly UUID MONEY_INCREASE_CASH_REGISTER_BELL = new UUID("104974e3-dfda-428b-99ee-b0d4e748d3a3"); /// - public readonly static UUID NULL_KEYSTROKE = new UUID("2ca849ba-2885-4bc3-90ef-d4987a5b983a"); + public static readonly UUID NULL_KEYSTROKE = new UUID("2ca849ba-2885-4bc3-90ef-d4987a5b983a"); /// - public readonly static UUID OBJECT_COLLISION = new UUID("be582e5d-b123-41a2-a150-454c39e961c8"); + public static readonly UUID OBJECT_COLLISION = new UUID("be582e5d-b123-41a2-a150-454c39e961c8"); /// rubber - public readonly static UUID OBJECT_COLLISION_RUBBER = new UUID("212b6d1e-8d9c-4986-b3aa-f3c6df8d987d"); + public static readonly UUID OBJECT_COLLISION_RUBBER = new UUID("212b6d1e-8d9c-4986-b3aa-f3c6df8d987d"); /// plastic - public readonly static UUID OBJECT_COLLISION_PLASTIC = new UUID("d55c7f3c-e1c3-4ddc-9eff-9ef805d9190e"); + public static readonly UUID OBJECT_COLLISION_PLASTIC = new UUID("d55c7f3c-e1c3-4ddc-9eff-9ef805d9190e"); /// flesh - public readonly static UUID OBJECT_COLLISION_FLESH = new UUID("2d8c6f51-149e-4e23-8413-93a379b42b67"); + public static readonly UUID OBJECT_COLLISION_FLESH = new UUID("2d8c6f51-149e-4e23-8413-93a379b42b67"); /// wood splintering? - public readonly static UUID OBJECT_COLLISION_WOOD_SPLINTERING = new UUID("6f00669f-15e0-4793-a63e-c03f62fee43a"); + public static readonly UUID OBJECT_COLLISION_WOOD_SPLINTERING = new UUID("6f00669f-15e0-4793-a63e-c03f62fee43a"); /// glass break - public readonly static UUID OBJECT_COLLISION_GLASS_BREAK = new UUID("85cda060-b393-48e6-81c8-2cfdfb275351"); + public static readonly UUID OBJECT_COLLISION_GLASS_BREAK = new UUID("85cda060-b393-48e6-81c8-2cfdfb275351"); /// metal clunk - public readonly static UUID OBJECT_COLLISION_METAL_CLUNK = new UUID("d1375446-1c4d-470b-9135-30132433b678"); + public static readonly UUID OBJECT_COLLISION_METAL_CLUNK = new UUID("d1375446-1c4d-470b-9135-30132433b678"); /// whoosh - public readonly static UUID OBJECT_CREATE_WHOOSH = new UUID("3c8fc726-1fd6-862d-fa01-16c5b2568db6"); + public static readonly UUID OBJECT_CREATE_WHOOSH = new UUID("3c8fc726-1fd6-862d-fa01-16c5b2568db6"); /// shake - public readonly static UUID OBJECT_DELETE_SHAKE = new UUID("0cb7b00a-4c10-6948-84de-a93c09af2ba9"); + public static readonly UUID OBJECT_DELETE_SHAKE = new UUID("0cb7b00a-4c10-6948-84de-a93c09af2ba9"); - /// - public readonly static UUID OBJECT_REZ = new UUID("f4a0660f-5446-dea2-80b7-6482a082803c"); + /// summon + public static readonly UUID OBJECT_REZ = new UUID("f4a0660f-5446-dea2-80b7-6482a082803c"); /// ding - public readonly static UUID PIE_MENU_APPEAR_DING = new UUID("8eaed61f-92ff-6485-de83-4dcc938a478e"); + public static readonly UUID PIE_MENU_APPEAR_DING = new UUID("8eaed61f-92ff-6485-de83-4dcc938a478e"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT = new UUID("d9f73cf8-17b4-6f7a-1565-7951226c305d"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT = new UUID("d9f73cf8-17b4-6f7a-1565-7951226c305d"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT1 = new UUID("f6ba9816-dcaf-f755-7b67-51b31b6233e5"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT1 = new UUID("f6ba9816-dcaf-f755-7b67-51b31b6233e5"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT2 = new UUID("7aff2265-d05b-8b72-63c7-dbf96dc2f21f"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT2 = new UUID("7aff2265-d05b-8b72-63c7-dbf96dc2f21f"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT3 = new UUID("09b2184e-8601-44e2-afbb-ce37434b8ba1"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT3 = new UUID("09b2184e-8601-44e2-afbb-ce37434b8ba1"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT4 = new UUID("bbe4c7fc-7044-b05e-7b89-36924a67593c"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT4 = new UUID("bbe4c7fc-7044-b05e-7b89-36924a67593c"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT5 = new UUID("d166039b-b4f5-c2ec-4911-c85c727b016c"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT5 = new UUID("d166039b-b4f5-c2ec-4911-c85c727b016c"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT6 = new UUID("242af82b-43c2-9a3b-e108-3b0c7e384981"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT6 = new UUID("242af82b-43c2-9a3b-e108-3b0c7e384981"); /// - public readonly static UUID PIE_MENU_SLICE_HIGHLIGHT7 = new UUID("c1f334fb-a5be-8fe7-22b3-29631c21cf0b"); + public static readonly UUID PIE_MENU_SLICE_HIGHLIGHT7 = new UUID("c1f334fb-a5be-8fe7-22b3-29631c21cf0b"); /// - public readonly static UUID SNAPSHOT = new UUID("3d09f582-3851-c0e0-f5ba-277ac5c73fb4"); + public static readonly UUID SNAPSHOT = new UUID("3d09f582-3851-c0e0-f5ba-277ac5c73fb4"); /// - public readonly static UUID TELEPORT_TEXTURE_APPLY = new UUID("d7a9a565-a013-2a69-797d-5332baa1a947"); + public static readonly UUID TELEPORT_TEXTURE_APPLY = new UUID("d7a9a565-a013-2a69-797d-5332baa1a947"); /// - public readonly static UUID THUNDER = new UUID("e95c96a5-293c-bb7a-57ad-ce2e785ad85f"); + public static readonly UUID THUNDER = new UUID("e95c96a5-293c-bb7a-57ad-ce2e785ad85f"); /// - public readonly static UUID WINDOW_CLOSE = new UUID("2c346eda-b60c-ab33-1119-b8941916a499"); + public static readonly UUID WINDOW_CLOSE = new UUID("2c346eda-b60c-ab33-1119-b8941916a499"); /// - public readonly static UUID WINDOW_OPEN = new UUID("c80260ba-41fd-8a46-768a-6bf236360e3a"); + public static readonly UUID WINDOW_OPEN = new UUID("c80260ba-41fd-8a46-768a-6bf236360e3a"); /// - public readonly static UUID ZIPPER = new UUID("6cf2be26-90cb-2669-a599-f5ab7698225f"); + public static readonly UUID ZIPPER = new UUID("6cf2be26-90cb-2669-a599-f5ab7698225f"); /// @@ -153,11 +153,11 @@ namespace OpenMetaverse /// containing a name to identify the purpose of the sound public static Dictionary ToDictionary() { - Dictionary dict = new Dictionary(); - Type type = typeof(Sounds); + var dict = new Dictionary(); + var type = typeof(Sounds); foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { - dict.Add((UUID)field.GetValue(type), field.Name); + dict.Add((UUID)field.GetValue(type), field.Name); } return dict; } diff --git a/OpenMetaverse/TerrainCompressor.cs b/OpenMetaverse/TerrainCompressor.cs index 13d50bff..43ffd4ae 100644 --- a/OpenMetaverse/TerrainCompressor.cs +++ b/OpenMetaverse/TerrainCompressor.cs @@ -116,13 +116,14 @@ namespace OpenMetaverse public static LayerDataPacket CreateLayerDataPacket(TerrainPatch[] patches, TerrainPatch.LayerType type) { - LayerDataPacket layer = new LayerDataPacket(); - layer.LayerID.Type = (byte)type; + LayerDataPacket layer = new LayerDataPacket {LayerID = {Type = (byte) type}}; - TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader(); - header.Stride = STRIDE; - header.PatchSize = 16; - header.Type = type; + TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader + { + Stride = STRIDE, + PatchSize = 16, + Type = type + }; // Should be enough to fit even the most poorly packed data byte[] data = new byte[patches.Length * 16 * 16 * 2]; @@ -131,8 +132,8 @@ namespace OpenMetaverse bitpack.PackBits(header.PatchSize, 8); bitpack.PackBits((int)header.Type, 8); - for (int i = 0; i < patches.Length; i++) - CreatePatch(bitpack, patches[i].Data, patches[i].X, patches[i].Y); + foreach (TerrainPatch t in patches) + CreatePatch(bitpack, t.Data, t.X, t.Y); bitpack.PackBits(END_OF_PATCHES, 8); @@ -154,13 +155,14 @@ namespace OpenMetaverse /// public static LayerDataPacket CreateLandPacket(float[] heightmap, int[] patches) { - LayerDataPacket layer = new LayerDataPacket(); - layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land; + LayerDataPacket layer = new LayerDataPacket {LayerID = {Type = (byte) TerrainPatch.LayerType.Land}}; - TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader(); - header.Stride = STRIDE; - header.PatchSize = 16; - header.Type = TerrainPatch.LayerType.Land; + TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader + { + Stride = STRIDE, + PatchSize = 16, + Type = TerrainPatch.LayerType.Land + }; byte[] data = new byte[1536]; BitPack bitpack = new BitPack(data, 0); @@ -168,8 +170,8 @@ namespace OpenMetaverse bitpack.PackBits(header.PatchSize, 8); bitpack.PackBits((int)header.Type, 8); - for (int i = 0; i < patches.Length; i++) - CreatePatchFromHeightmap(bitpack, heightmap, patches[i] % 16, (patches[i] - (patches[i] % 16)) / 16); + foreach (int t in patches) + CreatePatchFromHeightmap(bitpack, heightmap, t % 16, (t - (t % 16)) / 16); bitpack.PackBits(END_OF_PATCHES, 8); @@ -181,13 +183,14 @@ namespace OpenMetaverse public static LayerDataPacket CreateLandPacket(float[] patchData, int x, int y) { - LayerDataPacket layer = new LayerDataPacket(); - layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land; + LayerDataPacket layer = new LayerDataPacket {LayerID = {Type = (byte) TerrainPatch.LayerType.Land}}; - TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader(); - header.Stride = STRIDE; - header.PatchSize = 16; - header.Type = TerrainPatch.LayerType.Land; + TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader + { + Stride = STRIDE, + PatchSize = 16, + Type = TerrainPatch.LayerType.Land + }; byte[] data = new byte[1536]; BitPack bitpack = new BitPack(data, 0); @@ -207,13 +210,14 @@ namespace OpenMetaverse public static LayerDataPacket CreateLandPacket(float[,] patchData, int x, int y) { - LayerDataPacket layer = new LayerDataPacket(); - layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land; + LayerDataPacket layer = new LayerDataPacket {LayerID = {Type = (byte) TerrainPatch.LayerType.Land}}; - TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader(); - header.Stride = STRIDE; - header.PatchSize = 16; - header.Type = TerrainPatch.LayerType.Land; + TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader + { + Stride = STRIDE, + PatchSize = 16, + Type = TerrainPatch.LayerType.Land + }; byte[] data = new byte[1536]; BitPack bitpack = new BitPack(data, 0); @@ -252,7 +256,7 @@ namespace OpenMetaverse if (patchData.Length != 16 * 16) throw new ArgumentException("Patch data must be a 16x16 array"); - TerrainPatch.Header header = PrescanPatch(patchData); + var header = PrescanPatch(patchData); header.QuantWBits = 136; header.PatchIDs = (y & 0x1F); header.PatchIDs += (x << 5); @@ -281,7 +285,7 @@ namespace OpenMetaverse if (x < 0 || x > 15 || y < 0 || y > 15) throw new ArgumentException("X and Y patch offsets must be from 0 to 15"); - TerrainPatch.Header header = PrescanPatch(heightmap, x, y); + var header = PrescanPatch(heightmap, x, y); header.QuantWBits = 136; header.PatchIDs = (y & 0x1F); header.PatchIDs += (x << 5); @@ -360,10 +364,9 @@ namespace OpenMetaverse public static TerrainPatch.Header DecodePatchHeader(BitPack bitpack) { - TerrainPatch.Header header = new TerrainPatch.Header(); + TerrainPatch.Header header = new TerrainPatch.Header {QuantWBits = bitpack.UnpackBits(8)}; // Quantized word bits - header.QuantWBits = bitpack.UnpackBits(8); if (header.QuantWBits == END_OF_PATCHES) return header; @@ -391,22 +394,21 @@ namespace OpenMetaverse wbits = (int)minWbits; - for (int i = 0; i < patch.Length; i++) + foreach (int t in patch) { - temp = patch[i]; + temp = t; - if (temp != 0) + if (temp == 0) continue; + + // Get the absolute value + if (temp < 0) temp *= -1; + + for (int j = (int)maxWbits; j > (int)minWbits; j--) { - // Get the absolute value - if (temp < 0) temp *= -1; - - for (int j = (int)maxWbits; j > (int)minWbits; j--) + if ((temp & (1 << j)) != 0) { - if ((temp & (1 << j)) != 0) - { - if (j > wbits) wbits = j; - break; - } + if (j > wbits) wbits = j; + break; } } } @@ -433,16 +435,13 @@ namespace OpenMetaverse private static void IDCTColumn16(float[] linein, float[] lineout, int column) { - float total; - int usize; - for (int n = 0; n < 16; n++) { - total = OO_SQRT2 * linein[column]; + var total = OO_SQRT2 * linein[column]; for (int u = 1; u < 16; u++) { - usize = u * 16; + var usize = u * 16; total += linein[usize + column] * CosineTable16[usize + n]; } @@ -454,11 +453,10 @@ namespace OpenMetaverse { const float oosob = 2.0f / 16.0f; int lineSize = line * 16; - float total; for (int n = 0; n < 16; n++) { - total = OO_SQRT2 * linein[lineSize]; + var total = OO_SQRT2 * linein[lineSize]; for (int u = 1; u < 16; u++) { @@ -521,11 +519,10 @@ namespace OpenMetaverse public static void DecodePatch(int[] patches, BitPack bitpack, TerrainPatch.Header header, int size) { - int temp; for (int n = 0; n < size * size; n++) { // ? - temp = bitpack.UnpackBits(1); + var temp = bitpack.UnpackBits(1); if (temp != 0) { // Value or EOB @@ -567,9 +564,6 @@ namespace OpenMetaverse private static void EncodePatch(BitPack output, int[] patch, int postquant, int wbits) { - int temp; - bool eob; - if (postquant > 16 * 16 || postquant < 0) { Logger.Log("Postquant is outside the range of allowed values in EncodePatch()", Helpers.LogLevel.Error); @@ -580,12 +574,11 @@ namespace OpenMetaverse for (int i = 0; i < 16 * 16; i++) { - eob = false; - temp = patch[i]; + var temp = patch[i]; if (temp == 0) { - eob = true; + var eob = true; for (int j = i; j < 16 * 16 - postquant; j++) { @@ -601,10 +594,7 @@ namespace OpenMetaverse output.PackBits(ZERO_EOB, 2); return; } - else - { - output.PackBits(ZERO_CODE, 1); - } + output.PackBits(ZERO_CODE, 1); } else { diff --git a/OpenMetaverse/TerrainManager.cs b/OpenMetaverse/TerrainManager.cs index 8438fc60..47dd5ec2 100644 --- a/OpenMetaverse/TerrainManager.cs +++ b/OpenMetaverse/TerrainManager.cs @@ -25,7 +25,6 @@ */ using System; -using System.Collections.Generic; using OpenMetaverse.Packets; namespace OpenMetaverse @@ -42,8 +41,7 @@ namespace OpenMetaverse protected virtual void OnLandPatchReceived(LandPatchReceivedEventArgs e) { EventHandler handler = m_LandPatchReceivedEvent; - if (handler != null) - handler(this, e); + handler?.Invoke(this, e); } /// Thread sync lock object @@ -57,7 +55,7 @@ namespace OpenMetaverse } #endregion - private GridClient Client; + private readonly GridClient Client; /// /// Default constructor @@ -108,10 +106,12 @@ namespace OpenMetaverse if (Client.Settings.STORE_LAND_PATCHES) { - TerrainPatch patch = new TerrainPatch(); - patch.Data = heightmap; - patch.X = x; - patch.Y = y; + TerrainPatch patch = new TerrainPatch + { + Data = heightmap, + X = x, + Y = y + }; simulator.Terrain[y * 16 + x] = patch; } } @@ -182,7 +182,7 @@ namespace OpenMetaverse DecompressCloud(e.Simulator, bitpack, header); break; default: - Logger.Log("Unrecognized LayerData type " + type.ToString(), Helpers.LogLevel.Warning, Client); + Logger.Log("Unrecognized LayerData type " + type, Helpers.LogLevel.Warning, Client); break; } } @@ -199,23 +199,27 @@ namespace OpenMetaverse private readonly float[] m_HeightMap; /// Simulator from that sent tha data - public Simulator Simulator { get { return m_Simulator; } } + public Simulator Simulator => m_Simulator; + /// Sim coordinate of the patch - public int X { get { return m_X; } } + public int X => m_X; + /// Sim coordinate of the patch - public int Y { get { return m_Y; } } + public int Y => m_Y; + /// Size of tha patch - public int PatchSize { get { return m_PatchSize; } } + public int PatchSize => m_PatchSize; + /// Heightmap for the patch - public float[] HeightMap { get { return m_HeightMap; } } + public float[] HeightMap => m_HeightMap; public LandPatchReceivedEventArgs(Simulator simulator, int x, int y, int patchSize, float[] heightMap) { - this.m_Simulator = simulator; - this.m_X = x; - this.m_Y = y; - this.m_PatchSize = patchSize; - this.m_HeightMap = heightMap; + m_Simulator = simulator; + m_X = x; + m_Y = y; + m_PatchSize = patchSize; + m_HeightMap = heightMap; } } #endregion diff --git a/OpenMetaverse/TexturePipeline.cs b/OpenMetaverse/TexturePipeline.cs index e11c2af7..7b8e827c 100644 --- a/OpenMetaverse/TexturePipeline.cs +++ b/OpenMetaverse/TexturePipeline.cs @@ -139,7 +139,7 @@ namespace OpenMetaverse private System.Timers.Timer RefreshDownloadsTimer; /// Current number of pending and in-process transfers - public int TransferCount { get { return _Transfers.Count; } } + public int TransferCount => _Transfers.Count; /// /// Default constructor, Instantiates a new copy of the TexturePipeline class @@ -185,9 +185,11 @@ namespace OpenMetaverse if (downloadMaster == null) { // Instantiate master thread that manages the request pool - downloadMaster = new Thread(DownloadThread); - downloadMaster.Name = "TexturePipeline"; - downloadMaster.IsBackground = true; + downloadMaster = new Thread(DownloadThread) + { + Name = "TexturePipeline", + IsBackground = true + }; } _Running = true; @@ -215,7 +217,7 @@ namespace OpenMetaverse Logger.Log(String.Format("Combined Execution Time: {0}, Network Execution Time {1}, Network {2}K/sec, Image Size {3}", TotalTime, NetworkTime, Math.Round(TotalBytes / NetworkTime.TotalSeconds / 60, 2), TotalBytes), Helpers.LogLevel.Debug); #endif - if(null != RefreshDownloadsTimer) RefreshDownloadsTimer.Dispose(); + RefreshDownloadsTimer?.Dispose(); RefreshDownloadsTimer = null; if (downloadMaster != null && downloadMaster.IsAlive) @@ -231,9 +233,10 @@ namespace OpenMetaverse lock (_Transfers) _Transfers.Clear(); - for (int i = 0; i < resetEvents.Length; i++) - if (resetEvents[i] != null) - resetEvents[i].Set(); + foreach (AutoResetEvent t in resetEvents) + { + t?.Set(); + } _Running = false; } @@ -244,27 +247,25 @@ namespace OpenMetaverse { foreach (TaskInfo transfer in _Transfers.Values) { - if (transfer.State == TextureRequestState.Progress) - { - ImageDownload download = transfer.Transfer; + if (transfer.State != TextureRequestState.Progress) continue; + ImageDownload download = transfer.Transfer; - // Find the first missing packet in the download - ushort packet = 0; - lock (download) if (download.PacketsSeen != null && download.PacketsSeen.Count > 0) + // Find the first missing packet in the download + ushort packet = 0; + lock (download) if (download.PacketsSeen != null && download.PacketsSeen.Count > 0) packet = GetFirstMissingPacket(download.PacketsSeen); - if (download.TimeSinceLastPacket > 5000) - { - // We're not receiving data for this texture fast enough, bump up the priority by 5% - download.Priority *= 1.05f; + if (download.TimeSinceLastPacket > 5000) + { + // We're not receiving data for this texture fast enough, bump up the priority by 5% + download.Priority *= 1.05f; - download.TimeSinceLastPacket = 0; - RequestImage(download.ID, download.ImageType, download.Priority, download.DiscardLevel, packet); - } - if (download.TimeSinceLastPacket > _Client.Settings.PIPELINE_REQUEST_TIMEOUT) - { - resetEvents[transfer.RequestSlot].Set(); - } + download.TimeSinceLastPacket = 0; + RequestImage(download.ID, download.ImageType, download.Priority, download.DiscardLevel, packet); + } + if (download.TimeSinceLastPacket > _Client.Settings.PIPELINE_REQUEST_TIMEOUT) + { + resetEvents[transfer.RequestSlot].Set(); } } } @@ -291,60 +292,62 @@ namespace OpenMetaverse /// from the beginning of the request public void RequestTexture(UUID textureID, ImageType imageType, float priority, int discardLevel, uint packetStart, TextureDownloadCallback callback, bool progressive) { - if (textureID == UUID.Zero) - return; + if (textureID == UUID.Zero)return; + if (callback == null) return; - if (callback != null) + if (_Client.Assets.Cache.HasAsset(textureID)) { - if (_Client.Assets.Cache.HasAsset(textureID)) + ImageDownload image = new ImageDownload { - ImageDownload image = new ImageDownload(); - image.ID = textureID; - image.AssetData = _Client.Assets.Cache.GetCachedAssetBytes(textureID); - image.Size = image.AssetData.Length; - image.Transferred = image.AssetData.Length; - image.ImageType = imageType; - image.AssetType = AssetType.Texture; - image.Success = true; + ID = textureID, + AssetData = _Client.Assets.Cache.GetCachedAssetBytes(textureID) + }; + image.Size = image.AssetData.Length; + image.Transferred = image.AssetData.Length; + image.ImageType = imageType; + image.AssetType = AssetType.Texture; + image.Success = true; - callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData)); + callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData)); - _Client.Assets.FireImageProgressEvent(image.ID, image.Transferred, image.Size); - } - else + _Client.Assets.FireImageProgressEvent(image.ID, image.Transferred, image.Size); + } + else + { + lock (_Transfers) { - lock (_Transfers) + TaskInfo request; + + if (_Transfers.TryGetValue(textureID, out request)) { - TaskInfo request; - - if (_Transfers.TryGetValue(textureID, out request)) + request.Callbacks.Add(callback); + } + else + { + request = new TaskInfo { - request.Callbacks.Add(callback); - } - else + State = TextureRequestState.Pending, + RequestID = textureID, + ReportProgress = progressive, + RequestSlot = -1, + Type = imageType, + Callbacks = new List {callback} + }; + + + ImageDownload downloadParams = new ImageDownload { - request = new TaskInfo(); - request.State = TextureRequestState.Pending; - request.RequestID = textureID; - request.ReportProgress = progressive; - request.RequestSlot = -1; - request.Type = imageType; + ID = textureID, + Priority = priority, + ImageType = imageType, + DiscardLevel = discardLevel + }; - request.Callbacks = new List(); - request.Callbacks.Add(callback); - - ImageDownload downloadParams = new ImageDownload(); - downloadParams.ID = textureID; - downloadParams.Priority = priority; - downloadParams.ImageType = imageType; - downloadParams.DiscardLevel = discardLevel; - - request.Transfer = downloadParams; + request.Transfer = downloadParams; #if DEBUG_TIMING request.StartTime = DateTime.UtcNow; #endif - _Transfers.Add(textureID, request); - } + _Transfers.Add(textureID, request); } } } @@ -394,16 +397,23 @@ namespace OpenMetaverse } // Build and send the request packet - RequestImagePacket request = new RequestImagePacket(); - request.AgentData.AgentID = _Client.Self.AgentID; - request.AgentData.SessionID = _Client.Self.SessionID; - request.RequestImage = new RequestImagePacket.RequestImageBlock[1]; - request.RequestImage[0] = new RequestImagePacket.RequestImageBlock(); - request.RequestImage[0].DiscardLevel = (sbyte)discardLevel; - request.RequestImage[0].DownloadPriority = priority; - request.RequestImage[0].Packet = packetNum; - request.RequestImage[0].Image = imageID; - request.RequestImage[0].Type = (byte)type; + RequestImagePacket request = new RequestImagePacket + { + AgentData = + { + AgentID = _Client.Self.AgentID, + SessionID = _Client.Self.SessionID + }, + RequestImage = new RequestImagePacket.RequestImageBlock[1] + }; + request.RequestImage[0] = new RequestImagePacket.RequestImageBlock + { + DiscardLevel = (sbyte) discardLevel, + DownloadPriority = priority, + Packet = packetNum, + Image = imageID, + Type = (byte) type + }; _Client.Network.SendPacket(request, _Client.Network.CurrentSim); } @@ -421,41 +431,47 @@ namespace OpenMetaverse public void AbortTextureRequest(UUID textureID) { TaskInfo task; - if (TryGetTransferValue(textureID, out task)) + if (!TryGetTransferValue(textureID, out task)) return; + + // this means we've actually got the request assigned to the threadpool + if (task.State == TextureRequestState.Progress) { - // this means we've actually got the request assigned to the threadpool - if (task.State == TextureRequestState.Progress) + RequestImagePacket request = new RequestImagePacket { - RequestImagePacket request = new RequestImagePacket(); - request.AgentData.AgentID = _Client.Self.AgentID; - request.AgentData.SessionID = _Client.Self.SessionID; - request.RequestImage = new RequestImagePacket.RequestImageBlock[1]; - request.RequestImage[0] = new RequestImagePacket.RequestImageBlock(); - request.RequestImage[0].DiscardLevel = -1; - request.RequestImage[0].DownloadPriority = 0; - request.RequestImage[0].Packet = 0; - request.RequestImage[0].Image = textureID; - request.RequestImage[0].Type = (byte)task.Type; - _Client.Network.SendPacket(request); - - foreach (TextureDownloadCallback callback in task.Callbacks) - callback(TextureRequestState.Aborted, new AssetTexture(textureID, Utils.EmptyBytes)); - - _Client.Assets.FireImageProgressEvent(task.RequestID, task.Transfer.Transferred, task.Transfer.Size); - - resetEvents[task.RequestSlot].Set(); - - RemoveTransfer(textureID); - } - else + AgentData = + { + AgentID = _Client.Self.AgentID, + SessionID = _Client.Self.SessionID + }, + RequestImage = new RequestImagePacket.RequestImageBlock[1] + }; + request.RequestImage[0] = new RequestImagePacket.RequestImageBlock { - RemoveTransfer(textureID); + DiscardLevel = -1, + DownloadPriority = 0, + Packet = 0, + Image = textureID, + Type = (byte) task.Type + }; + _Client.Network.SendPacket(request); - foreach (TextureDownloadCallback callback in task.Callbacks) - callback(TextureRequestState.Aborted, new AssetTexture(textureID, Utils.EmptyBytes)); + foreach (var callback in task.Callbacks) + callback(TextureRequestState.Aborted, new AssetTexture(textureID, Utils.EmptyBytes)); - _Client.Assets.FireImageProgressEvent(task.RequestID, task.Transfer.Transferred, task.Transfer.Size); - } + _Client.Assets.FireImageProgressEvent(task.RequestID, task.Transfer.Transferred, task.Transfer.Size); + + resetEvents[task.RequestSlot].Set(); + + RemoveTransfer(textureID); + } + else + { + RemoveTransfer(textureID); + + foreach (var callback in task.Callbacks) + callback(TextureRequestState.Aborted, new AssetTexture(textureID, Utils.EmptyBytes)); + + _Client.Assets.FireImageProgressEvent(task.RequestID, task.Transfer.Transferred, task.Transfer.Size); } } @@ -464,8 +480,6 @@ namespace OpenMetaverse /// private void DownloadThread() { - int slot; - while (_Running) { // find free slots @@ -478,21 +492,22 @@ namespace OpenMetaverse { foreach (KeyValuePair request in _Transfers) { - if (request.Value.State == TextureRequestState.Pending) + switch (request.Value.State) { - nextTask = request.Value; - ++pending; - } - else if (request.Value.State == TextureRequestState.Progress) - { - ++active; + case TextureRequestState.Pending: + nextTask = request.Value; + ++pending; + break; + case TextureRequestState.Progress: + ++active; + break; } } } if (pending > 0 && active <= maxTextureRequests) { - slot = -1; + var slot = -1; // find available slot for reset event lock (lockerObject) { @@ -713,7 +728,7 @@ namespace OpenMetaverse RemoveTransfer(task.Transfer.ID); resetEvents[task.RequestSlot].Set(); // free up request slot _Client.Assets.Cache.SaveAssetToCache(task.RequestID, task.Transfer.AssetData); - foreach (TextureDownloadCallback callback in task.Callbacks) + foreach (var callback in task.Callbacks) callback(TextureRequestState.Finished, new AssetTexture(task.RequestID, task.Transfer.AssetData)); _Client.Assets.FireImageProgressEvent(task.RequestID, task.Transfer.Transferred, task.Transfer.Size); @@ -722,7 +737,7 @@ namespace OpenMetaverse { if (task.ReportProgress) { - foreach (TextureDownloadCallback callback in task.Callbacks) + foreach (var callback in task.Callbacks) callback(TextureRequestState.Progress, new AssetTexture(task.RequestID, task.Transfer.AssetData)); } @@ -787,7 +802,7 @@ namespace OpenMetaverse _Client.Assets.Cache.SaveAssetToCache(task.RequestID, task.Transfer.AssetData); - foreach (TextureDownloadCallback callback in task.Callbacks) + foreach (var callback in task.Callbacks) callback(TextureRequestState.Finished, new AssetTexture(task.RequestID, task.Transfer.AssetData)); _Client.Assets.FireImageProgressEvent(task.RequestID, task.Transfer.Transferred, task.Transfer.Size); @@ -796,7 +811,7 @@ namespace OpenMetaverse { if (task.ReportProgress) { - foreach (TextureDownloadCallback callback in task.Callbacks) + foreach (var callback in task.Callbacks) callback(TextureRequestState.Progress, new AssetTexture(task.RequestID, task.Transfer.AssetData)); } diff --git a/OpenMetaverse/ThreadUtil.cs b/OpenMetaverse/ThreadUtil.cs index e3937b49..790a0378 100644 --- a/OpenMetaverse/ThreadUtil.cs +++ b/OpenMetaverse/ThreadUtil.cs @@ -2,7 +2,6 @@ // http://www.eggheadcafe.com/articles/20060727.asp using System; -using System.Threading; /// /// @@ -21,13 +20,13 @@ public class ThreadUtil /// which in turn calls the DynamicInvoke method of the wrapped /// delegate /// - static DelegateWrapper wrapperInstance = new DelegateWrapper(InvokeWrappedDelegate); + static readonly DelegateWrapper wrapperInstance = InvokeWrappedDelegate; /// /// Callback used to call EndInvoke on the asynchronously /// invoked DelegateWrapper /// - static AsyncCallback callback = new AsyncCallback(EndWrapperInvoke); + static readonly AsyncCallback callback = EndWrapperInvoke; /// /// Executes the specified delegate with the specified arguments @@ -48,7 +47,7 @@ public class ThreadUtil /// /// /// - static void InvokeWrappedDelegate(Delegate d, object[] args) + private static void InvokeWrappedDelegate(Delegate d, object[] args) { d.DynamicInvoke(args); } @@ -58,7 +57,7 @@ public class ThreadUtil /// to prevent resource leaks /// /// - static void EndWrapperInvoke(IAsyncResult ar) + public static void EndWrapperInvoke(IAsyncResult ar) { wrapperInstance.EndInvoke(ar); ar.AsyncWaitHandle.Close(); diff --git a/OpenMetaverse/UDPBase.cs b/OpenMetaverse/UDPBase.cs index 52d10363..2ac82620 100644 --- a/OpenMetaverse/UDPBase.cs +++ b/OpenMetaverse/UDPBase.cs @@ -28,7 +28,6 @@ using System; using System.Net; using System.Net.Sockets; -using System.Threading; namespace OpenMetaverse { @@ -58,7 +57,7 @@ namespace OpenMetaverse /// Initialize the UDP packet handler in server mode /// /// Port to listening for incoming UDP packets on - public UDPBase(int port) + protected UDPBase(int port) { udpPort = port; } @@ -67,7 +66,7 @@ namespace OpenMetaverse /// Initialize the UDP packet handler in client mode /// /// Remote UDP server to connect to - public UDPBase(IPEndPoint endPoint) + protected UDPBase(IPEndPoint endPoint) { remoteEndPoint = endPoint; udpPort = 0; @@ -78,42 +77,41 @@ namespace OpenMetaverse /// public void Start() { - if (shutdownFlag) + if (!shutdownFlag) return; + + const int SIO_UDP_CONNRESET = -1744830452; + + IPEndPoint ipep = new IPEndPoint(Settings.BIND_ADDR, udpPort); + udpSocket = new Socket( + AddressFamily.InterNetwork, + SocketType.Dgram, + ProtocolType.Udp); + try { - const int SIO_UDP_CONNRESET = -1744830452; - - IPEndPoint ipep = new IPEndPoint(Settings.BIND_ADDR, udpPort); - udpSocket = new Socket( - AddressFamily.InterNetwork, - SocketType.Dgram, - ProtocolType.Udp); - try - { - // this udp socket flag is not supported under mono, - // so we'll catch the exception and continue - udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null); - } - catch (SocketException) - { - Logger.DebugLog("UDP SIO_UDP_CONNRESET flag not supported on this platform"); - } - - // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. This means that - // when running multiple connections, two can occasionally bind to the same port, leading to unexpected - // errors as they intercept each others messages. We need to prevent this. This is not allowed by - // default on Windows. - udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); - - udpSocket.Bind(ipep); - - // we're not shutting down, we're starting up - shutdownFlag = false; - - // kick off an async receive. The Start() method will return, the - // actual receives will occur asynchronously and will be caught in - // AsyncEndRecieve(). - AsyncBeginReceive(); + // this udp socket flag is not supported under mono, + // so we'll catch the exception and continue + udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null); } + catch (SocketException) + { + Logger.DebugLog("UDP SIO_UDP_CONNRESET flag not supported on this platform"); + } + + // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. This means that + // when running multiple connections, two can occasionally bind to the same port, leading to unexpected + // errors as they intercept each others messages. We need to prevent this. This is not allowed by + // default on Windows. + udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); + + udpSocket.Bind(ipep); + + // we're not shutting down, we're starting up + shutdownFlag = false; + + // kick off an async receive. The Start() method will return, the + // actual receives will occur asynchronously and will be caught in + // AsyncEndRecieve(). + AsyncBeginReceive(); } /// @@ -121,24 +119,20 @@ namespace OpenMetaverse /// public void Stop() { - if (!shutdownFlag) - { - // wait indefinitely for a writer lock. Once this is called, the .NET runtime - // will deny any more reader locks, in effect blocking all other send/receive - // threads. Once we have the lock, we set shutdownFlag to inform the other - // threads that the socket is closed. - shutdownFlag = true; - udpSocket.Close(); - } + if (shutdownFlag) return; + + // wait indefinitely for a writer lock. Once this is called, the .NET runtime + // will deny any more reader locks, in effect blocking all other send/receive + // threads. Once we have the lock, we set shutdownFlag to inform the other + // threads that the socket is closed. + shutdownFlag = true; + udpSocket.Close(); } /// /// /// - public bool IsRunning - { - get { return !shutdownFlag; } - } + public bool IsRunning => !shutdownFlag; private void AsyncBeginReceive() { @@ -146,113 +140,109 @@ namespace OpenMetaverse //WrappedObject wrappedBuffer = Pool.CheckOut(); UDPPacketBuffer buf = new UDPPacketBuffer(); - if (!shutdownFlag) - { - try - { - // kick off an async read - udpSocket.BeginReceiveFrom( - //wrappedBuffer.Instance.Data, - buf.Data, - 0, - UDPPacketBuffer.BUFFER_SIZE, - SocketFlags.None, - ref buf.RemoteEndPoint, - AsyncEndReceive, - //wrappedBuffer); - buf); - } - catch (SocketException e) - { - if (e.SocketErrorCode == SocketError.ConnectionReset) - { - Logger.Log("SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + udpPort, Helpers.LogLevel.Error); - bool salvaged = false; - while (!salvaged) - { - try - { - udpSocket.BeginReceiveFrom( - //wrappedBuffer.Instance.Data, - buf.Data, - 0, - UDPPacketBuffer.BUFFER_SIZE, - SocketFlags.None, - ref buf.RemoteEndPoint, - AsyncEndReceive, - //wrappedBuffer); - buf); - salvaged = true; - } - catch (SocketException) { } - catch (ObjectDisposedException) { return; } - } + if (shutdownFlag) return; - Logger.Log("Salvaged the UDP listener on port " + udpPort, Helpers.LogLevel.Info); - } - } - catch (ObjectDisposedException) { } + try + { + // kick off an async read + udpSocket.BeginReceiveFrom( + //wrappedBuffer.Instance.Data, + buf.Data, + 0, + UDPPacketBuffer.BufferSize, + SocketFlags.None, + ref buf.RemoteEndPoint, + AsyncEndReceive, + //wrappedBuffer); + buf); } + catch (SocketException e) + { + if (e.SocketErrorCode == SocketError.ConnectionReset) + { + Logger.Log("SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + udpPort, Helpers.LogLevel.Error); + bool salvaged = false; + while (!salvaged) + { + try + { + udpSocket.BeginReceiveFrom( + //wrappedBuffer.Instance.Data, + buf.Data, + 0, + UDPPacketBuffer.BufferSize, + SocketFlags.None, + ref buf.RemoteEndPoint, + AsyncEndReceive, + //wrappedBuffer); + buf); + salvaged = true; + } + catch (SocketException) { } + catch (ObjectDisposedException) { return; } + } + + Logger.Log("Salvaged the UDP listener on port " + udpPort, Helpers.LogLevel.Info); + } + } + catch (ObjectDisposedException) { } } private void AsyncEndReceive(IAsyncResult iar) { // Asynchronous receive operations will complete here through the call // to AsyncBeginReceive - if (!shutdownFlag) + if (shutdownFlag) return; + + // start another receive - this keeps the server going! + AsyncBeginReceive(); + + // get the buffer that was created in AsyncBeginReceive + // this is the received data + //WrappedObject wrappedBuffer = (WrappedObject)iar.AsyncState; + //UDPPacketBuffer buffer = wrappedBuffer.Instance; + UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState; + + try { - // start another receive - this keeps the server going! - AsyncBeginReceive(); + // get the length of data actually read from the socket, store it with the + // buffer + buffer.DataLength = udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint); - // get the buffer that was created in AsyncBeginReceive - // this is the received data - //WrappedObject wrappedBuffer = (WrappedObject)iar.AsyncState; - //UDPPacketBuffer buffer = wrappedBuffer.Instance; - UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState; - - try - { - // get the length of data actually read from the socket, store it with the - // buffer - buffer.DataLength = udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint); - - // call the abstract method PacketReceived(), passing the buffer that - // has just been filled from the socket read. - PacketReceived(buffer); - } - catch (SocketException) { } - catch (ObjectDisposedException) { } - //finally { wrappedBuffer.Dispose(); } + // call the abstract method PacketReceived(), passing the buffer that + // has just been filled from the socket read. + PacketReceived(buffer); } + catch (SocketException) { } + catch (ObjectDisposedException) { } + //finally { wrappedBuffer.Dispose(); } } public void AsyncBeginSend(UDPPacketBuffer buf) { - if (!shutdownFlag) + if (shutdownFlag) return; + try { - try - { - // Profiling heavily loaded clients was showing better performance with - // synchronous UDP packet sending - udpSocket.SendTo( - buf.Data, - 0, - buf.DataLength, - SocketFlags.None, - buf.RemoteEndPoint); + // Profiling heavily loaded clients was showing better performance with + // synchronous UDP packet sending + udpSocket.SendTo( + buf.Data, + 0, + buf.DataLength, + SocketFlags.None, + buf.RemoteEndPoint); - //udpSocket.BeginSendTo( - // buf.Data, - // 0, - // buf.DataLength, - // SocketFlags.None, - // buf.RemoteEndPoint, - // AsyncEndSend, - // buf); - } - catch (SocketException) { } - catch (ObjectDisposedException) { } + //udpSocket.BeginSendTo( + // buf.Data, + // 0, + // buf.DataLength, + // SocketFlags.None, + // buf.RemoteEndPoint, + // AsyncEndSend, + // buf); } + catch (SocketException) { } + catch (ObjectDisposedException) { } } //void AsyncEndSend(IAsyncResult result) diff --git a/OpenMetaverse/UtilizationStatistics.cs b/OpenMetaverse/UtilizationStatistics.cs index 5f07aecb..904345fb 100644 --- a/OpenMetaverse/UtilizationStatistics.cs +++ b/OpenMetaverse/UtilizationStatistics.cs @@ -24,12 +24,8 @@ * POSSIBILITY OF SUCH DAMAGE. */ - -using System; -using System.Text; using System.Threading; using System.Collections.Generic; -using OpenMetaverse.Packets; namespace OpenMetaverse.Stats { @@ -51,15 +47,15 @@ namespace OpenMetaverse.Stats public Stat(Type type, long txCount, long rxCount, long txBytes, long rxBytes) { - this.Type = type; - this.TxCount = txCount; - this.RxCount = rxCount; - this.TxBytes = txBytes; - this.RxBytes = rxBytes; + Type = type; + TxCount = txCount; + RxCount = rxCount; + TxBytes = txBytes; + RxBytes = rxBytes; } } - private Dictionary m_StatsCollection; + private readonly Dictionary m_StatsCollection; public UtilizationStatistics() { @@ -87,10 +83,7 @@ namespace OpenMetaverse.Stats } else { Stat stat; - if (txBytes > 0) - stat = new Stat(Type, 1, 0, txBytes, 0); - else - stat = new Stat(Type, 0, 1, 0, rxBytes); + stat = txBytes > 0 ? new Stat(Type, 1, 0, txBytes, 0) : new Stat(Type, 0, 1, 0, rxBytes); m_StatsCollection.Add(key, stat); } diff --git a/OpenMetaverse/WorkPool.cs b/OpenMetaverse/WorkPool.cs index 91f2ec70..af4e5177 100644 --- a/OpenMetaverse/WorkPool.cs +++ b/OpenMetaverse/WorkPool.cs @@ -106,7 +106,7 @@ namespace OpenMetaverse private static Type WorkItemCallbackType; private static MethodInfo QueueWorkItemFunc, QueueWorkItemFunc2; private static MethodInfo ShutdownFunc; - private static Func Invoker; + private static Func Invoker; public static bool Init() { @@ -123,9 +123,9 @@ namespace OpenMetaverse STPStartInfo.GetProperty("ThreadPoolName").SetValue(param, "LibOpenMetaverse Main ThreadPool", null); STPStartInfo.GetProperty("AreThreadsBackground").SetValue(param, true, null); STPStartInfo.GetProperty("MinWorkerThreads").SetValue(param, 2, null); - Pool = Activator.CreateInstance(SmartThreadPoolType, new object[] { param }); - QueueWorkItemFunc = SmartThreadPoolType.GetMethod("QueueWorkItem", new Type[] { WorkItemCallbackType }); - QueueWorkItemFunc2 = SmartThreadPoolType.GetMethod("QueueWorkItem", new Type[] { WorkItemCallbackType, typeof(object) }); + Pool = Activator.CreateInstance(SmartThreadPoolType, param); + QueueWorkItemFunc = SmartThreadPoolType.GetMethod("QueueWorkItem", new[] { WorkItemCallbackType }); + QueueWorkItemFunc2 = SmartThreadPoolType.GetMethod("QueueWorkItem", new[] { WorkItemCallbackType, typeof(object) }); ShutdownFunc = SmartThreadPoolType.GetMethod("Shutdown", new Type[] { }); Invoker = (inv, state) => @@ -145,11 +145,9 @@ namespace OpenMetaverse public static void Shutdown() { - if (Pool != null) - { - ShutdownFunc.Invoke(Pool, null); - Pool = null; - } + if (Pool == null) return; + ShutdownFunc.Invoke(Pool, null); + Pool = null; } @@ -161,19 +159,19 @@ namespace OpenMetaverse } else { - System.Threading.ThreadPool.QueueUserWorkItem(state => callback.Invoke(state)); + ThreadPool.QueueUserWorkItem(callback.Invoke); } } - public static void QueueUserWorkItem(System.Threading.WaitCallback callback, object state) + public static void QueueUserWorkItem(WaitCallback callback, object state) { if (Pool != null) { - QueueWorkItemFunc2.Invoke(Pool, new object[] { Delegate.CreateDelegate(WorkItemCallbackType, callback, Invoker.Method), state }); + QueueWorkItemFunc2.Invoke(Pool, new[] { Delegate.CreateDelegate(WorkItemCallbackType, callback, Invoker.Method), state }); } else { - System.Threading.ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); + ThreadPool.QueueUserWorkItem(callback.Invoke, state); } } } @@ -181,52 +179,44 @@ namespace OpenMetaverse public static class WorkPool { - private static bool UseSmartThreadPool = false; + private static bool UseSmartThreadPool; public static bool Init(bool useSmartThredPool) { - if (useSmartThredPool) - { - if (WorkPoolDynamic.Init()) - { - UseSmartThreadPool = true; - return true; - } - return false; - } + if (!useSmartThredPool) return true; + if (!WorkPoolDynamic.Init()) return false; + UseSmartThreadPool = true; return true; } public static void Shutdown() { - if (UseSmartThreadPool) - { - WorkPoolDynamic.Shutdown(); - UseSmartThreadPool = false; - } + if (!UseSmartThreadPool) return; + WorkPoolDynamic.Shutdown(); + UseSmartThreadPool = false; } - public static void QueueUserWorkItem(System.Threading.WaitCallback callback) + public static void QueueUserWorkItem(WaitCallback callback) { if (UseSmartThreadPool) { - WorkPoolDynamic.QueueUserWorkItem(sync => callback.Invoke(sync)); + WorkPoolDynamic.QueueUserWorkItem(callback.Invoke); } else { - ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync)); + ThreadPool.QueueUserWorkItem(callback.Invoke); } } - public static void QueueUserWorkItem(System.Threading.WaitCallback callback, object state) + public static void QueueUserWorkItem(WaitCallback callback, object state) { if (UseSmartThreadPool) { - WorkPoolDynamic.QueueUserWorkItem(sync => callback.Invoke(sync), state); + WorkPoolDynamic.QueueUserWorkItem(callback.Invoke, state); } else { - ThreadPool.QueueUserWorkItem(sync => callback.Invoke(sync), state); + ThreadPool.QueueUserWorkItem(callback.Invoke, state); } } } diff --git a/Programs/AvatarPreview/GLMesh.cs b/Programs/AvatarPreview/GLMesh.cs index 77056c9e..22e2320a 100644 --- a/Programs/AvatarPreview/GLMesh.cs +++ b/Programs/AvatarPreview/GLMesh.cs @@ -15,7 +15,7 @@ namespace AvatarPreview /// Subclass of LODMesh that adds an index array suitable for pushing /// direct to OpenGL /// - new public class LODMesh : LindenMesh.LODMesh + public new class LODMesh : LindenMesh.LODMesh { public ushort[] Indices; @@ -25,8 +25,8 @@ namespace AvatarPreview // Generate the index array Indices = new ushort[_numFaces * 3]; - int current = 0; - for (int i = 0; i < _numFaces; i++) + var current = 0; + for (var i = 0; i < _numFaces; i++) { Indices[current++] = (ushort)_faces[i].Indices[0]; Indices[current++] = (ushort)_faces[i].Indices[1]; @@ -57,56 +57,56 @@ namespace AvatarPreview { base.LoadMesh(filename); - float minX, minY, minZ; - minX = minY = minZ = Single.MaxValue; - float maxX, maxY, maxZ; - maxX = maxY = maxZ = Single.MinValue; + float minY, minZ; + var minX = minY = minZ = Single.MaxValue; + float maxY, maxZ; + var maxX = maxY = maxZ = Single.MinValue; // Generate the vertex array - RenderData.Vertices = new float[NumVertices * 3]; + RenderData.Vertices = new float[NumVertices * 3]; int current = 0; - for (int i = 0; i < NumVertices; i++) + for (int i = 0; i < NumVertices; i++) { - RenderData.Vertices[current++] = Vertices[i].Coord.X; - RenderData.Vertices[current++] = Vertices[i].Coord.Y; - RenderData.Vertices[current++] = Vertices[i].Coord.Z; - - if (Vertices[i].Coord.X < minX) - minX = Vertices[i].Coord.X; - else if (Vertices[i].Coord.X > maxX) - maxX = Vertices[i].Coord.X; - - if (Vertices[i].Coord.Y < minY) - minY = Vertices[i].Coord.Y; - else if (Vertices[i].Coord.Y > maxY) - maxY = Vertices[i].Coord.Y; - - if (Vertices[i].Coord.Z < minZ) - minZ = Vertices[i].Coord.Z; - else if (Vertices[i].Coord.Z > maxZ) - maxZ = Vertices[i].Coord.Z; + RenderData.Vertices[current++] = Vertices[i].Coord.X; + RenderData.Vertices[current++] = Vertices[i].Coord.Y; + RenderData.Vertices[current++] = Vertices[i].Coord.Z; + + if (Vertices[i].Coord.X < minX) + minX = Vertices[i].Coord.X; + else if (Vertices[i].Coord.X > maxX) + maxX = Vertices[i].Coord.X; + + if (Vertices[i].Coord.Y < minY) + minY = Vertices[i].Coord.Y; + else if (Vertices[i].Coord.Y > maxY) + maxY = Vertices[i].Coord.Y; + + if (Vertices[i].Coord.Z < minZ) + minZ = Vertices[i].Coord.Z; + else if (Vertices[i].Coord.Z > maxZ) + maxZ = Vertices[i].Coord.Z; } // Calculate the center-point from the bounding box edges RenderData.Center = new Vector3((minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2); // Generate the index array - RenderData.Indices = new ushort[NumFaces * 3]; + RenderData.Indices = new ushort[NumFaces * 3]; current = 0; - for (int i = 0; i < NumFaces; i++) + for (int i = 0; i < NumFaces; i++) { - RenderData.Indices[current++] = (ushort)Faces[i].Indices[0]; - RenderData.Indices[current++] = (ushort)Faces[i].Indices[1]; - RenderData.Indices[current++] = (ushort)Faces[i].Indices[2]; + RenderData.Indices[current++] = (ushort)Faces[i].Indices[0]; + RenderData.Indices[current++] = (ushort)Faces[i].Indices[1]; + RenderData.Indices[current++] = (ushort)Faces[i].Indices[2]; } // Generate the texcoord array - RenderData.TexCoords = new float[NumVertices * 2]; + RenderData.TexCoords = new float[NumVertices * 2]; current = 0; - for (int i = 0; i < NumVertices; i++) + for (int i = 0; i < NumVertices; i++) { - RenderData.TexCoords[current++] = Vertices[i].TexCoord.X; - RenderData.TexCoords[current++] = Vertices[i].TexCoord.Y; + RenderData.TexCoords[current++] = Vertices[i].TexCoord.X; + RenderData.TexCoords[current++] = Vertices[i].TexCoord.Y; } } @@ -114,7 +114,7 @@ namespace AvatarPreview { LODMesh lod = new LODMesh(); lod.LoadMesh(filename); - LodMeshes[level] = lod; + LodMeshes[level] = lod; } } } diff --git a/Programs/AvatarPreview/Program.cs b/Programs/AvatarPreview/Program.cs index ca0b165b..51b8edff 100644 --- a/Programs/AvatarPreview/Program.cs +++ b/Programs/AvatarPreview/Program.cs @@ -4,13 +4,13 @@ using System.Windows.Forms; namespace AvatarPreview { - static class Program + internal static class Program { /// /// The main entry point for the application. /// [STAThread] - static void Main() + public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); diff --git a/Programs/AvatarPreview/frmAvatar.cs b/Programs/AvatarPreview/frmAvatar.cs index 5a8f7cc5..58977857 100644 --- a/Programs/AvatarPreview/frmAvatar.cs +++ b/Programs/AvatarPreview/frmAvatar.cs @@ -45,51 +45,49 @@ namespace AvatarPreview private void lindenLabMeshToolStripMenuItem_Click(object sender, EventArgs e) { - OpenFileDialog dialog = new OpenFileDialog(); - dialog.Filter = "avatar_lad.xml|avatar_lad.xml"; + var dialog = new OpenFileDialog {Filter = @"avatar_lad.xml|avatar_lad.xml"}; - if (dialog.ShowDialog() == DialogResult.OK) + if (dialog.ShowDialog() != DialogResult.OK) return; + + _meshes.Clear(); + + try { - _meshes.Clear(); + // Parse through avatar_lad.xml to find all of the mesh references + XmlDocument lad = new XmlDocument(); + lad.Load(dialog.FileName); - try + XmlNodeList meshes = lad.GetElementsByTagName("mesh"); + + foreach (XmlNode meshNode in meshes) { - // Parse through avatar_lad.xml to find all of the mesh references - XmlDocument lad = new XmlDocument(); - lad.Load(dialog.FileName); + string type = meshNode.Attributes.GetNamedItem("type").Value; + int lod = Int32.Parse(meshNode.Attributes.GetNamedItem("lod").Value); + string fileName = meshNode.Attributes.GetNamedItem("file_name").Value; + //string minPixelWidth = meshNode.Attributes.GetNamedItem("min_pixel_width").Value; - XmlNodeList meshes = lad.GetElementsByTagName("mesh"); + // Mash up the filename with the current path + fileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dialog.FileName), fileName); - foreach (XmlNode meshNode in meshes) + GLMesh mesh = (_meshes.ContainsKey(type) ? _meshes[type] : new GLMesh(type)); + + if (lod == 0) { - string type = meshNode.Attributes.GetNamedItem("type").Value; - int lod = Int32.Parse(meshNode.Attributes.GetNamedItem("lod").Value); - string fileName = meshNode.Attributes.GetNamedItem("file_name").Value; - //string minPixelWidth = meshNode.Attributes.GetNamedItem("min_pixel_width").Value; - - // Mash up the filename with the current path - fileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dialog.FileName), fileName); - - GLMesh mesh = (_meshes.ContainsKey(type) ? _meshes[type] : new GLMesh(type)); - - if (lod == 0) - { - mesh.LoadMesh(fileName); - } - else - { - mesh.LoadLODMesh(lod, fileName); - } - - _meshes[type] = mesh; - glControl_Resize(null, null); - glControl.Invalidate(); + mesh.LoadMesh(fileName); } + else + { + mesh.LoadLODMesh(lod, fileName); + } + + _meshes[type] = mesh; + glControl_Resize(null, null); + glControl.Invalidate(); } - catch (Exception ex) - { - MessageBox.Show("Failed to load avatar mesh: " + ex.Message); - } + } + catch (Exception ex) + { + MessageBox.Show(@"Failed to load avatar mesh: " + ex.Message); } } @@ -122,7 +120,7 @@ namespace AvatarPreview private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show( - "Written by John Hurliman (http://www.jhurliman.org/)"); + @"Written by John Hurliman (http://www.jhurliman.org/)"); } private void glControl_Paint(object sender, PaintEventArgs e) @@ -227,7 +225,7 @@ namespace AvatarPreview { try { - System.Drawing.Image image = System.Drawing.Image.FromFile(dialog.FileName); + Image image = Image.FromFile(dialog.FileName); #region Dimensions Check @@ -271,7 +269,7 @@ namespace AvatarPreview } catch (Exception ex) { - MessageBox.Show("Failed to load image: " + ex.Message); + MessageBox.Show(@"Failed to load image: " + ex.Message); } } else @@ -281,8 +279,8 @@ namespace AvatarPreview #region Baking - Dictionary paramValues = GetParamValues(); - Dictionary layers = + var paramValues = GetParamValues(); + var layers = new Dictionary(); int textureCount = 0; @@ -304,10 +302,9 @@ namespace AvatarPreview // Compute the head bake Baker baker = new Baker(BakeType.Head); - foreach (KeyValuePair kvp in layers) + foreach (var kvp in layers) { - AppearanceManager.TextureData tdata = new AppearanceManager.TextureData(); - tdata.Texture = kvp.Value; + AppearanceManager.TextureData tdata = new AppearanceManager.TextureData {Texture = kvp.Value}; baker.AddTexture(tdata); } @@ -322,7 +319,7 @@ namespace AvatarPreview } else { - MessageBox.Show("Failed to create the bake layer, unknown error"); + MessageBox.Show(@"Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Upper") @@ -379,7 +376,7 @@ namespace AvatarPreview } else { - MessageBox.Show("Failed to create the bake layer, unknown error"); + MessageBox.Show(@"Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Lower") @@ -436,7 +433,7 @@ namespace AvatarPreview } else { - MessageBox.Show("Failed to create the bake layer, unknown error"); + MessageBox.Show(@"Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Bake") @@ -450,9 +447,9 @@ namespace AvatarPreview private Dictionary GetParamValues() { - Dictionary paramValues = new Dictionary(VisualParams.Params.Count); + var paramValues = new Dictionary(VisualParams.Params.Count); - foreach (KeyValuePair kvp in VisualParams.Params) + foreach (var kvp in VisualParams.Params) { VisualParam vp = kvp.Value; paramValues.Add(vp.ParamID, vp.DefaultValue); diff --git a/Programs/Baker/Baker.cs b/Programs/Baker/Baker.cs index fba119b1..2d438c0f 100644 --- a/Programs/Baker/Baker.cs +++ b/Programs/Baker/Baker.cs @@ -4,17 +4,17 @@ using System.Windows.Forms; namespace Baker { - static class Baker + internal static class Baker { /// /// The main entry point for the application. /// [STAThread] - static void Main(string[] args) + private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new frmBaker()); + Application.Run(new FrmBaker()); } } } \ No newline at end of file diff --git a/Programs/Baker/frmBaker.Designer.cs b/Programs/Baker/frmBaker.Designer.cs index d1f8e958..3e502a9f 100644 --- a/Programs/Baker/frmBaker.Designer.cs +++ b/Programs/Baker/frmBaker.Designer.cs @@ -1,6 +1,6 @@ namespace Baker { - partial class frmBaker + partial class FrmBaker { /// /// Required designer variable. @@ -111,7 +111,7 @@ namespace Baker this.Controls.Add(this.scrollWeight); this.Controls.Add(this.cmdLoadShirt); this.Controls.Add(this.pic1); - this.Name = "frmBaker"; + this.Name = "FrmBaker"; this.Text = "Baker"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmBaker_FormClosing); this.Load += new System.EventHandler(this.frmBaker_Load); diff --git a/Programs/Baker/frmBaker.cs b/Programs/Baker/frmBaker.cs index f24ebfd0..7e167da9 100644 --- a/Programs/Baker/frmBaker.cs +++ b/Programs/Baker/frmBaker.cs @@ -1,21 +1,16 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; -using System.Drawing.Imaging; -using System.Text; using System.Windows.Forms; using System.IO; using OpenMetaverse.Imaging; namespace Baker { - public partial class frmBaker : Form + public partial class FrmBaker : Form { - Bitmap AlphaMask; + Bitmap _alphaMask; - public frmBaker() + public FrmBaker() { InitializeComponent(); } @@ -32,13 +27,13 @@ namespace Baker if (stream != null) { - AlphaMask = LoadTGAClass.LoadTGA(stream); + _alphaMask = LoadTGAClass.LoadTGA(stream); stream.Close(); //ManagedImage managedImage = new ManagedImage(AlphaMask); // FIXME: Operate on ManagedImage instead of Bitmap - pic1.Image = Oven.ModifyAlphaMask(AlphaMask, (byte)scrollWeight.Value, 0.0f); + pic1.Image = Oven.ModifyAlphaMask(_alphaMask, (byte)scrollWeight.Value, 0.0f); } else { @@ -49,7 +44,7 @@ namespace Baker private void scrollWeight_Scroll(object sender, ScrollEventArgs e) { - pic1.Image = Oven.ModifyAlphaMask(AlphaMask, (byte)scrollWeight.Value, 0.0f); + pic1.Image = Oven.ModifyAlphaMask(_alphaMask, (byte)scrollWeight.Value, 0.0f); } private void frmBaker_FormClosing(object sender, FormClosingEventArgs e)