LightComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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/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. LightComponent::LightComponent(SceneNode* node)
  16. : SceneComponent(node, kClassType)
  17. , m_type(LightComponentType::kPoint)
  18. {
  19. m_point.m_radius = 1.0f;
  20. setLightComponentType(LightComponentType::kPoint);
  21. m_worldTransform = node->getWorldTransform();
  22. }
  23. LightComponent::~LightComponent()
  24. {
  25. if(m_type == LightComponentType::kDirectional)
  26. {
  27. SceneGraph::getSingleton().removeDirectionalLight(this);
  28. }
  29. }
  30. void LightComponent::setLightComponentType(LightComponentType newType)
  31. {
  32. ANKI_ASSERT(newType >= LightComponentType::kFirst && newType < LightComponentType::kCount);
  33. const LightComponentType oldType = m_type;
  34. const Bool typeChanged = newType != oldType;
  35. if(typeChanged)
  36. {
  37. m_type = newType;
  38. m_shadowAtlasUvViewportCount = 0;
  39. m_dirty = true;
  40. m_uuid = 0;
  41. if(newType == LightComponentType::kDirectional)
  42. {
  43. // Now it's directional, inform the scene
  44. SceneGraph::getSingleton().addDirectionalLight(this);
  45. }
  46. else if(oldType == LightComponentType::kDirectional)
  47. {
  48. // It was directional, inform the scene
  49. SceneGraph::getSingleton().removeDirectionalLight(this);
  50. }
  51. }
  52. }
  53. Error LightComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  54. {
  55. const Bool moveUpdated = info.m_node->movedThisFrame();
  56. updated = moveUpdated || m_dirty;
  57. m_dirty = false;
  58. if(moveUpdated)
  59. {
  60. m_worldTransform = info.m_node->getWorldTransform();
  61. }
  62. if(updated && m_type == LightComponentType::kPoint)
  63. {
  64. if(!m_shadow)
  65. {
  66. m_uuid = 0;
  67. }
  68. else if(m_uuid == 0)
  69. {
  70. m_uuid = SceneGraph::getSingleton().getNewUuid();
  71. }
  72. const Bool reallyShadow = m_shadow && m_shadowAtlasUvViewportCount == 6;
  73. // Upload to the GPU scene
  74. GpuSceneLight gpuLight = {};
  75. gpuLight.m_position = m_worldTransform.getOrigin().xyz();
  76. gpuLight.m_radius = m_point.m_radius;
  77. gpuLight.m_diffuseColor = m_diffColor.xyz();
  78. gpuLight.m_squareRadiusOverOne = 1.0f / (m_point.m_radius * m_point.m_radius);
  79. gpuLight.m_flags = GpuSceneLightFlag::kPointLight;
  80. gpuLight.m_flags |= (reallyShadow) ? GpuSceneLightFlag::kShadow : GpuSceneLightFlag::kNone;
  81. gpuLight.m_arrayIndex = getArrayIndex();
  82. gpuLight.m_uuid = m_uuid;
  83. for(U32 f = 0; f < m_shadowAtlasUvViewportCount; ++f)
  84. {
  85. gpuLight.m_spotLightMatrixOrPointLightUvViewports[f] = m_shadowAtlasUvViewports[f];
  86. }
  87. if(!m_gpuSceneLight.isValid())
  88. {
  89. m_gpuSceneLight.allocate();
  90. }
  91. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  92. }
  93. else if(updated && m_type == LightComponentType::kSpot)
  94. {
  95. if(!m_shadow)
  96. {
  97. m_uuid = 0;
  98. }
  99. else if(m_uuid == 0)
  100. {
  101. m_uuid = SceneGraph::getSingleton().getNewUuid();
  102. }
  103. const Bool reallyShadow = m_shadow && m_shadowAtlasUvViewportCount == 1;
  104. // Upload to the GPU scene
  105. GpuSceneLight gpuLight = {};
  106. gpuLight.m_position = m_worldTransform.getOrigin().xyz();
  107. gpuLight.m_radius = m_spot.m_distance;
  108. gpuLight.m_diffuseColor = m_diffColor.xyz();
  109. gpuLight.m_squareRadiusOverOne = 1.0f / (m_spot.m_distance * m_spot.m_distance);
  110. gpuLight.m_flags = GpuSceneLightFlag::kSpotLight;
  111. gpuLight.m_flags |= (reallyShadow) ? GpuSceneLightFlag::kShadow : GpuSceneLightFlag::kNone;
  112. gpuLight.m_arrayIndex = getArrayIndex();
  113. gpuLight.m_uuid = m_uuid;
  114. gpuLight.m_innerCos = cos(m_spot.m_innerAngle / 2.0f);
  115. gpuLight.m_direction = -m_worldTransform.getRotation().getZAxis();
  116. gpuLight.m_outerCos = cos(m_spot.m_outerAngle / 2.0f);
  117. Array<Vec4, 4> points;
  118. computeEdgesOfFrustum(m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle, &points[0]);
  119. for(U32 i = 0; i < 4; ++i)
  120. {
  121. m_worldTransform.transform(points[i]);
  122. gpuLight.m_edgePoints[i] = points[i].xyz0();
  123. }
  124. if(reallyShadow)
  125. {
  126. 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);
  127. const Mat4 proj = Mat4::calculatePerspectiveProjectionMatrix(m_spot.m_outerAngle, m_spot.m_outerAngle, kClusterObjectFrustumNearPlane,
  128. m_spot.m_distance);
  129. const Mat4 uvToAtlas(m_shadowAtlasUvViewports[0].z(), 0.0f, 0.0f, m_shadowAtlasUvViewports[0].x(), 0.0f, m_shadowAtlasUvViewports[0].w(),
  130. 0.0f, m_shadowAtlasUvViewports[0].y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
  131. m_spot.m_viewMat = Mat3x4(m_worldTransform.getInverse());
  132. m_spot.m_viewProjMat = proj * Mat4(m_spot.m_viewMat, Vec4(0.0f, 0.0f, 0.0f, 1.0f));
  133. const Mat4 texMat = uvToAtlas * biasMat4 * m_spot.m_viewProjMat;
  134. gpuLight.m_spotLightMatrixOrPointLightUvViewports[0] = texMat.getRow(0);
  135. gpuLight.m_spotLightMatrixOrPointLightUvViewports[1] = texMat.getRow(1);
  136. gpuLight.m_spotLightMatrixOrPointLightUvViewports[2] = texMat.getRow(2);
  137. gpuLight.m_spotLightMatrixOrPointLightUvViewports[3] = texMat.getRow(3);
  138. }
  139. if(!m_gpuSceneLight.isValid())
  140. {
  141. m_gpuSceneLight.allocate();
  142. }
  143. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  144. }
  145. else if(m_type == LightComponentType::kDirectional)
  146. {
  147. m_gpuSceneLight.free();
  148. }
  149. return Error::kNone;
  150. }
  151. void LightComponent::computeCascadeFrustums(const Frustum& primaryFrustum, ConstWeakArray<F32> cascadeDistances, WeakArray<Mat4> cascadeViewProjMats,
  152. WeakArray<Mat3x4> cascadeViewMats) const
  153. {
  154. ANKI_ASSERT(m_type == LightComponentType::kDirectional);
  155. ANKI_ASSERT(m_shadow);
  156. ANKI_ASSERT(cascadeViewProjMats.getSize() <= kMaxShadowCascades && cascadeViewProjMats.getSize() > 0);
  157. ANKI_ASSERT(cascadeDistances.getSize() == cascadeViewProjMats.getSize());
  158. const U32 shadowCascadeCount = cascadeViewProjMats.getSize();
  159. // Compute the texture matrices
  160. if(primaryFrustum.getFrustumType() == FrustumType::kPerspective)
  161. {
  162. // Get some stuff
  163. const F32 fovX = primaryFrustum.getFovX();
  164. const F32 fovY = primaryFrustum.getFovY();
  165. // Compute a sphere per cascade
  166. Array<Sphere, kMaxShadowCascades> boundingSpheres;
  167. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  168. {
  169. // Compute the center of the sphere
  170. // ^ z
  171. // |
  172. // ----------|---------- A(a, -f)
  173. // \ | /
  174. // \ | /
  175. // \ C(0,z) /
  176. // \ | /
  177. // \ | /
  178. // \---|---/ B(b, -n)
  179. // \ | /
  180. // \ | /
  181. // v
  182. // --------------------------> x
  183. // |
  184. // The square distance of A-C is equal to B-C. Solve the equation to find the z.
  185. const F32 f = cascadeDistances[cascade]; // Cascade far
  186. const F32 n = (cascade == 0) ? primaryFrustum.getNear() : cascadeDistances[cascade - 1]; // Cascade near
  187. const F32 a = f * tan(fovY / 2.0f) * fovX / fovY;
  188. const F32 b = n * tan(fovY / 2.0f) * fovX / fovY;
  189. const F32 z = (b * b + n * n - a * a - f * f) / (2.0f * (f - n));
  190. ANKI_ASSERT(absolute((Vec2(a, -f) - Vec2(0, z)).getLength() - (Vec2(b, -n) - Vec2(0, z)).getLength()) <= kEpsilonf * 100.0f);
  191. Vec3 C(0.0f, 0.0f, z); // Sphere center
  192. // Compute the radius of the sphere
  193. const Vec3 A(a, tan(fovY / 2.0f) * f, -f);
  194. const F32 r = (A - C).getLength();
  195. // Set the sphere
  196. boundingSpheres[cascade].setRadius(r);
  197. boundingSpheres[cascade].setCenter(primaryFrustum.getWorldTransform().transform(C));
  198. }
  199. // Compute the matrices
  200. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  201. {
  202. const Sphere& sphere = boundingSpheres[cascade];
  203. const Vec3 sphereCenter = sphere.getCenter().xyz();
  204. const F32 sphereRadius = sphere.getRadius();
  205. const Vec3& lightDir = getDirection();
  206. Array<Vec3, 2> sceneBounds = SceneGraph::getSingleton().getSceneBounds();
  207. const Vec3 sceneMin = sceneBounds[0] - Vec3(sphereRadius); // Push the bounds a bit
  208. const Vec3 sceneMax = sceneBounds[1] + Vec3(sphereRadius);
  209. // Compute the intersections with the scene bounds
  210. Vec3 eye;
  211. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  212. {
  213. // Inside the scene bounds
  214. const Aabb sceneBox(sceneMin, sceneMax);
  215. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  216. eye = sphereCenter + t * (-lightDir);
  217. }
  218. else
  219. {
  220. eye = sphereCenter + sphereRadius * (-lightDir);
  221. }
  222. // View
  223. Transform cascadeTransform = m_worldTransform;
  224. cascadeTransform.setOrigin(eye.xyz0());
  225. const Mat4 cascadeViewMat = Mat4(cascadeTransform.getInverse());
  226. // Projection
  227. const F32 far = (eye - sphereCenter).getLength() + sphereRadius;
  228. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(sphereRadius, -sphereRadius, sphereRadius, -sphereRadius,
  229. kClusterObjectFrustumNearPlane, far);
  230. // Now it's time to stabilize the shadows by aligning the projection matrix
  231. {
  232. // Project a random fixed point to the light matrix
  233. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1();
  234. // Chose a random low shadowmap size and align the random point
  235. const F32 shadowmapSize = 128.0f;
  236. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  237. const F32 alignedX = std::round(randomPointAlmostLightSpace.x() * shadowmapSize2) / shadowmapSize2;
  238. const F32 alignedY = std::round(randomPointAlmostLightSpace.y() * shadowmapSize2) / shadowmapSize2;
  239. const F32 dx = alignedX - randomPointAlmostLightSpace.x();
  240. const F32 dy = alignedY - randomPointAlmostLightSpace.y();
  241. // Fix the projection matrix by applying an offset
  242. Mat4 correctionTranslationMat = Mat4::getIdentity();
  243. correctionTranslationMat.setTranslationPart(Vec4(dx, dy, 0, 1.0f));
  244. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  245. }
  246. // Write the results
  247. cascadeViewProjMats[cascade] = cascadeProjMat * cascadeViewMat;
  248. if(cascade < cascadeViewMats.getSize())
  249. {
  250. cascadeViewMats[cascade] = Mat3x4(cascadeViewMat);
  251. }
  252. }
  253. }
  254. else
  255. {
  256. ANKI_ASSERT(!"TODO");
  257. }
  258. }
  259. void LightComponent::setShadowAtlasUvViewports(ConstWeakArray<Vec4> viewports)
  260. {
  261. ANKI_ASSERT(viewports.getSize() <= 6);
  262. if(m_type == LightComponentType::kPoint)
  263. {
  264. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 6);
  265. }
  266. else if(m_type == LightComponentType::kSpot)
  267. {
  268. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 1);
  269. }
  270. else
  271. {
  272. ANKI_ASSERT(viewports.getSize() == 0);
  273. }
  274. const Bool dirty = m_shadowAtlasUvViewportCount != viewports.getSize()
  275. || memcmp(m_shadowAtlasUvViewports.getBegin(), viewports.getBegin(), viewports.getSizeInBytes()) != 0;
  276. if(dirty)
  277. {
  278. m_shadowAtlasUvViewportCount = viewports.getSize();
  279. for(U32 i = 0; i < viewports.getSize(); ++i)
  280. {
  281. m_shadowAtlasUvViewports[i] = viewports[i];
  282. }
  283. m_dirty = true;
  284. }
  285. }
  286. } // end namespace anki