Light.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. //
  2. // Copyright (c) 2008-2020 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. /// \file
  23. #pragma once
  24. #include "../Math/Color.h"
  25. #include "../Graphics/Drawable.h"
  26. #include "../Math/Frustum.h"
  27. #include "../Graphics/Texture.h"
  28. namespace Urho3D
  29. {
  30. class Camera;
  31. struct LightBatchQueue;
  32. /// %Light types.
  33. enum LightType
  34. {
  35. LIGHT_DIRECTIONAL = 0,
  36. LIGHT_SPOT,
  37. LIGHT_POINT
  38. };
  39. static const float SHADOW_MIN_QUANTIZE = 0.1f;
  40. static const float SHADOW_MIN_VIEW = 1.0f;
  41. static const int MAX_LIGHT_SPLITS = 6;
  42. #ifdef DESKTOP_GRAPHICS
  43. static const unsigned MAX_CASCADE_SPLITS = 4;
  44. #else
  45. static const unsigned MAX_CASCADE_SPLITS = 1;
  46. #endif
  47. /// Depth bias parameters. Used both by lights (for shadow mapping) and materials.
  48. struct URHO3D_API BiasParameters
  49. {
  50. /// Construct undefined.
  51. BiasParameters() = default;
  52. /// Construct with initial values.
  53. BiasParameters(float constantBias, float slopeScaledBias, float normalOffset = 0.0f) :
  54. constantBias_(constantBias),
  55. slopeScaledBias_(slopeScaledBias),
  56. normalOffset_(normalOffset)
  57. {
  58. }
  59. /// Validate parameters.
  60. void Validate();
  61. /// Constant bias.
  62. float constantBias_;
  63. /// Slope scaled bias.
  64. float slopeScaledBias_;
  65. /// Normal offset multiplier.
  66. float normalOffset_;
  67. };
  68. /// Cascaded shadow map parameters.
  69. /// @pod
  70. struct URHO3D_API CascadeParameters
  71. {
  72. /// Construct undefined.
  73. CascadeParameters() = default;
  74. /// Construct with initial values.
  75. CascadeParameters(float split1, float split2, float split3, float split4, float fadeStart, float biasAutoAdjust = 1.0f) :
  76. fadeStart_(fadeStart),
  77. biasAutoAdjust_(biasAutoAdjust)
  78. {
  79. splits_[0] = split1;
  80. splits_[1] = split2;
  81. splits_[2] = split3;
  82. splits_[3] = split4;
  83. }
  84. /// Validate parameters.
  85. void Validate();
  86. /// Return shadow maximum range.
  87. float GetShadowRange() const
  88. {
  89. float ret = 0.0f;
  90. for (unsigned i = 0; i < MAX_CASCADE_SPLITS; ++i)
  91. ret = Max(ret, splits_[i]);
  92. return ret;
  93. }
  94. /// Far clip values of the splits.
  95. Vector4 splits_;
  96. /// The point relative to the total shadow range where shadow fade begins (0.0 - 1.0).
  97. float fadeStart_{};
  98. /// Automatic depth bias adjustment strength.
  99. float biasAutoAdjust_{};
  100. };
  101. /// Shadow map focusing parameters.
  102. /// @pod
  103. struct URHO3D_API FocusParameters
  104. {
  105. /// Construct undefined.
  106. FocusParameters() = default;
  107. /// Construct with initial values.
  108. FocusParameters(bool focus, bool nonUniform, bool autoSize, float quantize, float minView) :
  109. focus_(focus),
  110. nonUniform_(nonUniform),
  111. autoSize_(autoSize),
  112. quantize_(quantize),
  113. minView_(minView)
  114. {
  115. }
  116. /// Validate parameters.
  117. void Validate();
  118. /// Focus flag.
  119. bool focus_;
  120. /// Non-uniform focusing flag.
  121. bool nonUniform_;
  122. /// Auto-size (reduce resolution when far away) flag.
  123. bool autoSize_;
  124. /// Focus quantization.
  125. float quantize_;
  126. /// Minimum view size.
  127. float minView_;
  128. };
  129. /// %Light component.
  130. class URHO3D_API Light : public Drawable
  131. {
  132. URHO3D_OBJECT(Light, Drawable);
  133. public:
  134. /// Construct.
  135. explicit Light(Context* context);
  136. /// Destruct.
  137. ~Light() override;
  138. /// Register object factory. Drawable must be registered first.
  139. static void RegisterObject(Context* context);
  140. /// Process octree raycast. May be called from a worker thread.
  141. void ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results) override;
  142. /// Calculate distance and prepare batches for rendering. May be called from worker thread(s), possibly re-entrantly.
  143. void UpdateBatches(const FrameInfo& frame) override;
  144. /// Visualize the component as debug geometry.
  145. void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
  146. /// Set light type.
  147. /// @property
  148. void SetLightType(LightType type);
  149. /// Set vertex lighting mode.
  150. /// @property
  151. void SetPerVertex(bool enable);
  152. /// Set color.
  153. /// @property
  154. void SetColor(const Color& color);
  155. /// Set temperature of the light in Kelvin. Modulates the light color when "use physical values" is enabled.
  156. /// @property
  157. void SetTemperature(float temperature);
  158. /// Set area light radius. Greater than zero activates area light mode. Works only with PBR shaders.
  159. /// @property
  160. void SetRadius(float radius);
  161. /// Set tube area light length. Works only with PBR shaders.
  162. /// @property
  163. void SetLength(float length);
  164. /// Set use physical light values.
  165. /// @property
  166. void SetUsePhysicalValues(bool enable);
  167. /// Set specular intensity. Zero disables specular calculations.
  168. /// @property
  169. void SetSpecularIntensity(float intensity);
  170. /// Set light brightness multiplier. Both the color and specular intensity are multiplied with this. When "use physical values" is enabled, the value is specified in lumens.
  171. /// @property
  172. void SetBrightness(float brightness);
  173. /// Set range.
  174. /// @property
  175. void SetRange(float range);
  176. /// Set spotlight field of view.
  177. /// @property
  178. void SetFov(float fov);
  179. /// Set spotlight aspect ratio.
  180. /// @property
  181. void SetAspectRatio(float aspectRatio);
  182. /// Set fade out start distance.
  183. /// @property
  184. void SetFadeDistance(float distance);
  185. /// Set shadow fade out start distance. Only has effect if shadow distance is also non-zero.
  186. /// @property
  187. void SetShadowFadeDistance(float distance);
  188. /// Set shadow depth bias parameters.
  189. /// @property
  190. void SetShadowBias(const BiasParameters& parameters);
  191. /// Set directional light cascaded shadow parameters.
  192. /// @property
  193. void SetShadowCascade(const CascadeParameters& parameters);
  194. /// Set shadow map focusing parameters.
  195. /// @property
  196. void SetShadowFocus(const FocusParameters& parameters);
  197. /// Set light intensity in shadow between 0.0 - 1.0. 0.0 (the default) gives fully dark shadows.
  198. /// @property
  199. void SetShadowIntensity(float intensity);
  200. /// Set shadow resolution between 0.25 - 1.0. Determines the shadow map to use.
  201. /// @property
  202. void SetShadowResolution(float resolution);
  203. /// Set shadow camera near/far clip distance ratio for spot and point lights. Does not affect directional lights, since they are orthographic and have near clip 0.
  204. /// @property
  205. void SetShadowNearFarRatio(float nearFarRatio);
  206. /// Set maximum shadow extrusion for directional lights. The actual extrusion will be the smaller of this and camera far clip. Default 1000.
  207. /// @property
  208. void SetShadowMaxExtrusion(float extrusion);
  209. /// Set range attenuation texture.
  210. /// @property
  211. void SetRampTexture(Texture* texture);
  212. /// Set spotlight attenuation texture.
  213. /// @property
  214. void SetShapeTexture(Texture* texture);
  215. /// Return light type.
  216. /// @property
  217. LightType GetLightType() const { return lightType_; }
  218. /// Return vertex lighting mode.
  219. /// @property
  220. bool GetPerVertex() const { return perVertex_; }
  221. /// Return color.
  222. /// @property
  223. const Color& GetColor() const { return color_; }
  224. /// Return the temperature of the light in Kelvin.
  225. /// @property
  226. float GetTemperature() const { return temperature_; }
  227. /// Return area light mode radius. Works only with PBR shaders.
  228. /// @property
  229. float GetRadius() const { return lightRad_; }
  230. /// Return area tube light length. Works only with PBR shaders.
  231. /// @property
  232. float GetLength() const { return lightLength_; }
  233. /// Return if light uses temperature and brightness in lumens.
  234. /// @property
  235. bool GetUsePhysicalValues() const { return usePhysicalValues_; }
  236. /// Return the color value of the temperature in Kelvin.
  237. /// @property
  238. Color GetColorFromTemperature() const;
  239. /// Return specular intensity.
  240. /// @property
  241. float GetSpecularIntensity() const { return specularIntensity_; }
  242. /// Return brightness multiplier. Specified in lumens when "use physical values" is enabled.
  243. /// @property
  244. float GetBrightness() const { return brightness_; }
  245. /// Return effective color, multiplied by brightness and affected by temperature when "use physical values" is enabled. Alpha is always 1 so that can compare against the default black color to detect a light with no effect.
  246. /// @property
  247. Color GetEffectiveColor() const;
  248. /// Return effective specular intensity, multiplied by absolute value of brightness.
  249. /// @property
  250. float GetEffectiveSpecularIntensity() const { return specularIntensity_ * Abs(brightness_); }
  251. /// Return range.
  252. /// @property
  253. float GetRange() const { return range_; }
  254. /// Return spotlight field of view.
  255. /// @property
  256. float GetFov() const { return fov_; }
  257. /// Return spotlight aspect ratio.
  258. /// @property
  259. float GetAspectRatio() const { return aspectRatio_; }
  260. /// Return fade start distance.
  261. /// @property
  262. float GetFadeDistance() const { return fadeDistance_; }
  263. /// Return shadow fade start distance.
  264. /// @property
  265. float GetShadowFadeDistance() const { return shadowFadeDistance_; }
  266. /// Return shadow depth bias parameters.
  267. /// @property
  268. const BiasParameters& GetShadowBias() const { return shadowBias_; }
  269. /// Return directional light cascaded shadow parameters.
  270. /// @property
  271. const CascadeParameters& GetShadowCascade() const { return shadowCascade_; }
  272. /// Return shadow map focus parameters.
  273. /// @property
  274. const FocusParameters& GetShadowFocus() const { return shadowFocus_; }
  275. /// Return light intensity in shadow.
  276. /// @property
  277. float GetShadowIntensity() const { return shadowIntensity_; }
  278. /// Return shadow resolution.
  279. /// @property
  280. float GetShadowResolution() const { return shadowResolution_; }
  281. /// Return shadow camera near/far clip distance ratio.
  282. /// @property
  283. float GetShadowNearFarRatio() const { return shadowNearFarRatio_; }
  284. /// Return maximum shadow extrusion distance for directional lights.
  285. /// @property
  286. float GetShadowMaxExtrusion() const { return shadowMaxExtrusion_; }
  287. /// Return range attenuation texture.
  288. /// @property
  289. Texture* GetRampTexture() const { return rampTexture_; }
  290. /// Return spotlight attenuation texture.
  291. /// @property
  292. Texture* GetShapeTexture() const { return shapeTexture_; }
  293. /// Return spotlight frustum.
  294. /// @property
  295. Frustum GetFrustum() const;
  296. /// Return spotlight frustum in the specified view space.
  297. Frustum GetViewSpaceFrustum(const Matrix3x4& view) const;
  298. /// Return number of shadow map cascade splits for a directional light, considering also graphics API limitations.
  299. /// @property
  300. int GetNumShadowSplits() const;
  301. /// Return whether light has negative (darkening) color.
  302. /// @property
  303. bool IsNegative() const { return GetEffectiveColor().SumRGB() < 0.0f; }
  304. /// Set sort value based on intensity and view distance.
  305. void SetIntensitySortValue(float distance);
  306. /// Set sort value based on overall intensity over a bounding box.
  307. void SetIntensitySortValue(const BoundingBox& box);
  308. /// Set light queue used for this light. Called by View.
  309. void SetLightQueue(LightBatchQueue* queue);
  310. /// Return light volume model transform.
  311. const Matrix3x4& GetVolumeTransform(Camera* camera);
  312. /// Return light queue. Called by View.
  313. LightBatchQueue* GetLightQueue() const { return lightQueue_; }
  314. /// Return a divisor value based on intensity for calculating the sort value.
  315. float GetIntensityDivisor(float attenuation = 1.0f) const
  316. {
  317. return Max(GetEffectiveColor().SumRGB(), 0.0f) * attenuation + M_EPSILON;
  318. }
  319. /// Set ramp texture attribute.
  320. void SetRampTextureAttr(const ResourceRef& value);
  321. /// Set shape texture attribute.
  322. void SetShapeTextureAttr(const ResourceRef& value);
  323. /// Return ramp texture attribute.
  324. ResourceRef GetRampTextureAttr() const;
  325. /// Return shape texture attribute.
  326. ResourceRef GetShapeTextureAttr() const;
  327. /// Return a transform for deferred fullscreen quad (directional light) rendering.
  328. static Matrix3x4 GetFullscreenQuadTransform(Camera* camera);
  329. protected:
  330. /// Recalculate the world-space bounding box.
  331. void OnWorldBoundingBoxUpdate() override;
  332. private:
  333. /// Validate shadow focus.
  334. void ValidateShadowFocus() { shadowFocus_.Validate(); }
  335. /// Validate shadow cascade.
  336. void ValidateShadowCascade() { shadowCascade_.Validate(); }
  337. /// Validate shadow bias.
  338. void ValidateShadowBias() { shadowBias_.Validate(); }
  339. /// Light type.
  340. LightType lightType_;
  341. /// Color.
  342. Color color_;
  343. /// Light temperature.
  344. float temperature_;
  345. /// Radius of the light source. If above 0 it will turn the light into an area light. Works only with PBR shaders.
  346. float lightRad_;
  347. /// Length of the light source. If above 0 and radius is above 0 it will create a tube light. Works only with PBR shaders.
  348. float lightLength_;
  349. /// Shadow depth bias parameters.
  350. BiasParameters shadowBias_;
  351. /// Directional light cascaded shadow parameters.
  352. CascadeParameters shadowCascade_;
  353. /// Shadow map focus parameters.
  354. FocusParameters shadowFocus_;
  355. /// Custom world transform for the light volume.
  356. Matrix3x4 volumeTransform_;
  357. /// Range attenuation texture.
  358. SharedPtr<Texture> rampTexture_;
  359. /// Spotlight attenuation texture.
  360. SharedPtr<Texture> shapeTexture_;
  361. /// Light queue.
  362. LightBatchQueue* lightQueue_;
  363. /// Specular intensity.
  364. float specularIntensity_;
  365. /// Brightness multiplier.
  366. float brightness_;
  367. /// Range.
  368. float range_;
  369. /// Spotlight field of view.
  370. float fov_;
  371. /// Spotlight aspect ratio.
  372. float aspectRatio_;
  373. /// Fade start distance.
  374. float fadeDistance_;
  375. /// Shadow fade start distance.
  376. float shadowFadeDistance_;
  377. /// Light intensity in shadow.
  378. float shadowIntensity_;
  379. /// Shadow resolution.
  380. float shadowResolution_;
  381. /// Shadow camera near/far clip distance ratio.
  382. float shadowNearFarRatio_;
  383. /// Directional shadow max. extrusion distance.
  384. float shadowMaxExtrusion_;
  385. /// Per-vertex lighting flag.
  386. bool perVertex_;
  387. /// Use physical light values flag.
  388. bool usePhysicalValues_;
  389. };
  390. inline bool CompareLights(Light* lhs, Light* rhs)
  391. {
  392. // When sorting lights, give priority to per-vertex lights, so that vertex lit base pass can be evaluated first
  393. if (lhs->GetPerVertex() != rhs->GetPerVertex())
  394. return lhs->GetPerVertex();
  395. else
  396. return lhs->GetSortValue() < rhs->GetSortValue();
  397. }
  398. }