BsRendererView.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsRenderBeastPrerequisites.h"
  5. #include "BsPostProcessing.h"
  6. #include "BsObjectRendering.h"
  7. #include "Renderer/BsRenderQueue.h"
  8. #include "BsRendererObject.h"
  9. #include "Math/BsBounds.h"
  10. #include "Math/BsConvexVolume.h"
  11. #include "Renderer/BsLight.h"
  12. #include "BsLightGrid.h"
  13. #include "BsShadowRendering.h"
  14. #include "BsRenderCompositor.h"
  15. namespace bs { namespace ct
  16. {
  17. struct SceneInfo;
  18. class RendererLight;
  19. /** @addtogroup RenderBeast
  20. * @{
  21. */
  22. BS_PARAM_BLOCK_BEGIN(PerCameraParamDef)
  23. BS_PARAM_BLOCK_ENTRY(Vector3, gViewDir)
  24. BS_PARAM_BLOCK_ENTRY(Vector3, gViewOrigin)
  25. BS_PARAM_BLOCK_ENTRY(Matrix4, gMatViewProj)
  26. BS_PARAM_BLOCK_ENTRY(Matrix4, gMatView)
  27. BS_PARAM_BLOCK_ENTRY(Matrix4, gMatProj)
  28. BS_PARAM_BLOCK_ENTRY(Matrix4, gMatInvProj)
  29. BS_PARAM_BLOCK_ENTRY(Matrix4, gMatInvViewProj)
  30. BS_PARAM_BLOCK_ENTRY(Matrix4, gMatScreenToWorld)
  31. BS_PARAM_BLOCK_ENTRY(Matrix4, gNDCToPrevNDC)
  32. BS_PARAM_BLOCK_ENTRY(Vector2, gDeviceZToWorldZ)
  33. BS_PARAM_BLOCK_ENTRY(Vector2, gNDCZToWorldZ)
  34. BS_PARAM_BLOCK_ENTRY(Vector2, gNDCZToDeviceZ)
  35. BS_PARAM_BLOCK_ENTRY(Vector2, gNearFar)
  36. BS_PARAM_BLOCK_ENTRY(Vector4I, gViewportRectangle)
  37. BS_PARAM_BLOCK_ENTRY(Vector4, gClipToUVScaleOffset)
  38. BS_PARAM_BLOCK_ENTRY(float, gAmbientFactor)
  39. BS_PARAM_BLOCK_END
  40. extern PerCameraParamDef gPerCameraParamDef;
  41. BS_PARAM_BLOCK_BEGIN(SkyboxParamDef)
  42. BS_PARAM_BLOCK_ENTRY(Color, gClearColor)
  43. BS_PARAM_BLOCK_END
  44. extern SkyboxParamDef gSkyboxParamDef;
  45. /** Shader that renders a skybox using a cubemap or a solid color. */
  46. class SkyboxMat : public RendererMaterial<SkyboxMat>
  47. {
  48. RMAT_DEF("Skybox.bsl");
  49. /** Helper method used for initializing variations of this material. */
  50. template<bool color>
  51. static const ShaderVariation& getVariation()
  52. {
  53. static ShaderVariation variation = ShaderVariation(
  54. Vector<ShaderVariation::Param>{
  55. ShaderVariation::Param("SOLID_COLOR", color)
  56. });
  57. return variation;
  58. }
  59. public:
  60. SkyboxMat();
  61. /** Binds the material for rendering and sets up any parameters. */
  62. void bind(const SPtr<GpuParamBlockBuffer>& perCamera, const SPtr<Texture>& texture, const Color& solidColor);
  63. /**
  64. * Returns the material variation matching the provided parameters.
  65. *
  66. * @param[in] color When true the material will use a solid color to render a skybox. When false a user
  67. * provided texture will be used instead.
  68. */
  69. static SkyboxMat* getVariation(bool color);
  70. private:
  71. GpuParamTexture mSkyTextureParam;
  72. SPtr<GpuParamBlockBuffer> mParamBuffer;
  73. };
  74. /** Data shared between RENDERER_VIEW_DESC and RendererViewProperties */
  75. struct RendererViewData
  76. {
  77. RendererViewData();
  78. Matrix4 viewTransform;
  79. Matrix4 projTransform;
  80. Vector3 viewDirection;
  81. Vector3 viewOrigin;
  82. bool flipView;
  83. float nearPlane;
  84. float farPlane;
  85. ProjectionType projType;
  86. /**
  87. * When enabled, renderer extension callbacks will be triggered, allowing other systems to inject their own
  88. * render operations into the view.
  89. */
  90. bool triggerCallbacks : 1;
  91. /** When enabled, post-processing effects (like tonemapping) will be executed. */
  92. bool runPostProcessing : 1;
  93. /**
  94. * Determines if the view is currently rendering reflection probes. This ensures the systems can disable refl.
  95. * probe reads in order to prevent incorrect rendering (since probes won't yet have any data).
  96. */
  97. bool capturingReflections : 1;
  98. /**
  99. * When enabled the alpha channel of the final render target will be populated with an encoded depth value.
  100. * Parameters @p depthEncodeNear and @p depthEncodeFar control which range of the depth buffer to encode.
  101. */
  102. bool encodeDepth : 1;
  103. /**
  104. * Controls at which position to start encoding depth, in view space. Only relevant with @p encodeDepth is enabled.
  105. * Depth will be linearly interpolated between this value and @p depthEncodeFar.
  106. */
  107. float depthEncodeNear;
  108. /**
  109. * Controls at which position to stop encoding depth, in view space. Only relevant with @p encodeDepth is enabled.
  110. * Depth will be linearly interpolated between @p depthEncodeNear and this value.
  111. */
  112. float depthEncodeFar;
  113. UINT64 visibleLayers;
  114. ConvexVolume cullFrustum;
  115. };
  116. /** Data shared between RENDERER_VIEW_TARGET_DESC and RendererViewTargetProperties */
  117. struct RendererViewTargetData
  118. {
  119. SPtr<RenderTarget> target;
  120. Rect2I viewRect;
  121. Rect2 nrmViewRect;
  122. UINT32 targetWidth;
  123. UINT32 targetHeight;
  124. UINT32 numSamples;
  125. UINT32 clearFlags;
  126. Color clearColor;
  127. float clearDepthValue;
  128. UINT16 clearStencilValue;
  129. };
  130. /** Set of properties describing the output render target used by a renderer view. */
  131. struct RENDERER_VIEW_TARGET_DESC : RendererViewTargetData
  132. { };
  133. /** Set of properties used describing a specific view that the renderer can render. */
  134. struct RENDERER_VIEW_DESC : RendererViewData
  135. {
  136. RENDERER_VIEW_TARGET_DESC target;
  137. StateReduction stateReduction;
  138. Camera* sceneCamera;
  139. };
  140. /** Set of properties used describing a specific view that the renderer can render. */
  141. struct RendererViewProperties : RendererViewData
  142. {
  143. RendererViewProperties() {}
  144. RendererViewProperties(const RENDERER_VIEW_DESC& src);
  145. Matrix4 viewProjTransform;
  146. Matrix4 prevViewProjTransform;
  147. SPtr<RenderTarget> target;
  148. Rect2I viewRect;
  149. Rect2 nrmViewRect;
  150. UINT32 numSamples;
  151. UINT32 frameIdx;
  152. UINT32 clearFlags;
  153. Color clearColor;
  154. float clearDepthValue;
  155. UINT16 clearStencilValue;
  156. };
  157. /** Information whether certain scene objects are visible in a view, per object type. */
  158. struct VisibilityInfo
  159. {
  160. Vector<bool> renderables;
  161. Vector<bool> radialLights;
  162. Vector<bool> spotLights;
  163. Vector<bool> reflProbes;
  164. };
  165. /** Information used for culling an object against a view. */
  166. struct CullInfo
  167. {
  168. CullInfo(const Bounds& bounds, UINT64 layer = -1)
  169. :bounds(bounds), layer(layer)
  170. { }
  171. Bounds bounds;
  172. UINT64 layer;
  173. };
  174. /** Renderer information specific to a single render target. */
  175. struct RendererRenderTarget
  176. {
  177. SPtr<RenderTarget> target;
  178. Vector<Camera*> cameras;
  179. };
  180. /** Contains information about a single view into the scene, used by the renderer. */
  181. class RendererView
  182. {
  183. public:
  184. RendererView();
  185. RendererView(const RENDERER_VIEW_DESC& desc);
  186. /** Sets state reduction mode that determines how do render queues group & sort renderables. */
  187. void setStateReductionMode(StateReduction reductionMode);
  188. /** Updates the internal camera render settings. */
  189. void setRenderSettings(const SPtr<RenderSettings>& settings);
  190. /** Updates the internal information with a new view transform. */
  191. void setTransform(const Vector3& origin, const Vector3& direction, const Matrix4& view,
  192. const Matrix4& proj, const ConvexVolume& worldFrustum);
  193. /** Updates all internal information with new view information. */
  194. void setView(const RENDERER_VIEW_DESC& desc);
  195. /** Returns a structure describing the view. */
  196. const RendererViewProperties& getProperties() const { return mProperties; }
  197. /** Returns the scene camera this object is based of. This can be null for manually constructed renderer cameras. */
  198. Camera* getSceneCamera() const { return mCamera; }
  199. /** Prepares render targets for rendering. When done call endFrame(). */
  200. void beginFrame();
  201. /** Ends rendering and frees any acquired resources. */
  202. void endFrame();
  203. /**
  204. * Returns a render queue containing all opaque objects. Make sure to call determineVisible() beforehand if view
  205. * or object transforms changed since the last time it was called.
  206. */
  207. const SPtr<RenderQueue>& getOpaqueQueue() const { return mOpaqueQueue; }
  208. /**
  209. * Returns a render queue containing all transparent objects. Make sure to call determineVisible() beforehand if
  210. * view or object transforms changed since the last time it was called.
  211. */
  212. const SPtr<RenderQueue>& getTransparentQueue() const { return mTransparentQueue; }
  213. /** Returns the compositor in charge of rendering for this view. */
  214. const RenderCompositor& getCompositor() const { return mCompositor; }
  215. /**
  216. * Populates view render queues by determining visible renderable objects.
  217. *
  218. * @param[in] renderables A set of renderable objects to iterate over and determine visibility for.
  219. * @param[in] cullInfos A set of world bounds & other information relevant for culling the provided
  220. * renderable objects. Must be the same size as the @p renderables array.
  221. * @param[out] visibility Output parameter that will have the true bit set for any visible renderable
  222. * object. If the bit for an object is already set to true, the method will never
  223. * change it to false which allows the same bitfield to be provided to multiple
  224. * renderer views. Must be the same size as the @p renderables array.
  225. *
  226. * As a side-effect, per-view visibility data is also calculated and can be
  227. * retrieved by calling getVisibilityMask().
  228. */
  229. void determineVisible(const Vector<RendererObject*>& renderables, const Vector<CullInfo>& cullInfos,
  230. Vector<bool>* visibility = nullptr);
  231. /**
  232. * Calculates the visibility masks for all the lights of the provided type.
  233. *
  234. * @param[in] lights A set of lights to determine visibility for.
  235. * @param[in] bounds Bounding sphere for each provided light. Must be the same size as the @p lights
  236. * array.
  237. * @param[in] type Type of all the lights in the @p lights array.
  238. * @param[out] visibility Output parameter that will have the true bit set for any visible light. If the
  239. * bit for a light is already set to true, the method will never change it to false
  240. * which allows the same bitfield to be provided to multiple renderer views. Must
  241. * be the same size as the @p lights array.
  242. *
  243. * As a side-effect, per-view visibility data is also calculated and can be
  244. * retrieved by calling getVisibilityMask().
  245. */
  246. void determineVisible(const Vector<RendererLight>& lights, const Vector<Sphere>& bounds, LightType type,
  247. Vector<bool>* visibility = nullptr);
  248. /**
  249. * Culls the provided set of bounds against the current frustum and outputs a set of visibility flags determining
  250. * which entry is or isn't visible by this view. Both inputs must be arrays of the same size.
  251. */
  252. void calculateVisibility(const Vector<CullInfo>& cullInfos, Vector<bool>& visibility) const;
  253. /**
  254. * Culls the provided set of bounds against the current frustum and outputs a set of visibility flags determining
  255. * which entry is or isn't visible by this view. Both inputs must be arrays of the same size.
  256. */
  257. void calculateVisibility(const Vector<Sphere>& bounds, Vector<bool>& visibility) const;
  258. /**
  259. * Culls the provided set of bounds against the current frustum and outputs a set of visibility flags determining
  260. * which entry is or isn't visible by this view. Both inputs must be arrays of the same size.
  261. */
  262. void calculateVisibility(const Vector<AABox>& bounds, Vector<bool>& visibility) const;
  263. /** Returns the visibility mask calculated with the last call to determineVisible(). */
  264. const VisibilityInfo& getVisibilityMasks() const { return mVisibility; }
  265. /** Returns per-view settings that control rendering. */
  266. const RenderSettings& getRenderSettings() const { return *mRenderSettings; }
  267. /**
  268. * Retrieves a hash value that is updated whenever render settings change. This can be used by external systems
  269. * to detect when they need to update.
  270. */
  271. UINT64 getRenderSettingsHash() const { return mRenderSettingsHash; }
  272. /** Updates the GPU buffer containing per-view information, with the latest internal data. */
  273. void updatePerViewBuffer();
  274. /** Returns a buffer that stores per-view parameters. */
  275. SPtr<GpuParamBlockBuffer> getPerViewBuffer() const { return mParamBuffer; }
  276. /**
  277. * Returns information about visible lights, in the form of a light grid, used for forward rendering. Only valid
  278. * after a call to updateLightGrid().
  279. */
  280. const LightGrid& getLightGrid() const { return mLightGrid; }
  281. /** Updates the light grid used for forward rendering. */
  282. void updateLightGrid(const VisibleLightData& visibleLightData, const VisibleReflProbeData& visibleReflProbeData);
  283. /**
  284. * Returns a value that can be used for transforming x, y coordinates from NDC into UV coordinates that can be used
  285. * for sampling a texture projected on the view.
  286. *
  287. * @return Returns two 2D values that can be used to transform the coordinate as such: UV = NDC * xy + zw.
  288. */
  289. Vector4 getNDCToUV() const;
  290. /** Returns an index of this view within the parent view group. */
  291. UINT32 getViewIdx() const { return mViewIdx; }
  292. /** Assigns a view index to the view. To be called by the parent view group when the view is added to it. */
  293. void _setViewIdx(UINT32 viewIdx) { mViewIdx = viewIdx; }
  294. /**
  295. * Extracts the necessary values from the projection matrix that allow you to transform device Z value (range [0, 1]
  296. * into view Z value.
  297. *
  298. * @param[in] projMatrix Projection matrix that was used to create the device Z value to transform.
  299. * @return Returns two values that can be used to transform device z to view z using this formula:
  300. * z = (deviceZ + y) * x.
  301. */
  302. static Vector2 getDeviceZToViewZ(const Matrix4& projMatrix);
  303. /**
  304. * Extracts the necessary values from the projection matrix that allow you to transform NDC Z value (range depending
  305. * on render API) into view Z value.
  306. *
  307. * @param[in] projMatrix Projection matrix that was used to create the NDC Z value to transform.
  308. * @return Returns two values that can be used to transform NDC z to view z using this formula:
  309. * z = (NDCZ + y) * x.
  310. */
  311. static Vector2 getNDCZToViewZ(const Matrix4& projMatrix);
  312. /**
  313. * Returns a value that can be used for tranforming a depth value in NDC, to a depth value in device Z ([0, 1]
  314. * range using this formula: (NDCZ + y) * x.
  315. */
  316. static Vector2 getNDCZToDeviceZ();
  317. private:
  318. RendererViewProperties mProperties;
  319. RENDERER_VIEW_TARGET_DESC mTargetDesc;
  320. Camera* mCamera;
  321. SPtr<RenderQueue> mOpaqueQueue;
  322. SPtr<RenderQueue> mTransparentQueue;
  323. RenderCompositor mCompositor;
  324. SPtr<RenderSettings> mRenderSettings;
  325. UINT32 mRenderSettingsHash;
  326. SPtr<GpuParamBlockBuffer> mParamBuffer;
  327. VisibilityInfo mVisibility;
  328. LightGrid mLightGrid;
  329. UINT32 mViewIdx;
  330. };
  331. /** Contains one or multiple RendererView%s that are in some way related. */
  332. class RendererViewGroup
  333. {
  334. public:
  335. RendererViewGroup();
  336. RendererViewGroup(RendererView** views, UINT32 numViews, UINT32 shadowMapSize);
  337. /**
  338. * Updates the internal list of views. This is more efficient than always constructing a new instance of this class
  339. * when views change, as internal buffers don't need to be re-allocated.
  340. */
  341. void setViews(RendererView** views, UINT32 numViews);
  342. /** Returns a view at the specified index. Index must be less than the value returned by getNumViews(). */
  343. RendererView* getView(UINT32 idx) const { return mViews[idx]; }
  344. /** Returns the total number of views in the group. */
  345. UINT32 getNumViews() const { return (UINT32)mViews.size(); }
  346. /**
  347. * Returns information about visibility of various scene objects, from the perspective of all the views in the
  348. * group (visibility will be true if the object is visible from any of the views. determineVisibility() must be
  349. * called whenever the scene or view information changes (usually every frame).
  350. */
  351. const VisibilityInfo& getVisibilityInfo() const { return mVisibility; }
  352. /**
  353. * Returns information about lights visible from this group of views. Only valid after a call to
  354. * determineVisibility().
  355. */
  356. const VisibleLightData& getVisibleLightData() const { return mVisibleLightData; }
  357. /**
  358. * Returns information about refl. probes visible from this group of views. Only valid after a call to
  359. * determineVisibility().
  360. */
  361. const VisibleReflProbeData& getVisibleReflProbeData() const { return mVisibleReflProbeData; }
  362. /** Returns the object responsible for rendering shadows for this view group. */
  363. ShadowRendering& getShadowRenderer() { return mShadowRenderer; }
  364. /** Returns the object responsible for rendering shadows for this view group. */
  365. const ShadowRendering& getShadowRenderer() const { return mShadowRenderer; }
  366. /**
  367. * Updates visibility information for the provided scene objects, from the perspective of all views in this group,
  368. * and updates the render queues of each individual view. Use getVisibilityInfo() to retrieve the calculated
  369. * visibility information.
  370. */
  371. void determineVisibility(const SceneInfo& sceneInfo);
  372. private:
  373. Vector<RendererView*> mViews;
  374. VisibilityInfo mVisibility;
  375. VisibleLightData mVisibleLightData;
  376. VisibleReflProbeData mVisibleReflProbeData;
  377. // Note: Ideally we would want to keep this global, so all views share it. This way each view group renders its
  378. // own set of shadows, but there might be shadows that are shared, and therefore we could avoid rendering them
  379. // multiple times. Since non-primary view groups are used for pre-processing tasks exclusively (at the moment)
  380. // this isn't an issue right now.
  381. ShadowRendering mShadowRenderer;
  382. };
  383. /** @} */
  384. }}