| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539 |
- //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
- //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
- #include "BsRendererView.h"
- #include "BsCamera.h"
- #include "BsRenderable.h"
- #include "BsMaterial.h"
- #include "BsShader.h"
- #include "BsRenderTargets.h"
- #include "BsRendererUtility.h"
- #include "BsLightRendering.h"
- #include "BsGpuParamsSet.h"
- #include "BsRendererScene.h"
- namespace bs { namespace ct
- {
- PerCameraParamDef gPerCameraParamDef;
- SkyboxParamDef gSkyboxParamDef;
- template<bool SOLID_COLOR>
- SkyboxMat<SOLID_COLOR>::SkyboxMat()
- {
- SPtr<GpuParams> params = mParamsSet->getGpuParams();
- if(params->hasTexture(GPT_FRAGMENT_PROGRAM, "gSkyTex"))
- params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gSkyTex", mSkyTextureParam);
- mParamBuffer = gSkyboxParamDef.createBuffer();
- if(params->hasParamBlock(GPT_FRAGMENT_PROGRAM, "Params"))
- mParamsSet->setParamBlockBuffer("Params", mParamBuffer, true);
- }
- template<bool SOLID_COLOR>
- void SkyboxMat<SOLID_COLOR>::_initDefines(ShaderDefines& defines)
- {
- if (SOLID_COLOR)
- defines.set("SOLID_COLOR", 1);
- }
- template<bool SOLID_COLOR>
- void SkyboxMat<SOLID_COLOR>::bind(const SPtr<GpuParamBlockBuffer>& perCamera)
- {
- mParamsSet->setParamBlockBuffer("PerCamera", perCamera, true);
- gRendererUtility().setPass(mMaterial, 0);
- }
- template<bool SOLID_COLOR>
- void SkyboxMat<SOLID_COLOR>::setParams(const SPtr<Texture>& texture, const Color& solidColor)
- {
- mSkyTextureParam.set(texture, TextureSurface(1, 1, 0, 0));
- gSkyboxParamDef.gClearColor.set(mParamBuffer, solidColor);
- mParamBuffer->flushToGPU();
- gRendererUtility().setPassParams(mParamsSet);
- }
- RendererViewProperties::RendererViewProperties(const RENDERER_VIEW_DESC& src)
- :RendererViewData(src)
- {
- viewProjTransform = src.projTransform * src.viewTransform;
- target = src.target.target;
- viewRect = src.target.viewRect;
- nrmViewRect = src.target.nrmViewRect;
- numSamples = src.target.numSamples;
- clearFlags = src.target.clearFlags;
- clearColor = src.target.clearColor;
- clearDepthValue = src.target.clearDepthValue;
- clearStencilValue = src.target.clearStencilValue;
- }
- RendererView::RendererView()
- : mUsingGBuffer(false)
- {
- mParamBuffer = gPerCameraParamDef.createBuffer();
- }
- RendererView::RendererView(const RENDERER_VIEW_DESC& desc)
- : mProperties(desc), mTargetDesc(desc.target), mCamera(desc.sceneCamera), mUsingGBuffer(false)
- {
- mParamBuffer = gPerCameraParamDef.createBuffer();
- mProperties.prevViewProjTransform = mProperties.viewProjTransform;
- setStateReductionMode(desc.stateReduction);
- }
- void RendererView::setStateReductionMode(StateReduction reductionMode)
- {
- mOpaqueQueue = bs_shared_ptr_new<RenderQueue>(reductionMode);
- StateReduction transparentStateReduction = reductionMode;
- if (transparentStateReduction == StateReduction::Material)
- transparentStateReduction = StateReduction::Distance; // Transparent object MUST be sorted by distance
- mTransparentQueue = bs_shared_ptr_new<RenderQueue>(transparentStateReduction);
- }
- void RendererView::setPostProcessSettings(const SPtr<PostProcessSettings>& ppSettings)
- {
- if (mPostProcessInfo.settings == nullptr)
- mPostProcessInfo.settings = bs_shared_ptr_new<StandardPostProcessSettings>();
- SPtr<StandardPostProcessSettings> stdPPSettings = std::static_pointer_cast<StandardPostProcessSettings>(ppSettings);
- if (stdPPSettings != nullptr)
- *mPostProcessInfo.settings = *stdPPSettings;
- else
- *mPostProcessInfo.settings = StandardPostProcessSettings();
- mPostProcessInfo.settingDirty = true;
- }
- void RendererView::setTransform(const Vector3& origin, const Vector3& direction, const Matrix4& view,
- const Matrix4& proj, const ConvexVolume& worldFrustum)
- {
- mProperties.viewOrigin = origin;
- mProperties.viewDirection = direction;
- mProperties.viewTransform = view;
- mProperties.projTransform = proj;
- mProperties.cullFrustum = worldFrustum;
- mProperties.viewProjTransform = proj * view;
- }
- void RendererView::setView(const RENDERER_VIEW_DESC& desc)
- {
- if (mTargetDesc.targetWidth != desc.target.targetWidth ||
- mTargetDesc.targetHeight != desc.target.targetHeight)
- mRenderTargets = nullptr;
- mCamera = desc.sceneCamera;
- mProperties = desc;
- mTargetDesc = desc.target;
- setStateReductionMode(desc.stateReduction);
- }
- void RendererView::beginFrame(bool useGBuffer)
- {
- if (useGBuffer)
- {
- // Render scene objects to g-buffer
- bool createGBuffer = mRenderTargets == nullptr ||
- mRenderTargets->getHDR() != mProperties.isHDR ||
- mRenderTargets->getNumSamples() != mTargetDesc.numSamples;
- if (createGBuffer)
- mRenderTargets = RenderTargets::create(mTargetDesc, mProperties.isHDR);
- mRenderTargets->prepare();
- mUsingGBuffer = true;
- }
- }
- void RendererView::endFrame()
- {
- // Save view-projection matrix to use for temporal filtering
- mProperties.prevViewProjTransform = mProperties.viewProjTransform;
- mOpaqueQueue->clear();
- mTransparentQueue->clear();
- if(mUsingGBuffer)
- {
- mRenderTargets->cleanup();
- mUsingGBuffer = false;
- }
- }
- void RendererView::determineVisible(const Vector<RendererObject*>& renderables, const Vector<CullInfo>& cullInfos,
- Vector<bool>* visibility)
- {
- mVisibility.renderables.clear();
- mVisibility.renderables.resize(renderables.size(), false);
- if (mProperties.isOverlay)
- return;
- calculateVisibility(cullInfos, mVisibility.renderables);
- // Update per-object param buffers and queue render elements
- for(UINT32 i = 0; i < (UINT32)cullInfos.size(); i++)
- {
- if (!mVisibility.renderables[i])
- continue;
- const AABox& boundingBox = cullInfos[i].bounds.getBox();
- float distanceToCamera = (mProperties.viewOrigin - boundingBox.getCenter()).length();
- for (auto& renderElem : renderables[i]->elements)
- {
- // Note: I could keep opaque and transparent renderables in two separate arrays, so I don't need to do the
- // check here
- bool isTransparent = (renderElem.material->getShader()->getFlags() & (UINT32)ShaderFlags::Transparent) != 0;
- if (isTransparent)
- mTransparentQueue->add(&renderElem, distanceToCamera);
- else
- mOpaqueQueue->add(&renderElem, distanceToCamera);
- }
- }
- if(visibility != nullptr)
- {
- for (UINT32 i = 0; i < (UINT32)renderables.size(); i++)
- {
- bool visible = (*visibility)[i];
- (*visibility)[i] = visible || mVisibility.renderables[i];
- }
- }
- mOpaqueQueue->sort();
- mTransparentQueue->sort();
- }
- void RendererView::determineVisible(const Vector<RendererLight>& lights, const Vector<Sphere>& bounds,
- LightType lightType, Vector<bool>* visibility)
- {
- // Special case for directional lights, they're always visible
- if(lightType == LightType::Directional)
- {
- if (visibility)
- visibility->assign(lights.size(), true);
- return;
- }
- Vector<bool>* perViewVisibility;
- if(lightType == LightType::Radial)
- {
- mVisibility.radialLights.clear();
- mVisibility.radialLights.resize(lights.size(), false);
- perViewVisibility = &mVisibility.radialLights;
- }
- else // Spot
- {
- mVisibility.spotLights.clear();
- mVisibility.spotLights.resize(lights.size(), false);
- perViewVisibility = &mVisibility.spotLights;
- }
- if (mProperties.isOverlay)
- return;
- calculateVisibility(bounds, *perViewVisibility);
- if(visibility != nullptr)
- {
- for (UINT32 i = 0; i < (UINT32)lights.size(); i++)
- {
- bool visible = (*visibility)[i];
- (*visibility)[i] = visible || (*perViewVisibility)[i];
- }
- }
- }
- void RendererView::calculateVisibility(const Vector<CullInfo>& cullInfos, Vector<bool>& visibility) const
- {
- UINT64 cameraLayers = mProperties.visibleLayers;
- const ConvexVolume& worldFrustum = mProperties.cullFrustum;
- for (UINT32 i = 0; i < (UINT32)cullInfos.size(); i++)
- {
- if ((cullInfos[i].layer & cameraLayers) == 0)
- continue;
- // Do frustum culling
- // Note: This is bound to be a bottleneck at some point. When it is ensure that intersect methods use vector
- // operations, as it is trivial to update them. Also consider spatial partitioning.
- const Sphere& boundingSphere = cullInfos[i].bounds.getSphere();
- if (worldFrustum.intersects(boundingSphere))
- {
- // More precise with the box
- const AABox& boundingBox = cullInfos[i].bounds.getBox();
- if (worldFrustum.intersects(boundingBox))
- visibility[i] = true;
- }
- }
- }
- void RendererView::calculateVisibility(const Vector<Sphere>& bounds, Vector<bool>& visibility) const
- {
- const ConvexVolume& worldFrustum = mProperties.cullFrustum;
- for (UINT32 i = 0; i < (UINT32)bounds.size(); i++)
- {
- if (worldFrustum.intersects(bounds[i]))
- visibility[i] = true;
- }
- }
- void RendererView::calculateVisibility(const Vector<AABox>& bounds, Vector<bool>& visibility) const
- {
- const ConvexVolume& worldFrustum = mProperties.cullFrustum;
- for (UINT32 i = 0; i < (UINT32)bounds.size(); i++)
- {
- if (worldFrustum.intersects(bounds[i]))
- visibility[i] = true;
- }
- }
- Vector2 RendererView::getDeviceZToViewZ(const Matrix4& projMatrix)
- {
- // Returns a set of values that will transform depth buffer values (in range [0, 1]) to a distance
- // in view space. This involes applying the inverse projection transform to the depth value. When you multiply
- // a vector with the projection matrix you get [clipX, clipY, Az + B, C * z], where we don't care about clipX/clipY.
- // 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
- // value). The hardware will also automatically divide the z value with w to get the depth, therefore the final
- // formula is:
- // depth = (Az + B) / (C * z)
- // To get the z coordinate back we simply do the opposite:
- // z = B / (depth * C - A)
- // However some APIs will also do a transformation on the depth values before storing them to the texture
- // (e.g. OpenGL will transform from [-1, 1] to [0, 1]). And we need to reverse that as well. Therefore the final
- // formula is:
- // z = B / ((depth * (maxDepth - minDepth) + minDepth) * C - A)
- // Are we reorganize it because it needs to fit the "(1.0f / (depth + y)) * x" format used in the shader:
- // z = 1.0f / (depth + minDepth/(maxDepth - minDepth) - A/((maxDepth - minDepth) * C)) * B/((maxDepth - minDepth) * C)
- RenderAPI& rapi = RenderAPI::instance();
- const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
- float depthRange = rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue();
- float minDepth = rapiInfo.getMinimumDepthInputValue();
- float a = projMatrix[2][2];
- float b = projMatrix[2][3];
- float c = projMatrix[3][2];
- Vector2 output;
- if (c != 0.0f)
- {
- output.x = b / (depthRange * c);
- output.y = minDepth / depthRange - a / (depthRange * c);
- }
- else // Ortographic, assuming viewing towards negative Z
- {
- output.x = b / -depthRange;
- output.y = minDepth / depthRange - a / -depthRange;
- }
- return output;
- }
- Vector2 RendererView::getNDCZToViewZ(const Matrix4& projMatrix)
- {
- // Returns a set of values that will transform depth buffer values (e.g. [0, 1] in DX, [-1, 1] in GL) to a distance
- // in view space. This involes applying the inverse projection transform to the depth value. When you multiply
- // a vector with the projection matrix you get [clipX, clipY, Az + B, C * z], where we don't care about clipX/clipY.
- // 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
- // value). The hardware will also automatically divide the z value with w to get the depth, therefore the final
- // formula is:
- // depth = (Az + B) / (C * z)
- // To get the z coordinate back we simply do the opposite:
- // z = B / (depth * C - A)
- // Are we reorganize it because it needs to fit the "(1.0f / (depth + y)) * x" format used in the shader:
- // z = 1.0f / (depth - A/C) * B/C
- RenderAPI& rapi = RenderAPI::instance();
- const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
- float a = projMatrix[2][2];
- float b = projMatrix[2][3];
- float c = projMatrix[3][2];
- Vector2 output;
- if (c != 0.0f)
- {
- output.x = b / c;
- output.y = -a / c;
- }
- else // Ortographic, assuming viewing towards negative Z
- {
- output.x = -b;
- output.y = a;
- }
- return output;
- }
- Vector2 RendererView::getNDCZToDeviceZ()
- {
- RenderAPI& rapi = RenderAPI::instance();
- const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
- Vector2 ndcZToDeviceZ;
- ndcZToDeviceZ.x = 1.0f / (rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue());
- ndcZToDeviceZ.y = -rapiInfo.getMinimumDepthInputValue();
- return ndcZToDeviceZ;
- }
- void RendererView::updatePerViewBuffer()
- {
- RenderAPI& rapi = RenderAPI::instance();
- const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
- Matrix4 viewProj = mProperties.projTransform * mProperties.viewTransform;
- Matrix4 invViewProj = viewProj.inverse();
- gPerCameraParamDef.gMatProj.set(mParamBuffer, mProperties.projTransform);
- gPerCameraParamDef.gMatView.set(mParamBuffer, mProperties.viewTransform);
- gPerCameraParamDef.gMatViewProj.set(mParamBuffer, viewProj);
- gPerCameraParamDef.gMatInvViewProj.set(mParamBuffer, invViewProj); // Note: Calculate inverses separately (better precision possibly)
- gPerCameraParamDef.gMatInvProj.set(mParamBuffer, mProperties.projTransform.inverse());
- // Construct a special inverse view-projection matrix that had projection entries that effect z and w eliminated.
- // Used to transform a vector(clip_x, clip_y, view_z, view_w), where clip_x/clip_y are in clip space, and
- // view_z/view_w in view space, into world space.
- // Only projects z/w coordinates (cancels out with the inverse matrix below)
- Matrix4 projZ = Matrix4::IDENTITY;
- projZ[2][2] = mProperties.projTransform[2][2];
- projZ[2][3] = mProperties.projTransform[2][3];
- projZ[3][2] = mProperties.projTransform[3][2];
- projZ[3][3] = 0.0f;
-
- gPerCameraParamDef.gMatScreenToWorld.set(mParamBuffer, invViewProj * projZ);
- gPerCameraParamDef.gNDCToPrevNDC.set(mParamBuffer, mProperties.prevViewProjTransform * invViewProj);
- gPerCameraParamDef.gViewDir.set(mParamBuffer, mProperties.viewDirection);
- gPerCameraParamDef.gViewOrigin.set(mParamBuffer, mProperties.viewOrigin);
- gPerCameraParamDef.gDeviceZToWorldZ.set(mParamBuffer, getDeviceZToViewZ(mProperties.projTransform));
- gPerCameraParamDef.gNDCZToWorldZ.set(mParamBuffer, getNDCZToViewZ(mProperties.projTransform));
- gPerCameraParamDef.gNDCZToDeviceZ.set(mParamBuffer, getNDCZToDeviceZ());
- Vector2 nearFar(mProperties.nearPlane, mProperties.farPlane);
- gPerCameraParamDef.gNearFar.set(mParamBuffer, nearFar);
- const Rect2I& viewRect = mTargetDesc.viewRect;
- Vector4I viewportRect;
- viewportRect[0] = viewRect.x;
- viewportRect[1] = viewRect.y;
- viewportRect[2] = viewRect.width;
- viewportRect[3] = viewRect.height;
- gPerCameraParamDef.gViewportRectangle.set(mParamBuffer, viewportRect);
- float halfWidth = viewRect.width * 0.5f;
- float halfHeight = viewRect.height * 0.5f;
- float rtWidth = mTargetDesc.targetWidth != 0 ? (float)mTargetDesc.targetWidth : 20.0f;
- float rtHeight = mTargetDesc.targetHeight != 0 ? (float)mTargetDesc.targetHeight : 20.0f;
- Vector4 clipToUVScaleOffset;
- clipToUVScaleOffset.x = halfWidth / rtWidth;
- clipToUVScaleOffset.y = -halfHeight / rtHeight;
- clipToUVScaleOffset.z = viewRect.x / rtWidth + (halfWidth + rapiInfo.getHorizontalTexelOffset()) / rtWidth;
- clipToUVScaleOffset.w = viewRect.y / rtHeight + (halfHeight + rapiInfo.getVerticalTexelOffset()) / rtHeight;
- // Either of these flips the Y axis, but if they're both true they cancel out
- if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp) ^ rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
- clipToUVScaleOffset.y = -clipToUVScaleOffset.y;
- gPerCameraParamDef.gClipToUVScaleOffset.set(mParamBuffer, clipToUVScaleOffset);
- if (mProperties.noLighting)
- gPerCameraParamDef.gAmbientFactor.set(mParamBuffer, 100.0f);
- else
- gPerCameraParamDef.gAmbientFactor.set(mParamBuffer, 0.0f);
- }
- template class SkyboxMat<true>;
- template class SkyboxMat<false>;
- RendererViewGroup::RendererViewGroup(RendererView** views, UINT32 numViews)
- {
- setViews(views, numViews);
- }
- void RendererViewGroup::setViews(RendererView** views, UINT32 numViews)
- {
- mViews.clear();
- for (UINT32 i = 0; i < numViews; i++)
- mViews.push_back(views[i]);
- }
- void RendererViewGroup::determineVisibility(const SceneInfo& sceneInfo)
- {
- UINT32 numViews = (UINT32)mViews.size();
- // Generate render queues per camera
- mVisibility.renderables.resize(sceneInfo.renderables.size(), false);
- mVisibility.renderables.assign(sceneInfo.renderables.size(), false);
- for(UINT32 i = 0; i < numViews; i++)
- mViews[i]->determineVisible(sceneInfo.renderables, sceneInfo.renderableCullInfos, &mVisibility.renderables);
- // Calculate light visibility for all views
- UINT32 numRadialLights = (UINT32)sceneInfo.radialLights.size();
- mVisibility.radialLights.resize(numRadialLights, false);
- mVisibility.radialLights.assign(numRadialLights, false);
- UINT32 numSpotLights = (UINT32)sceneInfo.spotLights.size();
- mVisibility.spotLights.resize(numSpotLights, false);
- mVisibility.spotLights.assign(numSpotLights, false);
- for (UINT32 i = 0; i < numViews; i++)
- {
- mViews[i]->determineVisible(sceneInfo.radialLights, sceneInfo.radialLightWorldBounds, LightType::Radial,
- &mVisibility.radialLights);
- mViews[i]->determineVisible(sceneInfo.spotLights, sceneInfo.spotLightWorldBounds, LightType::Spot,
- &mVisibility.spotLights);
- }
- // Calculate refl. probe visibility for all views
- UINT32 numProbes = (UINT32)sceneInfo.reflProbes.size();
- mVisibility.reflProbes.resize(numProbes, false);
- mVisibility.reflProbes.assign(numProbes, false);
- // Note: Per-view visibility for refl. probes currently isn't calculated
- for (UINT32 i = 0; i < numViews; i++)
- {
- const auto& viewProps = mViews[i]->getProperties();
- // Don't recursively render reflection probes when generating reflection probe maps
- if (viewProps.renderingReflections)
- continue;
- mViews[i]->calculateVisibility(sceneInfo.reflProbeWorldBounds, mVisibility.reflProbes);
- }
- }
- }}
|