#pragma once #include namespace cgv{ namespace math{ template bool line_line_intersection(const vec& x1,const vec& d1,const vec& x2,const vec& d2, T& t1, T& t2, T eps=0.00001) { mat A(x1.dim(),2); A.set_col(0,d1); A.set_col(1,d2); vec b = transpose(A)*(x1-x2); A=transpose(A)*A; vec t; solve(A,b,t); vec s1 = x1 + t(0)*d1; vec s2 = x2 + t(1)*d2; t1 = t(0); t2 = t(1); return length(s1-s2)<= eps; } template bool line_circle_intersection(const vec& x,const vec& d,const vec& center,const vec& normal, const T& radius, vec& nearest_point, T eps=0.00001) { T s = dot(normal,d); if(s == 0) return false; T t = dot(normal,x)-dot(center,normal); t/=-s; vec v1 = x+t*d-center; nearest_point = radius*normalize(v1)+center; if(t < 0) return false; return ( fabs(length(v1)-radius) <= eps); } template bool ray_plane_intersection(const vec& x,const vec& d,const vec& plane, T& t) { t =0; T s =0; unsigned n = x.dim(); for(unsigned i = 0; i < n; i++) { t+=plane(i)*x(i); s+=plane(i)*d(i); } if(s == 0) return false; t+=plane(n); t/=-s; return ( t >= 0); } } }