Renderer.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. /// Force reload of shaders.
  192. void ReloadShaders();
  193. /// Return number of backbuffer viewports.
  194. unsigned GetNumViewports() const { return viewports_.Size(); }
  195. /// Return backbuffer viewport by index.
  196. Viewport* GetViewport(unsigned index) const;
  197. /// Return default renderpath.
  198. RenderPath* GetDefaultRenderPath() const;
  199. /// Return whether HDR rendering is enabled.
  200. bool GetHDRRendering() const { return hdrRendering_; }
  201. /// Return whether specular lighting is enabled.
  202. bool GetSpecularLighting() const { return specularLighting_; }
  203. /// Return whether drawing shadows is enabled.
  204. bool GetDrawShadows() const { return drawShadows_; }
  205. /// Return texture anisotropy.
  206. int GetTextureAnisotropy() const { return textureAnisotropy_; }
  207. /// Return texture filtering.
  208. TextureFilterMode GetTextureFilterMode() const { return textureFilterMode_; }
  209. /// Return texture quality level.
  210. int GetTextureQuality() const { return textureQuality_; }
  211. /// Return material quality level.
  212. int GetMaterialQuality() const { return materialQuality_; }
  213. /// Return shadow map resolution.
  214. int GetShadowMapSize() const { return shadowMapSize_; }
  215. /// Return shadow quality.
  216. int GetShadowQuality() const { return shadowQuality_; }
  217. /// Return whether shadow maps are reused.
  218. bool GetReuseShadowMaps() const { return reuseShadowMaps_; }
  219. /// Return maximum number of shadow maps per resolution.
  220. int GetMaxShadowMaps() const { return maxShadowMaps_; }
  221. /// Return whether dynamic instancing is in use.
  222. bool GetDynamicInstancing() const { return dynamicInstancing_; }
  223. /// Return minimum number of instances required in a batch group to render as instanced.
  224. int GetMinInstances() const { return minInstances_; }
  225. /// Return maximum number of triangles per object for instancing.
  226. int GetMaxInstanceTriangles() const { return maxInstanceTriangles_; }
  227. /// Return maximum number of sorted instances per batch group.
  228. int GetMaxSortedInstances() const { return maxSortedInstances_; }
  229. /// Return maximum number of occluder triangles.
  230. int GetMaxOccluderTriangles() const { return maxOccluderTriangles_; }
  231. /// Return occlusion buffer width.
  232. int GetOcclusionBufferSize() const { return occlusionBufferSize_; }
  233. /// Return occluder screen size threshold.
  234. float GetOccluderSizeThreshold() const { return occluderSizeThreshold_; }
  235. /// Return number of views rendered.
  236. unsigned GetNumViews() const { return numViews_; }
  237. /// Return number of primitives rendered.
  238. unsigned GetNumPrimitives() const { return numPrimitives_; }
  239. /// Return number of batches rendered.
  240. unsigned GetNumBatches() const { return numBatches_; }
  241. /// Return number of geometries rendered.
  242. unsigned GetNumGeometries(bool allViews = false) const;
  243. /// Return number of lights rendered.
  244. unsigned GetNumLights(bool allViews = false) const;
  245. /// Return number of shadow maps rendered.
  246. unsigned GetNumShadowMaps(bool allViews = false) const;
  247. /// Return number of occluders rendered.
  248. unsigned GetNumOccluders(bool allViews = false) const;
  249. /// Return the default zone.
  250. Zone* GetDefaultZone() const { return defaultZone_; }
  251. /// Return the directional light for fullscreen quad rendering.
  252. Light* GetQuadDirLight() const { return quadDirLight_; }
  253. /// Return the default material.
  254. Material* GetDefaultMaterial() const { return defaultMaterial_; }
  255. /// Return the default range attenuation texture.
  256. Texture2D* GetDefaultLightRamp() const { return defaultLightRamp_; }
  257. /// Return the default spotlight attenuation texture.
  258. Texture2D* GetDefaultLightSpot() const { return defaultLightSpot_; }
  259. /// Return the shadowed pointlight face selection cube map.
  260. TextureCube* GetFaceSelectCubeMap() const { return faceSelectCubeMap_; }
  261. /// Return the shadowed pointlight indirection cube map.
  262. TextureCube* GetIndirectionCubeMap() const { return indirectionCubeMap_; }
  263. /// Return the instancing vertex buffer
  264. VertexBuffer* GetInstancingBuffer() const { return dynamicInstancing_ ? instancingBuffer_ : (VertexBuffer*)0; }
  265. /// Return the frame update parameters.
  266. const FrameInfo& GetFrameInfo() const { return frame_; }
  267. /// Update for rendering. Called by HandleRenderUpdate().
  268. void Update(float timeStep);
  269. /// Render. Called by Engine.
  270. void Render();
  271. /// Add debug geometry to the debug renderer.
  272. void DrawDebugGeometry(bool depthTest);
  273. /// Queue a render surface's viewports for rendering. Called by the surface, or by View.
  274. void QueueRenderSurface(RenderSurface* renderTarget);
  275. /// Queue a viewport for rendering. Null surface means backbuffer.
  276. void QueueViewport(RenderSurface* renderTarget, Viewport* viewport);
  277. /// Return volume geometry for a light.
  278. Geometry* GetLightGeometry(Light* light);
  279. /// Allocate a shadow map. If shadow map reuse is disabled, a different map is returned each time.
  280. Texture2D* GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight);
  281. /// Allocate a rendertarget or depth-stencil texture for deferred rendering or postprocessing. Should only be called during actual rendering, not before.
  282. Texture2D* GetScreenBuffer(int width, int height, unsigned format, bool filtered, bool srgb, unsigned persistentKey = 0);
  283. /// Allocate a depth-stencil surface that does not need to be readable. Should only be called during actual rendering, not before.
  284. RenderSurface* GetDepthStencil(int width, int height);
  285. /// Allocate an occlusion buffer.
  286. OcclusionBuffer* GetOcclusionBuffer(Camera* camera);
  287. /// Allocate a temporary shadow camera and a scene node for it. Is thread-safe.
  288. Camera* GetShadowCamera();
  289. /// Choose shaders for a forward rendering batch.
  290. void SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows = true);
  291. /// Choose shaders for a deferred light volume batch.
  292. void SetLightVolumeBatchShaders(Batch& batch, const String& vsName, const String& psName);
  293. /// Set cull mode while taking possible projection flipping into account.
  294. void SetCullMode(CullMode mode, Camera* camera);
  295. /// Ensure sufficient size of the instancing vertex buffer. Return true if successful.
  296. bool ResizeInstancingBuffer(unsigned numInstances);
  297. /// Save the screen buffer allocation status. Called by View.
  298. void SaveScreenBufferAllocations();
  299. /// Restore the screen buffer allocation status. Called by View.
  300. void RestoreScreenBufferAllocations();
  301. /// Optimize a light by scissor rectangle.
  302. void OptimizeLightByScissor(Light* light, Camera* camera);
  303. /// Optimize a light by marking it to the stencil buffer and setting a stencil test.
  304. void OptimizeLightByStencil(Light* light, Camera* camera);
  305. /// Return a scissor rectangle for a light.
  306. const Rect& GetLightScissor(Light* light, Camera* camera);
  307. private:
  308. /// Initialize when screen mode initially set.
  309. void Initialize();
  310. /// Clear views from previous frame.
  311. void ResetViews();
  312. /// Reload shaders.
  313. void LoadShaders();
  314. /// Reload shaders for a material pass.
  315. void LoadPassShaders(Technique* tech, StringHash passType);
  316. /// Release shaders used in materials.
  317. void ReleaseMaterialShaders();
  318. /// Reload textures.
  319. void ReloadTextures();
  320. /// Create light volume geometries.
  321. void CreateGeometries();
  322. /// Create instancing vertex buffer.
  323. void CreateInstancingBuffer();
  324. /// Create point light shadow indirection texture data.
  325. void SetIndirectionTextureData();
  326. /// Prepare for rendering of a new view.
  327. void PrepareViewRender();
  328. /// Remove unused occlusion and screen buffers.
  329. void RemoveUnusedBuffers();
  330. /// Reset shadow map allocation counts.
  331. void ResetShadowMapAllocations();
  332. /// Reset screem buffer allocation counts.
  333. void ResetScreenBufferAllocations();
  334. /// Remove all shadow maps. Called when global shadow map resolution or format is changed.
  335. void ResetShadowMaps();
  336. /// Remove all occlusion and screen buffers.
  337. void ResetBuffers();
  338. /// Handle screen mode event.
  339. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  340. /// Handle graphics features (re)check event. Event only sent by D3D9Graphics class.
  341. void HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData);
  342. /// Handle render update event.
  343. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  344. /// Graphics subsystem.
  345. WeakPtr<Graphics> graphics_;
  346. /// Default renderpath.
  347. SharedPtr<RenderPath> defaultRenderPath_;
  348. /// Default zone.
  349. SharedPtr<Zone> defaultZone_;
  350. /// Directional light for drawing fullscreen quads.
  351. SharedPtr<Light> quadDirLight_;
  352. /// Directional light quad geometry.
  353. SharedPtr<Geometry> dirLightGeometry_;
  354. /// Spot light volume geometry.
  355. SharedPtr<Geometry> spotLightGeometry_;
  356. /// Point light volume geometry.
  357. SharedPtr<Geometry> pointLightGeometry_;
  358. /// Instance stream vertex buffer.
  359. SharedPtr<VertexBuffer> instancingBuffer_;
  360. /// Default material.
  361. SharedPtr<Material> defaultMaterial_;
  362. /// Default range attenuation texture.
  363. SharedPtr<Texture2D> defaultLightRamp_;
  364. /// Default spotlight attenuation texture.
  365. SharedPtr<Texture2D> defaultLightSpot_;
  366. /// Face selection cube map for shadowed pointlights.
  367. SharedPtr<TextureCube> faceSelectCubeMap_;
  368. /// Indirection cube map for shadowed pointlights.
  369. SharedPtr<TextureCube> indirectionCubeMap_;
  370. /// Reusable scene nodes with shadow camera components.
  371. Vector<SharedPtr<Node> > shadowCameraNodes_;
  372. /// Reusable occlusion buffers.
  373. Vector<SharedPtr<OcclusionBuffer> > occlusionBuffers_;
  374. /// Shadow maps by resolution.
  375. HashMap<int, Vector<SharedPtr<Texture2D> > > shadowMaps_;
  376. /// Shadow map dummy color buffers by resolution.
  377. HashMap<int, SharedPtr<Texture2D> > colorShadowMaps_;
  378. /// Shadow map allocations by resolution.
  379. HashMap<int, PODVector<Light*> > shadowMapAllocations_;
  380. /// Screen buffers by resolution and format.
  381. HashMap<long long, Vector<SharedPtr<Texture2D> > > screenBuffers_;
  382. /// Current screen buffer allocations by resolution and format.
  383. HashMap<long long, unsigned> screenBufferAllocations_;
  384. /// Saved status of screen buffer allocations for restoring.
  385. HashMap<long long, unsigned> savedScreenBufferAllocations_;
  386. /// Cache for light scissor queries.
  387. HashMap<Pair<Light*, Camera*>, Rect> lightScissorCache_;
  388. /// Viewports.
  389. Vector<SharedPtr<Viewport> > viewports_;
  390. /// Queued views.
  391. Vector<Pair<WeakPtr<RenderSurface>, WeakPtr<Viewport> > > queuedViews_;
  392. /// Views.
  393. Vector<SharedPtr<View> > views_;
  394. /// Octrees that have been updated during the frame.
  395. HashSet<Octree*> updatedOctrees_;
  396. /// Techniques for which missing shader error has been displayed.
  397. HashSet<Technique*> shaderErrorDisplayed_;
  398. /// Mutex for shadow camera allocation.
  399. Mutex rendererMutex_;
  400. /// Current variation names for deferred light volume shaders.
  401. Vector<String> deferredLightPSVariations_;
  402. /// Frame info for rendering.
  403. FrameInfo frame_;
  404. /// Texture anisotropy level.
  405. int textureAnisotropy_;
  406. /// Texture filtering mode.
  407. TextureFilterMode textureFilterMode_;
  408. /// Texture quality level.
  409. int textureQuality_;
  410. /// Material quality level.
  411. int materialQuality_;
  412. /// Shadow map resolution.
  413. int shadowMapSize_;
  414. /// Shadow quality.
  415. int shadowQuality_;
  416. /// Maximum number of shadow maps per resolution.
  417. int maxShadowMaps_;
  418. /// Minimum number of instances required in a batch group to render as instanced.
  419. int minInstances_;
  420. /// Maximum triangles per object for instancing.
  421. int maxInstanceTriangles_;
  422. /// Maximum sorted instances per batch group.
  423. int maxSortedInstances_;
  424. /// Maximum occluder triangles.
  425. int maxOccluderTriangles_;
  426. /// Occlusion buffer width.
  427. int occlusionBufferSize_;
  428. /// Occluder screen size threshold.
  429. float occluderSizeThreshold_;
  430. /// Number of views.
  431. unsigned numViews_;
  432. /// Number of occlusion buffers in use.
  433. unsigned numOcclusionBuffers_;
  434. /// Number of temporary shadow cameras in use.
  435. unsigned numShadowCameras_;
  436. /// Number of primitives (3D geometry only.)
  437. unsigned numPrimitives_;
  438. /// Number of batches (3D geometry only.)
  439. unsigned numBatches_;
  440. /// Frame number on which shaders last changed.
  441. unsigned shadersChangedFrameNumber_;
  442. /// Current stencil value for light optimization.
  443. unsigned char lightStencilValue_;
  444. /// HDR rendering flag.
  445. bool hdrRendering_;
  446. /// Specular lighting flag.
  447. bool specularLighting_;
  448. /// Draw shadows flag.
  449. bool drawShadows_;
  450. /// Shadow map reuse flag.
  451. bool reuseShadowMaps_;
  452. /// Dynamic instancing flag.
  453. bool dynamicInstancing_;
  454. /// Shaders need reloading flag.
  455. bool shadersDirty_;
  456. /// Initialized flag.
  457. bool initialized_;
  458. };
  459. }