vectorlib.h
Upload User: xuczgm
Upload Date: 2022-04-25
Package Size: 8601k
Code Size: 2k
Category:

Special Effects

Development Platform:

Visual C++

  1. #ifndef __VECTORLIB_H_INCLUDED__
  2. #define __VECTORLIB_H_INCLUDED__
  3. #include <math.h>
  4. /*************************** Macros and constants ***************************/
  5. // returns a number ranging from -1.0 to 1.0
  6. #define FRAND   (((float)rand()-(float)rand())/RAND_MAX)
  7. #define Clamp(x, min, max)  x = (x<min  ? min : x<max ? x : max);
  8. #define SQUARE(x)  (x)*(x)
  9. struct vector3_t
  10. {
  11.   vector3_t(float x, float y, float z) : x(x), y(y), z(z) {}
  12.   vector3_t(const vector3_t &v) : x(v.x), y(v.y), z(v.z) {}
  13.   vector3_t() : x(0.0f), y(0.0f), z(0.0f) {}
  14.   vector3_t& operator=(const vector3_t &rhs)
  15.   {
  16.     x = rhs.x;
  17.     y = rhs.y;
  18.     z = rhs.z;
  19.     return *this;
  20.   }
  21.   // vector add
  22.   vector3_t operator+(const vector3_t &rhs) const
  23.   {
  24.     return vector3_t(x + rhs.x, y + rhs.y, z + rhs.z);
  25.   }
  26.   // vector subtract
  27.   vector3_t operator-(const vector3_t &rhs) const
  28.   {
  29.     return vector3_t(x - rhs.x, y - rhs.y, z - rhs.z);
  30.   }
  31.   // scalar multiplication
  32.   vector3_t operator*(const float scalar) const
  33.   {
  34.     return vector3_t(x * scalar, y * scalar, z * scalar);
  35.   }
  36.   // dot product
  37.   float operator*(const vector3_t &rhs) const
  38.   {
  39.     return x * rhs.x + y * rhs.y + z * rhs.z;
  40.   }
  41.   // cross product
  42.   vector3_t operator^(const vector3_t &rhs) const
  43.   {
  44.     return vector3_t(y * rhs.z - rhs.y * z, rhs.x * z - x * rhs.z, x * rhs.y - rhs.x * y);
  45.   }
  46.   float& operator[](int index)
  47.   {
  48.     return v[index];
  49.   }
  50.   float Length()
  51.   {
  52.     float length = (float)sqrt(SQUARE(x) + SQUARE(y) + SQUARE(z));
  53.     return (length != 0.0f) ? length : 1.0f;
  54.   }
  55. /*****************************************************************************
  56.  Normalize()
  57.  Helper function to normalize vectors
  58. *****************************************************************************/
  59.   vector3_t Normalize()
  60.   {
  61.     *this = *this * (1.0f/Length());
  62.     return *this;
  63.   }
  64.   union
  65.   {
  66.     struct
  67.     {
  68.       float x;
  69.       float y;
  70.       float z;
  71.     };
  72.     float v[3];
  73.   };
  74. };
  75. #endif __VECTORLIB_H_INCLUDED__