Light.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "Light.h"
  27. #include "Node.h"
  28. #include "OctreeQuery.h"
  29. #include "Profiler.h"
  30. #include "ResourceCache.h"
  31. #include "Texture2D.h"
  32. #include "TextureCube.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. static const LightType DEFAULT_LIGHTTYPE = LIGHT_POINT;
  37. static const float DEFAULT_RANGE = 10.0f;
  38. static const float DEFAULT_FOV = 30.0f;
  39. static const float DEFAULT_SPECULARINTENSITY = 1.0f;
  40. static const float DEFAULT_CONSTANTBIAS = 0.0001f;
  41. static const float DEFAULT_SLOPESCALEDBIAS = 0.5f;
  42. static const float DEFAULT_BIASAUTOADJUST = 1.0f;
  43. static const float DEFAULT_SHADOWFADESTART = 0.8f;
  44. static const float DEFAULT_SHADOWQUANTIZE = 0.5f;
  45. static const float DEFAULT_SHADOWMINVIEW = 3.0f;
  46. static const float DEFAULT_SHADOWNEARFARRATIO = 0.002f;
  47. static const char* typeNames[] =
  48. {
  49. "Directional",
  50. "Spot",
  51. "Point",
  52. 0
  53. };
  54. void BiasParameters::Validate()
  55. {
  56. constantBias_ = Clamp(constantBias_, -1.0f, 1.0f);
  57. slopeScaledBias_ = Clamp(slopeScaledBias_, -16.0f, 16.0f);
  58. }
  59. void CascadeParameters::Validate()
  60. {
  61. for (unsigned i = 0; i < MAX_CASCADE_SPLITS; ++i)
  62. splits_[i] = Max(splits_[i], 0.0f);
  63. fadeStart_ = Clamp(fadeStart_, M_EPSILON, 1.0f);
  64. }
  65. void FocusParameters::Validate()
  66. {
  67. quantize_ = Max(quantize_, SHADOW_MIN_QUANTIZE);
  68. minView_ = Max(minView_, SHADOW_MIN_VIEW);
  69. }
  70. template<> LightType Variant::Get<LightType>() const
  71. {
  72. return (LightType)GetInt();
  73. }
  74. OBJECTTYPESTATIC(Light);
  75. Light::Light(Context* context) :
  76. Drawable(context, DRAWABLE_LIGHT),
  77. lightType_(DEFAULT_LIGHTTYPE),
  78. shadowBias_(BiasParameters(DEFAULT_CONSTANTBIAS, DEFAULT_SLOPESCALEDBIAS)),
  79. shadowCascade_(CascadeParameters(M_LARGE_VALUE, 0.0f, 0.0f, 0.0f, DEFAULT_SHADOWFADESTART)),
  80. shadowFocus_(FocusParameters(true, true, true, DEFAULT_SHADOWQUANTIZE, DEFAULT_SHADOWMINVIEW)),
  81. lightQueue_(0),
  82. specularIntensity_(DEFAULT_SPECULARINTENSITY),
  83. range_(DEFAULT_RANGE),
  84. fov_(DEFAULT_FOV),
  85. aspectRatio_(1.0f),
  86. fadeDistance_(0.0f),
  87. shadowFadeDistance_(0.0f),
  88. shadowIntensity_(0.0f),
  89. shadowResolution_(1.0f),
  90. shadowNearFarRatio_(DEFAULT_SHADOWNEARFARRATIO),
  91. perVertex_(false)
  92. {
  93. }
  94. Light::~Light()
  95. {
  96. }
  97. void Light::RegisterObject(Context* context)
  98. {
  99. context->RegisterFactory<Light>();
  100. ACCESSOR_ATTRIBUTE(Light, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  101. ENUM_ACCESSOR_ATTRIBUTE(Light, "Light Type", GetLightType, SetLightType, LightType, typeNames, DEFAULT_LIGHTTYPE, AM_DEFAULT);
  102. REF_ACCESSOR_ATTRIBUTE(Light, VAR_COLOR, "Color", GetColor, SetColor, Color, Color(), AM_DEFAULT);
  103. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Specular Intensity", GetSpecularIntensity, SetSpecularIntensity, float, DEFAULT_SPECULARINTENSITY, AM_DEFAULT);
  104. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Range", GetRange, SetRange, float, DEFAULT_RANGE, AM_DEFAULT);
  105. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Spot FOV", GetFov, SetFov, float, DEFAULT_FOV, AM_DEFAULT);
  106. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Spot Aspect Ratio", GetAspectRatio, SetAspectRatio, float, 1.0f, AM_DEFAULT);
  107. ACCESSOR_ATTRIBUTE(Light, VAR_RESOURCEREF, "Attenuation Texture", GetRampTextureAttr, SetRampTextureAttr, ResourceRef, ResourceRef(Texture2D::GetTypeStatic()), AM_DEFAULT);
  108. ACCESSOR_ATTRIBUTE(Light, VAR_RESOURCEREF, "Light Shape Texture", GetShapeTextureAttr, SetShapeTextureAttr, ResourceRef, ResourceRef(Texture2D::GetTypeStatic()), AM_DEFAULT);
  109. ACCESSOR_ATTRIBUTE(Light, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  110. ATTRIBUTE(Light, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  111. ATTRIBUTE(Light, VAR_BOOL, "Per Vertex", perVertex_, false, AM_DEFAULT);
  112. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  113. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Fade Distance", GetFadeDistance, SetFadeDistance, float, 0.0f, AM_DEFAULT);
  114. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  115. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Fade Distance", GetShadowFadeDistance, SetShadowFadeDistance, float, 0.0f, AM_DEFAULT);
  116. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Intensity", GetShadowIntensity, SetShadowIntensity, float, 0.0f, AM_DEFAULT);
  117. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Resolution", GetShadowResolution, SetShadowResolution, float, 1.0f, AM_DEFAULT);
  118. ATTRIBUTE(Light, VAR_BOOL, "Focus To Scene", shadowFocus_.focus_, true, AM_DEFAULT);
  119. ATTRIBUTE(Light, VAR_BOOL, "Non-uniform View", shadowFocus_.nonUniform_, true, AM_DEFAULT);
  120. ATTRIBUTE(Light, VAR_BOOL, "Auto-Reduce Size", shadowFocus_.autoSize_, true, AM_DEFAULT);
  121. ATTRIBUTE(Light, VAR_VECTOR4, "CSM Splits", shadowCascade_.splits_, Vector4(1000.0f, 0.0f, 0.0f, 0.0f), AM_DEFAULT);
  122. ATTRIBUTE(Light, VAR_FLOAT, "CSM Fade Start", shadowCascade_.fadeStart_, DEFAULT_SHADOWFADESTART, AM_DEFAULT);
  123. ATTRIBUTE(Light, VAR_FLOAT, "CSM Bias Auto Adjust", shadowCascade_.biasAutoAdjust_, DEFAULT_BIASAUTOADJUST, AM_DEFAULT);
  124. ATTRIBUTE(Light, VAR_FLOAT, "View Size Quantize", shadowFocus_.quantize_, DEFAULT_SHADOWQUANTIZE, AM_DEFAULT);
  125. ATTRIBUTE(Light, VAR_FLOAT, "View Size Minimum", shadowFocus_.minView_, DEFAULT_SHADOWMINVIEW, AM_DEFAULT);
  126. ATTRIBUTE(Light, VAR_FLOAT, "Depth Constant Bias", shadowBias_.constantBias_, DEFAULT_CONSTANTBIAS, AM_DEFAULT);
  127. ATTRIBUTE(Light, VAR_FLOAT, "Depth Slope Bias", shadowBias_.slopeScaledBias_, DEFAULT_SLOPESCALEDBIAS, AM_DEFAULT);
  128. ATTRIBUTE(Light, VAR_FLOAT, "Near/Farclip Ratio", shadowNearFarRatio_, DEFAULT_SHADOWNEARFARRATIO, AM_DEFAULT);
  129. ATTRIBUTE(Light, VAR_INT, "View Mask", viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
  130. ATTRIBUTE(Light, VAR_INT, "Light Mask", lightMask_, DEFAULT_LIGHTMASK, AM_DEFAULT);
  131. }
  132. void Light::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  133. {
  134. Component::OnSetAttribute(attr, src);
  135. // Validate the bias, cascade & focus parameters
  136. if (attr.offset_ >= offsetof(Light, shadowBias_) && attr.offset_ < (offsetof(Light, shadowBias_) + sizeof(BiasParameters)))
  137. shadowBias_.Validate();
  138. else if (attr.offset_ >= offsetof(Light, shadowCascade_) && attr.offset_ < (offsetof(Light, shadowCascade_) + sizeof(CascadeParameters)))
  139. shadowCascade_.Validate();
  140. else if (attr.offset_ >= offsetof(Light, shadowFocus_) && attr.offset_ < (offsetof(Light, shadowFocus_) + sizeof(FocusParameters)))
  141. shadowFocus_.Validate();
  142. }
  143. void Light::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  144. {
  145. // Do not record a raycast result for a directional light, as it would block all other results
  146. if (lightType_ == LIGHT_DIRECTIONAL)
  147. return;
  148. float distance;
  149. switch (query.level_)
  150. {
  151. case RAY_AABB_NOSUBOBJECTS:
  152. case RAY_AABB:
  153. Drawable::ProcessRayQuery(query, results);
  154. return;
  155. case RAY_OBB:
  156. {
  157. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  158. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  159. distance = localRay.HitDistance(GetWorldBoundingBox().Transformed(inverse));
  160. if (distance >= query.maxDistance_)
  161. return;
  162. }
  163. break;
  164. case RAY_TRIANGLE:
  165. if (lightType_ == LIGHT_SPOT)
  166. {
  167. distance = query.ray_.HitDistance(GetFrustum());
  168. if (distance >= query.maxDistance_)
  169. return;
  170. }
  171. else // if (lightType_ == LIGHT_POINT)
  172. {
  173. distance = query.ray_.HitDistance(Sphere(node_->GetWorldPosition(), range_));
  174. if (distance >= query.maxDistance_)
  175. return;
  176. }
  177. break;
  178. }
  179. // If the code reaches here then we have a hit
  180. RayQueryResult result;
  181. result.drawable_ = this;
  182. result.node_ = node_;
  183. result.distance_ = distance;
  184. result.subObject_ = M_MAX_UNSIGNED;
  185. results.Push(result);
  186. }
  187. void Light::UpdateBatches(const FrameInfo& frame)
  188. {
  189. switch (lightType_)
  190. {
  191. case LIGHT_DIRECTIONAL:
  192. // Directional light affects the whole scene, so it is always "closest"
  193. distance_ = 0.0f;
  194. break;
  195. default:
  196. distance_ = frame.camera_->GetDistance(node_->GetWorldPosition());
  197. break;
  198. }
  199. }
  200. void Light::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  201. {
  202. if (debug && IsEnabledEffective())
  203. {
  204. switch (lightType_)
  205. {
  206. case LIGHT_DIRECTIONAL:
  207. {
  208. Vector3 start = node_->GetWorldPosition();
  209. Vector3 end = start + node_->GetWorldDirection() * 10.f;
  210. for (short i = -1; i < 2; ++i)
  211. for (short j = -1; j < 2; ++j)
  212. {
  213. Vector3 offset = Vector3::UP * (5.f * i) + Vector3::RIGHT * (5.f * j);
  214. debug->AddSphere(Sphere(start + offset, 0.1f), color_, depthTest);
  215. debug->AddLine(start + offset, end + offset, color_, depthTest);
  216. }
  217. }
  218. break;
  219. case LIGHT_SPOT:
  220. debug->AddFrustum(GetFrustum(), color_, depthTest);
  221. break;
  222. case LIGHT_POINT:
  223. debug->AddSphere(Sphere(node_->GetWorldPosition(), range_), color_, depthTest);
  224. break;
  225. }
  226. }
  227. }
  228. void Light::SetLightType(LightType type)
  229. {
  230. lightType_ = type;
  231. OnMarkedDirty(node_);
  232. MarkNetworkUpdate();
  233. }
  234. void Light::SetPerVertex(bool enable)
  235. {
  236. perVertex_ = enable;
  237. MarkNetworkUpdate();
  238. }
  239. void Light::SetColor(const Color& color)
  240. {
  241. // Clamp RGB values to positive, as negative values behave erratically depending on whether the pass uses
  242. // replace or additive blend mode
  243. color_ = Color(Max(color.r_, 0.0f), Max(color.g_, 0.0f), Max(color.b_, 0.0f), 1.0f);
  244. MarkNetworkUpdate();
  245. }
  246. void Light::SetRange(float range)
  247. {
  248. range_ = Max(range, 0.0f);
  249. OnMarkedDirty(node_);
  250. MarkNetworkUpdate();
  251. }
  252. void Light::SetFov(float fov)
  253. {
  254. fov_ = Clamp(fov, 0.0f, M_MAX_FOV);
  255. OnMarkedDirty(node_);
  256. MarkNetworkUpdate();
  257. }
  258. void Light::SetAspectRatio(float aspectRatio)
  259. {
  260. aspectRatio_ = Max(aspectRatio, M_EPSILON);
  261. OnMarkedDirty(node_);
  262. MarkNetworkUpdate();
  263. }
  264. void Light::SetShadowNearFarRatio(float nearFarRatio)
  265. {
  266. shadowNearFarRatio_ = Clamp(nearFarRatio, 0.0f, 0.5f);
  267. MarkNetworkUpdate();
  268. }
  269. void Light::SetSpecularIntensity(float intensity)
  270. {
  271. specularIntensity_ = Max(intensity, 0.0f);
  272. MarkNetworkUpdate();
  273. }
  274. void Light::SetFadeDistance(float distance)
  275. {
  276. fadeDistance_ = Max(distance, 0.0f);
  277. MarkNetworkUpdate();
  278. }
  279. void Light::SetShadowBias(const BiasParameters& parameters)
  280. {
  281. shadowBias_ = parameters;
  282. shadowBias_.Validate();
  283. MarkNetworkUpdate();
  284. }
  285. void Light::SetShadowCascade(const CascadeParameters& parameters)
  286. {
  287. shadowCascade_ = parameters;
  288. shadowCascade_.Validate();
  289. MarkNetworkUpdate();
  290. }
  291. void Light::SetShadowFocus(const FocusParameters& parameters)
  292. {
  293. shadowFocus_ = parameters;
  294. shadowFocus_.Validate();
  295. MarkNetworkUpdate();
  296. }
  297. void Light::SetShadowFadeDistance(float distance)
  298. {
  299. shadowFadeDistance_ = Max(distance, 0.0f);
  300. MarkNetworkUpdate();
  301. }
  302. void Light::SetShadowIntensity(float intensity)
  303. {
  304. shadowIntensity_ = Clamp(intensity, 0.0f, 1.0f);
  305. MarkNetworkUpdate();
  306. }
  307. void Light::SetShadowResolution(float resolution)
  308. {
  309. shadowResolution_ = Clamp(resolution, 0.125f, 1.0f);
  310. MarkNetworkUpdate();
  311. }
  312. void Light::SetRampTexture(Texture* texture)
  313. {
  314. rampTexture_ = texture;
  315. MarkNetworkUpdate();
  316. }
  317. void Light::SetShapeTexture(Texture* texture)
  318. {
  319. shapeTexture_ = texture;
  320. MarkNetworkUpdate();
  321. }
  322. Frustum Light::GetFrustum() const
  323. {
  324. const Matrix3x4& transform = node_ ? node_->GetWorldTransform() : Matrix3x4::IDENTITY;
  325. Matrix3x4 frustumTransform(transform.Translation(), transform.Rotation(), 1.0f);
  326. Frustum ret;
  327. ret.Define(fov_, aspectRatio_, 1.0f, M_MIN_NEARCLIP, range_, frustumTransform);
  328. return ret;
  329. }
  330. Matrix3x4 Light::GetDirLightTransform(Camera* camera, bool getNearQuad)
  331. {
  332. if (!camera)
  333. return Matrix3x4::IDENTITY;
  334. Vector3 nearVector, farVector;
  335. camera->GetFrustumSize(nearVector, farVector);
  336. float nearClip = camera->GetNearClip();
  337. float farClip = camera->GetFarClip();
  338. float distance = getNearQuad ? nearClip : farClip;
  339. if (!camera->IsOrthographic())
  340. farVector *= (distance / farClip);
  341. else
  342. farVector.z_ *= (distance / farClip);
  343. // Set an epsilon from clip planes due to possible inaccuracy
  344. /// \todo Rather set an identity projection matrix
  345. farVector.z_ = Clamp(farVector.z_, (1.0f + M_LARGE_EPSILON) * nearClip, (1.0f - M_LARGE_EPSILON) * farClip);
  346. return Matrix3x4(Vector3(0.0f, 0.0f, farVector.z_), Quaternion::IDENTITY, Vector3(farVector.x_, farVector.y_, 1.0f));
  347. }
  348. const Matrix3x4& Light::GetVolumeTransform(Camera* camera)
  349. {
  350. const Matrix3x4& transform = node_->GetWorldTransform();
  351. switch (lightType_)
  352. {
  353. case LIGHT_DIRECTIONAL:
  354. volumeTransform_ = GetDirLightTransform(camera);
  355. break;
  356. case LIGHT_SPOT:
  357. {
  358. float yScale = tanf(fov_ * M_DEGTORAD * 0.5f) * range_;
  359. float xScale = aspectRatio_ * yScale;
  360. volumeTransform_ = Matrix3x4(transform.Translation(), transform.Rotation(), Vector3(xScale, yScale, range_));
  361. }
  362. break;
  363. case LIGHT_POINT:
  364. volumeTransform_ = Matrix3x4(transform.Translation(), Quaternion::IDENTITY, range_);
  365. break;
  366. }
  367. return volumeTransform_;
  368. }
  369. void Light::SetRampTextureAttr(ResourceRef value)
  370. {
  371. ResourceCache* cache = GetSubsystem<ResourceCache>();
  372. rampTexture_ = static_cast<Texture*>(cache->GetResource(value.type_, value.id_));
  373. }
  374. void Light::SetShapeTextureAttr(ResourceRef value)
  375. {
  376. ResourceCache* cache = GetSubsystem<ResourceCache>();
  377. shapeTexture_ = static_cast<Texture*>(cache->GetResource(value.type_, value.id_));
  378. }
  379. ResourceRef Light::GetRampTextureAttr() const
  380. {
  381. return GetResourceRef(rampTexture_, Texture2D::GetTypeStatic());
  382. }
  383. ResourceRef Light::GetShapeTextureAttr() const
  384. {
  385. return GetResourceRef(shapeTexture_, Texture2D::GetTypeStatic());
  386. }
  387. void Light::OnWorldBoundingBoxUpdate()
  388. {
  389. switch (lightType_)
  390. {
  391. case LIGHT_DIRECTIONAL:
  392. // Directional light always sets humongous bounding box not affected by transform
  393. worldBoundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE);
  394. break;
  395. case LIGHT_SPOT:
  396. // Frustum is already transformed into world space
  397. worldBoundingBox_.Define(GetFrustum());
  398. break;
  399. case LIGHT_POINT:
  400. {
  401. const Vector3& center = node_->GetWorldPosition();
  402. Vector3 edge(range_, range_, range_);
  403. worldBoundingBox_.Define(center - edge, center + edge);
  404. }
  405. break;
  406. }
  407. }
  408. void Light::SetIntensitySortValue(float distance)
  409. {
  410. // When sorting lights globally, give priority to directional lights so that they will be combined into the ambient pass
  411. if (lightType_ != LIGHT_DIRECTIONAL)
  412. sortValue_ = Max(distance, M_MIN_NEARCLIP) / (color_.Intensity() + M_EPSILON);
  413. else
  414. sortValue_ = M_EPSILON / (color_.Intensity() + M_EPSILON);
  415. // Additionally, give priority to vertex lights so that vertex light base passes can be determined before per pixel lights
  416. if (perVertex_)
  417. sortValue_ -= M_LARGE_VALUE;
  418. }
  419. void Light::SetIntensitySortValue(const BoundingBox& box)
  420. {
  421. // When sorting lights for object's maximum light cap, give priority based on attenuation and intensity
  422. switch (lightType_)
  423. {
  424. case LIGHT_DIRECTIONAL:
  425. sortValue_ = 1.0f / (color_.Intensity() + M_EPSILON);
  426. break;
  427. case LIGHT_SPOT:
  428. {
  429. Vector3 centerPos = box.Center();
  430. Vector3 lightPos = node_->GetWorldPosition();
  431. Vector3 lightDir = node_->GetWorldDirection();
  432. Ray lightRay(lightPos, lightDir);
  433. Vector3 centerProj = lightRay.Project(centerPos);
  434. float centerDistance = (centerProj - lightPos).Length();
  435. Ray centerRay(centerProj, (centerPos - centerProj).Normalized());
  436. float centerAngle = centerRay.HitDistance(box) / centerDistance;
  437. // Check if a corner of the bounding box is closer to the light ray than the center, use its angle in that case
  438. Vector3 cornerPos = centerPos + box.HalfSize() * Vector3(centerPos.x_ < centerProj.x_ ? 1.0f : -1.0f,
  439. centerPos.y_ < centerProj.y_ ? 1.0f : -1.0f, centerPos.z_ < centerProj.z_ ? 1.0f : -1.0f);
  440. Vector3 cornerProj = lightRay.Project(cornerPos);
  441. float cornerDistance = (cornerProj - lightPos).Length();
  442. float cornerAngle = (cornerPos - cornerProj).Length() / cornerDistance;
  443. float spotAngle = Min(centerAngle, cornerAngle);
  444. float maxAngle = tanf(fov_ * M_DEGTORAD * 0.5f);
  445. float spotFactor = Min(spotAngle / maxAngle, 1.0f);
  446. // We do not know the actual range attenuation ramp, so take only spot attenuation into account
  447. float att = Max(1.0f - spotFactor * spotFactor, M_EPSILON);
  448. sortValue_ = 1.0f / (color_.Intensity() * att + M_EPSILON);
  449. }
  450. break;
  451. case LIGHT_POINT:
  452. {
  453. Vector3 centerPos = box.Center();
  454. Vector3 lightPos = node_->GetWorldPosition();
  455. Vector3 lightDir = (centerPos - lightPos).Normalized();
  456. Ray lightRay(lightPos, lightDir);
  457. float distance = lightRay.HitDistance(box);
  458. float normDistance = distance / range_;
  459. float att = Max(1.0f - normDistance * normDistance, M_EPSILON);
  460. sortValue_ = 1.0f / (color_.Intensity() * att + M_EPSILON);
  461. }
  462. break;
  463. }
  464. }
  465. void Light::SetLightQueue(LightBatchQueue* queue)
  466. {
  467. lightQueue_ = queue;
  468. }
  469. }