src/proto2/Vector.hh
author saiam
Fri, 28 Nov 2008 22:26:23 +0000
changeset 128 890ac82cdcc0
parent 124 2fd698e04779
child 130 81406f8b7535
permissions -rw-r--r--
Documenting more, cleaning variables. This code needs some serious
rewriting. (And we havent too many features either)
#ifndef COOR_H
#define COOR_H

#include <iostream>
#include <cmath>

/**
 * 2D Vector class. Implements standard vector operations.
 */
template <typename T>
class _Vector {
public:
    T x;
    T y;
    
    _Vector() : x(0), y(0){}
    /**
     * @param x Initial x-coordinate.
     * @param y Initial y-coordinate.
     */
    _Vector(T x, T y) : x(x), y(y) {}
    /**
     * @param v Other vector to be copied.
     */
    _Vector(const _Vector &v) : x(v.x), y(v.y) {}

    void operator=(const _Vector &v) {
        this->x = v.x;
        this->y = v.y;
    }
    _Vector operator+(const _Vector &v) const {
        return _Vector(this->x+v.x, this->y+v.y);
    }
    _Vector operator-(const _Vector &v) const {
        return _Vector(this->x-v.x, this->y-v.y);
    }
    _Vector operator*(const T &d) const {
        return _Vector(this->x*d, this->y*d);
    }
    T operator*(const _Vector &v) const {
        return (this->x*v.x + this->y*v.y);
    }
    _Vector operator/(const T &d) const {
        return _Vector(this->x/d, this->y/d);
    } 
    void operator+=(const _Vector &v) {
        this->x += v.x;
        this->y += v.y;
    }
    void operator-=(const _Vector &v) {
        this->x -= v.x;
        this->y -= v.y;
    }
    void operator*=(const T &f) {
        this->x *= f;
        this->y *= f;
    }
    void operator/=(const T &d) {
        this->x /= d;
        this->y /= d;
    }
    T length() const {
        return sqrt(x*x+y*y);
    }
    _Vector roundToInt() const {
        return _Vector((int)x, (int)y);
    }
};

template<typename T>
bool operator==(const _Vector<T> &v1, const _Vector<T> &v2) {
    return ((v1.x == v2.x) && (v1.y == v2.y));
}
template<typename T>
bool operator!=(const _Vector<T> &v1, const _Vector<T> &v2) {
    return !(v1 == v2);
}

template<typename T>
std::ostream& operator<<(std::ostream &s, const _Vector<T> &v) {
    return s<<"("<<v.x<<", "<<v.y<<")";
}

typedef _Vector<float> Vector;

#endif