Light.h 15 KB

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