BsRendererView.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsRendererView.h"
  4. #include "BsCamera.h"
  5. #include "BsRenderable.h"
  6. #include "BsMaterial.h"
  7. #include "BsShader.h"
  8. #include "BsRenderTargets.h"
  9. #include "BsRendererUtility.h"
  10. #include "BsGpuParamsSet.h"
  11. namespace bs { namespace ct
  12. {
  13. PerCameraParamDef gPerCameraParamDef;
  14. SkyboxParamDef gSkyboxParamDef;
  15. template<bool SOLID_COLOR>
  16. SkyboxMat<SOLID_COLOR>::SkyboxMat()
  17. {
  18. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  19. if(params->hasTexture(GPT_FRAGMENT_PROGRAM, "gSkyTex"))
  20. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gSkyTex", mSkyTextureParam);
  21. mParamBuffer = gSkyboxParamDef.createBuffer();
  22. if(params->hasParamBlock(GPT_FRAGMENT_PROGRAM, "Params"))
  23. mParamsSet->setParamBlockBuffer("Params", mParamBuffer, true);
  24. }
  25. template<bool SOLID_COLOR>
  26. void SkyboxMat<SOLID_COLOR>::_initDefines(ShaderDefines& defines)
  27. {
  28. if (SOLID_COLOR)
  29. defines.set("SOLID_COLOR", 1);
  30. }
  31. template<bool SOLID_COLOR>
  32. void SkyboxMat<SOLID_COLOR>::bind(const SPtr<GpuParamBlockBuffer>& perCamera)
  33. {
  34. mParamsSet->setParamBlockBuffer("PerCamera", perCamera, true);
  35. gRendererUtility().setPass(mMaterial, 0);
  36. }
  37. template<bool SOLID_COLOR>
  38. void SkyboxMat<SOLID_COLOR>::setParams(const SPtr<Texture>& texture, const Color& solidColor)
  39. {
  40. mSkyTextureParam.set(texture, TextureSurface(1, 1, 0, 0));
  41. gSkyboxParamDef.gClearColor.set(mParamBuffer, solidColor);
  42. mParamBuffer->flushToGPU();
  43. gRendererUtility().setPassParams(mParamsSet);
  44. }
  45. RendererViewProperties::RendererViewProperties(const RENDERER_VIEW_DESC& src)
  46. :RendererViewData(src)
  47. {
  48. viewProjTransform = src.projTransform * src.viewTransform;
  49. target = src.target.target;
  50. nrmViewRect = src.target.nrmViewRect;
  51. numSamples = src.target.numSamples;
  52. clearFlags = src.target.clearFlags;
  53. clearColor = src.target.clearColor;
  54. clearDepthValue = src.target.clearDepthValue;
  55. clearStencilValue = src.target.clearStencilValue;
  56. }
  57. RendererView::RendererView()
  58. : mUsingGBuffer(false)
  59. {
  60. mParamBuffer = gPerCameraParamDef.createBuffer();
  61. }
  62. RendererView::RendererView(const RENDERER_VIEW_DESC& desc)
  63. : mProperties(desc), mTargetDesc(desc.target), mCamera(desc.sceneCamera), mUsingGBuffer(false)
  64. {
  65. mParamBuffer = gPerCameraParamDef.createBuffer();
  66. setStateReductionMode(desc.stateReduction);
  67. }
  68. void RendererView::setStateReductionMode(StateReduction reductionMode)
  69. {
  70. mOpaqueQueue = bs_shared_ptr_new<RenderQueue>(reductionMode);
  71. StateReduction transparentStateReduction = reductionMode;
  72. if (transparentStateReduction == StateReduction::Material)
  73. transparentStateReduction = StateReduction::Distance; // Transparent object MUST be sorted by distance
  74. mTransparentQueue = bs_shared_ptr_new<RenderQueue>(transparentStateReduction);
  75. }
  76. void RendererView::setPostProcessSettings(const SPtr<PostProcessSettings>& ppSettings)
  77. {
  78. if (mPostProcessInfo.settings == nullptr)
  79. mPostProcessInfo.settings = bs_shared_ptr_new<StandardPostProcessSettings>();
  80. SPtr<StandardPostProcessSettings> stdPPSettings = std::static_pointer_cast<StandardPostProcessSettings>(ppSettings);
  81. if (stdPPSettings != nullptr)
  82. *mPostProcessInfo.settings = *stdPPSettings;
  83. else
  84. *mPostProcessInfo.settings = StandardPostProcessSettings();
  85. mPostProcessInfo.settingDirty = true;
  86. }
  87. void RendererView::setTransform(const Vector3& origin, const Vector3& direction, const Matrix4& view,
  88. const Matrix4& proj, const ConvexVolume& worldFrustum)
  89. {
  90. mProperties.viewOrigin = origin;
  91. mProperties.viewDirection = direction;
  92. mProperties.viewTransform = view;
  93. mProperties.projTransform = proj;
  94. mProperties.cullFrustum = worldFrustum;
  95. mProperties.viewProjTransform = proj * view;
  96. }
  97. void RendererView::setView(const RENDERER_VIEW_DESC& desc)
  98. {
  99. if (mTargetDesc.targetWidth != desc.target.targetWidth ||
  100. mTargetDesc.targetHeight != desc.target.targetHeight)
  101. mRenderTargets = nullptr;
  102. mCamera = desc.sceneCamera;
  103. mProperties = desc;
  104. mTargetDesc = desc.target;
  105. setStateReductionMode(desc.stateReduction);
  106. }
  107. void RendererView::beginRendering(bool useGBuffer)
  108. {
  109. if (useGBuffer)
  110. {
  111. // Render scene objects to g-buffer
  112. bool createGBuffer = mRenderTargets == nullptr ||
  113. mRenderTargets->getHDR() != mProperties.isHDR ||
  114. mRenderTargets->getNumSamples() != mTargetDesc.numSamples;
  115. if (createGBuffer)
  116. mRenderTargets = RenderTargets::create(mTargetDesc, mProperties.isHDR);
  117. mRenderTargets->prepare();
  118. mUsingGBuffer = true;
  119. }
  120. }
  121. void RendererView::endRendering()
  122. {
  123. mOpaqueQueue->clear();
  124. mTransparentQueue->clear();
  125. if(mUsingGBuffer)
  126. {
  127. mRenderTargets->cleanup();
  128. mUsingGBuffer = false;
  129. }
  130. }
  131. void RendererView::determineVisible(const Vector<RendererObject*>& renderables, const Vector<CullInfo>& cullInfos,
  132. Vector<bool>* visibility)
  133. {
  134. mVisibility.renderables.clear();
  135. mVisibility.renderables.resize(renderables.size(), false);
  136. if (mProperties.isOverlay)
  137. return;
  138. calculateVisibility(cullInfos, mVisibility.renderables);
  139. // Update per-object param buffers and queue render elements
  140. for(UINT32 i = 0; i < (UINT32)cullInfos.size(); i++)
  141. {
  142. if (!mVisibility.renderables[i])
  143. continue;
  144. const AABox& boundingBox = cullInfos[i].bounds.getBox();
  145. float distanceToCamera = (mProperties.viewOrigin - boundingBox.getCenter()).length();
  146. for (auto& renderElem : renderables[i]->elements)
  147. {
  148. // Note: I could keep opaque and transparent renderables in two separate arrays, so I don't need to do the
  149. // check here
  150. bool isTransparent = (renderElem.material->getShader()->getFlags() & (UINT32)ShaderFlags::Transparent) != 0;
  151. if (isTransparent)
  152. mTransparentQueue->add(&renderElem, distanceToCamera);
  153. else
  154. mOpaqueQueue->add(&renderElem, distanceToCamera);
  155. }
  156. }
  157. if(visibility != nullptr)
  158. {
  159. for (UINT32 i = 0; i < (UINT32)renderables.size(); i++)
  160. {
  161. bool visible = (*visibility)[i];
  162. (*visibility)[i] = visible || mVisibility.renderables[i];
  163. }
  164. }
  165. mOpaqueQueue->sort();
  166. mTransparentQueue->sort();
  167. }
  168. void RendererView::calculateVisibility(const Vector<CullInfo>& cullInfos, Vector<bool>& visibility) const
  169. {
  170. UINT64 cameraLayers = mProperties.visibleLayers;
  171. const ConvexVolume& worldFrustum = mProperties.cullFrustum;
  172. for (UINT32 i = 0; i < (UINT32)cullInfos.size(); i++)
  173. {
  174. if ((cullInfos[i].layer & cameraLayers) == 0)
  175. continue;
  176. // Do frustum culling
  177. // Note: This is bound to be a bottleneck at some point. When it is ensure that intersect methods use vector
  178. // operations, as it is trivial to update them. Also consider spatial partitioning.
  179. const Sphere& boundingSphere = cullInfos[i].bounds.getSphere();
  180. if (worldFrustum.intersects(boundingSphere))
  181. {
  182. // More precise with the box
  183. const AABox& boundingBox = cullInfos[i].bounds.getBox();
  184. if (worldFrustum.intersects(boundingBox))
  185. visibility[i] = true;
  186. }
  187. }
  188. }
  189. void RendererView::calculateVisibility(const Vector<Sphere>& bounds, Vector<bool>& visibility) const
  190. {
  191. const ConvexVolume& worldFrustum = mProperties.cullFrustum;
  192. for (UINT32 i = 0; i < (UINT32)bounds.size(); i++)
  193. {
  194. if (worldFrustum.intersects(bounds[i]))
  195. visibility[i] = true;
  196. }
  197. }
  198. Vector2 RendererView::getDeviceZTransform(const Matrix4& projMatrix) const
  199. {
  200. // Returns a set of values that will transform depth buffer values (in range [0, 1]) to a distance
  201. // in view space. This involes applying the inverse projection transform to the depth value. When you multiply
  202. // a vector with the projection matrix you get [clipX, clipY, Az + B, C * z], where we don't care about clipX/clipY.
  203. // A is [2, 2], B is [2, 3] and C is [3, 2] elements of the projection matrix (only ones that matter for our depth
  204. // value). The hardware will also automatically divide the z value with w to get the depth, therefore the final
  205. // formula is:
  206. // depth = (Az + B) / (C * z)
  207. // To get the z coordinate back we simply do the opposite:
  208. // z = B / (depth * C - A)
  209. // However some APIs will also do a transformation on the depth values before storing them to the texture
  210. // (e.g. OpenGL will transform from [-1, 1] to [0, 1]). And we need to reverse that as well. Therefore the final
  211. // formula is:
  212. // z = B / ((depth * (maxDepth - minDepth) + minDepth) * C - A)
  213. // Are we reorganize it because it needs to fit the "(1.0f / (depth + y)) * x" format used in the shader:
  214. // z = 1.0f / (depth + minDepth/(maxDepth - minDepth) - A/((maxDepth - minDepth) * C)) * B/((maxDepth - minDepth) * C)
  215. RenderAPI& rapi = RenderAPI::instance();
  216. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  217. float depthRange = rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue();
  218. float minDepth = rapiInfo.getMinimumDepthInputValue();
  219. float a = projMatrix[2][2];
  220. float b = projMatrix[2][3];
  221. float c = projMatrix[3][2];
  222. Vector2 output;
  223. if (c != 0.0f)
  224. {
  225. output.x = b / (depthRange * c);
  226. output.y = minDepth / depthRange - a / (depthRange * c);
  227. }
  228. else // Ortographic, assuming viewing towards negative Z
  229. {
  230. output.x = b / -depthRange;
  231. output.y = minDepth / depthRange - a / -depthRange;
  232. }
  233. return output;
  234. }
  235. Vector2 RendererView::getNDCZTransform(const Matrix4& projMatrix) const
  236. {
  237. // Returns a set of values that will transform depth buffer values (e.g. [0, 1] in DX, [-1, 1] in GL) to a distance
  238. // in view space. This involes applying the inverse projection transform to the depth value. When you multiply
  239. // a vector with the projection matrix you get [clipX, clipY, Az + B, C * z], where we don't care about clipX/clipY.
  240. // A is [2, 2], B is [2, 3] and C is [3, 2] elements of the projection matrix (only ones that matter for our depth
  241. // value). The hardware will also automatically divide the z value with w to get the depth, therefore the final
  242. // formula is:
  243. // depth = (Az + B) / (C * z)
  244. // To get the z coordinate back we simply do the opposite:
  245. // z = B / (depth * C - A)
  246. // Are we reorganize it because it needs to fit the "(1.0f / (depth + y)) * x" format used in the shader:
  247. // z = 1.0f / (depth - A/C) * B/C
  248. RenderAPI& rapi = RenderAPI::instance();
  249. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  250. float a = projMatrix[2][2];
  251. float b = projMatrix[2][3];
  252. float c = projMatrix[3][2];
  253. Vector2 output;
  254. if (c != 0.0f)
  255. {
  256. output.x = b / c;
  257. output.y = -a / c;
  258. }
  259. else // Ortographic, assuming viewing towards negative Z
  260. {
  261. output.x = -b;
  262. output.y = a;
  263. }
  264. return output;
  265. }
  266. void RendererView::updatePerViewBuffer()
  267. {
  268. Matrix4 viewProj = mProperties.projTransform * mProperties.viewTransform;
  269. Matrix4 invViewProj = viewProj.inverse();
  270. gPerCameraParamDef.gMatProj.set(mParamBuffer, mProperties.projTransform);
  271. gPerCameraParamDef.gMatView.set(mParamBuffer, mProperties.viewTransform);
  272. gPerCameraParamDef.gMatViewProj.set(mParamBuffer, viewProj);
  273. gPerCameraParamDef.gMatInvViewProj.set(mParamBuffer, invViewProj); // Note: Calculate inverses separately (better precision possibly)
  274. gPerCameraParamDef.gMatInvProj.set(mParamBuffer, mProperties.projTransform.inverse());
  275. // Construct a special inverse view-projection matrix that had projection entries that affect z and w eliminated.
  276. // Used to transform a vector(clip_x, clip_y, view_z, view_w), where clip_x/clip_y are in clip space, and
  277. // view_z/view_w in view space, into world space.
  278. // Only projects z/w coordinates
  279. Matrix4 projZ = Matrix4::IDENTITY;
  280. projZ[2][2] = mProperties.projTransform[2][2];
  281. projZ[2][3] = mProperties.projTransform[2][3];
  282. projZ[3][2] = mProperties.projTransform[3][2];
  283. projZ[3][3] = 0.0f;
  284. gPerCameraParamDef.gMatScreenToWorld.set(mParamBuffer, invViewProj * projZ);
  285. gPerCameraParamDef.gViewDir.set(mParamBuffer, mProperties.viewDirection);
  286. gPerCameraParamDef.gViewOrigin.set(mParamBuffer, mProperties.viewOrigin);
  287. gPerCameraParamDef.gDeviceZToWorldZ.set(mParamBuffer, getDeviceZTransform(mProperties.projTransform));
  288. gPerCameraParamDef.gNDCZToWorldZ.set(mParamBuffer, getNDCZTransform(mProperties.projTransform));
  289. Vector2 nearFar(mProperties.nearPlane, mProperties.farPlane);
  290. gPerCameraParamDef.gNearFar.set(mParamBuffer, nearFar);
  291. const Rect2I& viewRect = mTargetDesc.viewRect;
  292. Vector4I viewportRect;
  293. viewportRect[0] = viewRect.x;
  294. viewportRect[1] = viewRect.y;
  295. viewportRect[2] = viewRect.width;
  296. viewportRect[3] = viewRect.height;
  297. gPerCameraParamDef.gViewportRectangle.set(mParamBuffer, viewportRect);
  298. float halfWidth = viewRect.width * 0.5f;
  299. float halfHeight = viewRect.height * 0.5f;
  300. float rtWidth = mTargetDesc.targetWidth != 0 ? (float)mTargetDesc.targetWidth : 20.0f;
  301. float rtHeight = mTargetDesc.targetHeight != 0 ? (float)mTargetDesc.targetHeight : 20.0f;
  302. RenderAPI& rapi = RenderAPI::instance();
  303. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  304. Vector4 clipToUVScaleOffset;
  305. clipToUVScaleOffset.x = halfWidth / rtWidth;
  306. clipToUVScaleOffset.y = -halfHeight / rtHeight;
  307. clipToUVScaleOffset.z = viewRect.x / rtWidth + (halfWidth + rapiInfo.getHorizontalTexelOffset()) / rtWidth;
  308. clipToUVScaleOffset.w = viewRect.y / rtHeight + (halfHeight + rapiInfo.getVerticalTexelOffset()) / rtHeight;
  309. // Either of these flips the Y axis, but if they're both true they cancel out
  310. if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp) ^ rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
  311. clipToUVScaleOffset.y = -clipToUVScaleOffset.y;
  312. gPerCameraParamDef.gClipToUVScaleOffset.set(mParamBuffer, clipToUVScaleOffset);
  313. if (mProperties.noLighting)
  314. gPerCameraParamDef.gAmbientFactor.set(mParamBuffer, 100.0f);
  315. else
  316. gPerCameraParamDef.gAmbientFactor.set(mParamBuffer, 0.0f);
  317. }
  318. template class SkyboxMat<true>;
  319. template class SkyboxMat<false>;
  320. }}