Renderer.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. //
  2. // Copyright (c) 2008-2015 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 "../Graphics/Batch.h"
  24. #include "../Math/Color.h"
  25. #include "../Graphics/Drawable.h"
  26. #include "../Container/HashSet.h"
  27. #include "../Core/Mutex.h"
  28. #include "../Graphics/Viewport.h"
  29. namespace Atomic
  30. {
  31. class Geometry;
  32. class Drawable;
  33. class Light;
  34. class Material;
  35. class Pass;
  36. class Technique;
  37. class Octree;
  38. class Graphics;
  39. class RenderPath;
  40. class RenderSurface;
  41. class ResourceCache;
  42. class Skeleton;
  43. class OcclusionBuffer;
  44. class Texture;
  45. class Texture2D;
  46. class TextureCube;
  47. class View;
  48. class Zone;
  49. static const int SHADOW_MIN_PIXELS = 64;
  50. static const int INSTANCING_BUFFER_DEFAULT_SIZE = 1024;
  51. /// Light vertex shader variations.
  52. enum LightVSVariation
  53. {
  54. LVS_DIR = 0,
  55. LVS_SPOT,
  56. LVS_POINT,
  57. LVS_SHADOW,
  58. LVS_SPOTSHADOW,
  59. LVS_POINTSHADOW,
  60. MAX_LIGHT_VS_VARIATIONS
  61. };
  62. /// Per-vertex light vertex shader variations.
  63. enum VertexLightVSVariation
  64. {
  65. VLVS_NOLIGHTS = 0,
  66. VLVS_1LIGHT,
  67. VLVS_2LIGHTS,
  68. VLVS_3LIGHTS,
  69. VLVS_4LIGHTS,
  70. MAX_VERTEXLIGHT_VS_VARIATIONS
  71. };
  72. /// Light pixel shader variations.
  73. enum LightPSVariation
  74. {
  75. LPS_NONE = 0,
  76. LPS_SPOT,
  77. LPS_POINT,
  78. LPS_POINTMASK,
  79. LPS_SPEC,
  80. LPS_SPOTSPEC,
  81. LPS_POINTSPEC,
  82. LPS_POINTMASKSPEC,
  83. LPS_SHADOW,
  84. LPS_SPOTSHADOW,
  85. LPS_POINTSHADOW,
  86. LPS_POINTMASKSHADOW,
  87. LPS_SHADOWSPEC,
  88. LPS_SPOTSHADOWSPEC,
  89. LPS_POINTSHADOWSPEC,
  90. LPS_POINTMASKSHADOWSPEC,
  91. MAX_LIGHT_PS_VARIATIONS
  92. };
  93. /// Deferred light volume vertex shader variations.
  94. enum DeferredLightVSVariation
  95. {
  96. DLVS_NONE = 0,
  97. DLVS_DIR,
  98. DLVS_ORTHO,
  99. DLVS_ORTHODIR,
  100. MAX_DEFERRED_LIGHT_VS_VARIATIONS
  101. };
  102. /// Deferred light volume pixels shader variations.
  103. enum DeferredLightPSVariation
  104. {
  105. DLPS_NONE = 0,
  106. DLPS_SPOT,
  107. DLPS_POINT,
  108. DLPS_POINTMASK,
  109. DLPS_SPEC,
  110. DLPS_SPOTSPEC,
  111. DLPS_POINTSPEC,
  112. DLPS_POINTMASKSPEC,
  113. DLPS_SHADOW,
  114. DLPS_SPOTSHADOW,
  115. DLPS_POINTSHADOW,
  116. DLPS_POINTMASKSHADOW,
  117. DLPS_SHADOWSPEC,
  118. DLPS_SPOTSHADOWSPEC,
  119. DLPS_POINTSHADOWSPEC,
  120. DLPS_POINTMASKSHADOWSPEC,
  121. DLPS_ORTHO,
  122. DLPS_ORTHOSPOT,
  123. DLPS_ORTHOPOINT,
  124. DLPS_ORTHOPOINTMASK,
  125. DLPS_ORTHOSPEC,
  126. DLPS_ORTHOSPOTSPEC,
  127. DLPS_ORTHOPOINTSPEC,
  128. DLPS_ORTHOPOINTMASKSPEC,
  129. DLPS_ORTHOSHADOW,
  130. DLPS_ORTHOSPOTSHADOW,
  131. DLPS_ORTHOPOINTSHADOW,
  132. DLPS_ORTHOPOINTMASKSHADOW,
  133. DLPS_ORTHOSHADOWSPEC,
  134. DLPS_ORTHOSPOTSHADOWSPEC,
  135. DLPS_ORTHOPOINTSHADOWSPEC,
  136. DLPS_ORTHOPOINTMASKSHADOWSPEC,
  137. MAX_DEFERRED_LIGHT_PS_VARIATIONS
  138. };
  139. /// High-level rendering subsystem. Manages drawing of 3D views.
  140. class ATOMIC_API Renderer : public Object
  141. {
  142. OBJECT(Renderer);
  143. public:
  144. /// Construct.
  145. Renderer(Context* context);
  146. /// Destruct.
  147. virtual ~Renderer();
  148. /// Set number of backbuffer viewports to render.
  149. void SetNumViewports(unsigned num);
  150. /// Set a backbuffer viewport.
  151. void SetViewport(unsigned index, Viewport* viewport);
  152. /// Set default renderpath.
  153. void SetDefaultRenderPath(RenderPath* renderPath);
  154. /// Set default renderpath from an XML file.
  155. void SetDefaultRenderPath(XMLFile* file);
  156. /// Set HDR rendering on/off.
  157. void SetHDRRendering(bool enable);
  158. /// Set specular lighting on/off.
  159. void SetSpecularLighting(bool enable);
  160. /// Set texture anisotropy.
  161. void SetTextureAnisotropy(int level);
  162. /// Set texture filtering.
  163. void SetTextureFilterMode(TextureFilterMode mode);
  164. /// Set texture quality level. See the QUALITY constants in GraphicsDefs.h.
  165. void SetTextureQuality(int quality);
  166. /// Set material quality level. See the QUALITY constants in GraphicsDefs.h.
  167. void SetMaterialQuality(int quality);
  168. /// Set shadows on/off.
  169. void SetDrawShadows(bool enable);
  170. /// Set shadow map resolution.
  171. void SetShadowMapSize(int size);
  172. /// Set shadow quality mode. See the SHADOWQUALITY constants in GraphicsDefs.h.
  173. void SetShadowQuality(int quality);
  174. /// Set reuse of shadow maps. Default is true. If disabled, also transparent geometry can be shadowed.
  175. void SetReuseShadowMaps(bool enable);
  176. /// Set maximum number of shadow maps created for one resolution. Only has effect if reuse of shadow maps is disabled.
  177. void SetMaxShadowMaps(int shadowMaps);
  178. /// Set dynamic instancing on/off.
  179. void SetDynamicInstancing(bool enable);
  180. /// Set minimum number of instances required in a batch group to render as instanced.
  181. void SetMinInstances(int instances);
  182. /// Set maximum number of sorted instances per batch group. If exceeded, instances are rendered unsorted.
  183. void SetMaxSortedInstances(int instances);
  184. /// Set maximum number of occluder trianges.
  185. void SetMaxOccluderTriangles(int triangles);
  186. /// Set occluder buffer width.
  187. void SetOcclusionBufferSize(int size);
  188. /// Set required screen size (1.0 = full screen) for occluders.
  189. void SetOccluderSizeThreshold(float screenSize);
  190. /// Set shadow depth bias multiplier for mobile platforms (OpenGL ES.) No effect on desktops. Default 2.
  191. void SetMobileShadowBiasMul(float mul);
  192. /// Set shadow depth bias addition for mobile platforms (OpenGL ES.) No effect on desktops. Default 0.0001.
  193. void SetMobileShadowBiasAdd(float add);
  194. /// Force reload of shaders.
  195. void ReloadShaders();
  196. /// Return number of backbuffer viewports.
  197. unsigned GetNumViewports() const { return viewports_.Size(); }
  198. /// Return backbuffer viewport by index.
  199. Viewport* GetViewport(unsigned index) const;
  200. /// Return default renderpath.
  201. RenderPath* GetDefaultRenderPath() const;
  202. /// Return whether HDR rendering is enabled.
  203. bool GetHDRRendering() const { return hdrRendering_; }
  204. /// Return whether specular lighting is enabled.
  205. bool GetSpecularLighting() const { return specularLighting_; }
  206. /// Return whether drawing shadows is enabled.
  207. bool GetDrawShadows() const { return drawShadows_; }
  208. /// Return texture anisotropy.
  209. int GetTextureAnisotropy() const { return textureAnisotropy_; }
  210. /// Return texture filtering.
  211. TextureFilterMode GetTextureFilterMode() const { return textureFilterMode_; }
  212. /// Return texture quality level.
  213. int GetTextureQuality() const { return textureQuality_; }
  214. /// Return material quality level.
  215. int GetMaterialQuality() const { return materialQuality_; }
  216. /// Return shadow map resolution.
  217. int GetShadowMapSize() const { return shadowMapSize_; }
  218. /// Return shadow quality.
  219. int GetShadowQuality() const { return shadowQuality_; }
  220. /// Return whether shadow maps are reused.
  221. bool GetReuseShadowMaps() const { return reuseShadowMaps_; }
  222. /// Return maximum number of shadow maps per resolution.
  223. int GetMaxShadowMaps() const { return maxShadowMaps_; }
  224. /// Return whether dynamic instancing is in use.
  225. bool GetDynamicInstancing() const { return dynamicInstancing_; }
  226. /// Return minimum number of instances required in a batch group to render as instanced.
  227. int GetMinInstances() const { return minInstances_; }
  228. /// Return maximum number of sorted instances per batch group.
  229. int GetMaxSortedInstances() const { return maxSortedInstances_; }
  230. /// Return maximum number of occluder triangles.
  231. int GetMaxOccluderTriangles() const { return maxOccluderTriangles_; }
  232. /// Return occlusion buffer width.
  233. int GetOcclusionBufferSize() const { return occlusionBufferSize_; }
  234. /// Return occluder screen size threshold.
  235. float GetOccluderSizeThreshold() const { return occluderSizeThreshold_; }
  236. /// Return shadow depth bias multiplier for mobile platforms.
  237. float GetMobileShadowBiasMul() const { return mobileShadowBiasMul_; }
  238. /// Return shadow depth bias addition for mobile platforms.
  239. float GetMobileShadowBiasAdd() const { return mobileShadowBiasAdd_; }
  240. /// Return number of views rendered.
  241. unsigned GetNumViews() const { return views_.Size(); }
  242. /// Return number of primitives rendered.
  243. unsigned GetNumPrimitives() const { return numPrimitives_; }
  244. /// Return number of batches rendered.
  245. unsigned GetNumBatches() const { return numBatches_; }
  246. /// Return number of geometries rendered.
  247. unsigned GetNumGeometries(bool allViews = false) const;
  248. /// Return number of lights rendered.
  249. unsigned GetNumLights(bool allViews = false) const;
  250. /// Return number of shadow maps rendered.
  251. unsigned GetNumShadowMaps(bool allViews = false) const;
  252. /// Return number of occluders rendered.
  253. unsigned GetNumOccluders(bool allViews = false) const;
  254. /// Return the default zone.
  255. Zone* GetDefaultZone() const { return defaultZone_; }
  256. /// Return the default material.
  257. Material* GetDefaultMaterial() const { return defaultMaterial_; }
  258. /// Return the default range attenuation texture.
  259. Texture2D* GetDefaultLightRamp() const { return defaultLightRamp_; }
  260. /// Return the default spotlight attenuation texture.
  261. Texture2D* GetDefaultLightSpot() const { return defaultLightSpot_; }
  262. /// Return the shadowed pointlight face selection cube map.
  263. TextureCube* GetFaceSelectCubeMap() const { return faceSelectCubeMap_; }
  264. /// Return the shadowed pointlight indirection cube map.
  265. TextureCube* GetIndirectionCubeMap() const { return indirectionCubeMap_; }
  266. /// Return the instancing vertex buffer
  267. VertexBuffer* GetInstancingBuffer() const { return dynamicInstancing_ ? instancingBuffer_ : (VertexBuffer*)0; }
  268. /// Return the frame update parameters.
  269. const FrameInfo& GetFrameInfo() const { return frame_; }
  270. /// Update for rendering. Called by HandleRenderUpdate().
  271. void Update(float timeStep);
  272. /// Render. Called by Engine.
  273. void Render();
  274. /// Add debug geometry to the debug renderer.
  275. void DrawDebugGeometry(bool depthTest);
  276. /// Queue a render surface's viewports for rendering. Called by the surface, or by View.
  277. void QueueRenderSurface(RenderSurface* renderTarget);
  278. /// Queue a viewport for rendering. Null surface means backbuffer.
  279. void QueueViewport(RenderSurface* renderTarget, Viewport* viewport);
  280. /// Return volume geometry for a light.
  281. Geometry* GetLightGeometry(Light* light);
  282. /// Return quad geometry used in postprocessing.
  283. Geometry* GetQuadGeometry();
  284. /// Allocate a shadow map. If shadow map reuse is disabled, a different map is returned each time.
  285. Texture2D* GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight);
  286. /// Allocate a rendertarget or depth-stencil texture for deferred rendering or postprocessing. Should only be called during actual rendering, not before.
  287. Texture* GetScreenBuffer(int width, int height, unsigned format, bool cubemap, bool filtered, bool srgb, unsigned persistentKey = 0);
  288. /// Allocate a depth-stencil surface that does not need to be readable. Should only be called during actual rendering, not before.
  289. RenderSurface* GetDepthStencil(int width, int height);
  290. /// Allocate an occlusion buffer.
  291. OcclusionBuffer* GetOcclusionBuffer(Camera* camera);
  292. /// Allocate a temporary shadow camera and a scene node for it. Is thread-safe.
  293. Camera* GetShadowCamera();
  294. /// Choose shaders for a forward rendering batch.
  295. void SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows = true);
  296. /// Choose shaders for a deferred light volume batch.
  297. void SetLightVolumeBatchShaders(Batch& batch, const String& vsName, const String& psName, const String& vsDefines, const String& psDefines);
  298. /// Set cull mode while taking possible projection flipping into account.
  299. void SetCullMode(CullMode mode, Camera* camera);
  300. /// Ensure sufficient size of the instancing vertex buffer. Return true if successful.
  301. bool ResizeInstancingBuffer(unsigned numInstances);
  302. /// Save the screen buffer allocation status. Called by View.
  303. void SaveScreenBufferAllocations();
  304. /// Restore the screen buffer allocation status. Called by View.
  305. void RestoreScreenBufferAllocations();
  306. /// Optimize a light by scissor rectangle.
  307. void OptimizeLightByScissor(Light* light, Camera* camera);
  308. /// Optimize a light by marking it to the stencil buffer and setting a stencil test.
  309. void OptimizeLightByStencil(Light* light, Camera* camera);
  310. /// Return a scissor rectangle for a light.
  311. const Rect& GetLightScissor(Light* light, Camera* camera);
  312. private:
  313. /// Initialize when screen mode initially set.
  314. void Initialize();
  315. /// Reload shaders.
  316. void LoadShaders();
  317. /// Reload shaders for a material pass.
  318. void LoadPassShaders(Pass* pass);
  319. /// Release shaders used in materials.
  320. void ReleaseMaterialShaders();
  321. /// Reload textures.
  322. void ReloadTextures();
  323. /// Create light volume geometries.
  324. void CreateGeometries();
  325. /// Create instancing vertex buffer.
  326. void CreateInstancingBuffer();
  327. /// Create point light shadow indirection texture data.
  328. void SetIndirectionTextureData();
  329. /// Prepare for rendering of a new view.
  330. void PrepareViewRender();
  331. /// Remove unused occlusion and screen buffers.
  332. void RemoveUnusedBuffers();
  333. /// Reset shadow map allocation counts.
  334. void ResetShadowMapAllocations();
  335. /// Reset screem buffer allocation counts.
  336. void ResetScreenBufferAllocations();
  337. /// Remove all shadow maps. Called when global shadow map resolution or format is changed.
  338. void ResetShadowMaps();
  339. /// Remove all occlusion and screen buffers.
  340. void ResetBuffers();
  341. /// Handle screen mode event.
  342. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  343. /// Handle render update event.
  344. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  345. /// Graphics subsystem.
  346. WeakPtr<Graphics> graphics_;
  347. /// Default renderpath.
  348. SharedPtr<RenderPath> defaultRenderPath_;
  349. /// Default zone.
  350. SharedPtr<Zone> defaultZone_;
  351. /// Directional light quad geometry.
  352. SharedPtr<Geometry> dirLightGeometry_;
  353. /// Spot light volume geometry.
  354. SharedPtr<Geometry> spotLightGeometry_;
  355. /// Point light volume geometry.
  356. SharedPtr<Geometry> pointLightGeometry_;
  357. /// Instance stream vertex buffer.
  358. SharedPtr<VertexBuffer> instancingBuffer_;
  359. /// Default material.
  360. SharedPtr<Material> defaultMaterial_;
  361. /// Default range attenuation texture.
  362. SharedPtr<Texture2D> defaultLightRamp_;
  363. /// Default spotlight attenuation texture.
  364. SharedPtr<Texture2D> defaultLightSpot_;
  365. /// Face selection cube map for shadowed pointlights.
  366. SharedPtr<TextureCube> faceSelectCubeMap_;
  367. /// Indirection cube map for shadowed pointlights.
  368. SharedPtr<TextureCube> indirectionCubeMap_;
  369. /// Reusable scene nodes with shadow camera components.
  370. Vector<SharedPtr<Node> > shadowCameraNodes_;
  371. /// Reusable occlusion buffers.
  372. Vector<SharedPtr<OcclusionBuffer> > occlusionBuffers_;
  373. /// Shadow maps by resolution.
  374. HashMap<int, Vector<SharedPtr<Texture2D> > > shadowMaps_;
  375. /// Shadow map dummy color buffers by resolution.
  376. HashMap<int, SharedPtr<Texture2D> > colorShadowMaps_;
  377. /// Shadow map allocations by resolution.
  378. HashMap<int, PODVector<Light*> > shadowMapAllocations_;
  379. /// Screen buffers by resolution and format.
  380. HashMap<long long, Vector<SharedPtr<Texture> > > screenBuffers_;
  381. /// Current screen buffer allocations by resolution and format.
  382. HashMap<long long, unsigned> screenBufferAllocations_;
  383. /// Saved status of screen buffer allocations for restoring.
  384. HashMap<long long, unsigned> savedScreenBufferAllocations_;
  385. /// Cache for light scissor queries.
  386. HashMap<Pair<Light*, Camera*>, Rect> lightScissorCache_;
  387. /// Backbuffer viewports.
  388. Vector<SharedPtr<Viewport> > viewports_;
  389. /// Render surface viewports queued for update.
  390. Vector<Pair<WeakPtr<RenderSurface>, WeakPtr<Viewport> > > queuedViewports_;
  391. /// Views that have been processed this frame.
  392. Vector<WeakPtr<View> > views_;
  393. /// Octrees that have been updated during the frame.
  394. HashSet<Octree*> updatedOctrees_;
  395. /// Techniques for which missing shader error has been displayed.
  396. HashSet<Technique*> shaderErrorDisplayed_;
  397. /// Mutex for shadow camera allocation.
  398. Mutex rendererMutex_;
  399. /// Current variation names for deferred light volume shaders.
  400. Vector<String> deferredLightPSVariations_;
  401. /// Frame info for rendering.
  402. FrameInfo frame_;
  403. /// Texture anisotropy level.
  404. int textureAnisotropy_;
  405. /// Texture filtering mode.
  406. TextureFilterMode textureFilterMode_;
  407. /// Texture quality level.
  408. int textureQuality_;
  409. /// Material quality level.
  410. int materialQuality_;
  411. /// Shadow map resolution.
  412. int shadowMapSize_;
  413. /// Shadow quality.
  414. int shadowQuality_;
  415. /// Maximum number of shadow maps per resolution.
  416. int maxShadowMaps_;
  417. /// Minimum number of instances required in a batch group to render as instanced.
  418. int minInstances_;
  419. /// Maximum sorted instances per batch group.
  420. int maxSortedInstances_;
  421. /// Maximum occluder triangles.
  422. int maxOccluderTriangles_;
  423. /// Occlusion buffer width.
  424. int occlusionBufferSize_;
  425. /// Occluder screen size threshold.
  426. float occluderSizeThreshold_;
  427. /// Mobile platform shadow depth bias multiplier.
  428. float mobileShadowBiasMul_;
  429. /// Mobile platform shadow depth bias addition.
  430. float mobileShadowBiasAdd_;
  431. /// Number of occlusion buffers in use.
  432. unsigned numOcclusionBuffers_;
  433. /// Number of temporary shadow cameras in use.
  434. unsigned numShadowCameras_;
  435. /// Number of primitives (3D geometry only.)
  436. unsigned numPrimitives_;
  437. /// Number of batches (3D geometry only.)
  438. unsigned numBatches_;
  439. /// Frame number on which shaders last changed.
  440. unsigned shadersChangedFrameNumber_;
  441. /// Current stencil value for light optimization.
  442. unsigned char lightStencilValue_;
  443. /// HDR rendering flag.
  444. bool hdrRendering_;
  445. /// Specular lighting flag.
  446. bool specularLighting_;
  447. /// Draw shadows flag.
  448. bool drawShadows_;
  449. /// Shadow map reuse flag.
  450. bool reuseShadowMaps_;
  451. /// Dynamic instancing flag.
  452. bool dynamicInstancing_;
  453. /// Shaders need reloading flag.
  454. bool shadersDirty_;
  455. /// Initialized flag.
  456. bool initialized_;
  457. /// Flag for views needing reset.
  458. bool resetViews_;
  459. };
  460. }