refactor(rendering): move old editor viewport passes out of engine

This commit is contained in:
2026-04-15 22:54:38 +08:00
parent dde03c5241
commit cd8ce5947c
12 changed files with 1192 additions and 1313 deletions

View File

@@ -1,499 +0,0 @@
#include "Rendering/Passes/BuiltinInfiniteGridPass.h"
#include <XCEngine/Core/Math/Matrix4.h>
#include <XCEngine/Core/Math/Vector4.h>
#include <XCEngine/Core/Asset/ResourceManager.h>
#include <XCEngine/Debug/Logger.h>
#include <XCEngine/RHI/RHICommandList.h>
#include <XCEngine/RHI/RHIDevice.h>
#include "Rendering/Internal/RenderSurfacePipelineUtils.h"
#include "Rendering/Materials/RenderMaterialStateUtils.h"
#include "Rendering/Internal/ShaderVariantUtils.h"
#include <algorithm>
#include <cmath>
#include <utility>
namespace XCEngine {
namespace Rendering {
namespace Passes {
namespace {
constexpr float kCameraHeightScaleFactor = 0.50f;
constexpr float kTransitionStart = 0.65f;
constexpr float kTransitionEnd = 0.95f;
constexpr float kMinimumVerticalViewComponent = 0.15f;
struct GridConstants {
Math::Matrix4x4 viewProjection = Math::Matrix4x4::Identity();
Math::Vector4 cameraPositionAndScale = Math::Vector4::Zero();
Math::Vector4 cameraRightAndFade = Math::Vector4::Zero();
Math::Vector4 cameraUpAndTanHalfFov = Math::Vector4::Zero();
Math::Vector4 cameraForwardAndAspect = Math::Vector4::Zero();
Math::Vector4 viewportNearFar = Math::Vector4::Zero();
Math::Vector4 gridTransition = Math::Vector4::Zero();
};
const Resources::ShaderPass* FindInfiniteGridCompatiblePass(
const Resources::Shader& shader,
Resources::ShaderBackend backend) {
const Resources::ShaderPass* gridPass = shader.FindPass("InfiniteGrid");
if (gridPass != nullptr &&
::XCEngine::Rendering::Internal::ShaderPassHasGraphicsVariants(shader, gridPass->name, backend)) {
return gridPass;
}
if (shader.GetPassCount() > 0 &&
::XCEngine::Rendering::Internal::ShaderPassHasGraphicsVariants(shader, shader.GetPasses()[0].name, backend)) {
return &shader.GetPasses()[0];
}
return nullptr;
}
RHI::GraphicsPipelineDesc CreatePipelineDesc(
RHI::RHIType backendType,
RHI::RHIPipelineLayout* pipelineLayout,
const Resources::Shader& shader,
const Containers::String& passName,
const RenderSurface& surface) {
RHI::GraphicsPipelineDesc pipelineDesc = {};
pipelineDesc.pipelineLayout = pipelineLayout;
pipelineDesc.topologyType = static_cast<uint32_t>(RHI::PrimitiveTopologyType::Triangle);
::XCEngine::Rendering::Internal::ApplySingleColorAttachmentPropertiesToGraphicsPipelineDesc(
surface,
pipelineDesc);
pipelineDesc.depthStencilFormat =
static_cast<uint32_t>(::XCEngine::Rendering::Internal::ResolveSurfaceDepthFormat(surface));
const Resources::ShaderPass* shaderPass = shader.FindPass(passName);
if (shaderPass != nullptr && shaderPass->hasFixedFunctionState) {
::XCEngine::Rendering::ApplyRenderState(shaderPass->fixedFunctionState, pipelineDesc);
} else {
Resources::MaterialRenderState fallbackState = {};
fallbackState.cullMode = Resources::MaterialCullMode::None;
fallbackState.depthWriteEnable = false;
fallbackState.depthTestEnable = true;
fallbackState.depthFunc = Resources::MaterialComparisonFunc::LessEqual;
fallbackState.blendEnable = true;
fallbackState.srcBlend = Resources::MaterialBlendFactor::SrcAlpha;
fallbackState.dstBlend = Resources::MaterialBlendFactor::InvSrcAlpha;
fallbackState.srcBlendAlpha = Resources::MaterialBlendFactor::One;
fallbackState.dstBlendAlpha = Resources::MaterialBlendFactor::InvSrcAlpha;
fallbackState.blendOp = Resources::MaterialBlendOp::Add;
fallbackState.blendOpAlpha = Resources::MaterialBlendOp::Add;
fallbackState.colorWriteMask = static_cast<uint8_t>(RHI::ColorWriteMask::All);
::XCEngine::Rendering::ApplyRenderState(fallbackState, pipelineDesc);
}
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Internal::ToShaderBackend(backendType);
if (const Resources::ShaderStageVariant* vertexVariant = shader.FindVariant(
passName,
Resources::ShaderType::Vertex,
backend)) {
if (shaderPass != nullptr) {
::XCEngine::Rendering::Internal::ApplyShaderStageVariant(
shader.GetPath(),
*shaderPass,
backend,
*vertexVariant,
pipelineDesc.vertexShader);
}
}
if (const Resources::ShaderStageVariant* fragmentVariant = shader.FindVariant(
passName,
Resources::ShaderType::Fragment,
backend)) {
if (shaderPass != nullptr) {
::XCEngine::Rendering::Internal::ApplyShaderStageVariant(
shader.GetPath(),
*shaderPass,
backend,
*fragmentVariant,
pipelineDesc.fragmentShader);
}
}
return pipelineDesc;
}
float SnapGridSpacing(float targetSpacing) {
const float clampedTarget = (std::max)(targetSpacing, 0.02f);
const float exponent = std::floor(std::log10(clampedTarget));
return std::pow(10.0f, exponent);
}
float ComputeTransitionBlend(float targetSpacing, float baseScale) {
const float normalizedSpacing = (std::max)(targetSpacing / (std::max)(baseScale, 1e-4f), 1.0f);
const float transitionPosition = std::log10(normalizedSpacing);
const float t =
(transitionPosition - kTransitionStart) /
(kTransitionEnd - kTransitionStart);
const float saturated = (std::clamp)(t, 0.0f, 1.0f);
return saturated * saturated * (3.0f - 2.0f * saturated);
}
float ComputeViewDistanceToGridPlane(const InfiniteGridPassData& data) {
const float cameraHeight = std::abs(data.cameraPosition.y);
const Math::Vector3 forward = data.cameraForward.Normalized();
const bool lookingTowardGrid =
(data.cameraPosition.y >= 0.0f && forward.y < 0.0f) ||
(data.cameraPosition.y < 0.0f && forward.y > 0.0f);
if (!lookingTowardGrid) {
return cameraHeight;
}
const float verticalViewComponent = (std::max)(std::abs(forward.y), kMinimumVerticalViewComponent);
return cameraHeight / verticalViewComponent;
}
Math::Matrix4x4 BuildInfiniteGridViewMatrix(const InfiniteGridPassData& data) {
const Math::Vector3 right = data.cameraRight.Normalized();
const Math::Vector3 up = data.cameraUp.Normalized();
const Math::Vector3 forward = data.cameraForward.Normalized();
Math::Matrix4x4 view = Math::Matrix4x4::Identity();
view.m[0][0] = right.x;
view.m[0][1] = right.y;
view.m[0][2] = right.z;
view.m[0][3] = -Math::Vector3::Dot(right, data.cameraPosition);
view.m[1][0] = up.x;
view.m[1][1] = up.y;
view.m[1][2] = up.z;
view.m[1][3] = -Math::Vector3::Dot(up, data.cameraPosition);
view.m[2][0] = forward.x;
view.m[2][1] = forward.y;
view.m[2][2] = forward.z;
view.m[2][3] = -Math::Vector3::Dot(forward, data.cameraPosition);
return view;
}
Math::Matrix4x4 BuildInfiniteGridProjectionMatrix(
const InfiniteGridPassData& data,
float viewportWidth,
float viewportHeight) {
const float aspect = viewportHeight > 0.0f
? viewportWidth / viewportHeight
: 1.0f;
return Math::Matrix4x4::Perspective(
data.verticalFovDegrees * Math::DEG_TO_RAD,
aspect,
data.nearClipPlane,
data.farClipPlane);
}
} // namespace
InfiniteGridParameters BuildInfiniteGridParameters(const InfiniteGridPassData& data) {
InfiniteGridParameters parameters = {};
if (!data.valid) {
return parameters;
}
const float cameraHeight = std::abs(data.cameraPosition.y);
const float viewDistance = ComputeViewDistanceToGridPlane(data);
const float targetSpacing = (std::max)(cameraHeight * kCameraHeightScaleFactor, 0.1f);
parameters.valid = true;
parameters.baseScale = SnapGridSpacing(targetSpacing);
parameters.transitionBlend = ComputeTransitionBlend(targetSpacing, parameters.baseScale);
parameters.fadeDistance = (std::max)(
parameters.baseScale * 320.0f,
viewDistance * 80.0f);
return parameters;
}
BuiltinInfiniteGridPass::BuiltinInfiniteGridPass(Containers::String shaderPath)
: m_shaderPath(std::move(shaderPath)) {
}
void BuiltinInfiniteGridPass::SetShaderPath(const Containers::String& shaderPath) {
if (m_shaderPath == shaderPath) {
return;
}
DestroyResources();
m_shaderPath = shaderPath;
}
const Containers::String& BuiltinInfiniteGridPass::GetShaderPath() const {
return m_shaderPath;
}
void BuiltinInfiniteGridPass::Shutdown() {
DestroyResources();
}
bool BuiltinInfiniteGridPass::Render(
const RenderContext& renderContext,
const RenderSurface& surface,
const InfiniteGridPassData& data) {
if (!data.valid || !renderContext.IsValid()) {
return false;
}
const std::vector<RHI::RHIResourceView*>& colorAttachments = surface.GetColorAttachments();
if (!::XCEngine::Rendering::Internal::HasSingleColorAttachment(surface) ||
colorAttachments.empty() ||
colorAttachments[0] == nullptr ||
surface.GetDepthAttachment() == nullptr) {
return false;
}
const Math::RectInt renderArea = surface.GetRenderArea();
if (renderArea.width <= 0 || renderArea.height <= 0) {
return false;
}
if (!EnsureInitialized(renderContext, surface)) {
return false;
}
const InfiniteGridParameters parameters = BuildInfiniteGridParameters(data);
if (!parameters.valid) {
return false;
}
const Math::Matrix4x4 viewProjection =
BuildInfiniteGridProjectionMatrix(
data,
static_cast<float>(renderArea.width),
static_cast<float>(renderArea.height)) *
BuildInfiniteGridViewMatrix(data);
const float aspect = renderArea.height > 0
? static_cast<float>(renderArea.width) / static_cast<float>(renderArea.height)
: 1.0f;
GridConstants constants = {};
constants.viewProjection = viewProjection.Transpose();
constants.cameraPositionAndScale = Math::Vector4(data.cameraPosition, parameters.baseScale);
constants.cameraRightAndFade = Math::Vector4(data.cameraRight, parameters.fadeDistance);
constants.cameraUpAndTanHalfFov = Math::Vector4(
data.cameraUp,
std::tan(data.verticalFovDegrees * Math::DEG_TO_RAD * 0.5f));
constants.cameraForwardAndAspect = Math::Vector4(data.cameraForward, aspect);
constants.viewportNearFar = Math::Vector4(
static_cast<float>(surface.GetWidth()),
static_cast<float>(surface.GetHeight()),
data.nearClipPlane,
data.farClipPlane);
constants.gridTransition = Math::Vector4(parameters.transitionBlend, 0.0f, 0.0f, 0.0f);
m_constantSet->WriteConstant(0, &constants, sizeof(constants));
RHI::RHICommandList* commandList = renderContext.commandList;
RHI::RHIResourceView* renderTarget = colorAttachments[0];
RHI::RHIResourceView* depthAttachment = surface.GetDepthAttachment();
if (surface.IsAutoTransitionEnabled()) {
commandList->TransitionBarrier(
renderTarget,
surface.GetColorStateAfter(),
RHI::ResourceStates::RenderTarget);
commandList->TransitionBarrier(
depthAttachment,
surface.GetDepthStateAfter(),
RHI::ResourceStates::DepthWrite);
}
commandList->SetRenderTargets(1, &renderTarget, depthAttachment);
const RHI::Viewport viewport = {
static_cast<float>(renderArea.x),
static_cast<float>(renderArea.y),
static_cast<float>(renderArea.width),
static_cast<float>(renderArea.height),
0.0f,
1.0f
};
const RHI::Rect scissorRect = {
renderArea.x,
renderArea.y,
renderArea.x + renderArea.width,
renderArea.y + renderArea.height
};
commandList->SetViewport(viewport);
commandList->SetScissorRect(scissorRect);
commandList->SetPrimitiveTopology(RHI::PrimitiveTopology::TriangleList);
commandList->SetPipelineState(m_pipelineState);
RHI::RHIDescriptorSet* descriptorSets[] = { m_constantSet };
commandList->SetGraphicsDescriptorSets(0, 1, descriptorSets, m_pipelineLayout);
commandList->Draw(3, 1, 0, 0);
commandList->EndRenderPass();
if (surface.IsAutoTransitionEnabled()) {
commandList->TransitionBarrier(
renderTarget,
RHI::ResourceStates::RenderTarget,
surface.GetColorStateAfter());
commandList->TransitionBarrier(
depthAttachment,
RHI::ResourceStates::DepthWrite,
surface.GetDepthStateAfter());
}
return true;
}
bool BuiltinInfiniteGridPass::EnsureInitialized(const RenderContext& renderContext, const RenderSurface& surface) {
const RHI::Format renderTargetFormat =
::XCEngine::Rendering::Internal::ResolveSurfaceColorFormat(surface, 0u);
const RHI::Format depthFormat =
::XCEngine::Rendering::Internal::ResolveSurfaceDepthFormat(surface);
const uint32_t renderTargetSampleCount =
::XCEngine::Rendering::Internal::ResolveSurfaceSampleCount(surface);
if (m_pipelineState != nullptr &&
m_pipelineLayout != nullptr &&
m_constantPool != nullptr &&
m_constantSet != nullptr &&
m_device == renderContext.device &&
m_backendType == renderContext.backendType &&
m_renderTargetFormat == renderTargetFormat &&
m_depthStencilFormat == depthFormat &&
m_renderTargetSampleCount == renderTargetSampleCount) {
return true;
}
DestroyResources();
return CreateResources(renderContext, surface);
}
bool BuiltinInfiniteGridPass::CreateResources(const RenderContext& renderContext, const RenderSurface& surface) {
if (!renderContext.IsValid()) {
return false;
}
if (!::XCEngine::Rendering::Internal::HasSingleColorAttachment(surface) ||
::XCEngine::Rendering::Internal::ResolveSurfaceColorFormat(surface, 0u) == RHI::Format::Unknown ||
::XCEngine::Rendering::Internal::ResolveSurfaceDepthFormat(surface) == RHI::Format::Unknown) {
return false;
}
if (m_shaderPath.Empty()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinInfiniteGridPass requires an injected shader path before resource creation");
return false;
}
m_device = renderContext.device;
m_backendType = renderContext.backendType;
m_builtinInfiniteGridShader = Resources::ResourceManager::Get().Load<Resources::Shader>(
m_shaderPath);
if (!m_builtinInfiniteGridShader.IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinInfiniteGridPass failed to load configured infinite-grid shader resource");
DestroyResources();
return false;
}
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Internal::ToShaderBackend(m_backendType);
const Resources::ShaderPass* infiniteGridPass =
FindInfiniteGridCompatiblePass(*m_builtinInfiniteGridShader.Get(), backend);
if (infiniteGridPass == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinInfiniteGridPass could not resolve a valid InfiniteGrid shader pass");
DestroyResources();
return false;
}
RHI::DescriptorSetLayoutBinding constantBinding = {};
constantBinding.binding = 0;
constantBinding.type = static_cast<uint32_t>(RHI::DescriptorType::CBV);
constantBinding.count = 1;
RHI::DescriptorSetLayoutDesc constantLayout = {};
constantLayout.bindings = &constantBinding;
constantLayout.bindingCount = 1;
RHI::RHIPipelineLayoutDesc pipelineLayoutDesc = {};
pipelineLayoutDesc.setLayouts = &constantLayout;
pipelineLayoutDesc.setLayoutCount = 1;
m_pipelineLayout = m_device->CreatePipelineLayout(pipelineLayoutDesc);
if (m_pipelineLayout == nullptr) {
DestroyResources();
return false;
}
RHI::DescriptorPoolDesc constantPoolDesc = {};
constantPoolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV;
constantPoolDesc.descriptorCount = 1;
constantPoolDesc.shaderVisible = false;
m_constantPool = m_device->CreateDescriptorPool(constantPoolDesc);
if (m_constantPool == nullptr) {
DestroyResources();
return false;
}
m_constantSet = m_constantPool->AllocateSet(constantLayout);
if (m_constantSet == nullptr) {
DestroyResources();
return false;
}
RHI::GraphicsPipelineDesc pipelineDesc = {};
pipelineDesc = CreatePipelineDesc(
m_backendType,
m_pipelineLayout,
*m_builtinInfiniteGridShader.Get(),
infiniteGridPass->name,
surface);
m_pipelineState = m_device->CreatePipelineState(pipelineDesc);
if (m_pipelineState == nullptr || !m_pipelineState->IsValid()) {
DestroyResources();
return false;
}
m_renderTargetFormat = ::XCEngine::Rendering::Internal::ResolveSurfaceColorFormat(surface, 0u);
m_depthStencilFormat = ::XCEngine::Rendering::Internal::ResolveSurfaceDepthFormat(surface);
m_renderTargetSampleCount = ::XCEngine::Rendering::Internal::ResolveSurfaceSampleCount(surface);
return true;
}
void BuiltinInfiniteGridPass::DestroyResources() {
if (m_pipelineState != nullptr) {
m_pipelineState->Shutdown();
delete m_pipelineState;
m_pipelineState = nullptr;
}
if (m_constantSet != nullptr) {
m_constantSet->Shutdown();
delete m_constantSet;
m_constantSet = nullptr;
}
if (m_constantPool != nullptr) {
m_constantPool->Shutdown();
delete m_constantPool;
m_constantPool = nullptr;
}
if (m_pipelineLayout != nullptr) {
m_pipelineLayout->Shutdown();
delete m_pipelineLayout;
m_pipelineLayout = nullptr;
}
m_device = nullptr;
m_backendType = RHI::RHIType::D3D12;
m_builtinInfiniteGridShader.Reset();
m_renderTargetFormat = RHI::Format::Unknown;
m_depthStencilFormat = RHI::Format::Unknown;
m_renderTargetSampleCount = 1u;
}
} // namespace Passes
} // namespace Rendering
} // namespace XCEngine

