Light.cpp 19 KB

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