LightComponent.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. // Copyright (C) 2009-2022, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Scene/Components/LightComponent.h>
  6. #include <AnKi/Scene/Components/FrustumComponent.h>
  7. #include <AnKi/Scene/SceneNode.h>
  8. #include <AnKi/Scene/SceneGraph.h>
  9. #include <AnKi/Scene/Octree.h>
  10. #include <AnKi/Collision.h>
  11. #include <AnKi/Resource/ResourceManager.h>
  12. #include <AnKi/Resource/ImageResource.h>
  13. #include <AnKi/Shaders/Include/ClusteredShadingTypes.h>
  14. namespace anki {
  15. ANKI_SCENE_COMPONENT_STATICS(LightComponent)
  16. LightComponent::LightComponent(SceneNode* node)
  17. : SceneComponent(node, getStaticClassId())
  18. , m_node(node)
  19. , m_uuid(node->getSceneGraph().getNewUuid())
  20. , m_type(LightComponentType::kPoint)
  21. , m_shadow(false)
  22. , m_markedForUpdate(true)
  23. {
  24. ANKI_ASSERT(m_uuid > 0);
  25. m_point.m_radius = 1.0f;
  26. if(node->getSceneGraph().getResourceManager().loadResource("EngineAssets/LightBulb.ankitex", m_pointDebugImage)
  27. || node->getSceneGraph().getResourceManager().loadResource("EngineAssets/SpotLight.ankitex", m_spotDebugImage))
  28. {
  29. ANKI_SCENE_LOGF("Failed to load resources");
  30. }
  31. }
  32. Error LightComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  33. {
  34. updated = m_markedForUpdate;
  35. m_markedForUpdate = false;
  36. if(updated && m_type == LightComponentType::kSpot)
  37. {
  38. const Mat4 biasMat4(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  39. const Mat4 proj = Mat4::calculatePerspectiveProjectionMatrix(m_spot.m_outerAngle, m_spot.m_outerAngle,
  40. kClusterObjectFrustumNearPlane, m_spot.m_distance);
  41. m_spot.m_textureMat = biasMat4 * proj * Mat4(m_worldtransform.getInverse());
  42. Array<Vec4, 4> points;
  43. computeEdgesOfFrustum(m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle, &points[0]);
  44. for(U32 i = 0; i < 4; ++i)
  45. {
  46. m_spot.m_edgePointsWspace[i] = m_worldtransform.transform(points[i].xyz());
  47. }
  48. }
  49. // Update the scene bounds always
  50. if(m_type == LightComponentType::kDirectional)
  51. {
  52. info.m_node->getSceneGraph().getOctree().getActualSceneBounds(m_dir.m_sceneMin, m_dir.m_sceneMax);
  53. }
  54. return Error::kNone;
  55. }
  56. void LightComponent::setupDirectionalLightQueueElement(const FrustumComponent& frustumComp,
  57. DirectionalLightQueueElement& el,
  58. WeakArray<FrustumComponent> cascadeFrustumComponents) const
  59. {
  60. ANKI_ASSERT(m_type == LightComponentType::kDirectional);
  61. ANKI_ASSERT(cascadeFrustumComponents.getSize() <= kMaxShadowCascades);
  62. const U32 shadowCascadeCount = cascadeFrustumComponents.getSize();
  63. el.m_drawCallback = [](RenderQueueDrawContext& ctx, ConstWeakArray<void*> userData) {
  64. ANKI_ASSERT(userData.getSize() == 1);
  65. static_cast<const LightComponent*>(userData[0])->draw(ctx);
  66. };
  67. el.m_drawCallbackUserData = this;
  68. el.m_uuid = m_uuid;
  69. el.m_diffuseColor = m_diffColor.xyz();
  70. el.m_direction = -m_worldtransform.getRotation().getZAxis().xyz();
  71. for(U32 i = 0; i < shadowCascadeCount; ++i)
  72. {
  73. el.m_shadowCascadesDistances[i] = frustumComp.getShadowCascadeDistance(i);
  74. }
  75. el.m_shadowCascadeCount = U8(shadowCascadeCount);
  76. el.m_shadowLayer = kMaxU8;
  77. if(shadowCascadeCount == 0)
  78. {
  79. return;
  80. }
  81. // Compute the texture matrices
  82. const Mat4 lightTrf(m_worldtransform);
  83. if(frustumComp.getFrustumType() == FrustumType::kPerspective)
  84. {
  85. // Get some stuff
  86. const F32 fovX = frustumComp.getFovX();
  87. const F32 fovY = frustumComp.getFovY();
  88. // Compute a sphere per cascade
  89. Array<Sphere, kMaxShadowCascades> boundingSpheres;
  90. for(U32 i = 0; i < shadowCascadeCount; ++i)
  91. {
  92. // Compute the center of the sphere
  93. // ^ z
  94. // |
  95. // ----------|---------- A(a, -f)
  96. // \ | /
  97. // \ | /
  98. // \ C(0,z) /
  99. // \ | /
  100. // \ | /
  101. // \---|---/ B(b, -n)
  102. // \ | /
  103. // \ | /
  104. // v
  105. // --------------------------> x
  106. // |
  107. // The square distance of A-C is equal to B-C. Solve the equation to find the z.
  108. const F32 f = frustumComp.getShadowCascadeDistance(i); // Cascade far
  109. const F32 n =
  110. (i == 0) ? frustumComp.getNear() : frustumComp.getShadowCascadeDistance(i - 1); // Cascade near
  111. const F32 a = f * tan(fovY / 2.0f) * fovX / fovY;
  112. const F32 b = n * tan(fovY / 2.0f) * fovX / fovY;
  113. const F32 z = (b * b + n * n - a * a - f * f) / (2.0f * (f - n));
  114. ANKI_ASSERT(absolute((Vec2(a, -f) - Vec2(0, z)).getLength() - (Vec2(b, -n) - Vec2(0, z)).getLength())
  115. <= kEpsilonf * 100.0f);
  116. Vec3 C(0.0f, 0.0f, z); // Sphere center
  117. // Compute the radius of the sphere
  118. const Vec3 A(a, tan(fovY / 2.0f) * f, -f);
  119. const F32 r = (A - C).getLength();
  120. // Set the sphere
  121. boundingSpheres[i].setRadius(r);
  122. boundingSpheres[i].setCenter(frustumComp.getWorldTransform().transform(C));
  123. }
  124. // Compute the matrices
  125. for(U32 i = 0; i < shadowCascadeCount; ++i)
  126. {
  127. const Sphere& sphere = boundingSpheres[i];
  128. const Vec3 sphereCenter = sphere.getCenter().xyz();
  129. const F32 sphereRadius = sphere.getRadius();
  130. const Vec3& lightDir = el.m_direction;
  131. const Vec3 sceneMin = m_dir.m_sceneMin - Vec3(sphereRadius); // Push the bounds a bit
  132. const Vec3 sceneMax = m_dir.m_sceneMax + Vec3(sphereRadius);
  133. // Compute the intersections with the scene bounds
  134. Vec3 eye;
  135. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  136. {
  137. // Inside the scene bounds
  138. const Aabb sceneBox(sceneMin, sceneMax);
  139. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  140. eye = sphereCenter + t * (-lightDir);
  141. }
  142. else
  143. {
  144. eye = sphereCenter + sphereRadius * (-lightDir);
  145. }
  146. // Projection
  147. const F32 far = (eye - sphereCenter).getLength() + sphereRadius;
  148. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(
  149. sphereRadius, -sphereRadius, sphereRadius, -sphereRadius, kClusterObjectFrustumNearPlane, far);
  150. // View
  151. Transform cascadeTransform = m_worldtransform;
  152. cascadeTransform.setOrigin(eye.xyz0());
  153. const Mat4 cascadeViewMat = Mat4(cascadeTransform.getInverse());
  154. // Now it's time to stabilize the shadows by aligning the projection matrix
  155. {
  156. // Project a random fixed point to the light matrix
  157. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1();
  158. // Chose a random low shadowmap size and align the random point
  159. const F32 shadowmapSize = 128.0f;
  160. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  161. const F32 alignedX = std::round(randomPointAlmostLightSpace.x() * shadowmapSize2) / shadowmapSize2;
  162. const F32 alignedY = std::round(randomPointAlmostLightSpace.y() * shadowmapSize2) / shadowmapSize2;
  163. const F32 dx = alignedX - randomPointAlmostLightSpace.x();
  164. const F32 dy = alignedY - randomPointAlmostLightSpace.y();
  165. // Fix the projection matrix by applying an offset
  166. Mat4 correctionTranslationMat = Mat4::getIdentity();
  167. correctionTranslationMat.setTranslationPart(Vec4(dx, dy, 0, 1.0f));
  168. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  169. }
  170. // Light matrix
  171. static const Mat4 biasMat4(0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
  172. 0.0f, 0.0f, 1.0f);
  173. el.m_textureMatrices[i] = biasMat4 * cascadeProjMat * cascadeViewMat;
  174. // Fill the frustum with the fixed projection parameters from the fixed projection matrix
  175. Plane plane;
  176. extractClipPlane(cascadeProjMat, FrustumPlaneType::kLeft, plane);
  177. const F32 left = plane.getOffset();
  178. extractClipPlane(cascadeProjMat, FrustumPlaneType::kRight, plane);
  179. const F32 right = -plane.getOffset();
  180. extractClipPlane(cascadeProjMat, FrustumPlaneType::kTop, plane);
  181. const F32 top = -plane.getOffset();
  182. extractClipPlane(cascadeProjMat, FrustumPlaneType::kBottom, plane);
  183. const F32 bottom = plane.getOffset();
  184. FrustumComponent& cascadeFrustumComp = cascadeFrustumComponents[i];
  185. cascadeFrustumComp.setOrthographic(kClusterObjectFrustumNearPlane, far, right, left, top, bottom);
  186. cascadeFrustumComp.setWorldTransform(cascadeTransform);
  187. }
  188. }
  189. else
  190. {
  191. ANKI_ASSERT(!"TODO");
  192. }
  193. }
  194. void LightComponent::draw(RenderQueueDrawContext& ctx) const
  195. {
  196. const Bool enableDepthTest = ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::kDepthTestOn);
  197. if(enableDepthTest)
  198. {
  199. ctx.m_commandBuffer->setDepthCompareOperation(CompareOperation::kLess);
  200. }
  201. else
  202. {
  203. ctx.m_commandBuffer->setDepthCompareOperation(CompareOperation::kAlways);
  204. }
  205. Vec3 color = m_diffColor.xyz();
  206. color /= max(max(color.x(), color.y()), color.z());
  207. ImageResourcePtr imageResource = (m_type == LightComponentType::kPoint) ? m_pointDebugImage : m_spotDebugImage;
  208. m_node->getSceneGraph().getDebugDrawer().drawBillboardTexture(
  209. ctx.m_projectionMatrix, ctx.m_viewMatrix, m_worldtransform.getOrigin().xyz(), color.xyz1(),
  210. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::kDitheredDepthTestOn), imageResource->getTextureView(),
  211. ctx.m_sampler, Vec2(0.75f), *ctx.m_stagingGpuAllocator, ctx.m_commandBuffer);
  212. // Restore state
  213. if(!enableDepthTest)
  214. {
  215. ctx.m_commandBuffer->setDepthCompareOperation(CompareOperation::kLess);
  216. }
  217. }
  218. } // end namespace anki