View File

@@ -1,73 +0,0 @@
#include "Rendering/Passes/BuiltinSelectionMaskPass.h"
#include "Components/GameObject.h"
#include "Resources/BuiltinResources.h"
#include <XCEngine/Rendering/FrameData/RenderSceneData.h>
#include <XCEngine/Rendering/FrameData/VisibleRenderItem.h>
#include <algorithm>
namespace XCEngine {
namespace Rendering {
namespace Passes {
BuiltinSelectionMaskPass::BuiltinSelectionMaskPass()
: BuiltinDepthStylePassBase(
BuiltinMaterialPass::SelectionMask,
Resources::GetBuiltinSelectionMaskShaderPath()) {
}
RHI::InputLayoutDesc BuiltinSelectionMaskPass::BuildInputLayout() {
return BuildCommonInputLayout();
}
const char* BuiltinSelectionMaskPass::GetName() const {
return "BuiltinSelectionMaskPass";
}
bool BuiltinSelectionMaskPass::Render(
const RenderContext& context,
const RenderSurface& surface,
const RenderSceneData& sceneData,
const std::vector<uint64_t>& selectedObjectIds) {
m_selectedObjectIds.clear();
m_selectedObjectIds.reserve(selectedObjectIds.size());
for (uint64_t selectedObjectId : selectedObjectIds) {
RenderObjectId renderObjectId = kInvalidRenderObjectId;
if (TryConvertRuntimeObjectIdToRenderObjectId(selectedObjectId, renderObjectId)) {
m_selectedObjectIds.push_back(renderObjectId);
}
}
if (m_selectedObjectIds.empty()) {
return false;
}
RenderSceneData selectionMaskSceneData = sceneData;
selectionMaskSceneData.cameraData.clearFlags = RenderClearFlags::Color;
selectionMaskSceneData.cameraData.clearColor = Math::Color::Black();
const RenderPassContext passContext = {
context,
surface,
selectionMaskSceneData,
nullptr,
nullptr,
RHI::ResourceStates::Common
};
return Execute(passContext);
}
bool BuiltinSelectionMaskPass::ShouldRenderVisibleItem(const VisibleRenderItem& visibleItem) const {
if (!IsValidRenderObjectId(visibleItem.renderObjectId)) {
return false;
}
return std::find(m_selectedObjectIds.begin(), m_selectedObjectIds.end(), visibleItem.renderObjectId) !=
m_selectedObjectIds.end();
}
} // namespace Passes
} // namespace Rendering
} // namespace XCEngine

