#include "Rendering/Pipelines/BuiltinForwardPipeline.h" #include "Components/GameObject.h" #include "Components/MeshFilterComponent.h" #include "Components/MeshRendererComponent.h" #include "Debug/Logger.h" #include "Core/Asset/ResourceManager.h" #include "RHI/RHICommandList.h" #include "Rendering/RenderMaterialUtility.h" #include "Rendering/RenderSurface.h" #include "Resources/BuiltinResources.h" #include "Resources/Material/Material.h" #include "Resources/Shader/Shader.h" #include "Resources/Texture/Texture.h" #include namespace XCEngine { namespace Rendering { namespace Pipelines { namespace Detail { class BuiltinForwardOpaquePass final : public RenderPass { public: explicit BuiltinForwardOpaquePass(BuiltinForwardPipeline& pipeline) : m_pipeline(pipeline) { } const char* GetName() const override { return "BuiltinForwardOpaquePass"; } bool Initialize(const RenderContext& context) override { return m_pipeline.EnsureInitialized(context); } void Shutdown() override { m_pipeline.DestroyPipelineResources(); } bool Execute(const RenderPassContext& context) override { return m_pipeline.ExecuteForwardOpaquePass(context); } private: BuiltinForwardPipeline& m_pipeline; }; } // namespace Detail namespace { constexpr uint32_t kDescriptorFirstSet = 1; constexpr uint32_t kDescriptorSetCount = 5; Resources::ShaderBackend ToShaderBackend(RHI::RHIType backendType) { switch (backendType) { case RHI::RHIType::D3D12: return Resources::ShaderBackend::D3D12; case RHI::RHIType::Vulkan: return Resources::ShaderBackend::Vulkan; case RHI::RHIType::OpenGL: default: return Resources::ShaderBackend::OpenGL; } } RHI::ShaderLanguage ToRHIShaderLanguage(Resources::ShaderLanguage language) { switch (language) { case Resources::ShaderLanguage::HLSL: return RHI::ShaderLanguage::HLSL; case Resources::ShaderLanguage::SPIRV: return RHI::ShaderLanguage::SPIRV; case Resources::ShaderLanguage::GLSL: default: return RHI::ShaderLanguage::GLSL; } } std::wstring ToWideAscii(const Containers::String& value) { std::wstring wide; wide.reserve(value.Length()); for (size_t index = 0; index < value.Length(); ++index) { wide.push_back(static_cast(value[index])); } return wide; } bool ShaderPassHasGraphicsVariants( const Resources::Shader& shader, const Containers::String& passName, Resources::ShaderBackend backend) { return shader.FindVariant(passName, Resources::ShaderType::Vertex, backend) != nullptr && shader.FindVariant(passName, Resources::ShaderType::Fragment, backend) != nullptr; } const Resources::ShaderPass* FindForwardCompatiblePass( const Resources::Shader& shader, const Resources::Material* material, Resources::ShaderBackend backend) { if (material != nullptr && !material->GetShaderPass().Empty()) { const Resources::ShaderPass* explicitPass = shader.FindPass(material->GetShaderPass()); if (explicitPass != nullptr && ShaderPassHasGraphicsVariants(shader, explicitPass->name, backend)) { return explicitPass; } } for (const Resources::ShaderPass& shaderPass : shader.GetPasses()) { if (ShaderPassMatchesBuiltinPass(shaderPass, BuiltinMaterialPass::ForwardLit) && ShaderPassHasGraphicsVariants(shader, shaderPass.name, backend)) { return &shaderPass; } } const Resources::ShaderPass* defaultPass = shader.FindPass("ForwardLit"); if (defaultPass != nullptr && ShaderPassHasGraphicsVariants(shader, defaultPass->name, backend)) { return defaultPass; } defaultPass = shader.FindPass("Default"); if (defaultPass != nullptr && ShaderPassHasGraphicsVariants(shader, defaultPass->name, backend)) { return defaultPass; } if (shader.GetPassCount() > 0 && ShaderPassHasGraphicsVariants(shader, shader.GetPasses()[0].name, backend)) { return &shader.GetPasses()[0]; } return nullptr; } void ApplyShaderStageVariant( const Resources::ShaderStageVariant& variant, RHI::ShaderCompileDesc& compileDesc) { compileDesc.source.assign( variant.sourceCode.CStr(), variant.sourceCode.CStr() + variant.sourceCode.Length()); compileDesc.sourceLanguage = ToRHIShaderLanguage(variant.language); compileDesc.entryPoint = ToWideAscii(variant.entryPoint); compileDesc.profile = ToWideAscii(variant.profile); } RHI::GraphicsPipelineDesc CreatePipelineDesc( RHI::RHIType backendType, RHI::RHIPipelineLayout* pipelineLayout, const Resources::Shader& shader, const Containers::String& passName, const Resources::Material* material) { RHI::GraphicsPipelineDesc pipelineDesc = {}; pipelineDesc.pipelineLayout = pipelineLayout; pipelineDesc.topologyType = static_cast(RHI::PrimitiveTopologyType::Triangle); pipelineDesc.renderTargetCount = 1; pipelineDesc.renderTargetFormats[0] = static_cast(RHI::Format::R8G8B8A8_UNorm); pipelineDesc.depthStencilFormat = static_cast(RHI::Format::D24_UNorm_S8_UInt); pipelineDesc.sampleCount = 1; ApplyMaterialRenderState(material, pipelineDesc); pipelineDesc.inputLayout = BuiltinForwardPipeline::BuildInputLayout(); const Resources::ShaderBackend backend = ToShaderBackend(backendType); const Resources::ShaderStageVariant* vertexVariant = shader.FindVariant(passName, Resources::ShaderType::Vertex, backend); const Resources::ShaderStageVariant* fragmentVariant = shader.FindVariant(passName, Resources::ShaderType::Fragment, backend); if (vertexVariant != nullptr) { ApplyShaderStageVariant(*vertexVariant, pipelineDesc.vertexShader); } if (fragmentVariant != nullptr) { ApplyShaderStageVariant(*fragmentVariant, pipelineDesc.fragmentShader); } return pipelineDesc; } } // namespace BuiltinForwardPipeline::BuiltinForwardPipeline() { m_passSequence.AddPass(std::make_unique(*this)); } BuiltinForwardPipeline::~BuiltinForwardPipeline() { Shutdown(); } std::unique_ptr BuiltinForwardPipelineAsset::CreatePipeline() const { return std::make_unique(); } RHI::InputLayoutDesc BuiltinForwardPipeline::BuildInputLayout() { RHI::InputLayoutDesc inputLayout = {}; RHI::InputElementDesc position = {}; position.semanticName = "POSITION"; position.semanticIndex = 0; position.format = static_cast(RHI::Format::R32G32B32_Float); position.inputSlot = 0; position.alignedByteOffset = 0; inputLayout.elements.push_back(position); RHI::InputElementDesc normal = {}; normal.semanticName = "NORMAL"; normal.semanticIndex = 0; normal.format = static_cast(RHI::Format::R32G32B32_Float); normal.inputSlot = 0; normal.alignedByteOffset = static_cast(offsetof(Resources::StaticMeshVertex, normal)); inputLayout.elements.push_back(normal); RHI::InputElementDesc texcoord = {}; texcoord.semanticName = "TEXCOORD"; texcoord.semanticIndex = 0; texcoord.format = static_cast(RHI::Format::R32G32_Float); texcoord.inputSlot = 0; texcoord.alignedByteOffset = static_cast(offsetof(Resources::StaticMeshVertex, uv0)); inputLayout.elements.push_back(texcoord); return inputLayout; } bool BuiltinForwardPipeline::Initialize(const RenderContext& context) { return m_passSequence.Initialize(context); } void BuiltinForwardPipeline::Shutdown() { m_passSequence.Shutdown(); } bool BuiltinForwardPipeline::Render( const RenderContext& context, const RenderSurface& surface, const RenderSceneData& sceneData) { if (!Initialize(context)) { return false; } const RenderPassContext passContext = { context, surface, sceneData }; return m_passSequence.Execute(passContext); } bool BuiltinForwardPipeline::ExecuteForwardOpaquePass(const RenderPassContext& passContext) { const RenderContext& context = passContext.renderContext; const RenderSurface& surface = passContext.surface; const RenderSceneData& sceneData = passContext.sceneData; const std::vector& colorAttachments = surface.GetColorAttachments(); if (colorAttachments.empty()) { return false; } std::vector renderTargets = colorAttachments; RHI::RHICommandList* commandList = context.commandList; if (surface.IsAutoTransitionEnabled()) { for (RHI::RHIResourceView* renderTarget : renderTargets) { if (renderTarget != nullptr) { commandList->TransitionBarrier( renderTarget, surface.GetColorStateBefore(), RHI::ResourceStates::RenderTarget); } } } commandList->SetRenderTargets( static_cast(renderTargets.size()), renderTargets.data(), surface.GetDepthAttachment()); const Math::RectInt renderArea = surface.GetRenderArea(); if (renderArea.width <= 0 || renderArea.height <= 0) { return false; } const RHI::Viewport viewport = { static_cast(renderArea.x), static_cast(renderArea.y), static_cast(renderArea.width), static_cast(renderArea.height), 0.0f, 1.0f }; const RHI::Rect scissorRect = { renderArea.x, renderArea.y, renderArea.x + renderArea.width, renderArea.y + renderArea.height }; const RHI::Rect clearRects[] = { scissorRect }; commandList->SetViewport(viewport); commandList->SetScissorRect(scissorRect); const Math::Color clearColor = surface.HasClearColorOverride() ? surface.GetClearColorOverride() : sceneData.cameraData.clearColor; const float clearValues[4] = { clearColor.r, clearColor.g, clearColor.b, clearColor.a }; if (HasRenderClearFlag(sceneData.cameraData.clearFlags, RenderClearFlags::Color)) { for (RHI::RHIResourceView* renderTarget : renderTargets) { if (renderTarget != nullptr) { commandList->ClearRenderTarget(renderTarget, clearValues, 1, clearRects); } } } if (surface.GetDepthAttachment() != nullptr && HasRenderClearFlag(sceneData.cameraData.clearFlags, RenderClearFlags::Depth)) { commandList->ClearDepthStencil(surface.GetDepthAttachment(), 1.0f, 0, 1, clearRects); } commandList->SetPrimitiveTopology(RHI::PrimitiveTopology::TriangleList); RHI::RHIPipelineState* currentPipelineState = nullptr; for (const VisibleRenderItem& visibleItem : sceneData.visibleItems) { const Resources::Material* material = ResolveMaterial(visibleItem); if (!MatchesBuiltinPass(material, BuiltinMaterialPass::ForwardLit)) { continue; } RHI::RHIPipelineState* pipelineState = GetOrCreatePipelineState(context, material); if (pipelineState == nullptr) { continue; } if (pipelineState != currentPipelineState) { commandList->SetPipelineState(pipelineState); currentPipelineState = pipelineState; } DrawVisibleItem(context, sceneData, visibleItem); } if (surface.IsAutoTransitionEnabled()) { for (RHI::RHIResourceView* renderTarget : renderTargets) { if (renderTarget != nullptr) { commandList->TransitionBarrier( renderTarget, RHI::ResourceStates::RenderTarget, surface.GetColorStateAfter()); } } } return true; } bool BuiltinForwardPipeline::EnsureInitialized(const RenderContext& context) { if (!context.IsValid()) { return false; } if (m_initialized && m_device == context.device && m_backendType == context.backendType) { return true; } DestroyPipelineResources(); m_device = context.device; m_backendType = context.backendType; m_initialized = CreatePipelineResources(context); return m_initialized; } bool BuiltinForwardPipeline::CreatePipelineResources(const RenderContext& context) { m_builtinForwardShader = Resources::ResourceManager::Get().Load( Resources::GetBuiltinForwardLitShaderPath()); if (!m_builtinForwardShader.IsValid()) { Debug::Logger::Get().Error( Debug::LogCategory::Rendering, "BuiltinForwardPipeline failed to load builtin forward shader resource"); return false; } RHI::DescriptorSetLayoutBinding constantBinding = {}; constantBinding.binding = 0; constantBinding.type = static_cast(RHI::DescriptorType::CBV); constantBinding.count = 1; RHI::DescriptorSetLayoutDesc constantLayout = {}; constantLayout.bindings = &constantBinding; constantLayout.bindingCount = 1; RHI::DescriptorSetLayoutDesc materialConstantLayout = {}; materialConstantLayout.bindings = &constantBinding; materialConstantLayout.bindingCount = 1; RHI::DescriptorSetLayoutBinding textureBinding = {}; textureBinding.binding = 0; textureBinding.type = static_cast(RHI::DescriptorType::SRV); textureBinding.count = 1; RHI::DescriptorSetLayoutDesc textureLayout = {}; textureLayout.bindings = &textureBinding; textureLayout.bindingCount = 1; RHI::DescriptorPoolDesc samplerPoolDesc = {}; samplerPoolDesc.type = RHI::DescriptorHeapType::Sampler; samplerPoolDesc.descriptorCount = 1; samplerPoolDesc.shaderVisible = true; m_samplerPool = context.device->CreateDescriptorPool(samplerPoolDesc); if (m_samplerPool == nullptr) { return false; } RHI::DescriptorSetLayoutBinding samplerBinding = {}; samplerBinding.binding = 0; samplerBinding.type = static_cast(RHI::DescriptorType::Sampler); samplerBinding.count = 1; RHI::DescriptorSetLayoutDesc samplerLayout = {}; samplerLayout.bindings = &samplerBinding; samplerLayout.bindingCount = 1; m_samplerSet = m_samplerPool->AllocateSet(samplerLayout); if (m_samplerSet == nullptr) { return false; } RHI::DescriptorSetLayoutBinding reservedBindings[3] = {}; reservedBindings[0].binding = 0; reservedBindings[0].type = static_cast(RHI::DescriptorType::CBV); reservedBindings[0].count = 1; reservedBindings[1].binding = 0; reservedBindings[1].type = static_cast(RHI::DescriptorType::SRV); reservedBindings[1].count = 1; reservedBindings[2].binding = 0; reservedBindings[2].type = static_cast(RHI::DescriptorType::Sampler); reservedBindings[2].count = 1; RHI::DescriptorSetLayoutDesc reservedLayout = {}; reservedLayout.bindings = reservedBindings; reservedLayout.bindingCount = 3; RHI::DescriptorSetLayoutDesc setLayouts[kDescriptorSetCount] = {}; setLayouts[0] = reservedLayout; setLayouts[1] = constantLayout; setLayouts[2] = materialConstantLayout; setLayouts[3] = textureLayout; setLayouts[4] = samplerLayout; RHI::RHIPipelineLayoutDesc pipelineLayoutDesc = {}; pipelineLayoutDesc.setLayouts = setLayouts; pipelineLayoutDesc.setLayoutCount = kDescriptorSetCount; m_pipelineLayout = context.device->CreatePipelineLayout(pipelineLayoutDesc); if (m_pipelineLayout == nullptr) { return false; } RHI::SamplerDesc samplerDesc = {}; samplerDesc.filter = static_cast(RHI::FilterMode::Linear); samplerDesc.addressU = static_cast(RHI::TextureAddressMode::Clamp); samplerDesc.addressV = static_cast(RHI::TextureAddressMode::Clamp); samplerDesc.addressW = static_cast(RHI::TextureAddressMode::Clamp); samplerDesc.mipLodBias = 0.0f; samplerDesc.maxAnisotropy = 1; samplerDesc.comparisonFunc = static_cast(RHI::ComparisonFunc::Always); samplerDesc.minLod = 0.0f; samplerDesc.maxLod = 1000.0f; m_sampler = context.device->CreateSampler(samplerDesc); if (m_sampler == nullptr) { return false; } m_samplerSet->UpdateSampler(0, m_sampler); const unsigned char whitePixel[4] = { 255, 255, 255, 255 }; RHI::TextureDesc textureDesc = {}; textureDesc.width = 1; textureDesc.height = 1; textureDesc.depth = 1; textureDesc.mipLevels = 1; textureDesc.arraySize = 1; textureDesc.format = static_cast(RHI::Format::R8G8B8A8_UNorm); textureDesc.textureType = static_cast(RHI::TextureType::Texture2D); textureDesc.sampleCount = 1; textureDesc.sampleQuality = 0; textureDesc.flags = 0; m_fallbackTexture = context.device->CreateTexture(textureDesc, whitePixel, sizeof(whitePixel), 4); if (m_fallbackTexture == nullptr) { return false; } RHI::ResourceViewDesc textureViewDesc = {}; textureViewDesc.format = static_cast(RHI::Format::R8G8B8A8_UNorm); textureViewDesc.dimension = RHI::ResourceViewDimension::Texture2D; textureViewDesc.mipLevel = 0; m_fallbackTextureView = context.device->CreateShaderResourceView(m_fallbackTexture, textureViewDesc); if (m_fallbackTextureView == nullptr) { return false; } return true; } void BuiltinForwardPipeline::DestroyPipelineResources() { m_resourceCache.Shutdown(); for (auto& pipelinePair : m_pipelineStates) { if (pipelinePair.second != nullptr) { pipelinePair.second->Shutdown(); delete pipelinePair.second; } } m_pipelineStates.clear(); for (auto& perObjectSetPair : m_perObjectSets) { DestroyOwnedDescriptorSet(perObjectSetPair.second); } m_perObjectSets.clear(); for (auto& materialBindingPair : m_materialBindings) { DestroyOwnedDescriptorSet(materialBindingPair.second.constantSet); DestroyOwnedDescriptorSet(materialBindingPair.second.textureSet); } m_materialBindings.clear(); if (m_fallbackTextureView != nullptr) { m_fallbackTextureView->Shutdown(); delete m_fallbackTextureView; m_fallbackTextureView = nullptr; } if (m_fallbackTexture != nullptr) { m_fallbackTexture->Shutdown(); delete m_fallbackTexture; m_fallbackTexture = nullptr; } if (m_sampler != nullptr) { m_sampler->Shutdown(); delete m_sampler; m_sampler = nullptr; } if (m_pipelineLayout != nullptr) { m_pipelineLayout->Shutdown(); delete m_pipelineLayout; m_pipelineLayout = nullptr; } if (m_samplerSet != nullptr) { m_samplerSet->Shutdown(); delete m_samplerSet; m_samplerSet = nullptr; } if (m_samplerPool != nullptr) { m_samplerPool->Shutdown(); delete m_samplerPool; m_samplerPool = nullptr; } m_device = nullptr; m_initialized = false; m_builtinForwardShader.Reset(); } BuiltinForwardPipeline::ResolvedShaderPass BuiltinForwardPipeline::ResolveForwardShaderPass( const Resources::Material* material) const { ResolvedShaderPass resolved = {}; const Resources::ShaderBackend backend = ToShaderBackend(m_backendType); if (material != nullptr && material->GetShader() != nullptr) { const Resources::Shader* materialShader = material->GetShader(); if (const Resources::ShaderPass* shaderPass = FindForwardCompatiblePass(*materialShader, material, backend)) { resolved.shader = materialShader; resolved.pass = shaderPass; resolved.passName = shaderPass->name; return resolved; } } if (m_builtinForwardShader.IsValid()) { const Resources::Shader* builtinShader = m_builtinForwardShader.Get(); if (const Resources::ShaderPass* shaderPass = FindForwardCompatiblePass(*builtinShader, nullptr, backend)) { resolved.shader = builtinShader; resolved.pass = shaderPass; resolved.passName = shaderPass->name; } } return resolved; } RHI::RHIPipelineState* BuiltinForwardPipeline::GetOrCreatePipelineState( const RenderContext& context, const Resources::Material* material) { const ResolvedShaderPass resolvedShaderPass = ResolveForwardShaderPass(material); if (resolvedShaderPass.shader == nullptr || resolvedShaderPass.pass == nullptr) { Debug::Logger::Get().Error( Debug::LogCategory::Rendering, "BuiltinForwardPipeline could not resolve a valid ForwardLit shader pass"); return nullptr; } PipelineStateKey pipelineKey = {}; pipelineKey.renderState = material != nullptr ? material->GetRenderState() : Resources::MaterialRenderState(); pipelineKey.shader = resolvedShaderPass.shader; pipelineKey.passName = resolvedShaderPass.passName; const auto existing = m_pipelineStates.find(pipelineKey); if (existing != m_pipelineStates.end()) { return existing->second; } const RHI::GraphicsPipelineDesc pipelineDesc = CreatePipelineDesc( context.backendType, m_pipelineLayout, *resolvedShaderPass.shader, resolvedShaderPass.passName, material); RHI::RHIPipelineState* pipelineState = context.device->CreatePipelineState(pipelineDesc); if (pipelineState == nullptr || !pipelineState->IsValid()) { Debug::Logger::Get().Error( Debug::LogCategory::Rendering, "BuiltinForwardPipeline failed to create pipeline state"); if (pipelineState != nullptr) { pipelineState->Shutdown(); delete pipelineState; } return nullptr; } m_pipelineStates.emplace(pipelineKey, pipelineState); return pipelineState; } RHI::RHIDescriptorSet* BuiltinForwardPipeline::GetOrCreatePerObjectSet(Core::uint64 objectId) { const auto existing = m_perObjectSets.find(objectId); if (existing != m_perObjectSets.end()) { return existing->second.set; } RHI::DescriptorPoolDesc poolDesc = {}; poolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV; poolDesc.descriptorCount = 1; poolDesc.shaderVisible = false; OwnedDescriptorSet descriptorSet = {}; descriptorSet.pool = m_device->CreateDescriptorPool(poolDesc); if (descriptorSet.pool == nullptr) { return nullptr; } RHI::DescriptorSetLayoutBinding binding = {}; binding.binding = 0; binding.type = static_cast(RHI::DescriptorType::CBV); binding.count = 1; RHI::DescriptorSetLayoutDesc layout = {}; layout.bindings = &binding; layout.bindingCount = 1; descriptorSet.set = descriptorSet.pool->AllocateSet(layout); if (descriptorSet.set == nullptr) { DestroyOwnedDescriptorSet(descriptorSet); return nullptr; } const auto result = m_perObjectSets.emplace(objectId, descriptorSet); return result.first->second.set; } BuiltinForwardPipeline::CachedMaterialBindings* BuiltinForwardPipeline::GetOrCreateMaterialBindings( const Resources::Material* material, RHI::RHIResourceView* textureView) { if (textureView == nullptr) { return nullptr; } CachedMaterialBindings& cachedBindings = m_materialBindings[material]; if (cachedBindings.constantSet.set == nullptr) { RHI::DescriptorPoolDesc constantPoolDesc = {}; constantPoolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV; constantPoolDesc.descriptorCount = 1; constantPoolDesc.shaderVisible = false; cachedBindings.constantSet.pool = m_device->CreateDescriptorPool(constantPoolDesc); if (cachedBindings.constantSet.pool == nullptr) { return nullptr; } RHI::DescriptorSetLayoutBinding constantBinding = {}; constantBinding.binding = 0; constantBinding.type = static_cast(RHI::DescriptorType::CBV); constantBinding.count = 1; RHI::DescriptorSetLayoutDesc constantLayout = {}; constantLayout.bindings = &constantBinding; constantLayout.bindingCount = 1; cachedBindings.constantSet.set = cachedBindings.constantSet.pool->AllocateSet(constantLayout); if (cachedBindings.constantSet.set == nullptr) { DestroyOwnedDescriptorSet(cachedBindings.constantSet); return nullptr; } } if (cachedBindings.textureSet.set == nullptr) { RHI::DescriptorPoolDesc texturePoolDesc = {}; texturePoolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV; texturePoolDesc.descriptorCount = 1; texturePoolDesc.shaderVisible = true; cachedBindings.textureSet.pool = m_device->CreateDescriptorPool(texturePoolDesc); if (cachedBindings.textureSet.pool == nullptr) { DestroyOwnedDescriptorSet(cachedBindings.constantSet); return nullptr; } RHI::DescriptorSetLayoutBinding textureBinding = {}; textureBinding.binding = 0; textureBinding.type = static_cast(RHI::DescriptorType::SRV); textureBinding.count = 1; RHI::DescriptorSetLayoutDesc textureLayout = {}; textureLayout.bindings = &textureBinding; textureLayout.bindingCount = 1; cachedBindings.textureSet.set = cachedBindings.textureSet.pool->AllocateSet(textureLayout); if (cachedBindings.textureSet.set == nullptr) { DestroyOwnedDescriptorSet(cachedBindings.textureSet); return nullptr; } } const Core::uint64 materialVersion = material != nullptr ? material->GetChangeVersion() : 0; if (cachedBindings.materialVersion != materialVersion || cachedBindings.textureView != textureView) { const BuiltinForwardMaterialData materialData = BuildBuiltinForwardMaterialData(material); const PerMaterialConstants materialConstants = { materialData.baseColorFactor }; cachedBindings.constantSet.set->WriteConstant(0, &materialConstants, sizeof(materialConstants)); cachedBindings.textureSet.set->Update(0, textureView); cachedBindings.materialVersion = materialVersion; cachedBindings.textureView = textureView; } return &cachedBindings; } void BuiltinForwardPipeline::DestroyOwnedDescriptorSet(OwnedDescriptorSet& descriptorSet) { if (descriptorSet.set != nullptr) { descriptorSet.set->Shutdown(); delete descriptorSet.set; descriptorSet.set = nullptr; } if (descriptorSet.pool != nullptr) { descriptorSet.pool->Shutdown(); delete descriptorSet.pool; descriptorSet.pool = nullptr; } } const Resources::Texture* BuiltinForwardPipeline::ResolveTexture(const Resources::Material* material) const { return ResolveBuiltinBaseColorTexture(material); } RHI::RHIResourceView* BuiltinForwardPipeline::ResolveTextureView( const VisibleRenderItem& visibleItem) { const Resources::Material* material = ResolveMaterial(visibleItem); const Resources::Texture* texture = ResolveTexture(material); if (texture != nullptr) { const RenderResourceCache::CachedTexture* cachedTexture = m_resourceCache.GetOrCreateTexture(m_device, texture); if (cachedTexture != nullptr && cachedTexture->shaderResourceView != nullptr) { return cachedTexture->shaderResourceView; } } return m_fallbackTextureView; } bool BuiltinForwardPipeline::DrawVisibleItem( const RenderContext& context, const RenderSceneData& sceneData, const VisibleRenderItem& visibleItem) { const RenderResourceCache::CachedMesh* cachedMesh = m_resourceCache.GetOrCreateMesh(m_device, visibleItem.mesh); if (cachedMesh == nullptr || cachedMesh->vertexBufferView == nullptr) { return false; } RHI::RHICommandList* commandList = context.commandList; RHI::RHIResourceView* vertexBuffers[] = { cachedMesh->vertexBufferView }; const uint64_t offsets[] = { 0 }; const uint32_t strides[] = { cachedMesh->vertexStride }; commandList->SetVertexBuffers(0, 1, vertexBuffers, offsets, strides); if (cachedMesh->indexBufferView != nullptr) { commandList->SetIndexBuffer(cachedMesh->indexBufferView, 0); } const PerObjectConstants constants = { sceneData.cameraData.projection, sceneData.cameraData.view, visibleItem.localToWorld.Transpose(), visibleItem.localToWorld.Inverse(), sceneData.lighting.HasMainDirectionalLight() ? Math::Vector4( sceneData.lighting.mainDirectionalLight.direction.x, sceneData.lighting.mainDirectionalLight.direction.y, sceneData.lighting.mainDirectionalLight.direction.z, sceneData.lighting.mainDirectionalLight.intensity) : Math::Vector4::Zero(), sceneData.lighting.HasMainDirectionalLight() ? Math::Vector4( sceneData.lighting.mainDirectionalLight.color.r, sceneData.lighting.mainDirectionalLight.color.g, sceneData.lighting.mainDirectionalLight.color.b, 1.0f) : Math::Vector4::Zero() }; RHI::RHIResourceView* textureView = ResolveTextureView(visibleItem); if (textureView == nullptr) { return false; } const Resources::Material* material = ResolveMaterial(visibleItem); RHI::RHIDescriptorSet* constantSet = GetOrCreatePerObjectSet( visibleItem.gameObject != nullptr ? visibleItem.gameObject->GetID() : 0); CachedMaterialBindings* materialBindings = GetOrCreateMaterialBindings(material, textureView); if (constantSet == nullptr || materialBindings == nullptr || materialBindings->constantSet.set == nullptr || materialBindings->textureSet.set == nullptr || m_samplerSet == nullptr) { return false; } constantSet->WriteConstant(0, &constants, sizeof(constants)); RHI::RHIDescriptorSet* descriptorSets[] = { constantSet, materialBindings->constantSet.set, materialBindings->textureSet.set, m_samplerSet }; commandList->SetGraphicsDescriptorSets(kDescriptorFirstSet, 4, descriptorSets, m_pipelineLayout); if (visibleItem.hasSection) { const Containers::Array& sections = visibleItem.mesh->GetSections(); if (visibleItem.sectionIndex >= sections.Size()) { return false; } const Resources::MeshSection& section = sections[visibleItem.sectionIndex]; if (cachedMesh->indexBufferView != nullptr && section.indexCount > 0) { // MeshLoader flattens section indices into a single global index buffer. commandList->DrawIndexed(section.indexCount, 1, section.startIndex, 0, 0); } else if (section.vertexCount > 0) { commandList->Draw(section.vertexCount, 1, section.baseVertex, 0); } return true; } if (cachedMesh->indexBufferView != nullptr && cachedMesh->indexCount > 0) { commandList->DrawIndexed(cachedMesh->indexCount, 1, 0, 0, 0); } else if (cachedMesh->vertexCount > 0) { commandList->Draw(cachedMesh->vertexCount, 1, 0, 0); } return true; } } // namespace Pipelines } // namespace Rendering } // namespace XCEngine