LightComponent.cpp 13 KB

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