LightComponent.cpp 9.1 KB

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