Extension methods

From XNAWiki
Jump to: navigation, search


Numbers

int

  • Random
       public static int Random(int begin, int end)
       {   // generate a sequence of numbers and randomize using the sorting approach
           return Enumerable.Range(begin, end).OrderBy(a => Guid.NewGuid());
       }

Graphics

Viewport

  • ToRectangle
       public static Rectangle ToRectangle(this Viewport vp)
       {
           return new Rectangle(vp.X, vp.Y, vp.Width, vp.Height);
       }
  • GetCenter
       public static Vector2 GetCenter(this Viewport viewPort)
       {
           return new Vector2(viewPort.Width / 2, viewPort.Height / 2);
       }

Vector2

  • ToPoint
       public static Point ToPoint(this Vector2 v)
       {
           return new Point((int)v.X, (int)v.Y);
       }
  • ToVector3
       public static Vector3 ToVector3(this Vector2 v)
       {
           return new Vector3(v.X, v.Y, 0);
       }

Texture2D

  • GetSourceRectangle
       public static Rectangle GetSourceRectangle(this Texture2D entity)
       {
           return new Rectangle(0, 0, entity.Width, entity.Height);
       }
  • GetSize

public static Vector2 GetSize(this Texture2D texture)

       {
           return new Vector2(texture.Width, texture.Height);
       }

Rectangle

  • CenterRectangle
       public static Rectangle CenterRectangle(this Rectangle r, int x, int y)
       {
           return new Rectangle(x - r.Center.X, y - r.Center.Y, r.Width, r.Height);
       }
  • GetSizeAsPoint
       public static Point GetSizeAsPoint(this Rectangle r)
       {
           return new Point(r.Width, r.Height);
       }
  • GetSizeAsVector2
       public static Vector2 GetSizeAsVector2(this Rectangle r)
       {
           return new Vector2(r.Width, r.Height);
       }
  • BottomRightAsPoint
       public static Point BottomRightAsPoint(this Rectangle r)
       {
          return new Point(r.Right, r.Bottom); 
       }
  • BottomRightAsVector2
       public static Vector2 BottomRightAsVector2(this Rectangle r)
       {
           return new Vector2(r.Right, r.Bottom);
       }
  • Contains
       public static bool Contains(this Rectangle r, float x, float y)
       {
           return x >= r.X && x <= r.X + r.Width && y >= r.Y && y <= r.Y + r.Height;
       }
       public static bool Contains(this Rectangle r, Vector2 pos)
       {
           return pos.X >= r.X && pos.X <= r.X + r.Width && pos.Y >= r.Y && pos.Y <= r.Y + r.Height;
       }
  • FromLTRB
       public static Rectangle FromLTRB(this Rectangle src, float left, float top, float right, float bottom)
       {
           return new Rectangle(src.X, src.Y, src.Right - src.X, src.Bottom - src.Y);
       }

Quaternion

  • Yaw
       public static Quaternion Yaw(this Quaternion q, float value)
       {
           return q * Quaternion.CreateFromYawPitchRoll(value, 0, 0);
       }
       public static void Yaw(this Quaternion q, float value, out Quaternion result)
       {
           result = q * Quaternion.CreateFromYawPitchRoll(value, 0, 0);
       }
       public static Quaternion Yaw(this Quaternion q, float value, bool normalize)
       {
           var ret = q * Quaternion.CreateFromYawPitchRoll(value, 0, 0);
           if (normalize) ret.Normalize();
           return ret;
       }
       public static void Yaw(this Quaternion q, float value, bool normalize, out Quaternion result)
       {
           result = q * Quaternion.CreateFromYawPitchRoll(value, 0, 0);
           if (normalize) result.Normalize();
       }
  • Pitch
       public static Quaternion Pitch(this Quaternion q, float value)
       {
           return q * Quaternion.CreateFromYawPitchRoll(0, value, 0);
       }
       public static void Pitch(this Quaternion q, float value, out Quaternion result)
       {
           result = q * Quaternion.CreateFromYawPitchRoll(0, value, 0);
       }
       public static Quaternion Pitch(this Quaternion q, float value, bool normalize)
       {
           var ret = q * Quaternion.CreateFromYawPitchRoll(0, value, 0);
           if (normalize) ret.Normalize();
           return ret;
       }
       public static void Pitch(this Quaternion q, float value, bool normalize, out Quaternion result)
       {
           result = q * Quaternion.CreateFromYawPitchRoll(0, value, 0);
           if (normalize) result.Normalize();
       }
  • Roll
       public static Quaternion Roll(this Quaternion q, float value)
       {
           return q * Quaternion.CreateFromYawPitchRoll(0, 0, value);
       }
       public static void Roll(this Quaternion q, float value, out Quaternion result)
       {
           result = q * Quaternion.CreateFromYawPitchRoll(0, 0, value);
       }
       public static Quaternion Roll(this Quaternion q, float value, bool normalize)
       {
           var ret = q * Quaternion.CreateFromYawPitchRoll(0, 0, value);
           if (normalize) ret.Normalize();
           return ret;
       }
       public static void Roll(this Quaternion q, float value, bool normalize, out Quaternion result)
       {
           result = q * Quaternion.CreateFromYawPitchRoll(0, 0, value);
           if (normalize) result.Normalize();
       }
  • ToYawPitchRoll
       public static void ToYawPitchRoll(this Quaternion q, out float yaw, out float pitch, out float roll)
       {
           var x = q.X;
           var y = q.Y;
           var z = q.Z;
           var w = q.W;
           yaw = (float) Math.Asin(-2f * (x * z - w * y));
           pitch = (float) Math.Atan2(2f * (y * z + w * x),
                                      w * w - x * x - y * y + z * z);
           roll = (float) Math.Atan2(2f * (x * y + w * z),
                                     w * w + x * x - y * y - z * z);
       }

