#include "object.h"

bool Object::collidate(const FVector &Ray, float &t1, float &t2, const int r) {
	float a=(force.x-Ray.x)*(force.x-Ray.x)+(force.y-Ray.y)*(force.y-Ray.y);
	if(a==0) return false;
	float b=2*(pos.x*(force.x-Ray.x)+pos.y*(force.y-Ray.y));
	float c=pos.x*pos.x+pos.y*pos.y-r*r;
	float t=b*b-4*a*c;
	if(t<0) return false;
	t=sqrtf(t);

	if(a<0) {
		t1=(-b-t)/(2*a);
		t2=(-b+t)/(2*a);
	}
	else {
		t2=(-b-t)/(2*a);
		t1=(-b+t)/(2*a);
	}

	return true;
}

bool Object::collidate(const FVector &Ray, float &t1, float &t2) {
	return collidate(Ray,t1,t2,r);
}

bool Object::collidate(const Object &Obj, float &t1, float &t2) {
	return collidate(Obj.force,t1,t2,r+Obj.r);
}

bool Object::collidate(const FVector &Ray, const float l, State &state) {
	float D=Ray.y*force.x-Ray.x*force.y;
	if(abs(D)<0.01) {
		float x=2*r;
		if(force.x!=0)
			x=pos.x-pos.y*force.x/force.y;
		else if(force.y!=0)
			x=pos.y-pos.x*force.y/force.x;
		if(abs(x)<=r) {
			if(Ray.x!=0)
				state.t_s = -pos.x/Ray.x;
			else if(Ray.y!=0)
				state.t_s = -pos.y/Ray.y;
			state.t_warte = 0;
			state.t_around= 1000000.f;
			state.obj=(Object*)this;
			return state.t_s>=0;
		}
		return false;
	}

	float D1=pos.y*force.x-pos.x*force.y;
	float D2=Ray.x*pos.y-Ray.y*pos.x;
	float tw=D2/D;

	state.t_s = D1/D;
	state.t_warte = tw - state.t_s;

	Vector p=pos+FVector(force.y,-force.x)*((r*0.9f)/length);
	D1=p.y*force.x-p.x*force.y;
	float tw1=D1/D;
	D2=Ray.x*p.y-Ray.y*p.x;	
	float tw2=D2/D;

	state.obj=(Object*)this;
	state.t_around=abs(state.t_s-tw1)*l/(length+0.001f);

	return state.t_s>=0&&state.t_warte+state.t_around>=0;
}
