module gedo.video.trajectory;



public import gedo.video.ggl;
private import gedo.file.path;
private import gedo.text.parser;
private import gedo.math.vector;



public Trajectory[] loadTrajectories(string path)
{
	Trajectory[] trajectories;

	auto text = cast(string).gedo.file.path.read(path);

	auto parser = new Parser(text);

	trajectories.length = parser.geti();

	foreach(inout trajectory; trajectories)
	{
		parser.gets();

		auto ts = (parser.geti()-1)*4;
		auto te = (parser.geti()-1)*4;

		Vector[] points;

		points.length = (te - ts + 1) * 2;

		foreach(inout point; points)
		{
			foreach(inout p; point)
			{
				p = parser.getf();
			}
		}

		trajectory = new Trajectory(ts, te, points);
	}

	return trajectories;
}



public class Trajectory
{
public:
	this(int ts, int te, Vector[] points)
	{
		_time[0] = ts;
		_time[1] = te;

		_points = points;
	}


	GGL_Vertex[] getVertices(int time, GGL_Vertex[] vertices, int wt, int ht)
	{
		int l = (vertices.length >> 1) - 1;

		//time += 1;

		int te = time*2;
		int ts = te - l;
		if(te <= _time[0])
		{
			return null;
		}
		else if(te > _time[1])
		{
			te = _time[1];
		}

		if(ts >= _time[1])
		{
			return null;
		}
		else if(ts < _time[0])
		{
			ts = _time[0];
		}

		te -= _time[0];
		ts -= _time[0];

		auto points = _points[ts*2 .. (te + 1)*2];

		float ytb = 1.0 / (2.0 * ht);
		float ytt = (2.0*ht - 1.0) / (2.0 * ht);

		float xto = 1.0 / (2.0 * wt);

		float k = 1.0 / ((points.length>>1) - 1) * (wt - 1.0)/wt;
		foreach(i, p; points)
		{
			float xt = xto + (i>>1) * k; 

			vertices[i].texCoord[0] = xt;
			if((i & 1) == 0)
			{
				vertices[i].texCoord[1] = ytb;
			}
			else
			{
				vertices[i].texCoord[1] = ytt;
			}
			vertices[i].position[] = p[];
		}

		return vertices[0 .. points.length];
	}


private:
	Vector[] _points;
	int[2]   _time;
}

