LightComponent.cpp 8.9 KB

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