fcull.sh 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. bool frustumCullingTest(mat4 mvp, vec3 bmin, vec3 bmax);
  2. struct Frustum
  3. {
  4. vec4 planes[6];
  5. };
  6. /**
  7. * Extract Frustum Planes from MVP Matrix
  8. *
  9. * Based on "Fast Extraction of Viewing Frustum Planes from the World-
  10. * View-Projection Matrix", by Gil Gribb and Klaus Hartmann.
  11. * This procedure computes the planes of the frustum and normalizes
  12. * them.
  13. */
  14. void loadFrustum(out Frustum f, mat4 mvp)
  15. {
  16. for (int i = 0; i < 3; ++i)
  17. {
  18. for (int j = 0; j < 2; ++j)
  19. {
  20. f.planes[i*2+j].x = mtxGetElement(mvp, 0, 3) + (j == 0 ? mtxGetElement(mvp, 0, i) : -mtxGetElement(mvp, 0, i));
  21. f.planes[i*2+j].y = mtxGetElement(mvp, 1, 3) + (j == 0 ? mtxGetElement(mvp, 1, i) : -mtxGetElement(mvp, 1, i));
  22. f.planes[i*2+j].z = mtxGetElement(mvp, 2, 3) + (j == 0 ? mtxGetElement(mvp, 2, i) : -mtxGetElement(mvp, 2, i));
  23. f.planes[i*2+j].w = mtxGetElement(mvp, 3, 3) + (j == 0 ? mtxGetElement(mvp, 3, i) : -mtxGetElement(mvp, 3, i));
  24. f.planes[i*2+j]*= length(f.planes[i*2+j].xyz);
  25. }
  26. }
  27. }
  28. /**
  29. * Negative Vertex of an AABB
  30. *
  31. * This procedure computes the negative vertex of an AABB
  32. * given a normal.
  33. * See the View Frustum Culling tutorial @ LightHouse3D.com
  34. * http://www.lighthouse3d.com/tutorials/view-frustum-culling/geometric-approach-testing-boxes-ii/
  35. */
  36. vec3 negativeVertex(vec3 bmin, vec3 bmax, vec3 n)
  37. {
  38. bvec3 b = greaterThan(n, vec3(0.0, 0.0, 0.0));
  39. return mix(bmin, bmax, b);
  40. }
  41. /**
  42. * Frustum-AABB Culling Test
  43. *
  44. * This procedure returns true if the AABB is either inside, or in
  45. * intersection with the frustum, and false otherwise.
  46. * The test is based on the View Frustum Culling tutorial @ LightHouse3D.com
  47. * http://www.lighthouse3d.com/tutorials/view-frustum-culling/geometric-approach-testing-boxes-ii/
  48. */
  49. bool frustumCullingTest(mat4 mvp, vec3 bmin, vec3 bmax)
  50. {
  51. float a = 1.0f;
  52. Frustum f;
  53. loadFrustum(f, mvp);
  54. for (int i = 0; i < 6 && a >= 0.0f; ++i)
  55. {
  56. vec3 n = negativeVertex(bmin, bmax, f.planes[i].xyz);
  57. a = dot(vec4(n, 1.0f), f.planes[i]);
  58. }
  59. return (a >= 0.0);
  60. }