LightComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. // Copyright (C) 2009-present, 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. // Calculate day of the year
  16. static U32 dayOfYear(U32 year, U32 month, U32 day)
  17. {
  18. struct tm date = {};
  19. date.tm_year = year - 1900;
  20. date.tm_mon = month - 1;
  21. date.tm_mday = day;
  22. mktime(&date);
  23. return date.tm_yday + 1;
  24. }
  25. static void solarPosition(U32 year, U32 month, U32 day, F32 hourUtc, F32 latitude, F32 longitude, F32& elevation, F32& azimuth)
  26. {
  27. const F32 N = F32(dayOfYear(year, month, day));
  28. // Fractional year (in radians)
  29. const F32 gamma = 2.0f * kPi / 365.0f * (N - 1.0f + (hourUtc - 12.0f) / 24.0f);
  30. // Equation of time (minutes)
  31. const F32 eqTime =
  32. 229.18f * (0.000075f + 0.001868f * cos(gamma) - 0.032077f * sin(gamma) - 0.014615f * cos(2.0f * gamma) - 0.040849f * sin(2.0f * gamma));
  33. // Solar declination (radians)
  34. const F32 decl = 0.006918f - 0.399912f * cos(gamma) + 0.070257f * sin(gamma) - 0.006758f * cos(2.0f * gamma) + 0.000907f * sin(2 * gamma)
  35. - 0.002697f * cos(3.0f * gamma) + 0.00148f * sin(3.0f * gamma);
  36. // Time offset (minutes)
  37. const F32 timeOffset = eqTime + 4.0f * longitude;
  38. // True solar time (degrees)
  39. const F32 tst = hourUtc * 60.0f + timeOffset;
  40. const F32 ha = toRad((tst / 4.0f) - 180.0f); // Hour angle in radians
  41. const F32 latRad = toRad(latitude);
  42. // Solar zenith angle
  43. const F32 cosZenith = sin(latRad) * sin(decl) + cos(latRad) * cos(decl) * cos(ha);
  44. const F32 zenith = acos(cosZenith);
  45. elevation = kPi / 2.0f - zenith;
  46. // Solar azimuth
  47. const F32 v = (sin(decl) - sin(latRad) * cos(zenith)) / (cos(latRad) * sin(zenith));
  48. const F32 azRad = acos(clamp(v, -1.0f, 1.0f));
  49. azimuth = azRad;
  50. if(ha > 0.0)
  51. {
  52. azimuth = 2.0f * kPi - azimuth;
  53. }
  54. }
  55. LightComponent::LightComponent(SceneNode* node)
  56. : SceneComponent(node, kClassType)
  57. , m_type(LightComponentType::kPoint)
  58. {
  59. m_point.m_radius = 1.0f;
  60. setLightComponentType(LightComponentType::kPoint);
  61. m_worldTransform = node->getWorldTransform();
  62. }
  63. LightComponent::~LightComponent()
  64. {
  65. }
  66. void LightComponent::setLightComponentType(LightComponentType newType)
  67. {
  68. ANKI_ASSERT(newType >= LightComponentType::kFirst && newType < LightComponentType::kCount);
  69. const Bool typeChanged = newType != m_type;
  70. if(typeChanged)
  71. {
  72. m_type = newType;
  73. m_shadowAtlasUvViewportCount = 0;
  74. m_shapeDirty = true;
  75. m_otherDirty = true;
  76. }
  77. }
  78. void LightComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  79. {
  80. const Bool moveUpdated = info.m_node->movedThisFrame();
  81. updated = moveUpdated || m_shapeDirty || m_otherDirty;
  82. if(moveUpdated)
  83. {
  84. m_worldTransform = info.m_node->getWorldTransform();
  85. }
  86. if(updated && m_type == LightComponentType::kPoint)
  87. {
  88. const Bool reallyShadow = m_shadow && m_shadowAtlasUvViewportCount == 6;
  89. // Upload the hash
  90. if(reallyShadow)
  91. {
  92. if(!m_hash.isValid())
  93. {
  94. m_hash.allocate();
  95. }
  96. if(m_shapeDirty || moveUpdated)
  97. {
  98. GpuSceneLightVisibleRenderablesHash hash = {};
  99. m_hash.uploadToGpuScene(hash);
  100. }
  101. }
  102. // Upload to the GPU scene
  103. GpuSceneLight gpuLight = {};
  104. gpuLight.m_position = m_worldTransform.getOrigin().xyz;
  105. gpuLight.m_radius = m_point.m_radius;
  106. gpuLight.m_diffuseColor = m_diffColor.xyz;
  107. gpuLight.m_visibleRenderablesHashIndex = (reallyShadow) ? m_hash.getIndex() : 0;
  108. gpuLight.m_isPointLight = 1;
  109. gpuLight.m_isSpotLight = 0;
  110. gpuLight.m_shadow = reallyShadow;
  111. gpuLight.m_cpuFeedback = m_shadow;
  112. gpuLight.m_componentArrayIndex = getArrayIndex();
  113. gpuLight.m_uuid = getUuid();
  114. for(U32 f = 0; f < m_shadowAtlasUvViewportCount; ++f)
  115. {
  116. gpuLight.m_spotLightMatrixOrPointLightUvViewports[f] = m_shadowAtlasUvViewports[f];
  117. }
  118. if(!m_gpuSceneLight.isValid())
  119. {
  120. m_gpuSceneLight.allocate();
  121. }
  122. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  123. }
  124. else if(updated && m_type == LightComponentType::kSpot)
  125. {
  126. const Bool reallyShadow = m_shadow && m_shadowAtlasUvViewportCount == 1;
  127. // Upload the hash
  128. if(reallyShadow)
  129. {
  130. if(!m_hash.isValid())
  131. {
  132. m_hash.allocate();
  133. }
  134. if(m_shapeDirty || moveUpdated)
  135. {
  136. GpuSceneLightVisibleRenderablesHash hash = {};
  137. m_hash.uploadToGpuScene(hash);
  138. }
  139. }
  140. // Upload to the GPU scene
  141. GpuSceneLight gpuLight = {};
  142. gpuLight.m_position = m_worldTransform.getOrigin().xyz;
  143. gpuLight.m_radius = m_spot.m_distance;
  144. gpuLight.m_diffuseColor = m_diffColor.xyz;
  145. gpuLight.m_visibleRenderablesHashIndex = (reallyShadow) ? m_hash.getIndex() : 0;
  146. gpuLight.m_isPointLight = 0;
  147. gpuLight.m_isSpotLight = 1;
  148. gpuLight.m_shadow = reallyShadow;
  149. gpuLight.m_cpuFeedback = m_shadow;
  150. gpuLight.m_componentArrayIndex = getArrayIndex();
  151. gpuLight.m_uuid = getUuid();
  152. gpuLight.m_innerCos = cos(m_spot.m_innerAngle / 2.0f);
  153. gpuLight.m_direction = -m_worldTransform.getRotation().getZAxis();
  154. gpuLight.m_outerCos = cos(m_spot.m_outerAngle / 2.0f);
  155. Array<Vec3, 4> points;
  156. computeEdgesOfFrustum(m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle, &points[0]);
  157. for(U32 i = 0; i < 4; ++i)
  158. {
  159. points[i] = m_worldTransform.transform(points[i]);
  160. gpuLight.m_edgePoints[i] = points[i].xyz0;
  161. }
  162. if(reallyShadow)
  163. {
  164. 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);
  165. const Mat4 proj = Mat4::calculatePerspectiveProjectionMatrix(m_spot.m_outerAngle, m_spot.m_outerAngle, kClusterObjectFrustumNearPlane,
  166. m_spot.m_distance);
  167. const Mat4 uvToAtlas(m_shadowAtlasUvViewports[0].z, 0.0f, 0.0f, m_shadowAtlasUvViewports[0].x, 0.0f, m_shadowAtlasUvViewports[0].w, 0.0f,
  168. m_shadowAtlasUvViewports[0].y, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
  169. m_spot.m_viewMat = Mat3x4(m_worldTransform.invert());
  170. m_spot.m_viewProjMat = proj * Mat4(m_spot.m_viewMat, Vec4(0.0f, 0.0f, 0.0f, 1.0f));
  171. const Mat4 texMat = uvToAtlas * biasMat4 * m_spot.m_viewProjMat;
  172. gpuLight.m_spotLightMatrixOrPointLightUvViewports[0] = texMat.getRow(0);
  173. gpuLight.m_spotLightMatrixOrPointLightUvViewports[1] = texMat.getRow(1);
  174. gpuLight.m_spotLightMatrixOrPointLightUvViewports[2] = texMat.getRow(2);
  175. gpuLight.m_spotLightMatrixOrPointLightUvViewports[3] = texMat.getRow(3);
  176. }
  177. if(!m_gpuSceneLight.isValid())
  178. {
  179. m_gpuSceneLight.allocate();
  180. }
  181. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  182. }
  183. else if(m_type == LightComponentType::kDirectional)
  184. {
  185. m_gpuSceneLight.free();
  186. if(updated && (m_dir.m_month >= 0 && m_dir.m_day >= 0 && m_dir.m_hour >= 0.0f))
  187. {
  188. F32 hour;
  189. F32 lat, lon;
  190. if(1)
  191. {
  192. // Location: Greece
  193. lat = 37.983326540467026f;
  194. lon = 23.722718055667336f;
  195. // Fix hour to UTC
  196. hour = m_dir.m_hour - 2.0f;
  197. }
  198. else
  199. {
  200. // Location: Norway
  201. lat = 63.42239805509379f;
  202. lon = 10.400744175764066f;
  203. // Fix hour to UTC
  204. hour = m_dir.m_hour - 1.0f;
  205. }
  206. F32 elevation, azimuth;
  207. solarPosition(2025, m_dir.m_month, m_dir.m_day, hour, lat, lon, elevation, azimuth);
  208. elevation = max(elevation, toRad(10.0f)); // Don't have it negative cause the renderer can't handle it
  209. const F32 polarAng = kPi / 2.0f - elevation;
  210. Vec3 newDir;
  211. newDir.setFromSphericalToCartesian(polarAng, azimuth);
  212. newDir = -newDir;
  213. const Vec3 zAxis = newDir;
  214. Vec3 yAxis = Vec3(0.0f, 1.0f, 0.0f);
  215. Vec3 xAxis = yAxis.cross(zAxis);
  216. yAxis = zAxis.cross(xAxis);
  217. // printf("%f : %f %f\n", m_dir.m_hour, toDegrees(elevation), toDegrees(azimuth));
  218. Mat3 rot;
  219. rot.setXAxis(xAxis);
  220. rot.setYAxis(yAxis);
  221. rot.setZAxis(zAxis);
  222. m_worldTransform.setRotation(rot);
  223. }
  224. }
  225. m_shapeDirty = false;
  226. m_otherDirty = false;
  227. }
  228. void LightComponent::computeCascadeFrustums(const Frustum& primaryFrustum, ConstWeakArray<F32> cascadeDistances, WeakArray<Mat4> cascadeProjMats,
  229. WeakArray<Mat3x4> cascadeViewMats,
  230. WeakArray<Array<F32, U32(FrustumPlaneType::kCount)>> cascadePlanes) const
  231. {
  232. ANKI_ASSERT(m_type == LightComponentType::kDirectional);
  233. ANKI_ASSERT(m_shadow);
  234. ANKI_ASSERT(cascadeProjMats.getSize() <= kMaxShadowCascades && cascadeProjMats.getSize() > 0);
  235. ANKI_ASSERT(cascadeDistances.getSize() == cascadeProjMats.getSize());
  236. const U32 shadowCascadeCount = cascadeProjMats.getSize();
  237. // Compute the texture matrices
  238. if(primaryFrustum.getFrustumType() == FrustumType::kPerspective)
  239. {
  240. // Get some stuff
  241. const F32 fovX = primaryFrustum.getFovX();
  242. const F32 fovY = primaryFrustum.getFovY();
  243. // Compute a sphere per cascade
  244. Array<Sphere, kMaxShadowCascades> boundingSpheres;
  245. Array<Vec3, 4> prevFarPlaneEdges;
  246. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  247. {
  248. if(cascade == 0)
  249. {
  250. Array<Vec3, 5> edgePoints;
  251. edgePoints[0] = Vec3(0.0f);
  252. computeEdgesOfFrustum(cascadeDistances[cascade], fovX, fovY, &edgePoints[1]);
  253. boundingSpheres[cascade] = computeBoundingSphere(edgePoints.getBegin(), edgePoints.getSize(), sizeof(edgePoints[0]));
  254. memcpy(&prevFarPlaneEdges[0], &edgePoints[1], sizeof(prevFarPlaneEdges));
  255. }
  256. else
  257. {
  258. Array<Vec3, 8> edgePoints;
  259. computeEdgesOfFrustum(cascadeDistances[cascade], fovX, fovY, &edgePoints[0]);
  260. memcpy(&edgePoints[4], &prevFarPlaneEdges[0], sizeof(prevFarPlaneEdges));
  261. boundingSpheres[cascade] = computeBoundingSphere(edgePoints.getBegin(), edgePoints.getSize(), sizeof(edgePoints[0]));
  262. memcpy(&prevFarPlaneEdges[0], &edgePoints[0], sizeof(prevFarPlaneEdges));
  263. }
  264. boundingSpheres[cascade].setCenter(primaryFrustum.getWorldTransform().transform(boundingSpheres[cascade].getCenter()));
  265. }
  266. // Compute the matrices
  267. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  268. {
  269. const Sphere& sphere = boundingSpheres[cascade];
  270. const Vec3 sphereCenter = sphere.getCenter().xyz;
  271. const F32 sphereRadius = sphere.getRadius();
  272. const Vec3& lightDir = getDirection();
  273. Array<Vec3, 2> sceneBounds = SceneGraph::getSingleton().getSceneBounds();
  274. const Vec3 sceneMin = sceneBounds[0] - Vec3(sphereRadius); // Push the bounds a bit
  275. const Vec3 sceneMax = sceneBounds[1] + Vec3(sphereRadius);
  276. // Compute the intersections with the scene bounds
  277. Vec3 eye;
  278. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  279. {
  280. // Inside the scene bounds
  281. const Aabb sceneBox(sceneMin, sceneMax);
  282. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  283. eye = sphereCenter + t * (-lightDir);
  284. }
  285. else
  286. {
  287. eye = sphereCenter + sphereRadius * (-lightDir);
  288. }
  289. // View
  290. const Vec3 zAxis = m_worldTransform.getRotation().getZAxis();
  291. const Vec3 xAxis = Vec3(0.0f, 1.0f, 0.0f).cross(zAxis).normalize();
  292. const Vec3 yAxis = zAxis.cross(xAxis).normalize();
  293. Mat3x4 rot;
  294. rot.setXAxis(xAxis);
  295. rot.setYAxis(yAxis);
  296. rot.setZAxis(zAxis);
  297. rot.setTranslationPart(Vec3(0.0f));
  298. const Transform cascadeTransform(eye.xyz0, rot, Vec4(1.0f, 1.0f, 1.0f, 0.0f));
  299. const Mat4 cascadeViewMat = Mat4(cascadeTransform.invert());
  300. // Projection
  301. const F32 far = (eye - sphereCenter).length() + sphereRadius;
  302. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(sphereRadius, -sphereRadius, sphereRadius, -sphereRadius,
  303. kClusterObjectFrustumNearPlane, far);
  304. if(cascadePlanes.getSize() > 0)
  305. {
  306. cascadePlanes[cascade][FrustumPlaneType::kLeft] = -sphereRadius;
  307. cascadePlanes[cascade][FrustumPlaneType::kRight] = sphereRadius;
  308. cascadePlanes[cascade][FrustumPlaneType::kBottom] = -sphereRadius;
  309. cascadePlanes[cascade][FrustumPlaneType::kTop] = sphereRadius;
  310. cascadePlanes[cascade][FrustumPlaneType::kNear] = kClusterObjectFrustumNearPlane;
  311. cascadePlanes[cascade][FrustumPlaneType::kFar] = far;
  312. }
  313. // Now it's time to stabilize the shadows by aligning the projection matrix
  314. {
  315. // Project a random fixed point to the light matrix
  316. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1;
  317. // Chose a random low shadowmap size and align the random point
  318. const F32 shadowmapSize = 128.0f;
  319. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  320. const F32 alignedX = std::round(randomPointAlmostLightSpace.x * shadowmapSize2) / shadowmapSize2;
  321. const F32 alignedY = std::round(randomPointAlmostLightSpace.y * shadowmapSize2) / shadowmapSize2;
  322. const F32 dx = alignedX - randomPointAlmostLightSpace.x;
  323. const F32 dy = alignedY - randomPointAlmostLightSpace.y;
  324. // Fix the projection matrix by applying an offset
  325. Mat4 correctionTranslationMat = Mat4::getIdentity();
  326. correctionTranslationMat.setTranslationPart(Vec3(dx, dy, 0.0f));
  327. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  328. }
  329. // Write the results
  330. cascadeProjMats[cascade] = cascadeProjMat;
  331. cascadeViewMats[cascade] = Mat3x4(cascadeViewMat);
  332. }
  333. }
  334. else
  335. {
  336. ANKI_ASSERT(!"TODO");
  337. }
  338. }
  339. void LightComponent::setShadowAtlasUvViewports(ConstWeakArray<Vec4> viewports)
  340. {
  341. ANKI_ASSERT(viewports.getSize() <= 6);
  342. if(m_type == LightComponentType::kPoint)
  343. {
  344. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 6);
  345. }
  346. else if(m_type == LightComponentType::kSpot)
  347. {
  348. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 1);
  349. }
  350. else
  351. {
  352. ANKI_ASSERT(viewports.getSize() == 0);
  353. }
  354. const Bool dirty = m_shadowAtlasUvViewportCount != viewports.getSize()
  355. || memcmp(m_shadowAtlasUvViewports.getBegin(), viewports.getBegin(), viewports.getSizeInBytes()) != 0;
  356. if(dirty)
  357. {
  358. m_shadowAtlasUvViewportCount = viewports.getSize() & 0b111;
  359. for(U32 i = 0; i < viewports.getSize(); ++i)
  360. {
  361. m_shadowAtlasUvViewports[i] = viewports[i];
  362. }
  363. m_shapeDirty = true;
  364. }
  365. }
  366. Error LightComponent::serialize(SceneSerializer& serializer)
  367. {
  368. ANKI_SERIALIZE(m_type, 1);
  369. ANKI_SERIALIZE(m_diffColor, 1);
  370. ANKI_SERIALIZE(m_point.m_radius, 1);
  371. ANKI_SERIALIZE(m_spot.m_distance, 1);
  372. ANKI_SERIALIZE(m_spot.m_outerAngle, 1);
  373. ANKI_SERIALIZE(m_spot.m_innerAngle, 1);
  374. ANKI_SERIALIZE(m_dir.m_month, 1);
  375. ANKI_SERIALIZE(m_dir.m_day, 1);
  376. ANKI_SERIALIZE(m_dir.m_hour, 1);
  377. U32 shadow = m_shadow;
  378. ANKI_SERIALIZE(shadow, 1);
  379. m_shadow = Bool(shadow);
  380. return Error::kNone;
  381. }
  382. } // end namespace anki