/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 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 Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#ifndef _BEZIER_H

#include <iostream>
#include <fstream>
//#include "settings.h"
#include "utility.h"
#include "quat.h"

#include "globals.h"

#define COLLISION_DIVS 1

#define COLLISION_QUAD_DIVS 8
#define QUAD_DIV_FAST_DISCARD true

#define SURFDRAW_VIS 2

#define INTERSECT_FUNCTION utility.IntersectTriangleF
#define INTERSECT_QUAD_FUNCTION utility.IntersectQuadrilateralF

using namespace std;

class BEZIER
{
private:
	void DrawSurf(int div, float trans);
	void DrawControlPoints();
	VERTEX Bernstein(float u, VERTEX *p);
	VERTEX BernsteinTangent(float u, VERTEX *p);
//	VERTEX SurfCoord(float px, float py);
	VERTEX SurfNorm(float px, float py);

public:
	BEZIER();
	~BEZIER();
	BEZIER(const BEZIER & other) {CopyFrom(other);}
	BEZIER & operator=(const BEZIER & other) {return CopyFrom(other);}
	void SetFromCorners(VERTEX fl, VERTEX fr, VERTEX bl, VERTEX br);
	void Visualize(bool wireframe, bool fill, VERTEX color);
	void Attach(BEZIER & other, bool reverse);
	void Attach(BEZIER & other) {Attach(other, false);}

	VERTEX SurfCoord(float px, float py);

	int NumTris(int divs) {return divs*divs*2;}
	void GetTri(int divs, int num, VERTEX outtri[3]);
	
	bool CollideSubDiv(VERTEX origin, VERTEX direction, VERTEX &outtri);
	bool CollideNewton(VERTEX origin, VERTEX direction, VERTEX &outtri);
	bool CollideSingleQuad(VERTEX origin, VERTEX direction, VERTEX &outtri);
	bool CollideSubDivQuad(VERTEX origin, VERTEX direction, VERTEX &outtri);
	bool CollideSubDivQuadSimple(VERTEX origin, VERTEX direction, VERTEX &outtri);
	bool CollideSubDivQuadSimpleNorm(VERTEX origin, VERTEX direction, VERTEX &outtri, VERTEX & normal);
	bool CollideQuadNewton(VERTEX origin, VERTEX direction, VERTEX &outtri);
	
	BEZIER & CopyFrom(const BEZIER &other);
	
	bool ReadFrom(ifstream &openfile);
	bool WriteTo(ofstream &openfile);

	VERTEX points[4][4];
	VERTEX center;
	float radius;
	float length;
	float dist_from_start;

	BEZIER *next_patch;
	float track_radius;
	int turn; //-1 - this is a left turn, +1 - a right turn, 0 - straight
	
	void Reverse();
};

#define _BEZIER_H
#endif
