Instantly share code, notes, and snippets.

gam0022/GLSLによるポリゴン（三角形）とレイ（半直線）の衝突判定 Last active Apr 3, 2016

What would you like to do?
これがGPUの力！three.jsによる“リアルタイム”なレイトレーシング 〜宝石編〜 ref: http://qiita.com/gam0022/items/9875480d33e03fe2113c
 // 3次正方行列の行列式をクラメルの公式で計算する float det( vec3 a, vec3 b, vec3 c ) { return (a.x * b.y * c.z) + (a.y * b.z * c.x) + (a.z * b.x * c.y) - (a.x * b.z * c.y) - (a.y * b.x * c.z) - (a.z * b.y * c.x); } // ポリゴン（三角形）とレイ（半直線）の衝突判定する void rayIntersectsTriangle( vec3 origin, vec3 ray, vec3 v0, vec3 v1, vec3 v2, inout Intersect nearest ) { vec3 invRay = -ray; vec3 edge1 = v1 - v0; vec3 edge2 = v2 - v0; float denominator = det( edge1, edge2, invRay ); if ( denominator == 0.0 ) return; float invDenominator = 1.0 / denominator; vec3 d = origin - v0; float u = det( d, edge2, invRay ) * invDenominator; if ( u < 0.0 || u > 1.0 ) return; float v = det( edge1, d, invRay ) * invDenominator; if ( v < 0.0 || u + v > 1.0 ) return; float t = det( edge1, edge2, d ) * invDenominator; if ( t < 0.0 || t > nearest.distance ) return; nearest.isHit = true; nearest.position = origin + ray * t; nearest.distance = t; nearest.normal = normalize( cross( edge1, edge2 ) ) * sign( invDenominator ); nearest.material = DIAMOND_MATERIAL; nearest.isFront = invDenominator > 0.0; }