The Allegro Wiki is migrating to github at https://github.com/liballeg/allegro_wiki/wiki

Vector3D

From Allegro Wiki
Jump to: navigation, search

Vector

Can be constructed by supplying one or three scalar arguments or another vector.

Overloads + and - operators for other vectors and * and / for scalars as well as the negating - operator.

Has Cross() and Dot() functions for products with vectors.

Normalize() and Clamp() are utility functions and should be self-explanatory.


xgl_vector.h

<highlightSyntax language="cpp">#ifndef __XGL_VECTOR_H__

  1. define __XGL_VECTOR_H__
  1. include <math.h>
  1. ifndef MAX
  #define MAX(a, b)      ((a) > (b) ? (a) : (b))
  1. endif
  2. ifndef MIN
  #define MIN(a, b)      ((a) < (b) ? (a) : (b))
  1. endif

class Vector { public:

  float x, y, z;
  // CtorVector3DDtor
  Vector() : x(0), y(0), z(0)
  {
  }
  Vector (float _c) : x(_c), y(_c), z(_c)
  {
  }
  Vector(float _x, float _y, float _z) : x(_x), y(_y), z(_z)
  {
  }
  Vector(const Vector &v)
  {
     x = v.x;
     y = v.y;
     z = v.z;
  }
  
  // Operators
  inline Vector operator += (Vector v)
  {
     x += v.x;
     y += v.y;
     z += v.z;
     
     return *this;
  }
  inline Vector operator + (Vector v)
  {
     return Vector(x + v.x, y + v.y, z + v.z);
  }
  inline Vector operator - ()
  {
     return Vector(-x, -y, -z);
  }
  inline Vector operator -= (Vector v)
  {
     x -= v.x;
     y -= v.y;
     z -= v.z;
     return *this;
  }
  inline Vector operator - (Vector v)
  {
     return Vector(x - v.x, y - v.y, z - v.z);
  }
  inline Vector operator *= (float f)
  {
     x *= f;
     y *= f;
     z *= f;
     
     return *this;
  }
  inline Vector operator /= (float f)
  {
     x /= f;
     y /= f;
     z /= f;
     
     return *this;
  }
  inline Vector operator * (float f)
  {
     return Vector(x * f, y * f, z * f);
  }
  inline Vector operator / (float f)
  {
     return Vector(x / f, y / f, z / f);
  }
  // Dot and cross product
  inline float Dot(Vector v)
  {
     return x*v.x + y*v.y + z*v.z;
  }
  inline Vector Cross(Vector v)
  {
     Vector t;
     //  a x b = (ay*bz - az*by, az*bx - ax*bz, ax*by - ay*bx)
     t.x = y * v.z - z * v.y;
     t.y = z * v.x - x * v.z;
     t.z = x * v.y - y * v.x;
     return t;
  }
  // Some utilities
  inline void Normalize()
  {
     float r = sqrt(x*x + y*y + z*z);
     x /= r;
     y /= r;
     z /= r;
  }
  inline void Clamp(float min, float max)
  {
     x = MIN(MAX(min, x), max);
     y = MIN(MAX(min, y), max);
     z = MIN(MAX(min, z), max);
  }

};

  1. endif /* __XGL_VECTOR_H__ */
</highlightSyntax>