Matrix

  • CreateRotationFromLine
       static Random = ms_random = new Random();
       public static Matrix CreateRotationFromLine(this Matrix math, Vector3 start, Vector3 end)
       {
           Vector3 p; // this vector should not be between start and end
           p.X = (float)ms_random.NextDouble();
           p.Y = (float)ms_random.NextDouble();
           p.Z = (float)ms_random.NextDouble();
           //
           Vector3 r = Vector3.Cross(p - start, end - start);
           Vector3 s = Vector3.Cross(r, end - start);
           r.Normalize();
           s.Normalize();
           //
           Vector3 forward = end - start;
           forward.Normalize();
           //
           float theta = 0;
           float rCosTheta = (float)Math.Cos(theta), 
                 rSinTheta = (float)Math.Sin(theta);
           //
           Vector3 up = new Vector3()
           {
               X = start.X + rCosTheta * r.X + rSinTheta * s.X,
               Y = start.Y + rCosTheta * r.Y + rSinTheta * s.Y,
               Z = start.Z + rCosTheta * r.Z + rSinTheta * s.Z
           };
           return Matrix.CreateWorld(start, forward, up);
       }

Model

  • BuildBoundingSphere
       public static BoundingSphere BuildBoundingSphere(this Model model)
       {
           BoundingSphere sphere=new BoundingSphere(Vector3.Zero,0);
           foreach (var mesh in model.Meshes)
           {
               sphere = BoundingSphere.CreateMerged(sphere, mesh.BoundingSphere);
           }
           return sphere;
       }

BoundingFrustum

  • BoundingFrustum
       public static BoundingFrustum BuildFrustum(this BoundingFrustum v, GraphicsDevice device,
                                        Vector3 up,
                                        float fov, float near, float far,
                                        Vector3 position,
                                        Vector3 target)
       {
           Matrix view = Matrix.CreateLookAt( position, target, up);
           Quaternion rotation = Quaternion.CreateFromRotationMatrix(Matrix.Invert(view));
           Matrix projection = Matrix.CreatePerspectiveFieldOfView(fov, device.Viewport.GetAspectRatio(), near, far);
           Matrix matrix = Matrix.CreateFromQuaternion(rotation);
           //Matrix matrix = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll);
           matrix.Translation = position;
           view = Matrix.Invert(matrix);
           var frustum = new BoundingFrustum(Matrix.Multiply(view, projection));
           return frustum;
       }
       public static BoundingFrustum BuildFrustum(this BoundingFrustum v, GraphicsDevice device,
                                                  Vector3 up,
                                                  float fov, float near, float far,
                                                  float yaw, float pitch, float roll,
                                                  float x, float y, float z,
                                                  float tx, float ty, float tz)
       {
           Matrix view = Matrix.CreateLookAt(new Vector3(x, y, z), new Vector3(tx, ty, tz), up);
           Quaternion rotation = Quaternion.CreateFromRotationMatrix(Matrix.Invert(view));
           Matrix projection = Matrix.CreatePerspectiveFieldOfView(fov, device.Viewport.GetAspectRatio(), near, far);
           Matrix matrix = Matrix.CreateFromQuaternion(rotation);
           matrix.Translation = new Vector3(x, y, z);                    
           view = Matrix.Invert(matrix);
           var frustum = new BoundingFrustum(Matrix.Multiply(view, projection));
           return frustum;     
       }

GameComponent

  • GetService
       public static T GetService<T>(this GameComponent component)
       {
           return (T) component.Game.Services.GetService(typeof (T));
       }

GameServiceContainer

  • GetService
       public static T GetService<T>(this GameServiceContainer service)
       {
           return (T) service.GetService(typeof (T));
       }

MouseState

  • GetPosition
       public static Vector2 GetPosition(this MouseState mouse)
       {
           return new Vector2(mouse.X, mouse.Y);
       }

Generics

  • Serialize
       public static void Serialize<T>(this T obj, string filename) where T : IContentSerializable
       {
               using (XmlWriter writer = XmlWriter.Create(filename, new XmlWriterSettings() { Indent = true }))
               {
                       IntermediateSerializer.Serialize(writer, obj, null);
               }
       }
  • IContentSerializable
       public interface IContentSerializable { }


  • Shuffling generic lists
       public static void Shuffle<T>(this List<T> listToShuffle, int numberOfTimesToShuffle = 5)
       {
           //make a new list of the wanted type
           List<T> newList = new List<T>();
           //for each time we want to shuffle
           for (int i = 0; i < numberOfTimesToShuffle; i++)
           {
               //while there are still items in our list
               while (listToShuffle.Count > 0)
               {
                   //get a random number within the list
                   int index = _rnd.Next(listToShuffle.Count);
                   //add the item at that position to the new list
                   newList.Add(listToShuffle[index]);
                   //and remove it from the old list
                   listToShuffle.RemoveAt(index);
               }
               //then copy all the items back in the old list again
               listToShuffle.AddRange(newList);
               //and clear the new list
               //to make ready for next shuffling
               newList.Clear();        
           }
       }
       //for getting random values
       private static Random _rnd = new Random();

float

  • ToNearestInt
       public static int ToNearestInt(this float f)
       {
           return (int)(f > 0 ? (f + 0.5f) : (f - 0.5f));
       }