Add procedural skybox scene coverage

This commit is contained in:
2026-04-05 23:44:32 +08:00
parent be2013f3c4
commit 8151be0f45
27 changed files with 1092 additions and 5 deletions

View File

@@ -0,0 +1,35 @@
// XC_BUILTIN_SKYBOX_OPENGL_PS
#version 430
layout(std140, binding = 0) uniform EnvironmentConstants {
vec4 gSkyboxTopColor;
vec4 gSkyboxHorizonColor;
vec4 gSkyboxBottomColor;
vec4 gCameraRightAndTanHalfFov;
vec4 gCameraUpAndAspect;
vec4 gCameraForwardAndUnused;
};
in vec2 vNdc;
layout(location = 0) out vec4 fragColor;
void main() {
float tanHalfFov = gCameraRightAndTanHalfFov.w;
float aspect = gCameraUpAndAspect.w;
vec3 viewRay = normalize(
gCameraForwardAndUnused.xyz +
vNdc.x * aspect * tanHalfFov * gCameraRightAndTanHalfFov.xyz +
vNdc.y * tanHalfFov * gCameraUpAndAspect.xyz);
float vertical = clamp(viewRay.y, -1.0, 1.0);
vec3 color = gSkyboxHorizonColor.rgb;
if (vertical >= 0.0) {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxTopColor.rgb, pow(clamp(vertical, 0.0, 1.0), 0.65));
} else {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxBottomColor.rgb, pow(clamp(-vertical, 0.0, 1.0), 0.55));
}
fragColor = vec4(color, 1.0);
}

View File

@@ -0,0 +1,35 @@
// XC_BUILTIN_SKYBOX_VULKAN_PS
#version 450
layout(set = 0, binding = 0, std140) uniform EnvironmentConstants {
vec4 gSkyboxTopColor;
vec4 gSkyboxHorizonColor;
vec4 gSkyboxBottomColor;
vec4 gCameraRightAndTanHalfFov;
vec4 gCameraUpAndAspect;
vec4 gCameraForwardAndUnused;
};
layout(location = 0) in vec2 vNdc;
layout(location = 0) out vec4 fragColor;
void main() {
float tanHalfFov = gCameraRightAndTanHalfFov.w;
float aspect = gCameraUpAndAspect.w;
vec3 viewRay = normalize(
gCameraForwardAndUnused.xyz +
vNdc.x * aspect * tanHalfFov * gCameraRightAndTanHalfFov.xyz +
vNdc.y * tanHalfFov * gCameraUpAndAspect.xyz);
float vertical = clamp(viewRay.y, -1.0, 1.0);
vec3 color = gSkyboxHorizonColor.rgb;
if (vertical >= 0.0) {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxTopColor.rgb, pow(clamp(vertical, 0.0, 1.0), 0.65));
} else {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxBottomColor.rgb, pow(clamp(-vertical, 0.0, 1.0), 0.55));
}
fragColor = vec4(color, 1.0);
}

View File

@@ -0,0 +1,34 @@
// XC_BUILTIN_SKYBOX_D3D12_PS
cbuffer EnvironmentConstants : register(b0) {
float4 gSkyboxTopColor;
float4 gSkyboxHorizonColor;
float4 gSkyboxBottomColor;
float4 gCameraRightAndTanHalfFov;
float4 gCameraUpAndAspect;
float4 gCameraForwardAndUnused;
}
struct PSInput {
float4 position : SV_POSITION;
float2 ndc : TEXCOORD0;
};
float4 MainPS(PSInput input) : SV_Target {
const float tanHalfFov = gCameraRightAndTanHalfFov.w;
const float aspect = gCameraUpAndAspect.w;
float3 viewRay = normalize(
gCameraForwardAndUnused.xyz +
input.ndc.x * aspect * tanHalfFov * gCameraRightAndTanHalfFov.xyz +
input.ndc.y * tanHalfFov * gCameraUpAndAspect.xyz);
const float vertical = clamp(viewRay.y, -1.0f, 1.0f);
float3 color = gSkyboxHorizonColor.rgb;
if (vertical >= 0.0f) {
color = lerp(gSkyboxHorizonColor.rgb, gSkyboxTopColor.rgb, pow(saturate(vertical), 0.65f));
} else {
color = lerp(gSkyboxHorizonColor.rgb, gSkyboxBottomColor.rgb, pow(saturate(-vertical), 0.55f));
}
return float4(color, 1.0f);
}

View File

@@ -0,0 +1,22 @@
Shader "Builtin Skybox"
{
SubShader
{
Pass
{
Name "Skybox"
Tags { "LightMode" = "Skybox" }
Resources
{
EnvironmentConstants (ConstantBuffer, 0, 0) [Semantic(Environment)]
}
HLSLPROGRAM
#pragma vertex MainVS
#pragma fragment MainPS
#pragma backend D3D12 HLSL "skybox.vs.hlsl" "skybox.ps.hlsl" vs_5_0 ps_5_0
#pragma backend OpenGL GLSL "skybox.vert.glsl" "skybox.frag.glsl"
#pragma backend Vulkan GLSL "skybox.vert.vk.glsl" "skybox.frag.vk.glsl"
ENDHLSL
}
}
}

View File

@@ -0,0 +1,16 @@
// XC_BUILTIN_SKYBOX_OPENGL_VS
#version 430
out vec2 vNdc;
void main() {
const vec2 positions[3] = vec2[3](
vec2(-1.0, -1.0),
vec2(-1.0, 3.0),
vec2( 3.0, -1.0)
);
vec2 position = positions[gl_VertexID];
gl_Position = vec4(position, 1.0, 1.0);
vNdc = position;
}

View File

@@ -0,0 +1,16 @@
// XC_BUILTIN_SKYBOX_VULKAN_VS
#version 450
layout(location = 0) out vec2 vNdc;
void main() {
const vec2 positions[3] = vec2[3](
vec2(-1.0, -1.0),
vec2(-1.0, 3.0),
vec2( 3.0, -1.0)
);
vec2 position = positions[gl_VertexIndex];
gl_Position = vec4(position, 1.0, 1.0);
vNdc = position;
}

View File

@@ -0,0 +1,18 @@
// XC_BUILTIN_SKYBOX_D3D12_VS
struct VSOutput {
float4 position : SV_POSITION;
float2 ndc : TEXCOORD0;
};
VSOutput MainVS(uint vertexId : SV_VertexID) {
const float2 positions[3] = {
float2(-1.0f, -1.0f),
float2(-1.0f, 3.0f),
float2( 3.0f, -1.0f)
};
VSOutput output;
output.position = float4(positions[vertexId], 1.0f, 1.0f);
output.ndc = positions[vertexId];
return output;
}

View File

@@ -64,6 +64,18 @@ public:
const Math::Color& GetClearColor() const { return m_clearColor; }
void SetClearColor(const Math::Color& value) { m_clearColor = value; }
bool IsSkyboxEnabled() const { return m_skyboxEnabled; }
void SetSkyboxEnabled(bool value) { m_skyboxEnabled = value; }
const Math::Color& GetSkyboxTopColor() const { return m_skyboxTopColor; }
void SetSkyboxTopColor(const Math::Color& value) { m_skyboxTopColor = value; }
const Math::Color& GetSkyboxHorizonColor() const { return m_skyboxHorizonColor; }
void SetSkyboxHorizonColor(const Math::Color& value) { m_skyboxHorizonColor = value; }
const Math::Color& GetSkyboxBottomColor() const { return m_skyboxBottomColor; }
void SetSkyboxBottomColor(const Math::Color& value) { m_skyboxBottomColor = value; }
void Serialize(std::ostream& os) const override;
void Deserialize(std::istream& is) override;
@@ -80,6 +92,10 @@ private:
uint32_t m_cullingMask = 0xFFFFFFFFu;
Math::Rect m_viewportRect = Math::Rect(0.0f, 0.0f, 1.0f, 1.0f);
Math::Color m_clearColor = Math::Color(0.192f, 0.302f, 0.475f, 1.0f);
bool m_skyboxEnabled = false;
Math::Color m_skyboxTopColor = Math::Color(0.18f, 0.36f, 0.74f, 1.0f);
Math::Color m_skyboxHorizonColor = Math::Color(0.78f, 0.84f, 0.92f, 1.0f);
Math::Color m_skyboxBottomColor = Math::Color(0.92f, 0.93f, 0.95f, 1.0f);
};
} // namespace Components

