2
0

LightComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/SceneNode.h>
  7. #include <AnKi/Scene/Frustum.h>
  8. #include <AnKi/Scene/SceneNode.h>
  9. #include <AnKi/Scene/SceneGraph.h>
  10. #include <AnKi/Scene/Octree.h>
  11. #include <AnKi/Collision.h>
  12. #include <AnKi/Resource/ResourceManager.h>
  13. #include <AnKi/Resource/ImageResource.h>
  14. #include <AnKi/Shaders/Include/ClusteredShadingTypes.h>
  15. namespace anki {
  16. LightComponent::LightComponent(SceneNode* node)
  17. : SceneComponent(node, getStaticClassId())
  18. , m_uuid(node->getSceneGraph().getNewUuid())
  19. , m_type(LightComponentType::kPoint)
  20. , m_spatial(this)
  21. {
  22. ANKI_ASSERT(m_uuid > 0);
  23. m_point.m_radius = 1.0f;
  24. setLightComponentType(LightComponentType::kPoint);
  25. m_worldTransform = node->getWorldTransform();
  26. }
  27. LightComponent::~LightComponent()
  28. {
  29. }
  30. void LightComponent::setLightComponentType(LightComponentType type)
  31. {
  32. ANKI_ASSERT(type >= LightComponentType::kFirst && type < LightComponentType::kCount);
  33. m_type = type;
  34. m_markedForUpdate = true;
  35. m_forceFullUpdate = true;
  36. if(type == LightComponentType::kDirectional)
  37. {
  38. m_spatial.setAlwaysVisible(true);
  39. m_spatial.setUpdatesOctreeBounds(false);
  40. }
  41. else
  42. {
  43. m_spatial.setAlwaysVisible(false);
  44. m_spatial.setUpdatesOctreeBounds(true);
  45. }
  46. }
  47. Error LightComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  48. {
  49. const Bool moveUpdated = info.m_node->movedThisFrame() || m_forceFullUpdate;
  50. const Bool shapeUpdated = m_markedForUpdate || m_forceFullUpdate;
  51. updated = moveUpdated || shapeUpdated;
  52. m_markedForUpdate = false;
  53. m_forceFullUpdate = false;
  54. if(moveUpdated)
  55. {
  56. m_worldTransform = info.m_node->getWorldTransform();
  57. }
  58. if(updated && m_type == LightComponentType::kPoint)
  59. {
  60. const Sphere sphere(m_worldTransform.getOrigin(), m_point.m_radius);
  61. m_spatial.setBoundingShape(sphere);
  62. if(m_shadow)
  63. {
  64. if(m_frustums == nullptr || m_frustumCount != 6) [[unlikely]]
  65. {
  66. // Allocate, initialize and update the frustums, just do everything to avoid bugs
  67. deleteArray(info.m_node->getMemoryPool(), m_frustums, m_frustumCount);
  68. m_frustums = newArray<Frustum>(info.m_node->getMemoryPool(), 6);
  69. m_frustumCount = 6;
  70. for(U32 i = 0; i < 6; i++)
  71. {
  72. m_frustums[i].init(FrustumType::kPerspective, &info.m_node->getMemoryPool());
  73. m_frustums[i].setPerspective(kClusterObjectFrustumNearPlane, m_point.m_radius, kPi / 2.0f,
  74. kPi / 2.0f);
  75. m_frustums[i].setWorldTransform(Transform(m_worldTransform.getOrigin(),
  76. Frustum::getOmnidirectionalFrustumRotations()[i], 1.0f));
  77. m_frustums[i].update();
  78. }
  79. }
  80. // Update the frustums
  81. for(U32 i = 0; i < 6; i++)
  82. {
  83. if(shapeUpdated)
  84. {
  85. m_frustums[i].setFar(m_point.m_radius);
  86. }
  87. if(moveUpdated || shapeUpdated)
  88. {
  89. m_frustums[i].setWorldTransform(Transform(m_worldTransform.getOrigin(),
  90. Frustum::getOmnidirectionalFrustumRotations()[i], 1.0f));
  91. }
  92. m_frustums[i].update();
  93. }
  94. }
  95. }
  96. else if(updated && m_type == LightComponentType::kSpot)
  97. {
  98. // Update texture matrix
  99. 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, 0.0f, 0.0f,
  100. 1.0f);
  101. const Mat4 proj = Mat4::calculatePerspectiveProjectionMatrix(m_spot.m_outerAngle, m_spot.m_outerAngle,
  102. kClusterObjectFrustumNearPlane, m_spot.m_distance);
  103. m_spot.m_textureMat = biasMat4 * proj * Mat4(m_worldTransform.getInverse());
  104. // Update the spatial
  105. Array<Vec4, 4> points;
  106. computeEdgesOfFrustum(m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle, &points[0]);
  107. Array<Vec3, 5> worldPoints;
  108. for(U32 i = 0; i < 4; ++i)
  109. {
  110. m_spot.m_edgePointsWspace[i] = m_worldTransform.transform(points[i].xyz());
  111. worldPoints[i] = m_spot.m_edgePointsWspace[i].xyz();
  112. }
  113. worldPoints[4] = m_worldTransform.getOrigin().xyz();
  114. m_spatial.setBoundingShape(ConstWeakArray<Vec3>(worldPoints));
  115. if(m_shadow)
  116. {
  117. if(m_frustums == nullptr || m_frustumCount != 1) [[unlikely]]
  118. {
  119. // Allocate, initialize and update the frustums, just do everything to avoid bugs
  120. deleteArray(info.m_node->getMemoryPool(), m_frustums, m_frustumCount);
  121. m_frustums = newArray<Frustum>(info.m_node->getMemoryPool(), 1);
  122. m_frustumCount = 1;
  123. m_frustums[0].init(FrustumType::kPerspective, &info.m_node->getMemoryPool());
  124. m_frustums[0].setPerspective(kClusterObjectFrustumNearPlane, m_spot.m_distance, m_spot.m_outerAngle,
  125. m_spot.m_outerAngle);
  126. m_frustums[0].setWorldTransform(m_worldTransform);
  127. m_frustums[0].update();
  128. }
  129. // Update the frustum
  130. if(shapeUpdated)
  131. {
  132. m_frustums[0].setFar(m_spot.m_distance);
  133. m_frustums[0].setFovX(m_spot.m_outerAngle);
  134. m_frustums[0].setFovY(m_spot.m_outerAngle);
  135. }
  136. if(moveUpdated)
  137. {
  138. m_frustums[0].setWorldTransform(m_worldTransform);
  139. }
  140. m_frustums[0].update();
  141. }
  142. }
  143. else if(m_type == LightComponentType::kDirectional)
  144. {
  145. // Update the scene bounds always
  146. info.m_node->getSceneGraph().getOctree().getActualSceneBounds(m_dir.m_sceneMin, m_dir.m_sceneMax);
  147. }
  148. const Bool spatialUpdated = m_spatial.update(info.m_node->getSceneGraph().getOctree());
  149. updated = updated || spatialUpdated;
  150. return Error::kNone;
  151. }
  152. void LightComponent::setupDirectionalLightQueueElement(const Frustum& primaryFrustum, DirectionalLightQueueElement& el,
  153. WeakArray<Frustum> cascadeFrustums) const
  154. {
  155. ANKI_ASSERT(m_type == LightComponentType::kDirectional);
  156. ANKI_ASSERT(cascadeFrustums.getSize() <= kMaxShadowCascades);
  157. const U32 shadowCascadeCount = cascadeFrustums.getSize();
  158. el.m_uuid = m_uuid;
  159. el.m_diffuseColor = m_diffColor.xyz();
  160. el.m_direction = -m_worldTransform.getRotation().getZAxis().xyz();
  161. for(U32 i = 0; i < shadowCascadeCount; ++i)
  162. {
  163. el.m_shadowCascadesDistances[i] = primaryFrustum.getShadowCascadeDistance(i);
  164. }
  165. el.m_shadowCascadeCount = U8(shadowCascadeCount);
  166. el.m_shadowLayer = kMaxU8;
  167. if(shadowCascadeCount == 0)
  168. {
  169. return;
  170. }
  171. // Compute the texture matrices
  172. const Mat4 lightTrf(m_worldTransform);
  173. if(primaryFrustum.getFrustumType() == FrustumType::kPerspective)
  174. {
  175. // Get some stuff
  176. const F32 fovX = primaryFrustum.getFovX();
  177. const F32 fovY = primaryFrustum.getFovY();
  178. // Compute a sphere per cascade
  179. Array<Sphere, kMaxShadowCascades> boundingSpheres;
  180. for(U32 i = 0; i < shadowCascadeCount; ++i)
  181. {
  182. // Compute the center of the sphere
  183. // ^ z
  184. // |
  185. // ----------|---------- A(a, -f)
  186. // \ | /
  187. // \ | /
  188. // \ C(0,z) /
  189. // \ | /
  190. // \ | /
  191. // \---|---/ B(b, -n)
  192. // \ | /
  193. // \ | /
  194. // v
  195. // --------------------------> x
  196. // |
  197. // The square distance of A-C is equal to B-C. Solve the equation to find the z.
  198. const F32 f = primaryFrustum.getShadowCascadeDistance(i); // Cascade far
  199. const F32 n =
  200. (i == 0) ? primaryFrustum.getNear() : primaryFrustum.getShadowCascadeDistance(i - 1); // Cascade near
  201. const F32 a = f * tan(fovY / 2.0f) * fovX / fovY;
  202. const F32 b = n * tan(fovY / 2.0f) * fovX / fovY;
  203. const F32 z = (b * b + n * n - a * a - f * f) / (2.0f * (f - n));
  204. ANKI_ASSERT(absolute((Vec2(a, -f) - Vec2(0, z)).getLength() - (Vec2(b, -n) - Vec2(0, z)).getLength())
  205. <= kEpsilonf * 100.0f);
  206. Vec3 C(0.0f, 0.0f, z); // Sphere center
  207. // Compute the radius of the sphere
  208. const Vec3 A(a, tan(fovY / 2.0f) * f, -f);
  209. const F32 r = (A - C).getLength();
  210. // Set the sphere
  211. boundingSpheres[i].setRadius(r);
  212. boundingSpheres[i].setCenter(primaryFrustum.getWorldTransform().transform(C));
  213. }
  214. // Compute the matrices
  215. for(U32 i = 0; i < shadowCascadeCount; ++i)
  216. {
  217. const Sphere& sphere = boundingSpheres[i];
  218. const Vec3 sphereCenter = sphere.getCenter().xyz();
  219. const F32 sphereRadius = sphere.getRadius();
  220. const Vec3& lightDir = el.m_direction;
  221. const Vec3 sceneMin = m_dir.m_sceneMin - Vec3(sphereRadius); // Push the bounds a bit
  222. const Vec3 sceneMax = m_dir.m_sceneMax + Vec3(sphereRadius);
  223. // Compute the intersections with the scene bounds
  224. Vec3 eye;
  225. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  226. {
  227. // Inside the scene bounds
  228. const Aabb sceneBox(sceneMin, sceneMax);
  229. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  230. eye = sphereCenter + t * (-lightDir);
  231. }
  232. else
  233. {
  234. eye = sphereCenter + sphereRadius * (-lightDir);
  235. }
  236. // Projection
  237. const F32 far = (eye - sphereCenter).getLength() + sphereRadius;
  238. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(
  239. sphereRadius, -sphereRadius, sphereRadius, -sphereRadius, kClusterObjectFrustumNearPlane, far);
  240. // View
  241. Transform cascadeTransform = m_worldTransform;
  242. cascadeTransform.setOrigin(eye.xyz0());
  243. const Mat4 cascadeViewMat = Mat4(cascadeTransform.getInverse());
  244. // Now it's time to stabilize the shadows by aligning the projection matrix
  245. {
  246. // Project a random fixed point to the light matrix
  247. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1();
  248. // Chose a random low shadowmap size and align the random point
  249. const F32 shadowmapSize = 128.0f;
  250. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  251. const F32 alignedX = std::round(randomPointAlmostLightSpace.x() * shadowmapSize2) / shadowmapSize2;
  252. const F32 alignedY = std::round(randomPointAlmostLightSpace.y() * shadowmapSize2) / shadowmapSize2;
  253. const F32 dx = alignedX - randomPointAlmostLightSpace.x();
  254. const F32 dy = alignedY - randomPointAlmostLightSpace.y();
  255. // Fix the projection matrix by applying an offset
  256. Mat4 correctionTranslationMat = Mat4::getIdentity();
  257. correctionTranslationMat.setTranslationPart(Vec4(dx, dy, 0, 1.0f));
  258. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  259. }
  260. // Light matrix
  261. 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, 0.0f,
  262. 0.0f, 1.0f);
  263. el.m_textureMatrices[i] = biasMat4 * cascadeProjMat * cascadeViewMat;
  264. // Fill the frustum with the fixed projection parameters from the fixed projection matrix
  265. Plane plane;
  266. extractClipPlane(cascadeProjMat, FrustumPlaneType::kLeft, plane);
  267. const F32 left = plane.getOffset();
  268. extractClipPlane(cascadeProjMat, FrustumPlaneType::kRight, plane);
  269. const F32 right = -plane.getOffset();
  270. extractClipPlane(cascadeProjMat, FrustumPlaneType::kTop, plane);
  271. const F32 top = -plane.getOffset();
  272. extractClipPlane(cascadeProjMat, FrustumPlaneType::kBottom, plane);
  273. const F32 bottom = plane.getOffset();
  274. Frustum& cascadeFrustum = cascadeFrustums[i];
  275. cascadeFrustum.init(FrustumType::kOrthographic, nullptr);
  276. cascadeFrustum.setOrthographic(kClusterObjectFrustumNearPlane, far, right, left, top, bottom);
  277. cascadeFrustum.setWorldTransform(cascadeTransform);
  278. [[maybe_unused]] const Bool updated = cascadeFrustum.update();
  279. ANKI_ASSERT(updated);
  280. }
  281. }
  282. else
  283. {
  284. ANKI_ASSERT(!"TODO");
  285. }
  286. }
  287. void LightComponent::onDestroy(SceneNode& node)
  288. {
  289. deleteArray(node.getMemoryPool(), m_frustums, m_frustumCount);
  290. m_spatial.removeFromOctree(node.getSceneGraph().getOctree());
  291. }
  292. } // end namespace anki