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