VisibilityAndCollisionFunctions.hlsl 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Shaders/Common.hlsl>
  7. /// https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection
  8. Bool testRayTriangle(Vec3 rayOrigin, Vec3 rayDir, Vec3 v0, Vec3 v1, Vec3 v2, Bool backfaceCulling, out F32 t, out F32 u, out F32 v)
  9. {
  10. const Vec3 v0v1 = v1 - v0;
  11. const Vec3 v0v2 = v2 - v0;
  12. const Vec3 pvec = cross(rayDir, v0v2);
  13. const F32 det = dot(v0v1, pvec);
  14. t = 0.0f;
  15. u = 0.0f;
  16. v = 0.0f;
  17. if((backfaceCulling && det < kEpsilonF32) || abs(det) < kEpsilonF32)
  18. {
  19. return false;
  20. }
  21. const F32 invDet = 1.0 / det;
  22. const Vec3 tvec = rayOrigin - v0;
  23. u = dot(tvec, pvec) * invDet;
  24. if(u < 0.0 || u > 1.0)
  25. {
  26. return false;
  27. }
  28. const Vec3 qvec = cross(tvec, v0v1);
  29. v = dot(rayDir, qvec) * invDet;
  30. if(v < 0.0 || u + v > 1.0)
  31. {
  32. return false;
  33. }
  34. t = dot(v0v2, qvec) * invDet;
  35. if(t <= kEpsilonF32)
  36. {
  37. // This is an addition to the original code. Can't have rays that don't touch the triangle
  38. return false;
  39. }
  40. return true;
  41. }
  42. /// Return true if to AABBs overlap.
  43. Bool aabbAabbOverlap(Vec3 aMin, Vec3 aMax, Vec3 bMin, Vec3 bMax)
  44. {
  45. return all(aMin < bMax) && all(bMin < aMax);
  46. }
  47. Bool testSphereSphereCollision(Vec3 sphereCenterA, F32 sphereRadiusA, Vec3 sphereCenterB, F32 sphereRadiusB)
  48. {
  49. const Vec3 vec = sphereCenterA - sphereCenterB;
  50. const F32 distSquared = dot(vec, vec);
  51. const F32 maxDist = sphereRadiusA + sphereRadiusB;
  52. return (distSquared < maxDist * maxDist);
  53. }
  54. /// Intersect a ray against an AABB. The ray is inside the AABB. The function returns the distance 'a' where the
  55. /// intersection point is rayOrigin + rayDir * a
  56. /// https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57. F32 testRayAabbInside(Vec3 rayOrigin, Vec3 rayDir, Vec3 aabbMin, Vec3 aabbMax)
  58. {
  59. const Vec3 intersectMaxPointPlanes = (aabbMax - rayOrigin) / rayDir;
  60. const Vec3 intersectMinPointPlanes = (aabbMin - rayOrigin) / rayDir;
  61. const Vec3 largestParams = max(intersectMaxPointPlanes, intersectMinPointPlanes);
  62. const F32 distToIntersect = min(min(largestParams.x, largestParams.y), largestParams.z);
  63. return distToIntersect;
  64. }
  65. /// Ray box intersection by Simon Green
  66. Bool testRayAabb(Vec3 rayOrigin, Vec3 rayDir, Vec3 aabbMin, Vec3 aabbMax, out F32 t0, out F32 t1)
  67. {
  68. const Vec3 invR = 1.0 / rayDir;
  69. const Vec3 tbot = invR * (aabbMin - rayOrigin);
  70. const Vec3 ttop = invR * (aabbMax - rayOrigin);
  71. const Vec3 tmin = min(ttop, tbot);
  72. const Vec3 tmax = max(ttop, tbot);
  73. t0 = max(tmin.x, max(tmin.y, tmin.z));
  74. t1 = min(tmax.x, min(tmax.y, tmax.z));
  75. return t0 < t1 && t1 > kEpsilonF32;
  76. }
  77. Bool testRayObb(Vec3 rayOrigin, Vec3 rayDir, Vec3 obbExtend, Mat4 obbTransformInv, out F32 t0, out F32 t1)
  78. {
  79. // Transform ray to OBB space
  80. const Vec3 rayOriginS = mul(obbTransformInv, Vec4(rayOrigin, 1.0)).xyz;
  81. const Vec3 rayDirS = mul(obbTransformInv, Vec4(rayDir, 0.0)).xyz;
  82. // Test as AABB
  83. return testRayAabb(rayOriginS, rayDirS, -obbExtend, obbExtend, t0, t1);
  84. }
  85. /// https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection
  86. Bool testRaySphere(Vec3 rayOrigin, Vec3 rayDir, Vec3 sphereCenter, F32 sphereRadius, out F32 t0, out F32 t1)
  87. {
  88. t0 = 0.0f;
  89. t1 = 0.0f;
  90. const Vec3 L = sphereCenter - rayOrigin;
  91. const F32 tca = dot(L, rayDir);
  92. const F32 d2 = dot(L, L) - tca * tca;
  93. const F32 radius2 = sphereRadius * sphereRadius;
  94. const F32 diff = radius2 - d2;
  95. if(diff < 0.0)
  96. {
  97. return false;
  98. }
  99. const F32 thc = sqrt(diff);
  100. t0 = tca - thc;
  101. t1 = tca + thc;
  102. if(t0 < 0.0 && t1 < 0.0)
  103. {
  104. return false;
  105. }
  106. // Swap
  107. if(t0 > t1)
  108. {
  109. const F32 tmp = t0;
  110. t0 = t1;
  111. t1 = tmp;
  112. }
  113. t0 = max(0.0, t0);
  114. return true;
  115. }
  116. F32 testPlanePoint(Vec3 planeNormal, F32 planeOffset, Vec3 point3d)
  117. {
  118. return dot(planeNormal, point3d) - planeOffset;
  119. }
  120. F32 testPlaneAabb(Vec3 planeNormal, F32 planeOffset, Vec3 aabbMin, Vec3 aabbMax)
  121. {
  122. const bool3 ge = planeNormal >= 0.0;
  123. const Vec3 diagMin = select(aabbMin, aabbMax, ge);
  124. const Vec3 diagMax = select(aabbMax, aabbMin, ge);
  125. F32 test = testPlanePoint(planeNormal, planeOffset, diagMin);
  126. if(test > 0.0)
  127. {
  128. return test;
  129. }
  130. test = testPlanePoint(planeNormal, planeOffset, diagMax);
  131. return (test >= 0.0) ? 0.0 : test;
  132. }
  133. F32 testPlaneSphere(Vec3 planeNormal, F32 planeOffset, Vec3 sphereCenter, F32 sphereRadius)
  134. {
  135. const F32 centerDist = testPlanePoint(planeNormal, planeOffset, sphereCenter);
  136. F32 dist = centerDist - sphereRadius;
  137. if(dist >= 0.0f)
  138. {
  139. return dist;
  140. }
  141. dist = centerDist + sphereRadius;
  142. return (dist < 0.0f) ? dist : 0.0f;
  143. }
  144. Bool aabbSphereOverlap(Vec3 aabbMin, Vec3 aabbMax, Vec3 sphereCenter, F32 sphereRadius)
  145. {
  146. Vec3 closestPoint = sphereCenter;
  147. #if 0
  148. [unroll] for(U32 i = 0; i < 3; ++i)
  149. {
  150. if(sphereCenter[i] < aabbMin[i])
  151. {
  152. closestPoint[i] = aabbMin[i];
  153. }
  154. else if(sphereCenter[i] > aabbMax[i])
  155. {
  156. closestPoint[i] = aabbMax[i];
  157. }
  158. }
  159. #else
  160. closestPoint = select(sphereCenter > aabbMax, aabbMax, sphereCenter);
  161. closestPoint = select(closestPoint < aabbMin, aabbMin, closestPoint);
  162. #endif
  163. const Vec3 sub = sphereCenter - closestPoint;
  164. return dot(sub, sub) <= square(sphereRadius);
  165. }
  166. Bool frustumTest(Vec4 frustumPlanes[6], Vec3 sphereCenter, F32 sphereRadius)
  167. {
  168. F32 minPlaneDistance = testPlanePoint(frustumPlanes[0].xyz, frustumPlanes[0].w, sphereCenter);
  169. [unroll] for(U32 i = 1; i < 6; ++i)
  170. {
  171. const F32 d = testPlanePoint(frustumPlanes[i].xyz, frustumPlanes[i].w, sphereCenter);
  172. minPlaneDistance = min(minPlaneDistance, d);
  173. }
  174. return minPlaneDistance > -sphereRadius;
  175. }
  176. /// Modified version found in https://zeux.io/2023/01/12/approximate-projected-bounds
  177. void projectAabb(Vec3 aabbMin, Vec3 aabbMax, Mat4 viewProjMat, out Vec2 minNdc, out Vec2 maxNdc, out F32 aabbMinDepth)
  178. {
  179. const Vec4 SX = mul(viewProjMat, Vec4(aabbMax.x - aabbMin.x, 0.0, 0.0, 0.0));
  180. const Vec4 SY = mul(viewProjMat, Vec4(0.0, aabbMax.y - aabbMin.y, 0.0, 0.0));
  181. const Vec4 SZ = mul(viewProjMat, Vec4(0.0, 0.0, aabbMax.z - aabbMin.z, 0.0));
  182. Vec4 aabbEdgesClip[8u];
  183. aabbEdgesClip[0] = mul(viewProjMat, Vec4(aabbMin.x, aabbMin.y, aabbMin.z, 1.0));
  184. aabbEdgesClip[1] = aabbEdgesClip[0] + SZ;
  185. aabbEdgesClip[2] = aabbEdgesClip[0] + SY;
  186. aabbEdgesClip[3] = aabbEdgesClip[2] + SZ;
  187. aabbEdgesClip[4] = aabbEdgesClip[0] + SX;
  188. aabbEdgesClip[5] = aabbEdgesClip[4] + SZ;
  189. aabbEdgesClip[6] = aabbEdgesClip[4] + SY;
  190. aabbEdgesClip[7] = aabbEdgesClip[6] + SZ;
  191. aabbMinDepth = 1.0f;
  192. minNdc = 1000.0f;
  193. maxNdc = -1000.0f;
  194. [unroll] for(U32 i = 0; i < 8; ++i)
  195. {
  196. Vec4 p = aabbEdgesClip[i];
  197. p.xyz /= abs(p.w);
  198. minNdc = min(minNdc, p.xy);
  199. maxNdc = max(maxNdc, p.xy);
  200. aabbMinDepth = min(aabbMinDepth, p.z);
  201. }
  202. if(aabbMinDepth < 0.0)
  203. {
  204. // Behind the camera so we can't be sure about our calculations
  205. minNdc = -1.0;
  206. maxNdc = 1.0;
  207. }
  208. aabbMinDepth = saturate(aabbMinDepth);
  209. }
  210. Bool cullHzb(Vec2 aabbMinNdc, Vec2 aabbMaxNdc, F32 aabbMinDepth, Texture2D<Vec4> hzb, SamplerState nearestAnyClampSampler)
  211. {
  212. Vec2 texSize;
  213. F32 mipCount;
  214. hzb.GetDimensions(0, texSize.x, texSize.y, mipCount);
  215. const Vec2 uva = saturate(ndcToUv(aabbMinNdc));
  216. const Vec2 uvb = saturate(ndcToUv(aabbMaxNdc));
  217. const Vec2 minUv = Vec2(uva.x, uvb.y);
  218. const Vec2 maxUv = Vec2(uvb.x, uva.y);
  219. const Vec2 sizeXY = (maxUv - minUv) * texSize;
  220. F32 mip = ceil(log2(max(sizeXY.x, sizeXY.y)));
  221. // Try to use a more detailed mip if you can
  222. const F32 levelLower = max(mip - 1.0, 0.0);
  223. const Vec2 mipSize = texSize / pow(2.0f, levelLower);
  224. const Vec2 a = floor(minUv * mipSize);
  225. const Vec2 b = ceil(maxUv * mipSize);
  226. const Vec2 dims = b - a;
  227. if(dims.x <= 2.0 && dims.y <= 2.0)
  228. {
  229. mip = levelLower;
  230. }
  231. // Sample mip
  232. Vec4 depths;
  233. depths[0] = hzb.SampleLevel(nearestAnyClampSampler, minUv, mip);
  234. depths[1] = hzb.SampleLevel(nearestAnyClampSampler, maxUv, mip);
  235. depths[2] = hzb.SampleLevel(nearestAnyClampSampler, Vec2(minUv.x, maxUv.y), mip);
  236. depths[3] = hzb.SampleLevel(nearestAnyClampSampler, Vec2(maxUv.x, minUv.y), mip);
  237. const F32 maxDepth = max4(depths);
  238. return (aabbMinDepth > maxDepth);
  239. }
  240. /// All cone values in local space.
  241. Bool cullBackfaceMeshlet(Vec3 coneDirection, F32 coneCosHalfAngle, Vec3 coneApex, Mat3x4 worldTransform, Vec3 cameraWorldPos)
  242. {
  243. const Vec3 apexWSpace = mul(worldTransform, Vec4(coneApex, 1.0f));
  244. const Vec3 coneAxisWSpace = normalize(mul(worldTransform, Vec4(coneDirection, 0.0f)));
  245. const Vec3 dir = normalize(apexWSpace - cameraWorldPos);
  246. return dot(dir, coneAxisWSpace) >= coneCosHalfAngle;
  247. }
  248. F32 distancePointToLineSegment(Vec2 p, Vec2 lineSegmentA, Vec2 lineSegmentB)
  249. {
  250. const Vec2 ap = p - lineSegmentA;
  251. const Vec2 ab = lineSegmentB - lineSegmentA;
  252. const F32 abLenSq = dot(ab, ab);
  253. if(abLenSq == 0.0f)
  254. {
  255. return length(p - lineSegmentA);
  256. }
  257. const F32 t = saturate(dot(ap, ab) / abLenSq);
  258. const Vec2 closestPoint = lineSegmentA + t * ab;
  259. return length(p - closestPoint);
  260. }
  261. Vec4 computePlane(Vec3 p0, Vec3 p1, Vec3 p2)
  262. {
  263. const Vec3 u = p1 - p0;
  264. const Vec3 v = p2 - p0;
  265. const Vec3 normal = normalize(cross(u, v));
  266. const F32 offset = dot(normal, p1);
  267. return Vec4(normal, offset);
  268. }