Renderer.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #pragma once
  24. #include "Batch.h"
  25. #include "Color.h"
  26. #include "Drawable.h"
  27. #include "HashSet.h"
  28. #include "Mutex.h"
  29. #include "Viewport.h"
  30. namespace Urho3D
  31. {
  32. class Geometry;
  33. class Drawable;
  34. class Light;
  35. class Material;
  36. class Pass;
  37. class Technique;
  38. class Octree;
  39. class Graphics;
  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 NUM_LIGHT_TYPES = 3;
  50. static const int NUM_SHADOWMAP_RESOLUTIONS = 3;
  51. static const int INSTANCING_BUFFER_DEFAULT_SIZE = 1024;
  52. /// Light vertex shader variations.
  53. enum LightVSVariation
  54. {
  55. LVS_DIR = 0,
  56. LVS_SPOT,
  57. LVS_POINT,
  58. LVS_SPEC,
  59. LVS_SPOTSPEC,
  60. LVS_POINTSPEC,
  61. LVS_SHADOW,
  62. LVS_SPOTSHADOW,
  63. LVS_POINTSHADOW,
  64. LVS_DIRSPECSHADOW,
  65. LVS_SPOTSPECSHADOW,
  66. LVS_POINTSPECSHADOW,
  67. MAX_LIGHT_VS_VARIATIONS
  68. };
  69. /// Per-vertex light vertex shader variations.
  70. enum VertexLightVSVariation
  71. {
  72. VLVS_NOLIGHTS = 0,
  73. VLVS_1LIGHT,
  74. VLVS_2LIGHTS,
  75. VLVS_3LIGHTS,
  76. VLVS_4LIGHTS,
  77. MAX_VERTEXLIGHT_VS_VARIATIONS
  78. };
  79. /// Light pixel shader variations.
  80. enum LightPSVariation
  81. {
  82. LPS_NONE = 0,
  83. LPS_SPOT,
  84. LPS_POINT,
  85. LPS_POINTMASK,
  86. LPS_SPEC,
  87. LPS_SPOTSPEC,
  88. LPS_POINTSPEC,
  89. LPS_POINTMASKSPEC,
  90. LPS_SHADOW,
  91. LPS_SPOTSHADOW,
  92. LPS_POINTSHADOW,
  93. LPS_POINTMASKSHADOW,
  94. LPS_SHADOWSPEC,
  95. LPS_SPOTSHADOWSPEC,
  96. LPS_POINTSHADOWSPEC,
  97. LPS_POINTMASKSHADOWSPEC,
  98. MAX_LIGHT_PS_VARIATIONS
  99. };
  100. /// Deferred light volume vertex shader variations.
  101. enum DeferredLightVSVariation
  102. {
  103. DLVS_NONE = 0,
  104. DLVS_DIR,
  105. DLVS_ORTHO,
  106. DLVS_ORTHODIR,
  107. MAX_DEFERRED_LIGHT_VS_VARIATIONS
  108. };
  109. /// Deferred light volume pixels shader variations.
  110. enum DeferredLightPSVariation
  111. {
  112. DLPS_NONE = 0,
  113. DLPS_SPOT,
  114. DLPS_POINT,
  115. DLPS_POINTMASK,
  116. DLPS_SPEC,
  117. DLPS_SPOTSPEC,
  118. DLPS_POINTSPEC,
  119. DLPS_POINTMASKSPEC,
  120. DLPS_SHADOW,
  121. DLPS_SPOTSHADOW,
  122. DLPS_POINTSHADOW,
  123. DLPS_POINTMASKSHADOW,
  124. DLPS_SHADOWSPEC,
  125. DLPS_SPOTSHADOWSPEC,
  126. DLPS_POINTSHADOWSPEC,
  127. DLPS_POINTMASKSHADOWSPEC,
  128. DLPS_ORTHO,
  129. DLPS_ORTHOSPOT,
  130. DLPS_ORTHOPOINT,
  131. DLPS_ORTHOPOINTMASK,
  132. DLPS_ORTHOSPEC,
  133. DLPS_ORTHOSPOTSPEC,
  134. DLPS_ORTHOPOINTSPEC,
  135. DLPS_ORTHOPOINTMASKSPEC,
  136. DLPS_ORTHOSHADOW,
  137. DLPS_ORTHOSPOTSHADOW,
  138. DLPS_ORTHOPOINTSHADOW,
  139. DLPS_ORTHOPOINTMASKSHADOW,
  140. DLPS_ORTHOSHADOWSPEC,
  141. DLPS_ORTHOSPOTSHADOWSPEC,
  142. DLPS_ORTHOPOINTSHADOWSPEC,
  143. DLPS_ORTHOPOINTMASKSHADOWSPEC,
  144. MAX_DEFERRED_LIGHT_PS_VARIATIONS
  145. };
  146. /// High-level rendering subsystem. Manages drawing of 3D views.
  147. class Renderer : public Object
  148. {
  149. OBJECT(Object);
  150. public:
  151. /// Construct.
  152. Renderer(Context* context);
  153. /// Destruct.
  154. virtual ~Renderer();
  155. /// Set number of viewports to render.
  156. void SetNumViewports(unsigned num);
  157. /// Set a viewport. Return true if successful.
  158. bool SetViewport(unsigned index, Viewport* viewport);
  159. /// Set rendering mode (forward / light pre-pass / deferred.)
  160. void SetRenderMode(RenderMode mode);
  161. /// Set specular lighting on/off.
  162. void SetSpecularLighting(bool enable);
  163. /// Set texture anisotropy.
  164. void SetTextureAnisotropy(int level);
  165. /// Set texture filtering.
  166. void SetTextureFilterMode(TextureFilterMode mode);
  167. /// Set texture quality level.
  168. void SetTextureQuality(int quality);
  169. /// Set material quality level.
  170. void SetMaterialQuality(int quality);
  171. /// Set shadows on/off.
  172. void SetDrawShadows(bool enable);
  173. /// Set shadow map resolution.
  174. void SetShadowMapSize(int size);
  175. /// Set shadow quality (amount of samples and bit depth.)
  176. void SetShadowQuality(int quality);
  177. /// Set reuse of shadow maps. Default is true. If disabled, also transparent geometry can be shadowed.
  178. void SetReuseShadowMaps(bool enable);
  179. /// Set maximum number of shadow maps created for one resolution. Only has effect if reuse of shadow maps is disabled.
  180. void SetMaxShadowMaps(int shadowMaps);
  181. /// Set maximum number of directional light shadow map cascades. Affects the size of directional light shadow maps.
  182. void SetMaxShadowCascades(int cascades);
  183. /// Set dynamic instancing on/off.
  184. void SetDynamicInstancing(bool enable);
  185. /// Set maximum number of triangles per object for instancing.
  186. void SetMaxInstanceTriangles(int triangles);
  187. /// Set maximum number of sorted instances per batch group. If exceeded, instances are rendered unsorted.
  188. void SetMaxSortedInstances(int instances);
  189. /// Set maximum number of occluder trianges.
  190. void SetMaxOccluderTriangles(int triangles);
  191. /// Set occluder buffer width.
  192. void SetOcclusionBufferSize(int size);
  193. /// Set required screen size (1.0 = full screen) for occluders.
  194. void SetOccluderSizeThreshold(float screenSize);
  195. /// Force reload of shaders.
  196. void ReloadShaders();
  197. /// Return number of viewports.
  198. unsigned GetNumViewports() const { return viewports_.Size(); }
  199. /// Return viewport.
  200. Viewport* GetViewport(unsigned index) const;
  201. /// Return rendering mode.
  202. RenderMode GetRenderMode() const { return renderMode_; }
  203. /// Return whether specular lighting is enabled.
  204. bool GetSpecularLighting() const { return specularLighting_; }
  205. /// Return whether drawing shadows is enabled.
  206. bool GetDrawShadows() const { return drawShadows_; }
  207. /// Return texture anisotropy.
  208. int GetTextureAnisotropy() const { return textureAnisotropy_; }
  209. /// Return texture filtering.
  210. TextureFilterMode GetTextureFilterMode() const { return textureFilterMode_; }
  211. /// Return texture quality level.
  212. int GetTextureQuality() const { return textureQuality_; }
  213. /// Return material quality level.
  214. int GetMaterialQuality() const { return materialQuality_; }
  215. /// Return shadow map resolution.
  216. int GetShadowMapSize() const { return shadowMapSize_; }
  217. /// Return shadow quality.
  218. int GetShadowQuality() const { return shadowQuality_; }
  219. /// Return whether shadow maps are reused.
  220. bool GetReuseShadowMaps() const { return reuseShadowMaps_; }
  221. /// Return maximum number of shadow maps per resolution.
  222. int GetMaxShadowMaps() const { return maxShadowMaps_; }
  223. /// Return maximum number of directional light shadow map cascades.
  224. int GetMaxShadowCascades() const;
  225. /// Return whether dynamic instancing is in use.
  226. bool GetDynamicInstancing() const { return dynamicInstancing_; }
  227. /// Return maximum number of triangles per object for instancing.
  228. int GetMaxInstanceTriangles() const { return maxInstanceTriangles_; }
  229. /// Return maximum number of sorted instances per batch group.
  230. int GetMaxSortedInstances() const { return maxSortedInstances_; }
  231. /// Return maximum number of occluder triangles.
  232. int GetMaxOccluderTriangles() const { return maxOccluderTriangles_; }
  233. /// Return occlusion buffer width.
  234. int GetOcclusionBufferSize() const { return occlusionBufferSize_; }
  235. /// Return occluder screen size threshold.
  236. float GetOccluderSizeThreshold() const { return occluderSizeThreshold_; }
  237. /// Return number of views rendered.
  238. unsigned GetNumViews() const { return numViews_; }
  239. /// Return number of primitives rendered.
  240. unsigned GetNumPrimitives() const { return numPrimitives_; }
  241. /// Return number of batches rendered.
  242. unsigned GetNumBatches() const { return numBatches_; }
  243. /// Return number of geometries rendered.
  244. unsigned GetNumGeometries(bool allViews = false) const;
  245. /// Return number of lights rendered.
  246. unsigned GetNumLights(bool allViews = false) const;
  247. /// Return number of shadow maps rendered.
  248. unsigned GetNumShadowMaps(bool allViews = false) const;
  249. /// Return number of occluders rendered.
  250. unsigned GetNumOccluders(bool allViews = false) const;
  251. /// Return the default zone.
  252. Zone* GetDefaultZone() const { return defaultZone_; }
  253. /// Return the directional light for fullscreen quad rendering.
  254. Light* GetQuadDirLight() const { return quadDirLight_; }
  255. /// Return the default material.
  256. Material* GetDefaultMaterial() const { return defaultMaterial_; }
  257. /// Return the default range attenuation texture.
  258. Texture2D* GetDefaultLightRamp() const { return defaultLightRamp_; }
  259. /// Return the default spotlight attenuation texture.
  260. Texture2D* GetDefaultLightSpot() const { return defaultLightSpot_; }
  261. /// Return the shadowed pointlight face selection cube map.
  262. TextureCube* GetFaceSelectCubeMap() const { return faceSelectCubeMap_; }
  263. /// Return the shadowed pointlight indirection cube map.
  264. TextureCube* GetIndirectionCubeMap() const { return indirectionCubeMap_; }
  265. /// Return the instancing vertex buffer
  266. VertexBuffer* GetInstancingBuffer() const { return dynamicInstancing_ ? instancingBuffer_ : (VertexBuffer*)0; }
  267. /// Return a vertex shader by name.
  268. ShaderVariation* GetVertexShader(const String& name, bool checkExists = false) const;
  269. /// Return a pixel shader by name.
  270. ShaderVariation* GetPixelShader(const String& name, bool checkExists = false) const;
  271. /// Return the stencil vertex shader.
  272. ShaderVariation* GetStencilVS() const { return stencilVS_; }
  273. /// Return the stencil pixel shader.
  274. ShaderVariation* GetStencilPS() const { return stencilPS_; }
  275. /// Return the frame update parameters.
  276. const FrameInfo& GetFrameInfo() { return frame_; }
  277. /// Update for rendering. Called by HandleRenderUpdate().
  278. void Update(float timeStep);
  279. /// Render. Called by Engine.
  280. void Render();
  281. /// Add debug geometry to the debug renderer.
  282. void DrawDebugGeometry(bool depthTest);
  283. /// Add a view. Return true if successful.
  284. bool AddView(RenderSurface* renderTarget, Viewport* viewport);
  285. /// Return volume geometry for a light.
  286. Geometry* GetLightGeometry(Light* light);
  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 = false);
  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. /// Get a shader program.
  298. ShaderVariation* GetShader(ShaderType type, const String& name, bool checkExists) const;
  299. /// Choose shaders for a forward rendering batch.
  300. void SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows = true);
  301. /// Choose shaders for a light volume batch.
  302. void SetLightVolumeBatchShaders(Batch& batch);
  303. /// Set cull mode while taking possible projection flipping into account.
  304. void SetCullMode(CullMode mode, Camera* camera);
  305. /// Ensure sufficient size of the instancing vertex buffer. Return true if successful.
  306. bool ResizeInstancingBuffer(unsigned numInstances);
  307. /// Save the screen buffer allocation status. Called by View.
  308. void SaveScreenBufferAllocations();
  309. /// Restore the screen buffer allocation status. Called by View.
  310. void RestoreScreenBufferAllocations();
  311. /// Optimize a light by scissor rectangle.
  312. void OptimizeLightByScissor(Light* light, Camera* camera);
  313. /// Optimize a light by marking it to the stencil buffer and setting a stencil test.
  314. void OptimizeLightByStencil(Light* light, Camera* camera);
  315. /// Return a scissor rectangle for a light.
  316. const Rect& GetLightScissor(Light* light, Camera* camera);
  317. private:
  318. /// Initialize when screen mode initially set.
  319. void Initialize();
  320. /// Clear views from previous frame.
  321. void ResetViews();
  322. /// Reload shaders.
  323. void LoadShaders();
  324. /// Reload shaders for a material technique.
  325. void LoadMaterialShaders(Technique* tech);
  326. /// Reload shaders for a material pass.
  327. void LoadPassShaders(Technique* tech, PassType type);
  328. /// Release shaders used in materials.
  329. void ReleaseMaterialShaders();
  330. /// Reload textures.
  331. void ReloadTextures();
  332. /// Create light volume geometries.
  333. void CreateGeometries();
  334. /// Create instancing vertex buffer.
  335. void CreateInstancingBuffer();
  336. /// Create point light shadow indirection texture data.
  337. void SetIndirectionTextureData();
  338. /// Prepare for rendering of a new view.
  339. void PrepareViewRender();
  340. /// Remove unused occlusion and screen buffers.
  341. void RemoveUnusedBuffers();
  342. /// Reset shadow map allocation counts.
  343. void ResetShadowMapAllocations();
  344. /// Reset screem buffer allocation counts.
  345. void ResetScreenBufferAllocations();
  346. /// Remove all shadow maps. Called when global shadow map resolution or format is changed.
  347. void ResetShadowMaps();
  348. /// Remove all occlusion and screen buffers.
  349. void ResetBuffers();
  350. /// Handle screen mode event.
  351. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  352. /// Handle graphics features (re)check event.
  353. void HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData);
  354. /// Handle render update event.
  355. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  356. /// Graphics subsystem.
  357. WeakPtr<Graphics> graphics_;
  358. /// Resource cache subsystem.
  359. WeakPtr<ResourceCache> cache_;
  360. /// Default zone.
  361. SharedPtr<Zone> defaultZone_;
  362. /// Directional light for drawing fullscreen quads.
  363. SharedPtr<Light> quadDirLight_;
  364. /// Directional light quad geometry.
  365. SharedPtr<Geometry> dirLightGeometry_;
  366. /// Spot light volume geometry.
  367. SharedPtr<Geometry> spotLightGeometry_;
  368. /// Point light volume geometry.
  369. SharedPtr<Geometry> pointLightGeometry_;
  370. /// Instance stream vertex buffer.
  371. SharedPtr<VertexBuffer> instancingBuffer_;
  372. /// Default material.
  373. SharedPtr<Material> defaultMaterial_;
  374. /// Default range attenuation texture.
  375. SharedPtr<Texture2D> defaultLightRamp_;
  376. /// Default spotlight attenuation texture.
  377. SharedPtr<Texture2D> defaultLightSpot_;
  378. /// Face selection cube map for shadowed pointlights.
  379. SharedPtr<TextureCube> faceSelectCubeMap_;
  380. /// Indirection cube map for shadowed pointlights.
  381. SharedPtr<TextureCube> indirectionCubeMap_;
  382. /// Stencil rendering vertex shader.
  383. SharedPtr<ShaderVariation> stencilVS_;
  384. /// Stencil rendering pixel shader.
  385. SharedPtr<ShaderVariation> stencilPS_;
  386. /// Light vertex shaders.
  387. Vector<SharedPtr<ShaderVariation> > lightVS_;
  388. /// Light pixel shaders.
  389. Vector<SharedPtr<ShaderVariation> > lightPS_;
  390. /// Reusable scene nodes with shadow camera components.
  391. Vector<SharedPtr<Node> > shadowCameraNodes_;
  392. /// Reusable occlusion buffers.
  393. Vector<SharedPtr<OcclusionBuffer> > occlusionBuffers_;
  394. /// Shadow maps by resolution.
  395. HashMap<int, Vector<SharedPtr<Texture2D> > > shadowMaps_;
  396. /// Shadow map dummy color buffers by resolution.
  397. HashMap<int, SharedPtr<Texture2D> > colorShadowMaps_;
  398. /// Shadow map allocations by resolution.
  399. HashMap<int, PODVector<Light*> > shadowMapAllocations_;
  400. /// Screen buffers by resolution and format.
  401. HashMap<long long, Vector<SharedPtr<Texture2D> > > screenBuffers_;
  402. /// Current screen buffer allocations by resolution and format.
  403. HashMap<long long, unsigned> screenBufferAllocations_;
  404. /// Saved status of screen buffer allocations for restoring.
  405. HashMap<long long, unsigned> savedScreenBufferAllocations_;
  406. /// Cache for light scissor queries.
  407. HashMap<Pair<Light*, Camera*>, Rect> lightScissorCache_;
  408. /// Viewports.
  409. Vector<SharedPtr<Viewport> > viewports_;
  410. /// Views.
  411. Vector<SharedPtr<View> > views_;
  412. /// Octrees that have been updated during the frame.
  413. HashSet<Octree*> updatedOctrees_;
  414. /// Techniques for which missing shader error has been displayed.
  415. HashSet<Technique*> shaderErrorDisplayed_;
  416. /// Mutex for shadow camera allocation.
  417. Mutex rendererMutex_;
  418. /// Base directory for shaders.
  419. String shaderPath_;
  420. /// Frame info for rendering.
  421. FrameInfo frame_;
  422. /// Rendering mode.
  423. RenderMode renderMode_;
  424. /// Texture anisotropy level.
  425. int textureAnisotropy_;
  426. /// Texture filtering mode.
  427. TextureFilterMode textureFilterMode_;
  428. /// Texture quality level.
  429. int textureQuality_;
  430. /// Material quality level.
  431. int materialQuality_;
  432. /// Shadow map resolution.
  433. int shadowMapSize_;
  434. /// Shadow quality.
  435. int shadowQuality_;
  436. /// Maximum number of shadow maps per resolution.
  437. int maxShadowMaps_;
  438. /// Maximum number of directional light shadow cascades.
  439. int maxShadowCascades_;
  440. /// Maximum triangles per object for instancing.
  441. int maxInstanceTriangles_;
  442. /// Maximum sorted instances per batch group.
  443. int maxSortedInstances_;
  444. /// Maximum occluder triangles.
  445. int maxOccluderTriangles_;
  446. /// Occlusion buffer width.
  447. int occlusionBufferSize_;
  448. /// Occluder screen size threshold.
  449. float occluderSizeThreshold_;
  450. /// Number of views.
  451. unsigned numViews_;
  452. /// Number of occlusion buffers in use.
  453. unsigned numOcclusionBuffers_;
  454. /// Number of temporary shadow cameras in use.
  455. unsigned numShadowCameras_;
  456. /// Number of primitives (3D geometry only.)
  457. unsigned numPrimitives_;
  458. /// Number of batches (3D geometry only.)
  459. unsigned numBatches_;
  460. /// Frame number on which shaders last changed.
  461. unsigned shadersChangedFrameNumber_;
  462. /// Current stencil value for light optimization.
  463. unsigned char lightStencilValue_;
  464. /// Specular lighting flag.
  465. bool specularLighting_;
  466. /// Draw shadows flag.
  467. bool drawShadows_;
  468. /// Shadow map reuse flag.
  469. bool reuseShadowMaps_;
  470. /// Dynamic instancing flag.
  471. bool dynamicInstancing_;
  472. /// Shaders need reloading flag.
  473. bool shadersDirty_;
  474. /// Initialized flag.
  475. bool initialized_;
  476. };
  477. }