View File

@@ -35,8 +35,17 @@ struct RenderCameraData {
Math::Matrix4x4 projection = Math::Matrix4x4::Identity();
Math::Matrix4x4 viewProjection = Math::Matrix4x4::Identity();
Math::Vector3 worldPosition = Math::Vector3::Zero();
Math::Vector3 worldRight = Math::Vector3::Right();
Math::Vector3 worldUp = Math::Vector3::Up();
Math::Vector3 worldForward = Math::Vector3::Forward();
Math::Color clearColor = Math::Color::Black();
RenderClearFlags clearFlags = RenderClearFlags::All;
bool perspectiveProjection = true;
float verticalFovRadians = 60.0f * Math::DEG_TO_RAD;
float orthographicSize = 5.0f;
float aspectRatio = 1.0f;
float nearClipPlane = 0.1f;
float farClipPlane = 1000.0f;
uint32_t viewportWidth = 0;
uint32_t viewportHeight = 0;
};

View File

@@ -0,0 +1,31 @@
#pragma once
#include <XCEngine/Core/Math/Color.h>
#include <cstdint>
namespace XCEngine {
namespace Rendering {
enum class RenderEnvironmentMode : uint32_t {
None = 0,
ProceduralSkybox
};
struct ProceduralSkyboxData {
Math::Color topColor = Math::Color(0.18f, 0.36f, 0.74f, 1.0f);
Math::Color horizonColor = Math::Color(0.78f, 0.84f, 0.92f, 1.0f);
Math::Color bottomColor = Math::Color(0.92f, 0.93f, 0.95f, 1.0f);
};
struct RenderEnvironmentData {
RenderEnvironmentMode mode = RenderEnvironmentMode::None;
ProceduralSkyboxData skybox = {};
bool HasProceduralSkybox() const {
return mode == RenderEnvironmentMode::ProceduralSkybox;
}
};
} // namespace Rendering
} // namespace XCEngine

View File

