Changeset 239


Ignore:
Timestamp:
Jan 19, 2011, 9:33:36 PM (9 years ago)
Author:
sam
Message:

Implement vector addition, subtraction etc. as well as euclidian distance.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/matrix.h

    r237 r239  
    1717#define __DH_MATRIX_H__
    1818
    19 #define OPERATORS(elems) \
    20     inline Vec##elems<T> operator+(Vec##elems<T> const &op) const \
     19#include <cmath>
     20
     21#define VECTOR_OP(elems, op) \
     22    inline Vec##elems<T> operator op(Vec##elems<T> const &val) const \
    2123    { \
    2224        Vec##elems<T> ret; \
    2325        for (int n = 0; n < elems; n++) \
    24             ret[n] = (*this)[n] + op[n]; \
     26            ret[n] = (*this)[n] op val[n]; \
    2527        return ret; \
    26     } \
    27  \
    28     inline Vec##elems<T> operator-(Vec##elems<T> const &op) const \
     28    }
     29
     30#define SCALAR_OP(elems, op) \
     31    inline Vec##elems<T> operator op(T const &val) const \
    2932    { \
    3033        Vec##elems<T> ret; \
    3134        for (int n = 0; n < elems; n++) \
    32             ret[n] = (*this)[n] - op[n]; \
     35            ret[n] = (*this)[n] op val; \
    3336        return ret; \
     37    }
     38
     39#define OPERATORS(elems) \
     40    T& operator[](int n) { return *(&x + n); } \
     41    T const& operator[](int n) const { return *(&x + n); } \
     42    \
     43    VECTOR_OP(elems, -) \
     44    VECTOR_OP(elems, +) \
     45    VECTOR_OP(elems, *) \
     46    VECTOR_OP(elems, /) \
     47    \
     48    SCALAR_OP(elems, -) \
     49    SCALAR_OP(elems, +) \
     50    SCALAR_OP(elems, *) \
     51    SCALAR_OP(elems, /) \
     52    \
     53    inline float len() const \
     54    { \
     55        T acc = 0; \
     56        for (int n = 0; n < elems; n++) \
     57            acc += (*this)[n] * (*this)[n]; \
     58        return sqrtf((float)acc); \
    3459    }
    3560
     
    3863    Vec2() { x = y = 0; }
    3964    Vec2(T _x, T _y) { x = _x; y = _y; }
    40     T& operator[](int n) { return *(&x + n); }
    41     T const& operator[](int n) const { return *(&x + n); }
    4265
    4366    OPERATORS(2)
     
    5477    Vec3() { x = y = z = 0; }
    5578    Vec3(T _x, T _y, T _z) { x = _x; y = _y; z = _z; }
    56     T& operator[](int n) { return *(&x + n); }
    5779
    5880    OPERATORS(3)
Note: See TracChangeset for help on using the changeset viewer.