Light.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. //
  2. // Copyright (c) 2008-2022 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. /// @nobind
  140. static void RegisterObject(Context* context);
  141. /// Process octree raycast. May be called from a worker thread.
  142. void ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results) override;
  143. /// Calculate distance and prepare batches for rendering. May be called from worker thread(s), possibly re-entrantly.
  144. void UpdateBatches(const FrameInfo& frame) override;
  145. /// Visualize the component as debug geometry.
  146. void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
  147. /// Set light type.
  148. /// @property
  149. void SetLightType(LightType type);
  150. /// Set vertex lighting mode.
  151. /// @property
  152. void SetPerVertex(bool enable);
  153. /// Set color.
  154. /// @property
  155. void SetColor(const Color& color);
  156. /// Set temperature of the light in Kelvin. Modulates the light color when "use physical values" is enabled.
  157. /// @property
  158. void SetTemperature(float temperature);
  159. /// Set area light radius. Greater than zero activates area light mode. Works only with PBR shaders.
  160. /// @property
  161. void SetRadius(float radius);
  162. /// Set tube area light length. Works only with PBR shaders.
  163. /// @property
  164. void SetLength(float length);
  165. /// Set use physical light values.
  166. /// @property
  167. void SetUsePhysicalValues(bool enable);
  168. /// Set specular intensity. Zero disables specular calculations.
  169. /// @property
  170. void SetSpecularIntensity(float intensity);
  171. /// 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.
  172. /// @property
  173. void SetBrightness(float brightness);
  174. /// Set range.
  175. /// @property
  176. void SetRange(float range);
  177. /// Set spotlight field of view.
  178. /// @property
  179. void SetFov(float fov);
  180. /// Set spotlight aspect ratio.
  181. /// @property
  182. void SetAspectRatio(float aspectRatio);
  183. /// Set fade out start distance.
  184. /// @property
  185. void SetFadeDistance(float distance);
  186. /// Set shadow fade out start distance. Only has effect if shadow distance is also non-zero.
  187. /// @property
  188. void SetShadowFadeDistance(float distance);
  189. /// Set shadow depth bias parameters.
  190. /// @property
  191. void SetShadowBias(const BiasParameters& parameters);
  192. /// Set directional light cascaded shadow parameters.
  193. /// @property
  194. void SetShadowCascade(const CascadeParameters& parameters);
  195. /// Set shadow map focusing parameters.
  196. /// @property
  197. void SetShadowFocus(const FocusParameters& parameters);
  198. /// Set light intensity in shadow between 0.0 - 1.0. 0.0 (the default) gives fully dark shadows.
  199. /// @property
  200. void SetShadowIntensity(float intensity);
  201. /// Set shadow resolution between 0.25 - 1.0. Determines the shadow map to use.
  202. /// @property
  203. void SetShadowResolution(float resolution);
  204. /// 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.
  205. /// @property
  206. void SetShadowNearFarRatio(float nearFarRatio);
  207. /// Set maximum shadow extrusion for directional lights. The actual extrusion will be the smaller of this and camera far clip. Default 1000.
  208. /// @property
  209. void SetShadowMaxExtrusion(float extrusion);
  210. /// Set range attenuation texture.
  211. /// @property
  212. void SetRampTexture(Texture* texture);
  213. /// Set spotlight attenuation texture.
  214. /// @property
  215. void SetShapeTexture(Texture* texture);
  216. /// Return light type.
  217. /// @property
  218. LightType GetLightType() const { return lightType_; }
  219. /// Return vertex lighting mode.
  220. /// @property
  221. bool GetPerVertex() const { return perVertex_; }
  222. /// Return color.
  223. /// @property
  224. const Color& GetColor() const { return color_; }
  225. /// Return the temperature of the light in Kelvin.
  226. /// @property
  227. float GetTemperature() const { return temperature_; }
  228. /// Return area light mode radius. Works only with PBR shaders.
  229. /// @property
  230. float GetRadius() const { return lightRad_; }
  231. /// Return area tube light length. Works only with PBR shaders.
  232. /// @property
  233. float GetLength() const { return lightLength_; }
  234. /// Return if light uses temperature and brightness in lumens.
  235. /// @property
  236. bool GetUsePhysicalValues() const { return usePhysicalValues_; }
  237. /// Return the color value of the temperature in Kelvin.
  238. /// @property
  239. Color GetColorFromTemperature() const;
  240. /// Return specular intensity.
  241. /// @property
  242. float GetSpecularIntensity() const { return specularIntensity_; }
  243. /// Return brightness multiplier. Specified in lumens when "use physical values" is enabled.
  244. /// @property
  245. float GetBrightness() const { return brightness_; }
  246. /// 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.
  247. /// @property
  248. Color GetEffectiveColor() const;
  249. /// Return effective specular intensity, multiplied by absolute value of brightness.
  250. /// @property
  251. float GetEffectiveSpecularIntensity() const { return specularIntensity_ * Abs(brightness_); }
  252. /// Return range.
  253. /// @property
  254. float GetRange() const { return range_; }
  255. /// Return spotlight field of view.
  256. /// @property
  257. float GetFov() const { return fov_; }
  258. /// Return spotlight aspect ratio.
  259. /// @property
  260. float GetAspectRatio() const { return aspectRatio_; }
  261. /// Return fade start distance.
  262. /// @property
  263. float GetFadeDistance() const { return fadeDistance_; }
  264. /// Return shadow fade start distance.
  265. /// @property
  266. float GetShadowFadeDistance() const { return shadowFadeDistance_; }
  267. /// Return shadow depth bias parameters.
  268. /// @property
  269. const BiasParameters& GetShadowBias() const { return shadowBias_; }
  270. /// Return directional light cascaded shadow parameters.
  271. /// @property
  272. const CascadeParameters& GetShadowCascade() const { return shadowCascade_; }
  273. /// Return shadow map focus parameters.
  274. /// @property
  275. const FocusParameters& GetShadowFocus() const { return shadowFocus_; }
  276. /// Return light intensity in shadow.
  277. /// @property
  278. float GetShadowIntensity() const { return shadowIntensity_; }
  279. /// Return shadow resolution.
  280. /// @property
  281. float GetShadowResolution() const { return shadowResolution_; }
  282. /// Return shadow camera near/far clip distance ratio.
  283. /// @property
  284. float GetShadowNearFarRatio() const { return shadowNearFarRatio_; }
  285. /// Return maximum shadow extrusion distance for directional lights.
  286. /// @property
  287. float GetShadowMaxExtrusion() const { return shadowMaxExtrusion_; }
  288. /// Return range attenuation texture.
  289. /// @property
  290. Texture* GetRampTexture() const { return rampTexture_; }
  291. /// Return spotlight attenuation texture.
  292. /// @property
  293. Texture* GetShapeTexture() const { return shapeTexture_; }
  294. /// Return spotlight frustum.
  295. /// @property
  296. Frustum GetFrustum() const;
  297. /// Return spotlight frustum in the specified view space.
  298. Frustum GetViewSpaceFrustum(const Matrix3x4& view) const;
  299. /// Return number of shadow map cascade splits for a directional light, considering also graphics API limitations.
  300. /// @property
  301. int GetNumShadowSplits() const;
  302. /// Return whether light has negative (darkening) color.
  303. /// @property
  304. bool IsNegative() const { return GetEffectiveColor().SumRGB() < 0.0f; }
  305. /// Set sort value based on intensity and view distance.
  306. void SetIntensitySortValue(float distance);
  307. /// Set sort value based on overall intensity over a bounding box.
  308. void SetIntensitySortValue(const BoundingBox& box);
  309. /// Set light queue used for this light. Called by View.
  310. void SetLightQueue(LightBatchQueue* queue);
  311. /// Return light volume model transform.
  312. const Matrix3x4& GetVolumeTransform(Camera* camera);
  313. /// Return light queue. Called by View.
  314. LightBatchQueue* GetLightQueue() const { return lightQueue_; }
  315. /// Return a divisor value based on intensity for calculating the sort value.
  316. float GetIntensityDivisor(float attenuation = 1.0f) const
  317. {
  318. return Max(GetEffectiveColor().SumRGB(), 0.0f) * attenuation + M_EPSILON;
  319. }
  320. /// Set ramp texture attribute.
  321. void SetRampTextureAttr(const ResourceRef& value);
  322. /// Set shape texture attribute.
  323. void SetShapeTextureAttr(const ResourceRef& value);
  324. /// Return ramp texture attribute.
  325. ResourceRef GetRampTextureAttr() const;
  326. /// Return shape texture attribute.
  327. ResourceRef GetShapeTextureAttr() const;
  328. /// Return a transform for deferred fullscreen quad (directional light) rendering.
  329. static Matrix3x4 GetFullscreenQuadTransform(Camera* camera);
  330. protected:
  331. /// Recalculate the world-space bounding box.
  332. void OnWorldBoundingBoxUpdate() override;
  333. private:
  334. /// Validate shadow focus.
  335. void ValidateShadowFocus() { shadowFocus_.Validate(); }
  336. /// Validate shadow cascade.
  337. void ValidateShadowCascade() { shadowCascade_.Validate(); }
  338. /// Validate shadow bias.
  339. void ValidateShadowBias() { shadowBias_.Validate(); }
  340. /// Light type.
  341. LightType lightType_;
  342. /// Color.
  343. Color color_;
  344. /// Light temperature.
  345. float temperature_;
  346. /// Radius of the light source. If above 0 it will turn the light into an area light. Works only with PBR shaders.
  347. float lightRad_;
  348. /// Length of the light source. If above 0 and radius is above 0 it will create a tube light. Works only with PBR shaders.
  349. float lightLength_;
  350. /// Shadow depth bias parameters.
  351. BiasParameters shadowBias_;
  352. /// Directional light cascaded shadow parameters.
  353. CascadeParameters shadowCascade_;
  354. /// Shadow map focus parameters.
  355. FocusParameters shadowFocus_;
  356. /// Custom world transform for the light volume.
  357. Matrix3x4 volumeTransform_;
  358. /// Range attenuation texture.
  359. SharedPtr<Texture> rampTexture_;
  360. /// Spotlight attenuation texture.
  361. SharedPtr<Texture> shapeTexture_;
  362. /// Light queue.
  363. LightBatchQueue* lightQueue_;
  364. /// Specular intensity.
  365. float specularIntensity_;
  366. /// Brightness multiplier.
  367. float brightness_;
  368. /// Range.
  369. float range_;
  370. /// Spotlight field of view.
  371. float fov_;
  372. /// Spotlight aspect ratio.
  373. float aspectRatio_;
  374. /// Fade start distance.
  375. float fadeDistance_;
  376. /// Shadow fade start distance.
  377. float shadowFadeDistance_;
  378. /// Light intensity in shadow.
  379. float shadowIntensity_;
  380. /// Shadow resolution.
  381. float shadowResolution_;
  382. /// Shadow camera near/far clip distance ratio.
  383. float shadowNearFarRatio_;
  384. /// Directional shadow max. extrusion distance.
  385. float shadowMaxExtrusion_;
  386. /// Per-vertex lighting flag.
  387. bool perVertex_;
  388. /// Use physical light values flag.
  389. bool usePhysicalValues_;
  390. };
  391. inline bool CompareLights(Light* lhs, Light* rhs)
  392. {
  393. // When sorting lights, give priority to per-vertex lights, so that vertex lit base pass can be evaluated first
  394. if (lhs->GetPerVertex() != rhs->GetPerVertex())
  395. return lhs->GetPerVertex();
  396. else
  397. return lhs->GetSortValue() < rhs->GetSortValue();
  398. }
  399. }