From 7e4bdad41a973ba8e0cf439b545d91e4a3cbfd94 Mon Sep 17 00:00:00 2001 From: Latif Khalifa Date: Fri, 27 Jun 2014 11:15:54 +0200 Subject: [PATCH] Better hashcodes for Vectors and Vertices --- OpenMetaverse/Rendering/Rendering.cs | 32 +++++++++++++++++++++++++++- OpenMetaverseTypes/Vector2.cs | 4 +++- OpenMetaverseTypes/Vector3.cs | 5 ++++- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/OpenMetaverse/Rendering/Rendering.cs b/OpenMetaverse/Rendering/Rendering.cs index 06f09335..285ca561 100644 --- a/OpenMetaverse/Rendering/Rendering.cs +++ b/OpenMetaverse/Rendering/Rendering.cs @@ -80,7 +80,7 @@ namespace OpenMetaverse.Rendering #region Structs [StructLayout(LayoutKind.Explicit)] - public struct Vertex + public struct Vertex : IEquatable { [FieldOffset(0)] public Vector3 Position; @@ -93,6 +93,36 @@ namespace OpenMetaverse.Rendering { return String.Format("P: {0} N: {1} T: {2}", Position, Normal, TexCoord); } + + public override int GetHashCode() + { + int hash = Position.GetHashCode(); + hash = hash * 31 + Normal.GetHashCode(); + hash = hash * 31 + TexCoord.GetHashCode(); + return hash; + } + + public static bool operator ==(Vertex value1, Vertex value2) + { + return value1.Position == value2.Position + && value1.Normal == value2.Normal + && value1.TexCoord == value2.TexCoord; + } + + public static bool operator !=(Vertex value1, Vertex value2) + { + return !(value1 == value2); + } + + public override bool Equals(object obj) + { + return (obj is Vertex) ? this == (Vertex)obj : false; + } + + public bool Equals(Vertex other) + { + return this == other; + } } public struct ProfileFace diff --git a/OpenMetaverseTypes/Vector2.cs b/OpenMetaverseTypes/Vector2.cs index 14a90012..f2330bf2 100644 --- a/OpenMetaverseTypes/Vector2.cs +++ b/OpenMetaverseTypes/Vector2.cs @@ -355,7 +355,9 @@ namespace OpenMetaverse public override int GetHashCode() { - return X.GetHashCode() ^ Y.GetHashCode(); + int hash = X.GetHashCode(); + hash = hash * 31 + Y.GetHashCode(); + return hash; } /// diff --git a/OpenMetaverseTypes/Vector3.cs b/OpenMetaverseTypes/Vector3.cs index 834f9984..06285597 100644 --- a/OpenMetaverseTypes/Vector3.cs +++ b/OpenMetaverseTypes/Vector3.cs @@ -441,7 +441,10 @@ namespace OpenMetaverse public override int GetHashCode() { - return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); + int hash = X.GetHashCode(); + hash = hash * 31 + Y.GetHashCode(); + hash = hash * 31 + Z.GetHashCode(); + return hash; } ///