View File

@@ -1,465 +0,0 @@
#include "Rendering/Passes/BuiltinSelectionOutlinePass.h"
#include "Core/Asset/ResourceManager.h"
#include "Debug/Logger.h"
#include "Rendering/Internal/RenderSurfacePipelineUtils.h"
#include "Rendering/Internal/ShaderVariantUtils.h"
#include "Rendering/Materials/RenderMaterialStateUtils.h"
#include "RHI/RHICommandList.h"
#include "RHI/RHIDevice.h"
#include <XCEngine/Resources/BuiltinResources.h>
#include <utility>
namespace XCEngine {
namespace Rendering {
namespace Passes {
namespace {
const Resources::ShaderPass* FindSelectionOutlineCompatiblePass(
const Resources::Shader& shader,
Resources::ShaderBackend backend) {
const Resources::ShaderPass* outlinePass = shader.FindPass("SelectionOutline");
if (outlinePass != nullptr &&
::XCEngine::Rendering::Internal::ShaderPassHasGraphicsVariants(shader, outlinePass->name, backend)) {
return outlinePass;
}
const Resources::ShaderPass* editorOutlinePass = shader.FindPass("EditorSelectionOutline");
if (editorOutlinePass != nullptr &&
::XCEngine::Rendering::Internal::ShaderPassHasGraphicsVariants(
shader,
editorOutlinePass->name,
backend)) {
return editorOutlinePass;
}
if (shader.GetPassCount() > 0 &&
::XCEngine::Rendering::Internal::ShaderPassHasGraphicsVariants(
shader,
shader.GetPasses()[0].name,
backend)) {
return &shader.GetPasses()[0];
}
return nullptr;
}
RHI::GraphicsPipelineDesc CreatePipelineDesc(
RHI::RHIType backendType,
RHI::RHIPipelineLayout* pipelineLayout,
const Resources::Shader& shader,
const Containers::String& passName,
const RenderSurface& surface) {
RHI::GraphicsPipelineDesc pipelineDesc = {};
pipelineDesc.pipelineLayout = pipelineLayout;
pipelineDesc.topologyType = static_cast<uint32_t>(RHI::PrimitiveTopologyType::Triangle);
::XCEngine::Rendering::Internal::ApplySingleColorAttachmentPropertiesToGraphicsPipelineDesc(
surface,
pipelineDesc);
pipelineDesc.depthStencilFormat = static_cast<uint32_t>(RHI::Format::Unknown);
const Resources::ShaderPass* shaderPass = shader.FindPass(passName);
if (shaderPass != nullptr && shaderPass->hasFixedFunctionState) {
::XCEngine::Rendering::ApplyRenderState(shaderPass->fixedFunctionState, pipelineDesc);
} else {
Resources::MaterialRenderState fallbackState = {};
fallbackState.cullMode = Resources::MaterialCullMode::None;
fallbackState.depthWriteEnable = false;
fallbackState.depthTestEnable = false;
fallbackState.depthFunc = Resources::MaterialComparisonFunc::Always;
fallbackState.blendEnable = true;
fallbackState.srcBlend = Resources::MaterialBlendFactor::SrcAlpha;
fallbackState.dstBlend = Resources::MaterialBlendFactor::InvSrcAlpha;
fallbackState.srcBlendAlpha = Resources::MaterialBlendFactor::One;
fallbackState.dstBlendAlpha = Resources::MaterialBlendFactor::InvSrcAlpha;
fallbackState.blendOp = Resources::MaterialBlendOp::Add;
fallbackState.blendOpAlpha = Resources::MaterialBlendOp::Add;
fallbackState.colorWriteMask = static_cast<uint8_t>(RHI::ColorWriteMask::All);
::XCEngine::Rendering::ApplyRenderState(fallbackState, pipelineDesc);
}
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Internal::ToShaderBackend(backendType);
if (const Resources::ShaderStageVariant* vertexVariant =
shader.FindVariant(passName, Resources::ShaderType::Vertex, backend)) {
if (shaderPass != nullptr) {
::XCEngine::Rendering::Internal::ApplyShaderStageVariant(
shader.GetPath(),
*shaderPass,
backend,
*vertexVariant,
pipelineDesc.vertexShader);
}
}
if (const Resources::ShaderStageVariant* fragmentVariant =
shader.FindVariant(passName, Resources::ShaderType::Fragment, backend)) {
if (shaderPass != nullptr) {
::XCEngine::Rendering::Internal::ApplyShaderStageVariant(
shader.GetPath(),
*shaderPass,
backend,
*fragmentVariant,
pipelineDesc.fragmentShader);
}
}
return pipelineDesc;
}
} // namespace
BuiltinSelectionOutlinePass::BuiltinSelectionOutlinePass(Containers::String shaderPath)
: m_shaderPath(shaderPath.Empty() ? Resources::GetBuiltinSelectionOutlineShaderPath() : std::move(shaderPath)) {
ResetState();
}
void BuiltinSelectionOutlinePass::SetShaderPath(const Containers::String& shaderPath) {
if (m_shaderPath == shaderPath) {
return;
}
DestroyResources();
m_shaderPath = shaderPath;
}
const Containers::String& BuiltinSelectionOutlinePass::GetShaderPath() const {
return m_shaderPath;
}
void BuiltinSelectionOutlinePass::Shutdown() {
DestroyResources();
}
bool BuiltinSelectionOutlinePass::Render(
const RenderContext& renderContext,
const RenderSurface& surface,
const SelectionOutlinePassInputs& inputs,
const SelectionOutlineStyle& style) {
if (!renderContext.IsValid() ||
inputs.selectionMaskTextureView == nullptr ||
inputs.depthTextureView == nullptr) {
return false;
}
const std::vector<RHI::RHIResourceView*>& colorAttachments = surface.GetColorAttachments();
if (!::XCEngine::Rendering::Internal::HasSingleColorAttachment(surface) ||
colorAttachments.empty() ||
colorAttachments[0] == nullptr) {
return false;
}
const Math::RectInt renderArea = surface.GetRenderArea();
if (renderArea.width <= 0 || renderArea.height <= 0) {
return false;
}
if (!EnsureInitialized(renderContext, surface)) {
return false;
}
OutlineConstants constants = {};
constants.viewportSizeAndTexelSize = Math::Vector4(
static_cast<float>(surface.GetWidth()),
static_cast<float>(surface.GetHeight()),
surface.GetWidth() > 0 ? 1.0f / static_cast<float>(surface.GetWidth()) : 0.0f,
surface.GetHeight() > 0 ? 1.0f / static_cast<float>(surface.GetHeight()) : 0.0f);
constants.outlineColor = Math::Vector4(
style.outlineColor.r,
style.outlineColor.g,
style.outlineColor.b,
style.outlineColor.a);
constants.outlineInfo = Math::Vector4(
style.debugSelectionMask ? 1.0f : 0.0f,
style.outlineWidthPixels,
0.0f,
0.0f);
constants.depthParams = Math::Vector4(1.0e-5f, 0.0f, 0.0f, 0.0f);
m_constantSet->WriteConstant(0, &constants, sizeof(constants));
m_textureSet->Update(0, inputs.selectionMaskTextureView);
m_textureSet->Update(1, inputs.depthTextureView);
RHI::RHICommandList* commandList = renderContext.commandList;
RHI::RHIResourceView* renderTarget = colorAttachments[0];
if (surface.IsAutoTransitionEnabled()) {
commandList->TransitionBarrier(
renderTarget,
surface.GetColorStateAfter(),
RHI::ResourceStates::RenderTarget);
commandList->TransitionBarrier(
inputs.selectionMaskTextureView,
inputs.selectionMaskState,
RHI::ResourceStates::PixelShaderResource);
commandList->TransitionBarrier(
inputs.depthTextureView,
inputs.depthTextureState,
RHI::ResourceStates::PixelShaderResource);
}
commandList->SetRenderTargets(1, &renderTarget, nullptr);
const RHI::Viewport viewport = {
static_cast<float>(renderArea.x),
static_cast<float>(renderArea.y),
static_cast<float>(renderArea.width),
static_cast<float>(renderArea.height),
0.0f,
1.0f
};
const RHI::Rect scissorRect = {
renderArea.x,
renderArea.y,
renderArea.x + renderArea.width,
renderArea.y + renderArea.height
};
commandList->SetViewport(viewport);
commandList->SetScissorRect(scissorRect);
commandList->SetPrimitiveTopology(RHI::PrimitiveTopology::TriangleList);
commandList->SetPipelineState(m_pipelineState);
RHI::RHIDescriptorSet* descriptorSets[] = { m_constantSet, m_textureSet };
commandList->SetGraphicsDescriptorSets(0, 2, descriptorSets, m_pipelineLayout);
commandList->Draw(3, 1, 0, 0);
commandList->EndRenderPass();
if (surface.IsAutoTransitionEnabled()) {
commandList->TransitionBarrier(
renderTarget,
RHI::ResourceStates::RenderTarget,
surface.GetColorStateAfter());
commandList->TransitionBarrier(
inputs.selectionMaskTextureView,
RHI::ResourceStates::PixelShaderResource,
inputs.selectionMaskState);
commandList->TransitionBarrier(
inputs.depthTextureView,
RHI::ResourceStates::PixelShaderResource,
inputs.depthTextureState);
}
return true;
}
bool BuiltinSelectionOutlinePass::EnsureInitialized(const RenderContext& renderContext, const RenderSurface& surface) {
const RHI::Format renderTargetFormat =
::XCEngine::Rendering::Internal::ResolveSurfaceColorFormat(surface, 0u);
const uint32_t renderTargetSampleCount =
::XCEngine::Rendering::Internal::ResolveSurfaceSampleCount(surface);
if (m_pipelineLayout != nullptr &&
m_pipelineState != nullptr &&
m_constantPool != nullptr &&
m_constantSet != nullptr &&
m_texturePool != nullptr &&
m_textureSet != nullptr &&
m_device == renderContext.device &&
m_backendType == renderContext.backendType &&
m_renderTargetFormat == renderTargetFormat &&
m_renderTargetSampleCount == renderTargetSampleCount) {
return true;
}
if (HasCreatedResources()) {
DestroyResources();
}
return CreateResources(renderContext, surface);
}
bool BuiltinSelectionOutlinePass::CreateResources(const RenderContext& renderContext, const RenderSurface& surface) {
if (!renderContext.IsValid()) {
return false;
}
if (!::XCEngine::Rendering::Internal::HasSingleColorAttachment(surface) ||
::XCEngine::Rendering::Internal::ResolveSurfaceColorFormat(surface, 0u) == RHI::Format::Unknown) {
return false;
}
if (m_shaderPath.Empty()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinSelectionOutlinePass requires an injected shader path before resource creation");
return false;
}
Resources::ResourceHandle<Resources::Shader> shader = Resources::ResourceManager::Get().Load<Resources::Shader>(
m_shaderPath);
if (!shader.IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinSelectionOutlinePass failed to load configured selection-outline shader resource");
ResetState();
return false;
}
m_device = renderContext.device;
m_backendType = renderContext.backendType;
m_builtinSelectionOutlineShader.emplace(std::move(shader));
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Internal::ToShaderBackend(m_backendType);
const Resources::ShaderPass* outlinePass =
FindSelectionOutlineCompatiblePass(*m_builtinSelectionOutlineShader->Get(), backend);
if (outlinePass == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinSelectionOutlinePass could not resolve a valid SelectionOutline shader pass");
DestroyResources();
return false;
}
RHI::DescriptorSetLayoutBinding constantBinding = {};
constantBinding.binding = 0;
constantBinding.type = static_cast<uint32_t>(RHI::DescriptorType::CBV);
constantBinding.count = 1;
RHI::DescriptorSetLayoutBinding textureBindings[2] = {};
textureBindings[0].binding = 0;
textureBindings[0].type = static_cast<uint32_t>(RHI::DescriptorType::SRV);
textureBindings[0].count = 1;
textureBindings[1].binding = 1;
textureBindings[1].type = static_cast<uint32_t>(RHI::DescriptorType::SRV);
textureBindings[1].count = 1;
RHI::DescriptorSetLayoutDesc constantLayout = {};
constantLayout.bindings = &constantBinding;
constantLayout.bindingCount = 1;
RHI::DescriptorSetLayoutDesc textureLayout = {};
textureLayout.bindings = textureBindings;
textureLayout.bindingCount = 2;
RHI::DescriptorSetLayoutDesc setLayouts[2] = {};
setLayouts[0] = constantLayout;
setLayouts[1] = textureLayout;
RHI::RHIPipelineLayoutDesc pipelineLayoutDesc = {};
pipelineLayoutDesc.setLayouts = setLayouts;
pipelineLayoutDesc.setLayoutCount = 2;
m_pipelineLayout = m_device->CreatePipelineLayout(pipelineLayoutDesc);
if (m_pipelineLayout == nullptr) {
DestroyResources();
return false;
}
RHI::DescriptorPoolDesc constantPoolDesc = {};
constantPoolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV;
constantPoolDesc.descriptorCount = 1;
constantPoolDesc.shaderVisible = false;
m_constantPool = m_device->CreateDescriptorPool(constantPoolDesc);
if (m_constantPool == nullptr) {
DestroyResources();
return false;
}
m_constantSet = m_constantPool->AllocateSet(constantLayout);
if (m_constantSet == nullptr) {
DestroyResources();
return false;
}
RHI::DescriptorPoolDesc texturePoolDesc = {};
texturePoolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV;
texturePoolDesc.descriptorCount = 2;
texturePoolDesc.shaderVisible = true;
m_texturePool = m_device->CreateDescriptorPool(texturePoolDesc);
if (m_texturePool == nullptr) {
DestroyResources();
return false;
}
m_textureSet = m_texturePool->AllocateSet(textureLayout);
if (m_textureSet == nullptr) {
DestroyResources();
return false;
}
m_pipelineState = m_device->CreatePipelineState(
CreatePipelineDesc(
m_backendType,
m_pipelineLayout,
*m_builtinSelectionOutlineShader->Get(),
outlinePass->name,
surface));
if (m_pipelineState == nullptr || !m_pipelineState->IsValid()) {
DestroyResources();
return false;
}
m_renderTargetFormat = ::XCEngine::Rendering::Internal::ResolveSurfaceColorFormat(surface, 0u);
m_renderTargetSampleCount = ::XCEngine::Rendering::Internal::ResolveSurfaceSampleCount(surface);
return true;
}
bool BuiltinSelectionOutlinePass::HasCreatedResources() const {
return m_device != nullptr ||
m_pipelineLayout != nullptr ||
m_pipelineState != nullptr ||
m_constantPool != nullptr ||
m_constantSet != nullptr ||
m_texturePool != nullptr ||
m_textureSet != nullptr ||
m_builtinSelectionOutlineShader.has_value();
}
void BuiltinSelectionOutlinePass::DestroyResources() {
if (m_pipelineState != nullptr) {
m_pipelineState->Shutdown();
delete m_pipelineState;
m_pipelineState = nullptr;
}
if (m_textureSet != nullptr) {
m_textureSet->Shutdown();
delete m_textureSet;
m_textureSet = nullptr;
}
if (m_texturePool != nullptr) {
m_texturePool->Shutdown();
delete m_texturePool;
m_texturePool = nullptr;
}
if (m_constantSet != nullptr) {
m_constantSet->Shutdown();
delete m_constantSet;
m_constantSet = nullptr;
}
if (m_constantPool != nullptr) {
m_constantPool->Shutdown();
delete m_constantPool;
m_constantPool = nullptr;
}
if (m_pipelineLayout != nullptr) {
m_pipelineLayout->Shutdown();
delete m_pipelineLayout;
m_pipelineLayout = nullptr;
}
if (m_builtinSelectionOutlineShader.has_value()) {
m_builtinSelectionOutlineShader.reset();
}
ResetState();
}
void BuiltinSelectionOutlinePass::ResetState() {
m_device = nullptr;
m_backendType = RHI::RHIType::D3D12;
m_pipelineLayout = nullptr;
m_pipelineState = nullptr;
m_constantPool = nullptr;
m_constantSet = nullptr;
m_texturePool = nullptr;
m_textureSet = nullptr;
m_builtinSelectionOutlineShader.reset();
m_renderTargetFormat = RHI::Format::Unknown;
m_renderTargetSampleCount = 1u;
}
} // namespace Passes
} // namespace Rendering
} // namespace XCEngine