Renderer.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  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 "HashMap.h"
  28. #include "HashSet.h"
  29. #include "RenderSurface.h"
  30. class DebugRenderer;
  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 ResourceCache;
  40. class Skeleton;
  41. class OcclusionBuffer;
  42. class Texture2D;
  43. class View;
  44. class Zone;
  45. static const int SHADOW_MIN_PIXELS = 64;
  46. static const int NUM_SHADOWMAP_RESOLUTIONS = 3;
  47. static const int MIN_INSTANCES = 4;
  48. static const int INSTANCING_BUFFER_DEFAULT_SIZE = 1024;
  49. /// Light vertex shader variations
  50. enum LightVSVariation
  51. {
  52. LVS_NONE = 0,
  53. LVS_SPOT,
  54. LVS_SHADOW,
  55. LVS_SPOTSHADOW,
  56. MAX_LIGHT_VS_VARIATIONS
  57. };
  58. /// Light pixel shader variations
  59. enum LightPSVariation
  60. {
  61. LPS_NONE = 0,
  62. LPS_SPEC,
  63. LPS_SHADOW,
  64. LPS_SHADOWSPEC,
  65. LPS_SPOT,
  66. LPS_SPOTSPEC,
  67. LPS_SPOTSHADOW,
  68. LPS_SPOTSHADOWSPEC,
  69. LPS_POINT,
  70. LPS_POINTSPEC,
  71. LPS_POINTSHADOW,
  72. LPS_POINTSHADOWSPEC,
  73. LPS_POINTMASK,
  74. LPS_POINTMASKSPEC,
  75. LPS_POINTMASKSHADOW,
  76. LPS_POINTMASKSHADOWSPEC,
  77. MAX_LIGHT_PS_VARIATIONS
  78. };
  79. /// Deferred light volume vertex shader variations
  80. enum DeferredLightVSVariation
  81. {
  82. DLVS_NONE = 0,
  83. DLVS_DIR,
  84. DLVS_ORTHO,
  85. DLVS_ORTHODIR,
  86. MAX_DEFERRED_LIGHT_VS_VARIATIONS
  87. };
  88. /// Deferred light volume pixels shader variations
  89. enum DeferredLightPSVariation
  90. {
  91. DLPS_NONE = 0,
  92. DLPS_SPEC,
  93. DLPS_SHADOW,
  94. DLPS_SHADOWSPEC,
  95. DLPS_SPOT,
  96. DLPS_SPOTSPEC,
  97. DLPS_SPOTSHADOW,
  98. DLPS_SPOTSHADOWSPEC,
  99. DLPS_POINT,
  100. DLPS_POINTSPEC,
  101. DLPS_POINTSHADOW,
  102. DLPS_POINTSHADOWSPEC,
  103. DLPS_POINTMASK,
  104. DLPS_POINTMASKSPEC,
  105. DLPS_POINTMASKSHADOW,
  106. DLPS_POINTMASKSHADOWSPEC,
  107. DLPS_ORTHO,
  108. DLPS_ORTHOSPEC,
  109. DLPS_ORTHOSHADOW,
  110. DLPS_ORTHOSHADOWSPEC,
  111. DLPS_ORTHOSPOT,
  112. DLPS_ORTHOSPOTSPEC,
  113. DLPS_ORTHOSPOTSHADOW,
  114. DLPS_ORTHOSPOTSHADOWSPEC,
  115. DLPS_ORTHOPOINT,
  116. DLPS_ORTHOPOINTSPEC,
  117. DLPS_ORTHOPOINTSHADOW,
  118. DLPS_ORTHOPOINTSHADOWSPEC,
  119. DLPS_ORTHOPOINTMASK,
  120. DLPS_ORTHOPOINTMASKSPEC,
  121. DLPS_ORTHOPOINTMASKSHADOW,
  122. DLPS_ORTHOPOINTMASKSHADOWSPEC,
  123. MAX_DEFERRED_LIGHT_PS_VARIATIONS
  124. };
  125. /// Deferred rendering edge filter parameters
  126. struct EdgeFilterParameters
  127. {
  128. /// Construct as undefined
  129. EdgeFilterParameters()
  130. {
  131. }
  132. /// Construct with initial values
  133. EdgeFilterParameters(float radius, float threshold, float strength) :
  134. radius_(radius),
  135. threshold_(threshold),
  136. strength_(strength)
  137. {
  138. }
  139. //! Validate parameters
  140. void Validate();
  141. //! Radius for calculating luminance gradient
  142. float radius_;
  143. //! Luminance difference threshold needed to pass pixel
  144. float threshold_;
  145. //! Filter strength
  146. float strength_;
  147. };
  148. /// High-level rendering subsystem. Manages drawing of 3D views
  149. class Renderer : public Object
  150. {
  151. OBJECT(Object);
  152. friend class View;
  153. public:
  154. /// Construct
  155. Renderer(Context* context);
  156. /// Destruct
  157. virtual ~Renderer();
  158. /// Set number of viewports to render
  159. void SetNumViewports(unsigned num);
  160. /// Set a viewport
  161. void SetViewport(unsigned index, const Viewport& viewport);
  162. /// Set specular lighting on/off
  163. void SetSpecularLighting(bool enable);
  164. /// Set shadows on/off
  165. void SetDrawShadows(bool enable);
  166. /// Set texture anisotropy
  167. void SetTextureAnisotropy(int level);
  168. /// Set texture filtering
  169. void SetTextureFilterMode(TextureFilterMode mode);
  170. /// Set texture quality level
  171. void SetTextureQuality(int quality);
  172. /// Set material quality level
  173. void SetMaterialQuality(int quality);
  174. /// Set shadow map resolution
  175. void SetShadowMapSize(int size);
  176. /// Set shadow map 24-bit depth on/off
  177. void SetShadowMapHiresDepth(bool enable);
  178. /// Set reuse of shadowmaps. Default is true, disabling allows transparent geometry shadowing
  179. void SetReuseShadowMaps(bool enable);
  180. /// Set number of full, half and quarter size shadowmaps. Only has effect if reuse of shadowmaps is disabled first
  181. void SetNumShadowMaps(unsigned full, unsigned half, unsigned quarter);
  182. /// Set dynamic instancing on/off
  183. void SetDynamicInstancing(bool enable);
  184. /// Set deferred rendering edge filter parameters
  185. void SetEdgeFilter(const EdgeFilterParameters& parameters);
  186. /// Set maximum number of occluder trianges
  187. void SetMaxOccluderTriangles(int triangles);
  188. /// Set occluder buffer width
  189. void SetOcclusionBufferSize(int size);
  190. /// Set required size (1.0 = full screen) for occluders
  191. void SetOccluderSizeThreshold(float screenSize);
  192. /// Return number of viewports
  193. unsigned GetNumViewports() const { return viewports_.Size(); }
  194. /// Return viewport
  195. const Viewport& GetViewport(unsigned index) const;
  196. /// Return whether specular lighting is enabled
  197. bool GetSpecularLighting() const { return specularLighting_; }
  198. /// Return whether drawing shadows is enabled
  199. bool GetDrawShadows() const { return drawShadows_; }
  200. /// Return texture anisotropy
  201. int GetTextureAnisotropy() const { return textureAnisotropy_; }
  202. /// Return texture filtering
  203. TextureFilterMode GetTextureFilterMode() const { return textureFilterMode_; }
  204. /// Return texture quality level
  205. int GetTextureQuality() const { return textureQuality_; }
  206. /// Return material quality level
  207. int GetMaterialQuality() const { return materialQuality_; }
  208. /// Return shadow map resolution
  209. int GetShadowMapSize() const { return shadowMapSize_; }
  210. /// Return whether shadow maps use 24-bit depth
  211. bool GetShadowMapHiresDepth() const { return shadowMapHiresDepth_; }
  212. /// Return whether shadow maps are reused
  213. bool GetReuseShadowMaps() const { return reuseShadowMaps_; }
  214. /// Return number of full resolution shadow maps
  215. unsigned GetNumFullShadowMaps() const { return shadowMaps_[0].Size(); }
  216. /// Return number of half resolution shadow maps
  217. unsigned GetNumHalfShadowMaps() const { return shadowMaps_[1].Size(); }
  218. /// Return number of quarter resolution shadow maps
  219. unsigned GetNumQuarterShadowMaps() const { return shadowMaps_[2].Size(); }
  220. /// Return whether dynamic instancing is in use
  221. bool GetDynamicInstancing() const { return dynamicInstancing_; }
  222. /// Return deferred rendering edge filter parameters
  223. const EdgeFilterParameters& GetEdgeFilter() const { return edgeFilter_; }
  224. /// Return maximum number of occluder triangles
  225. int GetMaxOccluderTriangles() const { return maxOccluderTriangles_; }
  226. /// Return occlusion buffer width
  227. int GetOcclusionBufferSize() const { return occlusionBufferSize_; }
  228. /// Return occluder screen size threshold
  229. float GetOccluderSizeThreshold() const { return occluderSizeThreshold_; }
  230. /// Return number of views rendered
  231. unsigned GetNumViews() const { return numViews_; }
  232. /// Return number of primitives rendered
  233. unsigned GetNumPrimitives() const { return numPrimitives_; }
  234. /// Return number of batches rendered
  235. unsigned GetNumBatches() const { return numBatches_; }
  236. /// Return number of geometries rendered
  237. unsigned GetNumGeometries(bool allViews = false) const;
  238. /// Return number of lights rendered
  239. unsigned GetNumLights(bool allViews = false) const;
  240. /// Return number of shadow maps rendered
  241. unsigned GetNumShadowMaps(bool allViews = false) const;
  242. /// Return number of occluders rendered
  243. unsigned GetNumOccluders(bool allViews = false) const;
  244. /// Return number of directional light shadow occluders rendered
  245. unsigned GetNumShadowOccluders(bool allViews = false) const;
  246. /// Return an occlusion buffer for inspection
  247. const OcclusionBuffer* GetOcclusionBuffer(float aspectRatio, bool halfResolution = false);
  248. /// Return the default zone
  249. Zone* GetDefaultZone() const { return defaultZone_; }
  250. /// Return the default material
  251. Material* GetDefaultMaterial() const { return defaultMaterial_; }
  252. /// Return the default range attenuation texture
  253. Texture2D* GetDefaultLightRamp() const { return defaultLightRamp_; }
  254. /// Return the default spotlight attenuation texture
  255. Texture2D* GetDefaultLightSpot() const { return defaultLightSpot; }
  256. /// Return a vertex shader by name
  257. ShaderVariation* GetVertexShader(const String& name, bool checkExists = false) const;
  258. /// Return a pixel shader by name
  259. ShaderVariation* GetPixelShader(const String& name, bool checkExists = false) const;
  260. /// Return the frame update parameters
  261. const FrameInfo& GetFrameInfo() { return frame_; }
  262. /// Update for rendering. Called by handleRenderUpdate()
  263. void Update(float timeStep);
  264. /// Render. Called by Engine
  265. void Render();
  266. /// Add debug geometry to the debug graphics(s)
  267. void DrawDebugGeometry(bool depthTest);
  268. private:
  269. /// Initialize when screen mode initially set
  270. void Initialize();
  271. /// Clear views from previous frame
  272. void ResetViews();
  273. /// Add a view. Return true if successful
  274. bool AddView(RenderSurface* renderTarget, const Viewport& viewport);
  275. /// Return an occlusion buffer for use
  276. OcclusionBuffer* GetOrCreateOcclusionBuffer(Camera* camera, int maxOccluderTriangles, bool halfResolution = false);
  277. /// Return volume geometry for a light
  278. Geometry* GetLightGeometry(Light* light);
  279. /// Return shadow map by resolution. If shadow map reuse is disabled, a different map is returned each time
  280. Texture2D* GetShadowMap(float resolution);
  281. /// Reset shadow map use count
  282. void ResetShadowMapUseCount();
  283. /// Get a shader program
  284. ShaderVariation* GetShader(const String& name, const String& extension, bool checkExists) const;
  285. /// Choose shaders for a batch
  286. void SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows = true);
  287. /// Choose light volume shaders for a batch
  288. void SetLightVolumeShaders(Batch& batch);
  289. /// Reload shaders
  290. void LoadShaders();
  291. /// Reload shaders for a material technique
  292. void LoadMaterialShaders(Technique* technique);
  293. /// Reload shaders for a material pass
  294. void LoadPassShaders(Technique* technique, PassType pass, bool allowShadows = true);
  295. /// Release shaders used in materials
  296. void ReleaseMaterialShaders();
  297. /// Reload textures
  298. void ReloadTextures();
  299. /// Create light volume geometries
  300. void CreateGeometries();
  301. /// Create instancing vertex buffer
  302. void CreateInstancingBuffer();
  303. /// Ensure sufficient size of the instancing vertex buffer. Return true if successful
  304. bool ResizeInstancingBuffer(unsigned numInstances);
  305. /// Create shadow maps. Return true if successful
  306. bool CreateShadowMaps();
  307. /// Split a light into several for shadow mapping
  308. unsigned SplitLight(Light* light);
  309. /// Allocate a shadow camera and a scene node for it
  310. Camera* CreateShadowCamera();
  311. /// Allocate (if necessary) and clone a light. Attach it to a temporary scene node
  312. Light* CreateSplitLight(Light* original);
  313. /// Allocate a temporary scene node for attaching a split light or a shadow camera
  314. Node* CreateTempNode();
  315. /// Set up a light volume rendering batch
  316. void SetupLightBatch(Batch& batch);
  317. /// Draw a full screen quad (either near or far)
  318. void DrawFullScreenQuad(Camera& camera, ShaderVariation* vs, ShaderVariation* ps, bool nearQuad, const HashMap<StringHash, Vector4>& shaderParameters);
  319. /// Handle screen mode event
  320. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  321. /// Handle render update event
  322. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  323. /// Graphics
  324. WeakPtr<Graphics> graphics_;
  325. /// Resource cache
  326. WeakPtr<ResourceCache> cache_;
  327. /// Default zone
  328. SharedPtr<Zone> defaultZone_;
  329. /// Directional light geometry
  330. SharedPtr<Geometry> dirLightGeometry_;
  331. /// Point light volume geometry
  332. SharedPtr<Geometry> pointLightGeometry_;
  333. /// Spot light volume geometry
  334. SharedPtr<Geometry> spotLightGeometry_;
  335. /// Instance stream vertex buffer
  336. SharedPtr<VertexBuffer> instancingBuffer_;
  337. /// Default material
  338. SharedPtr<Material> defaultMaterial_;
  339. /// Default range attenuation texture
  340. SharedPtr<Texture2D> defaultLightRamp_;
  341. /// Default spotlight attenuation texture
  342. SharedPtr<Texture2D> defaultLightSpot;
  343. /// Shadow maps by resolution
  344. Vector<SharedPtr<Texture2D> > shadowMaps_[NUM_SHADOWMAP_RESOLUTIONS];
  345. /// Shadow map dummy color textures by resolution
  346. SharedPtr<Texture2D> colorShadowMaps_[NUM_SHADOWMAP_RESOLUTIONS];
  347. /// Shadow map use count if reusing is disabled. Is reset for each view
  348. unsigned shadowMapUseCount_[NUM_SHADOWMAP_RESOLUTIONS];
  349. /// Stencil rendering vertex shader
  350. SharedPtr<ShaderVariation> stencilVS_;
  351. /// Stencil rendering pixel shader
  352. SharedPtr<ShaderVariation> stencilPS_;
  353. /// Light vertex shaders
  354. Vector<SharedPtr<ShaderVariation> > lightVS_;
  355. /// Light pixel shaders
  356. Vector<SharedPtr<ShaderVariation> > lightPS_;
  357. /// Reusable shadow cameras
  358. Vector<SharedPtr<Camera> > shadowCameraStore_;
  359. /// Reusable split lights
  360. Vector<SharedPtr<Light> > splitLightStore_;
  361. /// Reusable temporary scene nodes
  362. Vector<SharedPtr<Node> > tempNodeStore_;
  363. /// Occlusion buffers
  364. HashMap<int, SharedPtr<OcclusionBuffer> > occlusionBuffers_;
  365. /// Viewports
  366. Vector<Viewport> viewports_;
  367. /// Views
  368. Vector<SharedPtr<View> > views_;
  369. /// Octrees that have been updated during the frame
  370. HashSet<Octree*> updateOctrees_;
  371. /// Techniques for which missing shader error has been displayed
  372. HashSet<Technique*> shaderErrorDisplayed_;
  373. /// Vertex shader format
  374. String vsFormat_;
  375. /// Pixel shader format
  376. String psFormat_;
  377. /// Base directory for shaders
  378. String shaderPath_;
  379. /// Number of views
  380. unsigned numViews_;
  381. /// Number of shadow cameras
  382. unsigned numShadowCameras_;
  383. /// Number of split lights
  384. unsigned numSplitLights_;
  385. /// Number of temporary scene nodes
  386. unsigned numTempNodes_;
  387. /// Number of primitives (3D geometry only)
  388. unsigned numPrimitives_;
  389. /// Number of batches (3D geometry only)
  390. unsigned numBatches_;
  391. /// Specular lighting flag
  392. bool specularLighting_;
  393. /// Draw shadows flag
  394. bool drawShadows_;
  395. /// Texture anisotropy level
  396. int textureAnisotropy_;
  397. /// Texture filtering mode
  398. TextureFilterMode textureFilterMode_;
  399. /// Texture quality level
  400. int textureQuality_;
  401. /// Material quality level
  402. int materialQuality_;
  403. /// Shadow map resolution
  404. int shadowMapSize_;
  405. /// Shadow map 24-bit depth flag
  406. bool shadowMapHiresDepth_;
  407. /// Shadow map reuse flag
  408. bool reuseShadowMaps_;
  409. /// Dynamic instancing flag
  410. bool dynamicInstancing_;
  411. /// Deferred rendering edge filter parameters
  412. EdgeFilterParameters edgeFilter_;
  413. /// Maximum occluder triangles
  414. int maxOccluderTriangles_;
  415. /// Occlusion buffer width
  416. int occlusionBufferSize_;
  417. /// Occluder screen size threshold
  418. float occluderSizeThreshold_;
  419. /// Frame number on which shaders last changed
  420. unsigned shadersChangedFrameNumber_;
  421. /// Frame info for rendering
  422. FrameInfo frame_;
  423. /// Shaders need reloading flag
  424. bool shadersDirty_;
  425. /// Initialized flag
  426. bool initialized_;
  427. };