Renderer.h 20 KB

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