@@ -3,6 +3,7 @@
#include <XCEngine/Core/Math/Vector3.h>
#include <XCEngine/Core/Math/Vector4.h>
#include <XCEngine/Rendering/FrameData/RenderCameraData.h>
#include <XCEngine/Rendering/FrameData/RenderEnvironmentData.h>
#include <XCEngine/Rendering/FrameData/VisibleRenderItem.h>
#include <array>
@@ -81,6 +82,7 @@ struct RenderLightingData {
struct RenderSceneData {
Components::CameraComponent* camera = nullptr;
RenderCameraData cameraData;
RenderEnvironmentData environment;
RenderLightingData lighting;
std::vector<VisibleRenderItem> visibleItems;

View File

@@ -38,6 +38,7 @@ class RenderSurface;
namespace Pipelines {
namespace Detail {
class BuiltinForwardOpaquePass;
class BuiltinForwardSkyboxPass;
class BuiltinForwardTransparentPass;
} // namespace Detail
@@ -57,6 +58,7 @@ public:
private:
friend class Detail::BuiltinForwardOpaquePass;
friend class Detail::BuiltinForwardSkyboxPass;
friend class Detail::BuiltinForwardTransparentPass;
struct OwnedDescriptorSet {
@@ -98,6 +100,15 @@ private:
Math::Vector4 baseColorFactor = Math::Vector4::One();
};
struct SkyboxConstants {
Math::Vector4 topColor = Math::Vector4::Zero();
Math::Vector4 horizonColor = Math::Vector4::Zero();
Math::Vector4 bottomColor = Math::Vector4::Zero();
Math::Vector4 cameraRightAndTanHalfFov = Math::Vector4::Zero();
Math::Vector4 cameraUpAndAspect = Math::Vector4::Zero();
Math::Vector4 cameraForwardAndUnused = Math::Vector4::Zero();
};
struct PassLayoutKey {
const Resources::Shader* shader = nullptr;
Containers::String passName;
@@ -235,9 +246,11 @@ private:
RHI::RHIResourceView* ResolveTextureView(const VisibleRenderItem& visibleItem);
static LightingConstants BuildLightingConstants(const RenderLightingData& lightingData);
static AdditionalLightConstants BuildAdditionalLightConstants(const RenderAdditionalLightData& lightData);
bool HasProceduralSkybox(const RenderSceneData& sceneData) const;
bool BeginForwardScenePass(const RenderPassContext& context);
void EndForwardScenePass(const RenderPassContext& context);
bool ExecuteForwardOpaquePass(const RenderPassContext& context);
bool ExecuteForwardSkyboxPass(const RenderPassContext& context);
bool ExecuteForwardTransparentPass(const RenderPassContext& context);
bool DrawVisibleItems(
const RenderContext& context,
@@ -247,12 +260,16 @@ private:
const RenderContext& context,
const RenderSceneData& sceneData,
const VisibleRenderItem& visibleItem);
bool EnsureSkyboxResources(const RenderContext& context);
bool CreateSkyboxResources(const RenderContext& context);
void DestroySkyboxResources();
RHI::RHIDevice* m_device = nullptr;
RHI::RHIType m_backendType = RHI::RHIType::D3D12;
bool m_initialized = false;
Resources::ResourceHandle<Resources::Shader> m_builtinForwardShader;
Resources::ResourceHandle<Resources::Shader> m_builtinUnlitShader;
Resources::ResourceHandle<Resources::Shader> m_builtinSkyboxShader;
RenderResourceCache m_resourceCache;
@@ -263,6 +280,10 @@ private:
RHI::RHISampler* m_shadowSampler = nullptr;
RHI::RHITexture* m_fallbackTexture = nullptr;
RHI::RHIResourceView* m_fallbackTextureView = nullptr;
RHI::RHIPipelineLayout* m_skyboxPipelineLayout = nullptr;
RHI::RHIPipelineState* m_skyboxPipelineState = nullptr;
RHI::RHIDescriptorPool* m_skyboxConstantPool = nullptr;
RHI::RHIDescriptorSet* m_skyboxConstantSet = nullptr;
RenderPassSequence m_passSequence;
};

View File

@@ -28,6 +28,7 @@ Containers::String GetBuiltinUnlitShaderPath();
Containers::String GetBuiltinDepthOnlyShaderPath();
Containers::String GetBuiltinShadowCasterShaderPath();
Containers::String GetBuiltinObjectIdShaderPath();
Containers::String GetBuiltinSkyboxShaderPath();
Containers::String GetBuiltinDefaultPrimitiveTexturePath();
bool TryParseBuiltinPrimitiveType(const Containers::String& path, BuiltinPrimitiveType& outPrimitiveType);

View File

@@ -48,6 +48,10 @@ void CameraComponent::Serialize(std::ostream& os) const {
os << "cullingMask=" << m_cullingMask << ";";
os << "viewportRect=" << m_viewportRect.x << "," << m_viewportRect.y << "," << m_viewportRect.width << "," << m_viewportRect.height << ";";
os << "clearColor=" << m_clearColor.r << "," << m_clearColor.g << "," << m_clearColor.b << "," << m_clearColor.a << ";";
os << "skyboxEnabled=" << (m_skyboxEnabled ? 1 : 0) << ";";
os << "skyboxTopColor=" << m_skyboxTopColor.r << "," << m_skyboxTopColor.g << "," << m_skyboxTopColor.b << "," << m_skyboxTopColor.a << ";";
os << "skyboxHorizonColor=" << m_skyboxHorizonColor.r << "," << m_skyboxHorizonColor.g << "," << m_skyboxHorizonColor.b << "," << m_skyboxHorizonColor.a << ";";
os << "skyboxBottomColor=" << m_skyboxBottomColor.r << "," << m_skyboxBottomColor.g << "," << m_skyboxBottomColor.b << "," << m_skyboxBottomColor.a << ";";
}
void CameraComponent::Deserialize(std::istream& is) {
@@ -95,6 +99,20 @@ void CameraComponent::Deserialize(std::istream& is) {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_clearColor.r >> m_clearColor.g >> m_clearColor.b >> m_clearColor.a;
} else if (key == "skyboxEnabled") {
m_skyboxEnabled = (std::stoi(value) != 0);
} else if (key == "skyboxTopColor") {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_skyboxTopColor.r >> m_skyboxTopColor.g >> m_skyboxTopColor.b >> m_skyboxTopColor.a;
} else if (key == "skyboxHorizonColor") {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_skyboxHorizonColor.r >> m_skyboxHorizonColor.g >> m_skyboxHorizonColor.b >> m_skyboxHorizonColor.a;
} else if (key == "skyboxBottomColor") {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_skyboxBottomColor.r >> m_skyboxBottomColor.g >> m_skyboxBottomColor.b >> m_skyboxBottomColor.a;
}
}
}

View File

@@ -4,9 +4,11 @@
#include "XCEngine/RHI/Vulkan/VulkanPipelineLayout.h"
#include "XCEngine/RHI/Vulkan/VulkanShader.h"
#include "XCEngine/RHI/Vulkan/VulkanShaderCompiler.h"
#include "XCEngine/Debug/Logger.h"
#include <algorithm>
#include <map>
#include <sstream>
#include <vector>
namespace XCEngine {
@@ -110,10 +112,21 @@ bool VulkanPipelineState::EnsurePipelineLayout(const GraphicsPipelineDesc& desc)
bool VulkanPipelineState::CreateGraphicsPipeline(const GraphicsPipelineDesc& desc) {
VulkanCompiledShader vertexShader = {};
VulkanCompiledShader fragmentShader = {};
if (!CompileVulkanShader(desc.vertexShader, vertexShader, nullptr) ||
!CompileVulkanShader(desc.fragmentShader, fragmentShader, nullptr) ||
std::string vertexError;
std::string fragmentError;
if (!CompileVulkanShader(desc.vertexShader, vertexShader, &vertexError) ||
!CompileVulkanShader(desc.fragmentShader, fragmentShader, &fragmentError) ||
vertexShader.type != ShaderType::Vertex ||
fragmentShader.type != ShaderType::Fragment) {
std::ostringstream message;
message << "VulkanPipelineState failed to compile graphics shaders.";
if (!vertexError.empty()) {
message << " Vertex: " << vertexError;
}
if (!fragmentError.empty()) {
message << " Fragment: " << fragmentError;
}
Debug::Logger::Get().Error(Debug::LogCategory::Rendering, message.str().c_str());
return false;
}
@@ -316,18 +329,23 @@ bool VulkanPipelineState::CreateGraphicsPipeline(const GraphicsPipelineDesc& des
pipelineInfo.renderPass = m_renderPass;
pipelineInfo.subpass = 0;
const bool success = vkCreateGraphicsPipelines(
const VkResult pipelineCreateResult = vkCreateGraphicsPipelines(
m_device,
VK_NULL_HANDLE,
1,
&pipelineInfo,
nullptr,
&m_pipeline) == VK_SUCCESS;
&m_pipeline);
const bool success = pipelineCreateResult == VK_SUCCESS;
vkDestroyShaderModule(m_device, fragmentModule, nullptr);
vkDestroyShaderModule(m_device, vertexModule, nullptr);
if (!success) {
std::ostringstream message;
message << "VulkanPipelineState vkCreateGraphicsPipelines failed with VkResult="
<< static_cast<int>(pipelineCreateResult);
Debug::Logger::Get().Error(Debug::LogCategory::Rendering, message.str().c_str());
return false;
}

View File

@@ -1,5 +1,6 @@
#include "Rendering/Execution/CameraRenderer.h"
#include "Components/CameraComponent.h"
#include "Rendering/Caches/DirectionalShadowSurfaceCache.h"
#include "Rendering/Passes/BuiltinDepthOnlyPass.h"
#include "Rendering/Passes/BuiltinObjectIdPass.h"
@@ -241,6 +242,23 @@ RenderDirectionalShadowData BuildDirectionalShadowData(
return shadowData;
}
RenderEnvironmentData BuildEnvironmentData(const CameraRenderRequest& request) {
RenderEnvironmentData environment = {};
if (request.camera == nullptr ||
request.surface.GetDepthAttachment() == nullptr ||
!HasRenderClearFlag(request.clearFlags, RenderClearFlags::Color) ||
!request.camera->IsSkyboxEnabled() ||
request.camera->GetProjectionType() != Components::CameraProjectionType::Perspective) {
return environment;
}
environment.mode = RenderEnvironmentMode::ProceduralSkybox;
environment.skybox.topColor = request.camera->GetSkyboxTopColor();
environment.skybox.horizonColor = request.camera->GetSkyboxHorizonColor();
environment.skybox.bottomColor = request.camera->GetSkyboxBottomColor();
return environment;
}
} // namespace
CameraRenderer::CameraRenderer()
@@ -407,6 +425,7 @@ bool CameraRenderer::BuildSceneDataForRequest(
}
outSceneData.cameraData.clearFlags = request.clearFlags;
outSceneData.environment = BuildEnvironmentData(request);
if (request.hasClearColorOverride) {
outSceneData.cameraData.clearColor = request.clearColorOverride;
}

View File

@@ -22,12 +22,22 @@ RenderCameraData BuildRenderCameraData(
cameraData.viewportWidth = viewportWidth;
cameraData.viewportHeight = viewportHeight;
cameraData.worldPosition = camera.transform().GetPosition();
cameraData.worldRight = camera.transform().GetRight();
cameraData.worldUp = camera.transform().GetUp();
cameraData.worldForward = camera.transform().GetForward();
cameraData.clearColor = camera.GetClearColor();
cameraData.perspectiveProjection =
camera.GetProjectionType() == Components::CameraProjectionType::Perspective;
cameraData.verticalFovRadians = camera.GetFieldOfView() * Math::DEG_TO_RAD;
cameraData.orthographicSize = camera.GetOrthographicSize();
cameraData.nearClipPlane = camera.GetNearClipPlane();
cameraData.farClipPlane = camera.GetFarClipPlane();
const Math::Matrix4x4 view = camera.transform().GetWorldToLocalMatrix();
const float aspect = viewportHeight > 0
? static_cast<float>(viewportWidth) / static_cast<float>(viewportHeight)
: 1.0f;
cameraData.aspectRatio = aspect;
Math::Matrix4x4 projection = Math::Matrix4x4::Identity();
if (camera.GetProjectionType() == Components::CameraProjectionType::Perspective) {

View File

@@ -3,11 +3,13 @@
#include "Debug/Logger.h"
#include "Core/Asset/ResourceManager.h"
#include "RHI/RHICommandList.h"
#include "Rendering/Detail/ShaderVariantUtils.h"
#include "Rendering/Materials/RenderMaterialResolve.h"
#include "Rendering/RenderSurface.h"
#include "Resources/BuiltinResources.h"
#include <cstddef>
#include <cmath>
namespace XCEngine {
namespace Rendering {
@@ -40,6 +42,32 @@ private:
BuiltinForwardPipeline& m_pipeline;
};
class BuiltinForwardSkyboxPass final : public RenderPass {
public:
explicit BuiltinForwardSkyboxPass(BuiltinForwardPipeline& pipeline)
: m_pipeline(pipeline) {
}
const char* GetName() const override {
return "BuiltinForwardSkyboxPass";
}
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.ExecuteForwardSkyboxPass(context);
}
private:
BuiltinForwardPipeline& m_pipeline;
};
class BuiltinForwardTransparentPass final : public RenderPass {
public:
explicit BuiltinForwardTransparentPass(BuiltinForwardPipeline& pipeline)
@@ -75,10 +103,66 @@ bool IsDepthFormat(RHI::Format format) {
format == RHI::Format::D32_Float;
}
const Resources::ShaderPass* FindCompatibleSkyboxPass(
const Resources::Shader& shader,
Resources::ShaderBackend backend) {
const Resources::ShaderPass* skyboxPass = shader.FindPass("Skybox");
if (skyboxPass != nullptr &&
::XCEngine::Rendering::Detail::ShaderPassHasGraphicsVariants(shader, skyboxPass->name, backend)) {
return skyboxPass;
}
if (shader.GetPassCount() > 0 &&
::XCEngine::Rendering::Detail::ShaderPassHasGraphicsVariants(shader, shader.GetPasses()[0].name, backend)) {
return &shader.GetPasses()[0];
}
return nullptr;
}
RHI::GraphicsPipelineDesc CreateSkyboxPipelineDesc(
RHI::RHIType backendType,
RHI::RHIPipelineLayout* pipelineLayout,
const Resources::Shader& shader,
const Containers::String& passName) {
RHI::GraphicsPipelineDesc pipelineDesc = {};
pipelineDesc.pipelineLayout = pipelineLayout;
pipelineDesc.topologyType = static_cast<uint32_t>(RHI::PrimitiveTopologyType::Triangle);
pipelineDesc.renderTargetCount = 1;
pipelineDesc.renderTargetFormats[0] = static_cast<uint32_t>(RHI::Format::R8G8B8A8_UNorm);
pipelineDesc.depthStencilFormat = static_cast<uint32_t>(RHI::Format::D24_UNorm_S8_UInt);
pipelineDesc.sampleCount = 1;
pipelineDesc.rasterizerState.fillMode = static_cast<uint32_t>(RHI::FillMode::Solid);
pipelineDesc.rasterizerState.cullMode = static_cast<uint32_t>(RHI::CullMode::None);
pipelineDesc.rasterizerState.frontFace = static_cast<uint32_t>(RHI::FrontFace::CounterClockwise);
pipelineDesc.rasterizerState.depthClipEnable = true;
pipelineDesc.blendState.blendEnable = false;
pipelineDesc.blendState.colorWriteMask = static_cast<uint8_t>(RHI::ColorWriteMask::All);
pipelineDesc.depthStencilState.depthTestEnable = true;
pipelineDesc.depthStencilState.depthWriteEnable = false;
pipelineDesc.depthStencilState.depthFunc = static_cast<uint32_t>(RHI::ComparisonFunc::LessEqual);
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Detail::ToShaderBackend(backendType);
if (const Resources::ShaderStageVariant* vertexVariant =
shader.FindVariant(passName, Resources::ShaderType::Vertex, backend)) {
::XCEngine::Rendering::Detail::ApplyShaderStageVariant(*vertexVariant, pipelineDesc.vertexShader);
}
if (const Resources::ShaderStageVariant* fragmentVariant =
shader.FindVariant(passName, Resources::ShaderType::Fragment, backend)) {
::XCEngine::Rendering::Detail::ApplyShaderStageVariant(*fragmentVariant, pipelineDesc.fragmentShader);
}
return pipelineDesc;
}
} // namespace
BuiltinForwardPipeline::BuiltinForwardPipeline() {
m_passSequence.AddPass(std::make_unique<Detail::BuiltinForwardOpaquePass>(*this));
m_passSequence.AddPass(std::make_unique<Detail::BuiltinForwardSkyboxPass>(*this));
m_passSequence.AddPass(std::make_unique<Detail::BuiltinForwardTransparentPass>(*this));
}
@@ -145,6 +229,11 @@ bool BuiltinForwardPipeline::Render(
return m_passSequence.Execute(passContext);
}
bool BuiltinForwardPipeline::HasProceduralSkybox(const RenderSceneData& sceneData) const {
return sceneData.environment.HasProceduralSkybox() &&
sceneData.cameraData.perspectiveProjection;
}
bool BuiltinForwardPipeline::BeginForwardScenePass(const RenderPassContext& passContext) {
const RenderContext& context = passContext.renderContext;
const RenderSurface& surface = passContext.surface;
@@ -200,7 +289,8 @@ bool BuiltinForwardPipeline::BeginForwardScenePass(const RenderPassContext& pass
? surface.GetClearColorOverride()
: sceneData.cameraData.clearColor;
const float clearValues[4] = { clearColor.r, clearColor.g, clearColor.b, clearColor.a };
if (HasRenderClearFlag(sceneData.cameraData.clearFlags, RenderClearFlags::Color)) {
if (HasRenderClearFlag(sceneData.cameraData.clearFlags, RenderClearFlags::Color) &&
!HasProceduralSkybox(sceneData)) {
for (RHI::RHIResourceView* renderTarget : renderTargets) {
if (renderTarget != nullptr) {
commandList->ClearRenderTarget(renderTarget, clearValues, 1, clearRects);
@@ -256,6 +346,51 @@ bool BuiltinForwardPipeline::ExecuteForwardOpaquePass(const RenderPassContext& p
return DrawVisibleItems(context, sceneData, false);
}
bool BuiltinForwardPipeline::ExecuteForwardSkyboxPass(const RenderPassContext& passContext) {
const RenderContext& context = passContext.renderContext;
const RenderSurface& surface = passContext.surface;
const RenderSceneData& sceneData = passContext.sceneData;
if (!HasProceduralSkybox(sceneData)) {
return true;
}
if (surface.GetDepthAttachment() == nullptr) {
return true;
}
if (!EnsureSkyboxResources(context) ||
m_skyboxPipelineLayout == nullptr ||
m_skyboxPipelineState == nullptr ||
m_skyboxConstantSet == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline skybox pass failed to initialize runtime skybox resources");
return false;
}
SkyboxConstants constants = {};
constants.topColor = sceneData.environment.skybox.topColor.ToVector4();
constants.horizonColor = sceneData.environment.skybox.horizonColor.ToVector4();
constants.bottomColor = sceneData.environment.skybox.bottomColor.ToVector4();
constants.cameraRightAndTanHalfFov = Math::Vector4(
sceneData.cameraData.worldRight,
std::tan(sceneData.cameraData.verticalFovRadians * 0.5f));
constants.cameraUpAndAspect = Math::Vector4(
sceneData.cameraData.worldUp,
sceneData.cameraData.aspectRatio);
constants.cameraForwardAndUnused = Math::Vector4(sceneData.cameraData.worldForward, 0.0f);
m_skyboxConstantSet->WriteConstant(0, &constants, sizeof(constants));
RHI::RHICommandList* commandList = context.commandList;
commandList->SetPrimitiveTopology(RHI::PrimitiveTopology::TriangleList);
commandList->SetPipelineState(m_skyboxPipelineState);
RHI::RHIDescriptorSet* descriptorSets[] = { m_skyboxConstantSet };
commandList->SetGraphicsDescriptorSets(0, 1, descriptorSets, m_skyboxPipelineLayout);
commandList->Draw(3, 1, 0, 0);
return true;
}
bool BuiltinForwardPipeline::ExecuteForwardTransparentPass(const RenderPassContext& passContext) {
const RenderContext& context = passContext.renderContext;
const RenderSceneData& sceneData = passContext.sceneData;
@@ -345,6 +480,15 @@ bool BuiltinForwardPipeline::CreatePipelineResources(const RenderContext& contex
return false;
}
m_builtinSkyboxShader = Resources::ResourceManager::Get().Load<Resources::Shader>(
Resources::GetBuiltinSkyboxShaderPath());
if (!m_builtinSkyboxShader.IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to load builtin skybox shader resource");
return false;
}
RHI::SamplerDesc samplerDesc = {};
samplerDesc.filter = static_cast<uint32_t>(RHI::FilterMode::Linear);
samplerDesc.addressU = static_cast<uint32_t>(RHI::TextureAddressMode::Clamp);
@@ -396,6 +540,123 @@ bool BuiltinForwardPipeline::CreatePipelineResources(const RenderContext& contex
return true;
}
bool BuiltinForwardPipeline::EnsureSkyboxResources(const RenderContext& context) {
if (m_skyboxPipelineLayout != nullptr &&
m_skyboxPipelineState != nullptr &&
m_skyboxConstantPool != nullptr &&
m_skyboxConstantSet != nullptr) {
return true;
}
DestroySkyboxResources();
return CreateSkyboxResources(context);
}
bool BuiltinForwardPipeline::CreateSkyboxResources(const RenderContext& context) {
if (!context.IsValid() || !m_builtinSkyboxShader.IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline skybox resources require a valid context and loaded shader");
return false;
}
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Detail::ToShaderBackend(m_backendType);
const Resources::ShaderPass* skyboxPass =
FindCompatibleSkyboxPass(*m_builtinSkyboxShader.Get(), backend);
if (skyboxPass == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline could not resolve a valid skybox shader pass");
return false;
}
RHI::DescriptorSetLayoutBinding constantBinding = {};
constantBinding.binding = 0;
constantBinding.type = static_cast<uint32_t>(RHI::DescriptorType::CBV);
constantBinding.count = 1;
constantBinding.visibility = static_cast<uint32_t>(RHI::ShaderVisibility::All);
RHI::DescriptorSetLayoutDesc constantLayout = {};
constantLayout.bindings = &constantBinding;
constantLayout.bindingCount = 1;
RHI::RHIPipelineLayoutDesc pipelineLayoutDesc = {};
pipelineLayoutDesc.setLayouts = &constantLayout;
pipelineLayoutDesc.setLayoutCount = 1;
m_skyboxPipelineLayout = m_device->CreatePipelineLayout(pipelineLayoutDesc);
if (m_skyboxPipelineLayout == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to create skybox pipeline layout");
DestroySkyboxResources();
return false;
}
RHI::DescriptorPoolDesc constantPoolDesc = {};
constantPoolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV;
constantPoolDesc.descriptorCount = 1;
constantPoolDesc.shaderVisible = false;
m_skyboxConstantPool = m_device->CreateDescriptorPool(constantPoolDesc);
if (m_skyboxConstantPool == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to create skybox descriptor pool");
DestroySkyboxResources();
return false;
}
m_skyboxConstantSet = m_skyboxConstantPool->AllocateSet(constantLayout);
if (m_skyboxConstantSet == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to allocate skybox descriptor set");
DestroySkyboxResources();
return false;
}
m_skyboxPipelineState = m_device->CreatePipelineState(
CreateSkyboxPipelineDesc(
m_backendType,
m_skyboxPipelineLayout,
*m_builtinSkyboxShader.Get(),
skyboxPass->name));
if (m_skyboxPipelineState == nullptr || !m_skyboxPipelineState->IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to create skybox graphics pipeline state");
DestroySkyboxResources();
return false;
}
return true;
}
void BuiltinForwardPipeline::DestroySkyboxResources() {
if (m_skyboxPipelineState != nullptr) {
m_skyboxPipelineState->Shutdown();
delete m_skyboxPipelineState;
m_skyboxPipelineState = nullptr;
}
if (m_skyboxConstantSet != nullptr) {
m_skyboxConstantSet->Shutdown();
delete m_skyboxConstantSet;
m_skyboxConstantSet = nullptr;
}
if (m_skyboxConstantPool != nullptr) {
m_skyboxConstantPool->Shutdown();
delete m_skyboxConstantPool;
m_skyboxConstantPool = nullptr;
}
if (m_skyboxPipelineLayout != nullptr) {
m_skyboxPipelineLayout->Shutdown();
delete m_skyboxPipelineLayout;
m_skyboxPipelineLayout = nullptr;
}
}
void BuiltinForwardPipeline::DestroyPipelineResources() {
m_resourceCache.Shutdown();
@@ -423,6 +684,8 @@ void BuiltinForwardPipeline::DestroyPipelineResources() {
m_fallbackTextureView = nullptr;
}
DestroySkyboxResources();
if (m_fallbackTexture != nullptr) {
m_fallbackTexture->Shutdown();
delete m_fallbackTexture;
@@ -445,6 +708,7 @@ void BuiltinForwardPipeline::DestroyPipelineResources() {
m_initialized = false;
m_builtinForwardShader.Reset();
m_builtinUnlitShader.Reset();
m_builtinSkyboxShader.Reset();
}
} // namespace Pipelines

View File

@@ -32,6 +32,7 @@ constexpr const char* kBuiltinUnlitShaderPath = "builtin://shaders/unlit";
constexpr const char* kBuiltinDepthOnlyShaderPath = "builtin://shaders/depth-only";
constexpr const char* kBuiltinShadowCasterShaderPath = "builtin://shaders/shadow-caster";
constexpr const char* kBuiltinObjectIdShaderPath = "builtin://shaders/object-id";
constexpr const char* kBuiltinSkyboxShaderPath = "builtin://shaders/skybox";
constexpr const char* kBuiltinDefaultPrimitiveTexturePath = "builtin://textures/default-primitive-albedo";
constexpr float kPi = 3.14159265358979323846f;
@@ -52,6 +53,8 @@ constexpr const char* kBuiltinShadowCasterShaderManifestRelativePath =
"engine/assets/builtin/shaders/shadow-caster/shadow-caster.shader";
constexpr const char* kBuiltinObjectIdShaderManifestRelativePath =
"engine/assets/builtin/shaders/object-id/object-id.shader";
constexpr const char* kBuiltinSkyboxShaderManifestRelativePath =
"engine/assets/builtin/shaders/skybox/skybox.shader";
Containers::String NormalizeBuiltinAssetPath(const std::filesystem::path& path) {
return Containers::String(path.lexically_normal().generic_string().c_str());
@@ -130,6 +133,9 @@ const char* GetBuiltinShaderManifestRelativePath(const Containers::String& built
if (builtinShaderPath == Containers::String(kBuiltinObjectIdShaderPath)) {
return kBuiltinObjectIdShaderManifestRelativePath;
}
if (builtinShaderPath == Containers::String(kBuiltinSkyboxShaderPath)) {
return kBuiltinSkyboxShaderManifestRelativePath;
}
return nullptr;
}
@@ -670,6 +676,10 @@ Shader* BuildBuiltinObjectIdShader(const Containers::String& path) {
return TryLoadBuiltinShaderFromManifest(path);
}
Shader* BuildBuiltinSkyboxShader(const Containers::String& path) {
return TryLoadBuiltinShaderFromManifest(path);
}
Material* BuildDefaultPrimitiveMaterial(const Containers::String& path) {
auto* material = new Material();
IResource::ConstructParams params;
@@ -788,6 +798,10 @@ Containers::String GetBuiltinObjectIdShaderPath() {
return Containers::String(kBuiltinObjectIdShaderPath);
}
Containers::String GetBuiltinSkyboxShaderPath() {
return Containers::String(kBuiltinSkyboxShaderPath);
}
Containers::String GetBuiltinDefaultPrimitiveTexturePath() {
return Containers::String(kBuiltinDefaultPrimitiveTexturePath);
}
@@ -886,6 +900,8 @@ LoadResult CreateBuiltinShaderResource(const Containers::String& path) {
shader = BuildBuiltinShadowCasterShader(path);
} else if (path == GetBuiltinObjectIdShaderPath()) {
shader = BuildBuiltinObjectIdShader(path);
} else if (path == GetBuiltinSkyboxShaderPath()) {
shader = BuildBuiltinSkyboxShader(path);
} else {
return LoadResult(Containers::String("Unknown builtin shader: ") + path);
}

View File

@@ -25,6 +25,10 @@ TEST(CameraComponent_Test, DefaultValues) {
EXPECT_FLOAT_EQ(camera.GetViewportRect().y, 0.0f);
EXPECT_FLOAT_EQ(camera.GetViewportRect().width, 1.0f);
EXPECT_FLOAT_EQ(camera.GetViewportRect().height, 1.0f);
EXPECT_FALSE(camera.IsSkyboxEnabled());
EXPECT_FLOAT_EQ(camera.GetSkyboxTopColor().r, 0.18f);
EXPECT_FLOAT_EQ(camera.GetSkyboxHorizonColor().g, 0.84f);
EXPECT_FLOAT_EQ(camera.GetSkyboxBottomColor().b, 0.95f);
}
TEST(CameraComponent_Test, SetterClamping) {
@@ -57,6 +61,10 @@ TEST(CameraComponent_Test, SerializeRoundTripPreservesViewportAndClearState) {
source.SetStackType(CameraStackType::Overlay);
source.SetCullingMask(0x0000000Fu);
source.SetViewportRect(XCEngine::Math::Rect(0.25f, 0.125f, 0.5f, 0.625f));
source.SetSkyboxEnabled(true);
source.SetSkyboxTopColor(XCEngine::Math::Color(0.12f, 0.21f, 0.64f, 1.0f));
source.SetSkyboxHorizonColor(XCEngine::Math::Color(0.71f, 0.76f, 0.88f, 1.0f));
source.SetSkyboxBottomColor(XCEngine::Math::Color(0.92f, 0.82f, 0.58f, 1.0f));
std::stringstream stream;
source.Serialize(stream);
@@ -71,6 +79,10 @@ TEST(CameraComponent_Test, SerializeRoundTripPreservesViewportAndClearState) {
EXPECT_FLOAT_EQ(target.GetViewportRect().y, 0.125f);
EXPECT_FLOAT_EQ(target.GetViewportRect().width, 0.5f);
EXPECT_FLOAT_EQ(target.GetViewportRect().height, 0.625f);
EXPECT_TRUE(target.IsSkyboxEnabled());
EXPECT_FLOAT_EQ(target.GetSkyboxTopColor().b, 0.64f);
EXPECT_FLOAT_EQ(target.GetSkyboxHorizonColor().g, 0.76f);
EXPECT_FLOAT_EQ(target.GetSkyboxBottomColor().r, 0.92f);
}
TEST(LightComponent_Test, DefaultValues) {

View File

@@ -24,6 +24,7 @@ add_custom_target(rendering_integration_tests
rendering_integration_depth_sort_scene
rendering_integration_material_state_scene
rendering_integration_offscreen_scene
rendering_integration_skybox_scene
)
add_custom_target(rendering_all_tests

View File

@@ -16,3 +16,4 @@ add_subdirectory(cull_material_scene)
add_subdirectory(depth_sort_scene)
add_subdirectory(material_state_scene)
add_subdirectory(offscreen_scene)
add_subdirectory(skybox_scene)

View File

@@ -0,0 +1,63 @@
cmake_minimum_required(VERSION 3.15)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
project(rendering_integration_skybox_scene)
set(ENGINE_ROOT_DIR ${CMAKE_SOURCE_DIR}/engine)
set(PACKAGE_DIR ${CMAKE_SOURCE_DIR}/mvs/OpenGL/package)
get_filename_component(PROJECT_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../.. ABSOLUTE)
find_package(Vulkan QUIET)
add_executable(rendering_integration_skybox_scene
main.cpp
${CMAKE_SOURCE_DIR}/tests/RHI/integration/fixtures/RHIIntegrationFixture.cpp
${PACKAGE_DIR}/src/glad.c
)
target_include_directories(rendering_integration_skybox_scene PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tests/RHI/integration/fixtures
${ENGINE_ROOT_DIR}/include
${PACKAGE_DIR}/include
${PROJECT_ROOT_DIR}/engine/src
)
target_link_libraries(rendering_integration_skybox_scene PRIVATE
d3d12
dxgi
d3dcompiler
winmm
opengl32
XCEngine
GTest::gtest
)
if(TARGET Vulkan::Vulkan)
target_link_libraries(rendering_integration_skybox_scene PRIVATE Vulkan::Vulkan)
target_compile_definitions(rendering_integration_skybox_scene PRIVATE XCENGINE_SUPPORT_VULKAN)
endif()
target_compile_definitions(rendering_integration_skybox_scene PRIVATE
UNICODE
_UNICODE
XCENGINE_SUPPORT_OPENGL
XCENGINE_SUPPORT_D3D12
)
add_custom_command(TARGET rendering_integration_skybox_scene POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_SOURCE_DIR}/tests/RHI/integration/compare_ppm.py
$<TARGET_FILE_DIR:rendering_integration_skybox_scene>/
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/GT.ppm
$<TARGET_FILE_DIR:rendering_integration_skybox_scene>/GT.ppm
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${ENGINE_ROOT_DIR}/third_party/renderdoc/renderdoc.dll
$<TARGET_FILE_DIR:rendering_integration_skybox_scene>/
)
include(GoogleTest)
gtest_discover_tests(rendering_integration_skybox_scene)

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,376 @@
#include <gtest/gtest.h>
#include "../RenderingIntegrationMain.h"
#include <XCEngine/Components/CameraComponent.h>
#include <XCEngine/Components/GameObject.h>
#include <XCEngine/Components/MeshFilterComponent.h>
#include <XCEngine/Components/MeshRendererComponent.h>
#include <XCEngine/Core/Asset/IResource.h>
#include <XCEngine/Core/Math/Color.h>
#include <XCEngine/Core/Math/Quaternion.h>
#include <XCEngine/Core/Math/Vector3.h>
#include <XCEngine/Core/Math/Vector4.h>
#include <XCEngine/Rendering/Execution/SceneRenderer.h>
#include <XCEngine/Rendering/RenderContext.h>
#include <XCEngine/Rendering/RenderSurface.h>
#include <XCEngine/Resources/BuiltinResources.h>
#include <XCEngine/Resources/Material/Material.h>
#include <XCEngine/Resources/Mesh/Mesh.h>
#include <XCEngine/RHI/RHITexture.h>
#include <XCEngine/Scene/Scene.h>
#include "../../../RHI/integration/fixtures/RHIIntegrationFixture.h"
#include <memory>
#include <vector>
using namespace XCEngine::Components;
using namespace XCEngine::Math;
using namespace XCEngine::Rendering;
using namespace XCEngine::Resources;
using namespace XCEngine::RHI;
using namespace XCEngine::RHI::Integration;
namespace {
constexpr const char* kD3D12Screenshot = "skybox_scene_d3d12.ppm";
constexpr const char* kOpenGLScreenshot = "skybox_scene_opengl.ppm";
constexpr const char* kVulkanScreenshot = "skybox_scene_vulkan.ppm";
constexpr uint32_t kFrameWidth = 1280;
constexpr uint32_t kFrameHeight = 720;
Mesh* CreateQuadMesh() {
auto* mesh = new Mesh();
IResource::ConstructParams params = {};
params.name = "SkyboxSceneQuad";
params.path = "Tests/Rendering/SkyboxScene/quad.mesh";
params.guid = ResourceGUID::Generate(params.path);
mesh->Initialize(params);
StaticMeshVertex vertices[4] = {};
vertices[0].position = Vector3(-1.0f, -1.0f, 0.0f);
vertices[0].normal = Vector3::Back();
vertices[0].uv0 = Vector2(0.0f, 1.0f);
vertices[1].position = Vector3(-1.0f, 1.0f, 0.0f);
vertices[1].normal = Vector3::Back();
vertices[1].uv0 = Vector2(0.0f, 0.0f);
vertices[2].position = Vector3(1.0f, -1.0f, 0.0f);
vertices[2].normal = Vector3::Back();
vertices[2].uv0 = Vector2(1.0f, 1.0f);
vertices[3].position = Vector3(1.0f, 1.0f, 0.0f);
vertices[3].normal = Vector3::Back();
vertices[3].uv0 = Vector2(1.0f, 0.0f);
const uint32_t indices[6] = { 0, 1, 2, 2, 1, 3 };
mesh->SetVertexData(
vertices,
sizeof(vertices),
4,
sizeof(StaticMeshVertex),
VertexAttribute::Position | VertexAttribute::Normal | VertexAttribute::UV0);
mesh->SetIndexData(indices, sizeof(indices), 6, true);
MeshSection section = {};
section.baseVertex = 0;
section.vertexCount = 4;
section.startIndex = 0;
section.indexCount = 6;
section.materialID = 0;
mesh->AddSection(section);
return mesh;
}
Material* CreateMaterial(
const char* name,
const char* path,
const Vector4& baseColor,
MaterialRenderQueue renderQueue,
const MaterialRenderState& renderState) {
auto* material = new Material();
IResource::ConstructParams params = {};
params.name = name;
params.path = path;
params.guid = ResourceGUID::Generate(params.path);
material->Initialize(params);
material->SetShader(ResourceManager::Get().Load<Shader>(GetBuiltinUnlitShaderPath()));
material->SetRenderQueue(renderQueue);
material->SetRenderState(renderState);
material->SetFloat4("_BaseColor", baseColor);
return material;
}
GameObject* CreateRenderableObject(
Scene& scene,
const char* name,
Mesh* mesh,
Material* material,
const Vector3& position,
const Vector3& scale,
const Quaternion& rotation = Quaternion::Identity()) {
GameObject* object = scene.CreateGameObject(name);
object->GetTransform()->SetLocalPosition(position);
object->GetTransform()->SetLocalScale(scale);
object->GetTransform()->SetLocalRotation(rotation);
auto* meshFilter = object->AddComponent<MeshFilterComponent>();
auto* meshRenderer = object->AddComponent<MeshRendererComponent>();
meshFilter->SetMesh(ResourceHandle<Mesh>(mesh));
meshRenderer->SetMaterial(0, ResourceHandle<Material>(material));
return object;
}
const char* GetScreenshotFilename(RHIType backendType) {
switch (backendType) {
case RHIType::D3D12:
return kD3D12Screenshot;
case RHIType::Vulkan:
return kVulkanScreenshot;
case RHIType::OpenGL:
default:
return kOpenGLScreenshot;
}
}
int GetComparisonThreshold(RHIType backendType) {
(void)backendType;
return 10;
}
class SkyboxSceneTest : public RHIIntegrationFixture {
protected:
void SetUp() override;
void TearDown() override;
void RenderFrame() override;
private:
void BuildScene();
RHIResourceView* GetCurrentBackBufferView();
std::unique_ptr<Scene> mScene;
std::unique_ptr<SceneRenderer> mSceneRenderer;
std::vector<RHIResourceView*> mBackBufferViews;
std::vector<Material*> mMaterials;
Mesh* mMesh = nullptr;
RHITexture* mDepthTexture = nullptr;
RHIResourceView* mDepthView = nullptr;
};
void SkyboxSceneTest::SetUp() {
RHIIntegrationFixture::SetUp();
mSceneRenderer = std::make_unique<SceneRenderer>();
mScene = std::make_unique<Scene>("SkyboxScene");
mMesh = CreateQuadMesh();
ASSERT_NE(mMesh, nullptr);
BuildScene();
TextureDesc depthDesc = {};
depthDesc.width = kFrameWidth;
depthDesc.height = kFrameHeight;
depthDesc.depth = 1;
depthDesc.mipLevels = 1;
depthDesc.arraySize = 1;
depthDesc.format = static_cast<uint32_t>(Format::D24_UNorm_S8_UInt);
depthDesc.textureType = static_cast<uint32_t>(XCEngine::RHI::TextureType::Texture2D);
depthDesc.sampleCount = 1;
depthDesc.sampleQuality = 0;
depthDesc.flags = 0;
mDepthTexture = GetDevice()->CreateTexture(depthDesc);
ASSERT_NE(mDepthTexture, nullptr);
ResourceViewDesc depthViewDesc = {};
depthViewDesc.format = static_cast<uint32_t>(Format::D24_UNorm_S8_UInt);
depthViewDesc.dimension = ResourceViewDimension::Texture2D;
depthViewDesc.mipLevel = 0;
mDepthView = GetDevice()->CreateDepthStencilView(mDepthTexture, depthViewDesc);
ASSERT_NE(mDepthView, nullptr);
mBackBufferViews.resize(2, nullptr);
}
void SkyboxSceneTest::TearDown() {
mSceneRenderer.reset();
if (mDepthView != nullptr) {
mDepthView->Shutdown();
delete mDepthView;
mDepthView = nullptr;
}
if (mDepthTexture != nullptr) {
mDepthTexture->Shutdown();
delete mDepthTexture;
mDepthTexture = nullptr;
}
for (RHIResourceView*& backBufferView : mBackBufferViews) {
if (backBufferView != nullptr) {
backBufferView->Shutdown();
delete backBufferView;
backBufferView = nullptr;
}
}
mBackBufferViews.clear();
mScene.reset();
for (Material* material : mMaterials) {
delete material;
}
mMaterials.clear();
delete mMesh;
mMesh = nullptr;
RHIIntegrationFixture::TearDown();
}
void SkyboxSceneTest::BuildScene() {
ASSERT_NE(mScene, nullptr);
GameObject* cameraObject = mScene->CreateGameObject("MainCamera");
auto* camera = cameraObject->AddComponent<CameraComponent>();
camera->SetPrimary(true);
camera->SetProjectionType(CameraProjectionType::Perspective);
camera->SetFieldOfView(46.0f);
camera->SetNearClipPlane(0.1f);
camera->SetFarClipPlane(20.0f);
camera->SetClearColor(XCEngine::Math::Color(0.01f, 0.01f, 0.01f, 1.0f));
camera->SetSkyboxEnabled(true);
camera->SetSkyboxTopColor(XCEngine::Math::Color(0.11f, 0.29f, 0.64f, 1.0f));
camera->SetSkyboxHorizonColor(XCEngine::Math::Color(0.82f, 0.87f, 0.96f, 1.0f));
camera->SetSkyboxBottomColor(XCEngine::Math::Color(0.96f, 0.93f, 0.86f, 1.0f));
MaterialRenderState opaqueState = {};
opaqueState.cullMode = MaterialCullMode::Back;
MaterialRenderState transparentState = {};
transparentState.blendEnable = true;
transparentState.srcBlend = MaterialBlendFactor::SrcAlpha;
transparentState.dstBlend = MaterialBlendFactor::InvSrcAlpha;
transparentState.srcBlendAlpha = MaterialBlendFactor::One;
transparentState.dstBlendAlpha = MaterialBlendFactor::Zero;
transparentState.depthTestEnable = true;
transparentState.depthWriteEnable = false;
transparentState.depthFunc = MaterialComparisonFunc::LessEqual;
transparentState.cullMode = MaterialCullMode::None;
Material* cubeMaterial = CreateMaterial(
"SkyboxOpaqueCubeMaterial",
"Tests/Rendering/SkyboxScene/opaque_cube.mat",
Vector4(0.86f, 0.18f, 0.14f, 1.0f),
MaterialRenderQueue::Geometry,
opaqueState);
Material* transparentMaterial = CreateMaterial(
"SkyboxTransparentQuadMaterial",
"Tests/Rendering/SkyboxScene/transparent_quad.mat",
Vector4(0.12f, 0.88f, 0.74f, 0.56f),
MaterialRenderQueue::Transparent,
transparentState);
mMaterials = { cubeMaterial, transparentMaterial };
CreateRenderableObject(
*mScene,
"OpaqueQuad",
mMesh,
cubeMaterial,
Vector3(-0.54f, -0.10f, 3.25f),
Vector3(1.20f, 1.20f, 1.0f),
Quaternion::FromEulerAngles(0.0f, -0.38f, 0.0f));
CreateRenderableObject(
*mScene,
"TransparentQuad",
mMesh,
transparentMaterial,
Vector3(0.82f, 0.06f, 4.1f),
Vector3(1.48f, 1.48f, 1.0f),
Quaternion::FromEulerAngles(0.0f, -0.34f, 0.0f));
}
RHIResourceView* SkyboxSceneTest::GetCurrentBackBufferView() {
const int backBufferIndex = GetCurrentBackBufferIndex();
if (backBufferIndex < 0) {
return nullptr;
}
if (static_cast<size_t>(backBufferIndex) >= mBackBufferViews.size()) {
mBackBufferViews.resize(static_cast<size_t>(backBufferIndex) + 1, nullptr);
}
if (mBackBufferViews[backBufferIndex] == nullptr) {
ResourceViewDesc viewDesc = {};
viewDesc.format = static_cast<uint32_t>(Format::R8G8B8A8_UNorm);
viewDesc.dimension = ResourceViewDimension::Texture2D;
viewDesc.mipLevel = 0;
mBackBufferViews[backBufferIndex] = GetDevice()->CreateRenderTargetView(GetCurrentBackBuffer(), viewDesc);
}
return mBackBufferViews[backBufferIndex];
}
void SkyboxSceneTest::RenderFrame() {
ASSERT_NE(mScene, nullptr);
ASSERT_NE(mSceneRenderer, nullptr);
RHICommandList* commandList = GetCommandList();
ASSERT_NE(commandList, nullptr);
commandList->Reset();
RenderSurface surface(kFrameWidth, kFrameHeight);
surface.SetColorAttachment(GetCurrentBackBufferView());
surface.SetDepthAttachment(mDepthView);
RenderContext renderContext = {};
renderContext.device = GetDevice();
renderContext.commandList = commandList;
renderContext.commandQueue = GetCommandQueue();
renderContext.backendType = GetBackendType();
ASSERT_TRUE(mSceneRenderer->Render(*mScene, nullptr, renderContext, surface));
commandList->Close();
void* commandLists[] = { commandList };
GetCommandQueue()->ExecuteCommandLists(1, commandLists);
}
TEST_P(SkyboxSceneTest, RenderSkyboxScene) {
RHICommandQueue* commandQueue = GetCommandQueue();
RHISwapChain* swapChain = GetSwapChain();
const int targetFrameCount = 30;
const char* screenshotFilename = GetScreenshotFilename(GetBackendType());
const int comparisonThreshold = GetComparisonThreshold(GetBackendType());
for (int frameCount = 0; frameCount <= targetFrameCount; ++frameCount) {
if (frameCount > 0) {
commandQueue->WaitForPreviousFrame();
}
BeginRender();
RenderFrame();
if (frameCount >= targetFrameCount) {
commandQueue->WaitForIdle();
ASSERT_TRUE(TakeScreenshot(screenshotFilename));
ASSERT_TRUE(CompareWithGoldenTemplate(screenshotFilename, "GT.ppm", static_cast<float>(comparisonThreshold)));
break;
}
swapChain->Present(0, 0);
}
}
} // namespace
INSTANTIATE_TEST_SUITE_P(D3D12, SkyboxSceneTest, ::testing::Values(RHIType::D3D12));
INSTANTIATE_TEST_SUITE_P(OpenGL, SkyboxSceneTest, ::testing::Values(RHIType::OpenGL));
#if defined(XCENGINE_SUPPORT_VULKAN)
INSTANTIATE_TEST_SUITE_P(Vulkan, SkyboxSceneTest, ::testing::Values(RHIType::Vulkan));
#endif
GTEST_API_ int main(int argc, char** argv) {
return RunRenderingIntegrationTestMain(argc, argv);
}

View File

@@ -145,6 +145,27 @@ TEST(BuiltinForwardPipeline_Test, BuiltinUnlitShaderDeclaresExplicitSurfaceResou
delete shader;
}
TEST(BuiltinForwardPipeline_Test, BuiltinSkyboxShaderDeclaresExplicitEnvironmentResourceContract) {
ShaderLoader loader;
LoadResult result = loader.Load(GetBuiltinSkyboxShaderPath());
ASSERT_TRUE(result);
ASSERT_NE(result.resource, nullptr);
Shader* shader = static_cast<Shader*>(result.resource);
ASSERT_NE(shader, nullptr);
const ShaderPass* pass = shader->FindPass("Skybox");
ASSERT_NE(pass, nullptr);
ASSERT_EQ(pass->resources.Size(), 1u);
EXPECT_EQ(pass->resources[0].semantic, "Environment");
EXPECT_EQ(pass->resources[0].type, ShaderResourceType::ConstantBuffer);
EXPECT_EQ(pass->resources[0].set, 0u);
EXPECT_EQ(pass->resources[0].binding, 0u);
delete shader;
}
TEST(BuiltinForwardPipeline_Test, BuildsBuiltinPassResourceBindingPlanFromExplicitForwardResources) {
ShaderLoader loader;
LoadResult result = loader.Load(GetBuiltinForwardLitShaderPath());

View File

@@ -159,10 +159,18 @@ TEST_F(RenderSceneUtilityTest, BuildRenderCameraDataMatchesCameraTransformConven
EXPECT_EQ(cameraData.viewportWidth, 1280u);
EXPECT_EQ(cameraData.viewportHeight, 720u);
EXPECT_EQ(cameraData.worldPosition, cameraObject->GetTransform()->GetPosition());
EXPECT_EQ(cameraData.worldRight, cameraObject->GetTransform()->GetRight());
EXPECT_EQ(cameraData.worldUp, cameraObject->GetTransform()->GetUp());
EXPECT_EQ(cameraData.worldForward, cameraObject->GetTransform()->GetForward());
EXPECT_FLOAT_EQ(cameraData.clearColor.r, camera->GetClearColor().r);
EXPECT_FLOAT_EQ(cameraData.clearColor.g, camera->GetClearColor().g);
EXPECT_FLOAT_EQ(cameraData.clearColor.b, camera->GetClearColor().b);
EXPECT_FLOAT_EQ(cameraData.clearColor.a, camera->GetClearColor().a);
EXPECT_TRUE(cameraData.perspectiveProjection);
EXPECT_FLOAT_EQ(cameraData.verticalFovRadians, 53.0f * XCEngine::Math::DEG_TO_RAD);
EXPECT_FLOAT_EQ(cameraData.aspectRatio, 1280.0f / 720.0f);
EXPECT_FLOAT_EQ(cameraData.nearClipPlane, 0.03f);
EXPECT_FLOAT_EQ(cameraData.farClipPlane, 1500.0f);
}
TEST_F(RenderSceneUtilityTest, CollectRenderItemsForEntityIdsFiltersInvalidTargets) {