View.h 14 KB

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