View.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 "HashSet.h"
  25. #include "Light.h"
  26. #include "List.h"
  27. #include "Object.h"
  28. #include "Polyhedron.h"
  29. #include "Zone.h"
  30. namespace Urho3D
  31. {
  32. class Camera;
  33. class DebugRenderer;
  34. class Light;
  35. class Drawable;
  36. class OcclusionBuffer;
  37. class Octree;
  38. class RenderPath;
  39. class RenderSurface;
  40. class Technique;
  41. class Texture2D;
  42. class Viewport;
  43. class Zone;
  44. struct RenderPathCommand;
  45. struct WorkItem;
  46. /// Intermediate light processing result.
  47. struct LightQueryResult
  48. {
  49. /// Light.
  50. Light* light_;
  51. /// Lit geometries.
  52. PODVector<Drawable*> litGeometries_;
  53. /// Shadow casters.
  54. PODVector<Drawable*> shadowCasters_;
  55. /// Shadow cameras.
  56. Camera* shadowCameras_[MAX_LIGHT_SPLITS];
  57. /// Shadow caster start indices.
  58. unsigned shadowCasterBegin_[MAX_LIGHT_SPLITS];
  59. /// Shadow caster end indices.
  60. unsigned shadowCasterEnd_[MAX_LIGHT_SPLITS];
  61. /// Combined bounding box of shadow casters in light view or projection space.
  62. BoundingBox shadowCasterBox_[MAX_LIGHT_SPLITS];
  63. /// Shadow camera near splits (directional lights only.)
  64. float shadowNearSplits_[MAX_LIGHT_SPLITS];
  65. /// Shadow camera far splits (directional lights only.)
  66. float shadowFarSplits_[MAX_LIGHT_SPLITS];
  67. /// Shadow map split count.
  68. unsigned numSplits_;
  69. };
  70. /// Scene render pass info.
  71. struct ScenePassInfo
  72. {
  73. /// Pass name hash.
  74. StringHash pass_;
  75. /// Allow instancing flag.
  76. bool allowInstancing_;
  77. /// Mark to stencil flag.
  78. bool markToStencil_;
  79. /// Light scissor optimization flag.
  80. bool useScissor_;
  81. /// Vertex light flag.
  82. bool vertexLights_;
  83. /// Batch queue.
  84. BatchQueue* batchQueue_;
  85. };
  86. /// Per-thread geometry, light and scene range collection structure.
  87. struct PerThreadSceneResult
  88. {
  89. /// Geometry objects.
  90. PODVector<Drawable*> geometries_;
  91. /// Lights.
  92. PODVector<Light*> lights_;
  93. /// Scene minimum Z value.
  94. float minZ_;
  95. /// Scene maximum Z value.
  96. float maxZ_;
  97. };
  98. static const unsigned MAX_VIEWPORT_TEXTURES = 2;
  99. /// Internal structure for 3D rendering work. Created for each backbuffer and texture viewport, but not for shadow cameras.
  100. class URHO3D_API View : public Object
  101. {
  102. friend void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex);
  103. friend void ProcessLightWork(const WorkItem* item, unsigned threadIndex);
  104. OBJECT(View);
  105. public:
  106. /// Construct.
  107. View(Context* context);
  108. /// Destruct.
  109. virtual ~View();
  110. /// Define with rendertarget and viewport. Return true if successful.
  111. bool Define(RenderSurface* renderTarget, Viewport* viewport);
  112. /// Update and cull objects and construct rendering batches.
  113. void Update(const FrameInfo& frame);
  114. /// Render batches.
  115. void Render();
  116. /// Return graphics subsystem.
  117. Graphics* GetGraphics() const;
  118. /// Return renderer subsystem.
  119. Renderer* GetRenderer() const;
  120. /// Return scene.
  121. Scene* GetScene() const { return scene_; }
  122. /// Return octree.
  123. Octree* GetOctree() const { return octree_; }
  124. /// Return camera.
  125. Camera* GetCamera() const { return camera_; }
  126. /// Return information of the frame being rendered.
  127. const FrameInfo& GetFrameInfo() const { return frame_; }
  128. /// Return the rendertarget. 0 if using the backbuffer.
  129. RenderSurface* GetRenderTarget() const { return renderTarget_; }
  130. /// Return whether should draw debug geometry.
  131. bool GetDrawDebug() const { return drawDebug_; }
  132. /// Return geometry objects.
  133. const PODVector<Drawable*>& GetGeometries() const { return geometries_; }
  134. /// Return occluder objects.
  135. const PODVector<Drawable*>& GetOccluders() const { return occluders_; }
  136. /// Return lights.
  137. const PODVector<Light*>& GetLights() const { return lights_; }
  138. /// Return light batch queues.
  139. const Vector<LightBatchQueue>& GetLightQueues() const { return lightQueues_; }
  140. /// Set global (per-frame) shader parameters. Called by Batch and internally by View.
  141. void SetGlobalShaderParameters();
  142. /// Set camera-specific shader parameters. Called by Batch and internally by View.
  143. void SetCameraShaderParameters(Camera* camera, bool setProjectionMatrix, bool overrideView);
  144. /// Set G-buffer offset and inverse size shader parameters. Called by Batch and internally by View.
  145. void SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect);
  146. private:
  147. /// Query the octree for drawable objects.
  148. void GetDrawables();
  149. /// Construct batches from the drawable objects.
  150. void GetBatches();
  151. /// Update geometries and sort batches.
  152. void UpdateGeometries();
  153. /// Get pixel lit batches for a certain light and drawable.
  154. void GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue);
  155. /// Execute render commands.
  156. void ExecuteRenderPathCommands();
  157. /// Set rendertargets for current render command.
  158. void SetRenderTargets(RenderPathCommand& command);
  159. /// Set textures for current render command.
  160. void SetTextures(RenderPathCommand& command);
  161. /// Perform a quad rendering command.
  162. void RenderQuad(RenderPathCommand& command);
  163. /// Check if a command is enabled and has content to render. To be called only after render update has completed for the frame.
  164. bool IsNecessary(const RenderPathCommand& command);
  165. /// Check if a command reads the destination render target.
  166. bool CheckViewportRead(const RenderPathCommand& command);
  167. /// Check if a command writes into the destination render target.
  168. bool CheckViewportWrite(const RenderPathCommand& command);
  169. /// Check whether a command should use pingponging instead of resolve from destination render target to viewport texture.
  170. bool CheckPingpong(unsigned index);
  171. /// Allocate needed screen buffers.
  172. void AllocateScreenBuffers();
  173. /// Blit the viewport from one surface to another.
  174. void BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite);
  175. /// Draw a fullscreen quad. Shaders and renderstates must have been set beforehand.
  176. void DrawFullscreenQuad(bool nearQuad);
  177. /// Query for occluders as seen from a camera.
  178. void UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera);
  179. /// Draw occluders to occlusion buffer.
  180. void DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders);
  181. /// Query for lit geometries and shadow casters for a light.
  182. void ProcessLight(LightQueryResult& query, unsigned threadIndex);
  183. /// Process shadow casters' visibilities and build their combined view- or projection-space bounding box.
  184. void ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex);
  185. /// Set up initial shadow camera view(s).
  186. void SetupShadowCameras(LightQueryResult& query);
  187. /// Set up a directional light shadow camera
  188. void SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit);
  189. /// Finalize shadow camera view after shadow casters and the shadow map are known.
  190. void FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& shadowCasterBox);
  191. /// Quantize a directional light shadow camera view to eliminate swimming.
  192. void QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& viewBox);
  193. /// Check visibility of one shadow caster.
  194. bool IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView, const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox);
  195. /// Return the viewport for a shadow map split.
  196. IntRect GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap);
  197. /// Find and set a new zone for a drawable when it has moved.
  198. void FindZone(Drawable* drawable);
  199. /// Return material technique, considering the drawable's LOD distance.
  200. Technique* GetTechnique(Drawable* drawable, Material* material);
  201. /// Check if material should render an auxiliary view (if it has a camera attached.)
  202. void CheckMaterialForAuxView(Material* material);
  203. /// Choose shaders for a batch and add it to queue.
  204. void AddBatchToQueue(BatchQueue& queue, Batch& batch, Technique* tech, bool allowInstancing = true, bool allowShadows = true);
  205. /// Prepare instancing buffer by filling it with all instance transforms.
  206. void PrepareInstancingBuffer();
  207. /// Set up a light volume rendering batch.
  208. void SetupLightVolumeBatch(Batch& batch);
  209. /// Render a shadow map.
  210. void RenderShadowMap(const LightBatchQueue& queue);
  211. /// Return the proper depth-stencil surface to use for a rendertarget.
  212. RenderSurface* GetDepthStencil(RenderSurface* renderTarget);
  213. /// Return the drawable's zone, or camera zone if it has override mode enabled.
  214. Zone* GetZone(Drawable* drawable)
  215. {
  216. if (cameraZoneOverride_)
  217. return cameraZone_;
  218. Zone* drawableZone = drawable->GetZone();
  219. return drawableZone ? drawableZone : cameraZone_;
  220. }
  221. /// Return the drawable's light mask, considering also its zone.
  222. unsigned GetLightMask(Drawable* drawable)
  223. {
  224. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  225. }
  226. /// Return the drawable's shadow mask, considering also its zone.
  227. unsigned GetShadowMask(Drawable* drawable)
  228. {
  229. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  230. }
  231. /// Return hash code for a vertex light queue.
  232. unsigned long long GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  233. {
  234. unsigned long long hash = 0;
  235. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  236. hash += (unsigned long long)(*i);
  237. return hash;
  238. }
  239. /// Graphics subsystem.
  240. WeakPtr<Graphics> graphics_;
  241. /// Renderer subsystem.
  242. WeakPtr<Renderer> renderer_;
  243. /// Scene to use.
  244. Scene* scene_;
  245. /// Octree to use.
  246. Octree* octree_;
  247. /// Camera to use.
  248. Camera* camera_;
  249. /// Camera's scene node.
  250. Node* cameraNode_;
  251. /// Zone the camera is inside, or default zone if not assigned.
  252. Zone* cameraZone_;
  253. /// Zone at far clip plane.
  254. Zone* farClipZone_;
  255. /// Occlusion buffer for the main camera.
  256. OcclusionBuffer* occlusionBuffer_;
  257. /// Destination color rendertarget.
  258. RenderSurface* renderTarget_;
  259. /// Substitute rendertarget for deferred rendering. Allocated if necessary.
  260. RenderSurface* substituteRenderTarget_;
  261. /// Texture(s) for sampling the viewport contents. Allocated if necessary.
  262. Texture2D* viewportTextures_[MAX_VIEWPORT_TEXTURES];
  263. /// Color rendertarget active for the current renderpath command.
  264. RenderSurface* currentRenderTarget_;
  265. /// Texture containing the latest viewport texture.
  266. Texture2D* currentViewportTexture_;
  267. /// Viewport rectangle.
  268. IntRect viewRect_;
  269. /// Viewport size.
  270. IntVector2 viewSize_;
  271. /// Destination rendertarget size.
  272. IntVector2 rtSize_;
  273. /// Information of the frame being rendered.
  274. FrameInfo frame_;
  275. /// Minimum Z value of the visible scene.
  276. float minZ_;
  277. /// Maximum Z value of the visible scene.
  278. float maxZ_;
  279. /// Material quality level.
  280. int materialQuality_;
  281. /// Maximum number of occluder triangles.
  282. int maxOccluderTriangles_;
  283. /// Minimum number of instances required in a batch group to render as instanced.
  284. int minInstances_;
  285. /// Highest zone priority currently visible.
  286. int highestZonePriority_;
  287. /// Camera zone's override flag.
  288. bool cameraZoneOverride_;
  289. /// Draw shadows flag.
  290. bool drawShadows_;
  291. /// Deferred flag. Inferred from the existence of a light volume command in the renderpath.
  292. bool deferred_;
  293. /// Deferred ambient pass flag. This means that the destination rendertarget is being written to at the same time as albedo/normal/depth buffers, and needs to be RGBA on OpenGL.
  294. bool deferredAmbient_;
  295. /// Forward light base pass optimization flag. If in use, combine the base pass and first light for all opaque objects.
  296. bool useLitBase_;
  297. /// Has scene passes flag. If no scene passes, view can be defined without a valid scene or camera to only perform quad rendering.
  298. bool hasScenePasses_;
  299. /// Draw debug geometry flag. Copied from the viewport.
  300. bool drawDebug_;
  301. /// Renderpath.
  302. RenderPath* renderPath_;
  303. /// Per-thread octree query results.
  304. Vector<PODVector<Drawable*> > tempDrawables_;
  305. /// Per-thread geometries, lights and Z range collection results.
  306. Vector<PerThreadSceneResult> sceneResults_;
  307. /// Visible zones.
  308. PODVector<Zone*> zones_;
  309. /// Visible geometry objects.
  310. PODVector<Drawable*> geometries_;
  311. /// Geometry objects that will be updated in the main thread.
  312. PODVector<Drawable*> nonThreadedGeometries_;
  313. /// Geometry objects that will be updated in worker threads.
  314. PODVector<Drawable*> threadedGeometries_;
  315. /// Occluder objects.
  316. PODVector<Drawable*> occluders_;
  317. /// Lights.
  318. PODVector<Light*> lights_;
  319. /// Drawables that limit their maximum light count.
  320. HashSet<Drawable*> maxLightsDrawables_;
  321. /// Rendertargets defined by the renderpath.
  322. HashMap<StringHash, Texture2D*> renderTargets_;
  323. /// Intermediate light processing results.
  324. Vector<LightQueryResult> lightQueryResults_;
  325. /// Info for scene render passes defined by the renderpath.
  326. Vector<ScenePassInfo> scenePasses_;
  327. /// Per-pixel light queues.
  328. Vector<LightBatchQueue> lightQueues_;
  329. /// Per-vertex light queues.
  330. HashMap<unsigned long long, LightBatchQueue> vertexLightQueues_;
  331. /// Batch queues.
  332. HashMap<StringHash, BatchQueue> batchQueues_;
  333. /// Hash of the GBuffer pass, or null if none.
  334. StringHash gBufferPassName_;
  335. /// Hash of the opaque forward base pass.
  336. StringHash basePassName_;
  337. /// Hash of the alpha pass.
  338. StringHash alphaPassName_;
  339. /// Hash of the forward light pass.
  340. StringHash lightPassName_;
  341. /// Hash of the litbase pass.
  342. StringHash litBasePassName_;
  343. /// Hash of the litalpha pass.
  344. StringHash litAlphaPassName_;
  345. /// Name of light volume vertex shader.
  346. String lightVolumeVSName_;
  347. /// Name of light volume pixel shader.
  348. String lightVolumePSName_;
  349. };
  350. }