/*
 * BSPTree.h
 *
 * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef ZOOM_BSPTREE_H_
#define ZOOM_BSPTREE_H_

#include "Triangle.h"
#include "TriangleRecord.h"
#include "MathUtil.h"

#include <list>
#include <cmath>

#include <vmmlib/vector.hpp>
#include <boost/shared_ptr.hpp>

namespace Zoom {

class BSPTree {
  public:
    BSPTree(const std::list<TriangleRecord> &triangles);

    BSPTree(const BSPTree &tree) : frontTree(0), backTree(0) {
      *this = tree;
    }

    virtual ~BSPTree() {
      if(frontTree)
        delete frontTree;

      if(backTree)
        delete backTree;
    }

    BSPTree& operator=(const BSPTree &tree);

    template<typename T>
    void visit(const T& visitor, const vmml::vec3f &p) const {
      doVisit<const T>(visitor, p);
    }

    template<typename T>
    void visit(T& visitor, const vmml::vec3f &p) const {
      doVisit(visitor, p);
    }

  private:
    MathUtil::Plane plane;
    std::list<TriangleRecord> triangles;
    BSPTree *frontTree, *backTree;

    template<typename T>
    void doVisit(T& visitor, const vmml::vec3f &p) const {
      if(plane.isBehind(p)) {
        if(frontTree)
          frontTree->visit(visitor, p);

        for(std::list<TriangleRecord>::const_iterator t = triangles.begin(); t != triangles.end(); ++t) {
          visitor(*t);
        }

        if(backTree)
          backTree->visit(visitor, p);
      }
      else {
        if(backTree)
          backTree->visit(visitor, p);

        for(std::list<TriangleRecord>::const_iterator t = triangles.begin(); t != triangles.end(); ++t) {
          visitor(*t);
        }

        if(frontTree)
          frontTree->visit(visitor, p);
      }
    }

    void partition(const TriangleRecord &t, std::list<TriangleRecord> *front, std::list<TriangleRecord> *back) const;

    static vmml::vec3f findCenter(const std::list<TriangleRecord> &triangles);
    static const Triangle* findNearestTriangle(const std::list<TriangleRecord> &triangles, const vmml::vec3f &v);
};

}

#endif /* ZOOM_BSPTREE_H_ */
