feat: 添加独立的输入系统和平台抽象层

- 新增 Platform 模块:PlatformTypes.h, Window.h, WindowsWindow
- 新增 Input 模块:InputTypes, InputEvent, InputAxis, InputModule, InputManager
- 新增 WindowsInputModule 处理 Win32 消息转换
- 将 RHI 集成测试从 render_model 迁移到 sphere
- 更新 CMakeLists.txt 添加 Platform 和 Input 模块
This commit is contained in:
2026-03-22 15:21:52 +08:00
parent 6af872e9eb
commit 36d3decef6
29 changed files with 2896 additions and 236 deletions

View File

@@ -9,4 +9,4 @@ enable_testing()
add_subdirectory(minimal)
add_subdirectory(triangle)
add_subdirectory(quad)
add_subdirectory(render_model)
add_subdirectory(sphere)

View File

@@ -2,27 +2,27 @@ cmake_minimum_required(VERSION 3.15)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
project(D3D12_RenderModel)
project(D3D12_Sphere)
set(ENGINE_ROOT_DIR ${CMAKE_SOURCE_DIR}/engine)
add_executable(D3D12_RenderModel
add_executable(D3D12_Sphere
WIN32
main.cpp
)
target_include_directories(D3D12_RenderModel PRIVATE
target_include_directories(D3D12_Sphere PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${ENGINE_ROOT_DIR}/include
${ENGINE_ROOT_DIR}
)
target_compile_definitions(D3D12_RenderModel PRIVATE
target_compile_definitions(D3D12_Sphere PRIVATE
UNICODE
_UNICODE
)
target_link_libraries(D3D12_RenderModel PRIVATE
target_link_libraries(D3D12_Sphere PRIVATE
d3d12
dxgi
d3dcompiler
@@ -30,26 +30,26 @@ target_link_libraries(D3D12_RenderModel PRIVATE
XCEngine
)
add_custom_command(TARGET D3D12_RenderModel POST_BUILD
add_custom_command(TARGET D3D12_Sphere POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_CURRENT_SOURCE_DIR}/Res
$<TARGET_FILE_DIR:D3D12_RenderModel>/Res
$<TARGET_FILE_DIR:D3D12_Sphere>/Res
)
add_custom_command(TARGET D3D12_RenderModel POST_BUILD
add_custom_command(TARGET D3D12_Sphere POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_SOURCE_DIR}/tests/RHI/D3D12/integration/compare_ppm.py
$<TARGET_FILE_DIR:D3D12_RenderModel>/
$<TARGET_FILE_DIR:D3D12_Sphere>/
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_SOURCE_DIR}/tests/RHI/D3D12/integration/run_integration_test.py
$<TARGET_FILE_DIR:D3D12_RenderModel>/
$<TARGET_FILE_DIR:D3D12_Sphere>/
)
add_test(NAME D3D12_RenderModel_Integration
COMMAND ${Python3_EXECUTABLE} $<TARGET_FILE_DIR:D3D12_RenderModel>/run_integration_test.py
$<TARGET_FILE:D3D12_RenderModel>
add_test(NAME D3D12_Sphere_Integration
COMMAND ${Python3_EXECUTABLE} $<TARGET_FILE_DIR:D3D12_Sphere>/run_integration_test.py
$<TARGET_FILE:D3D12_Sphere>
screenshot.ppm
${CMAKE_CURRENT_SOURCE_DIR}/GT.ppm
5
WORKING_DIRECTORY $<TARGET_FILE_DIR:D3D12_RenderModel>
WORKING_DIRECTORY $<TARGET_FILE_DIR:D3D12_Sphere>
)

Binary file not shown.

View File

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

View File

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

View File

@@ -0,0 +1,24 @@
struct Vertex {
float4 pos : POSITION;
float4 texcoord : TEXCOORD0;
};
struct VSOut {
float4 pos : SV_POSITION;
float4 texcoord : TEXCOORD0;
};
cbuffer MatrixBuffer : register(b0) {
float4x4 gMVP;
};
VSOut MainVS(Vertex v) {
VSOut o;
o.pos = mul(gMVP, v.pos);
o.texcoord = v.texcoord;
return o;
}
float4 MainPS(VSOut i) : SV_TARGET {
return float4(1.0f, 0.0f, 0.0f, 1.0f);
}

View File

@@ -0,0 +1,23 @@
struct Vertex {
float4 pos : POSITION;
float4 texcoord : TEXCOORD0;
};
struct VSOut {
float4 pos : SV_POSITION;
float4 texcoord : TEXCOORD0;
};
VSOut MainVS(Vertex v) {
VSOut o;
o.pos = v.pos;
o.texcoord = v.texcoord;
return o;
}
Texture2D T_DiffuseTexture : register(t0);
SamplerState samplerState : register(s0);
float4 MainPS(VSOut i) : SV_TARGET {
return T_DiffuseTexture.Sample(samplerState, i.texcoord.xy);
}

View File

@@ -6,7 +6,6 @@
#include <math.h>
#include <stdarg.h>
#include <string>
#include <fstream>
#include <vector>
#include "XCEngine/RHI/RHIEnums.h"
@@ -23,8 +22,8 @@
#include "XCEngine/RHI/D3D12/D3D12RenderTargetView.h"
#include "XCEngine/RHI/D3D12/D3D12DepthStencilView.h"
#include "XCEngine/RHI/D3D12/D3D12Shader.h"
#include "XCEngine/RHI/D3D12/D3D12PipelineState.h"
#include "XCEngine/RHI/D3D12/D3D12RootSignature.h"
#include "XCEngine/RHI/D3D12/D3D12PipelineState.h"
#include "XCEngine/RHI/D3D12/D3D12ShaderResourceView.h"
#include "XCEngine/RHI/D3D12/D3D12Screenshot.h"
#include "XCEngine/Debug/Logger.h"
@@ -43,57 +42,45 @@ using namespace XCEngine::Containers;
#pragma comment(lib,"d3dcompiler.lib")
#pragma comment(lib,"winmm.lib")
// Global D3D12 objects
D3D12Device gDevice;
D3D12CommandQueue gCommandQueue;
D3D12SwapChain gSwapChain;
D3D12CommandAllocator gCommandAllocator;
D3D12CommandList gCommandList;
D3D12Fence gFence;
// Render targets
D3D12Texture gColorRTs[2];
D3D12Texture gDepthStencil;
D3D12DescriptorHeap gRTVHeap;
D3D12DescriptorHeap gDSVHeap;
D3D12DescriptorHeap gSRVHeap;
D3D12RenderTargetView gRTVs[2];
D3D12DepthStencilView gDSV;
// Pipeline objects
D3D12Shader gVertexShader;
D3D12Shader gGeometryShader;
D3D12Shader gPixelShader;
D3D12RootSignature gRootSignature;
D3D12PipelineState gPipelineState;
// Model data
D3D12Buffer gVertexBuffer;
D3D12Buffer gIndexBuffer;
UINT gIndexCount = 0;
// Texture
D3D12Buffer gMVPBuffer;
D3D12Texture gDiffuseTexture;
D3D12DescriptorHeap gSRVHeap;
D3D12ShaderResourceView gDiffuseSRV;
// Matrices
float gProjectionMatrix[16];
float gViewMatrix[16];
float gModelMatrix[16];
float gIT_ModelMatrix[16];
// Descriptor sizes
UINT gRTVDescriptorSize = 0;
UINT gDSVDescriptorSize = 0;
int gCurrentRTIndex = 0;
UINT64 gFenceValue = 0;
// Window
UINT gIndexCount = 0;
float gProjectionMatrix[16];
float gViewMatrix[16];
float gModelMatrix[16];
float gMVPMatrix[16];
float gTempMatrix[16];
float gTransposedMatrix[16];
HWND gHWND = nullptr;
int gWidth = 1280;
int gHeight = 720;
// Log helper
void Log(const char* format, ...) {
char buffer[1024];
va_list args;
@@ -103,7 +90,6 @@ void Log(const char* format, ...) {
Logger::Get().Debug(LogCategory::Rendering, String(buffer));
}
// Window procedure
LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_CLOSE:
@@ -113,7 +99,6 @@ LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
return DefWindowProc(hwnd, msg, wParam, lParam);
}
// Matrix utilities
void IdentityMatrix(float* m) {
memset(m, 0, 16 * sizeof(float));
m[0] = m[5] = m[10] = m[15] = 1.0f;
@@ -153,12 +138,15 @@ void LookAtMatrix(float* m, const float* eye, const float* target, const float*
m[15] = 1.0f;
}
void RotationYMatrix(float* m, float angle) {
IdentityMatrix(m);
float c = cosf(angle);
float s = sinf(angle);
m[0] = c; m[2] = s;
m[8] = -s; m[10] = c;
void MultiplyMatrix(float* dst, const float* a, const float* b) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
dst[i * 4 + j] = 0;
for (int k = 0; k < 4; k++) {
dst[i * 4 + j] += a[i * 4 + k] * b[k * 4 + j];
}
}
}
}
void TransposeMatrix(float* dst, const float* src) {
@@ -169,28 +157,15 @@ void TransposeMatrix(float* dst, const float* src) {
}
}
void InvertMatrix(float* dst, const float* src) {
// Simplified inverse for orthogonal matrices
memcpy(dst, src, 16 * sizeof(float));
// For rotation matrices, inverse = transpose
float tmp[16];
TransposeMatrix(tmp, src);
memcpy(dst, tmp, 16 * sizeof(float));
}
// Simple sphere generation
struct Vertex {
float position[4];
float pos[4];
float texcoord[4];
float normal[4];
float tangent[4];
};
void GenerateSphere(std::vector<Vertex>& vertices, std::vector<UINT16>& indices, float radius, int segments) {
void GenerateSphere(std::vector<Vertex>& vertices, std::vector<UINT32>& indices, float radius, int segments) {
vertices.clear();
indices.clear();
// Generate vertices
for (int lat = 0; lat <= segments; lat++) {
float theta = lat * 3.14159f / segments;
float sinTheta = sinf(theta);
@@ -202,31 +177,20 @@ void GenerateSphere(std::vector<Vertex>& vertices, std::vector<UINT16>& indices,
float cosPhi = cosf(phi);
Vertex v;
v.position[0] = radius * sinTheta * cosPhi;
v.position[1] = radius * cosTheta;
v.position[2] = radius * sinTheta * sinPhi;
v.position[3] = 1.0f;
v.pos[0] = radius * sinTheta * cosPhi;
v.pos[1] = radius * cosTheta;
v.pos[2] = radius * sinTheta * sinPhi;
v.pos[3] = 1.0f;
v.texcoord[0] = (float)lon / segments;
v.texcoord[1] = (float)lat / segments;
v.texcoord[2] = 0.0f;
v.texcoord[3] = 0.0f;
v.normal[0] = sinTheta * cosPhi;
v.normal[1] = cosTheta;
v.normal[2] = sinTheta * sinPhi;
v.normal[3] = 0.0f;
v.tangent[0] = -sinPhi;
v.tangent[1] = 0.0f;
v.tangent[2] = cosPhi;
v.tangent[3] = 0.0f;
vertices.push_back(v);
}
}
// Generate indices
for (int lat = 0; lat < segments; lat++) {
for (int lon = 0; lon < segments; lon++) {
int first = lat * (segments + 1) + lon;
@@ -243,8 +207,7 @@ void GenerateSphere(std::vector<Vertex>& vertices, std::vector<UINT16>& indices,
}
}
// Load texture
bool LoadTexture(const char* filename, D3D12Texture& texture, D3D12ShaderResourceView& srv, ID3D12Device* device, D3D12DescriptorHeap& srvHeap) {
bool LoadTexture(const char* filename, D3D12Texture& texture, D3D12ShaderResourceView& srv, ID3D12Device* device, D3D12DescriptorHeap& srvHeap, ID3D12GraphicsCommandList* commandList, D3D12CommandAllocator& allocator, D3D12CommandQueue& queue) {
int width, height, channels;
stbi_uc* pixels = stbi_load(filename, &width, &height, &channels, STBI_rgb_alpha);
if (!pixels) {
@@ -252,29 +215,30 @@ bool LoadTexture(const char* filename, D3D12Texture& texture, D3D12ShaderResourc
return false;
}
Log("[INFO] Loaded texture %s: %dx%d", filename, width, height);
allocator.Reset();
commandList->Reset(allocator.GetCommandAllocator(), nullptr);
// Create texture using InitializeFromData
if (!texture.InitializeFromData(device, nullptr, pixels, width, height, DXGI_FORMAT_R8G8B8A8_UNORM)) {
if (!texture.InitializeFromData(device, commandList, pixels, width, height, DXGI_FORMAT_R8G8B8A8_UNORM)) {
Log("[ERROR] Failed to initialize texture");
stbi_image_free(pixels);
return false;
}
texture.SetName(filename);
stbi_image_free(pixels);
commandList->Close();
ID3D12CommandList* lists[] = { commandList };
queue.ExecuteCommandListsInternal(1, lists);
queue.WaitForIdle();
// Create SRV
srvHeap.Initialize(device, DescriptorHeapType::CBV_SRV_UAV, 1);
texture.SetName(filename);
srvHeap.Initialize(device, DescriptorHeapType::CBV_SRV_UAV, 1, true);
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = D3D12ShaderResourceView::CreateDesc(Format::R8G8B8A8_UNorm, D3D12_SRV_DIMENSION_TEXTURE2D);
srv.InitializeAt(device, texture.GetResource(), srvHeap.GetCPUDescriptorHandleForHeapStart(), &srvDesc);
return true;
}
// Initialize D3D12
bool InitD3D12() {
// Create device
RHIDeviceDesc deviceDesc;
deviceDesc.windowHandle = gHWND;
deviceDesc.width = gWidth;
@@ -291,238 +255,250 @@ bool InitD3D12() {
ID3D12Device* device = gDevice.GetDevice();
IDXGIFactory4* factory = gDevice.GetFactory();
// Create command queue
if (!gCommandQueue.Initialize(device, CommandQueueType::Direct)) {
Log("[ERROR] Failed to initialize command queue");
return false;
}
// Create swap chain
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferCount = 2;
swapChainDesc.BufferDesc.Width = gWidth;
swapChainDesc.BufferDesc.Height = gHeight;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = gHWND;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.Windowed = true;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
IDXGISwapChain* dxgiSwapChain = nullptr;
HRESULT hr = factory->CreateSwapChain(gCommandQueue.GetCommandQueue(), &swapChainDesc, &dxgiSwapChain);
if (FAILED(hr)) {
Log("[ERROR] Failed to create swap chain");
return false;
}
if (!gSwapChain.Initialize(dxgiSwapChain, (uint32_t)gWidth, (uint32_t)gHeight)) {
if (!gSwapChain.Initialize(factory, gCommandQueue.GetCommandQueue(), gHWND, gWidth, gHeight, 2)) {
Log("[ERROR] Failed to initialize swap chain");
return false;
}
// Initialize depth stencil
gDepthStencil.InitializeDepthStencil(device, gWidth, gHeight);
// Create RTV heap
gRTVHeap.Initialize(device, DescriptorHeapType::RTV, 2);
gRTVDescriptorSize = gDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType::RTV);
// Create DSV heap
gDSVHeap.Initialize(device, DescriptorHeapType::DSV, 1);
gDSVDescriptorSize = gDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType::DSV);
// Create RTVs for back buffers
D3D12_CPU_DESCRIPTOR_HANDLE rtvHeapStart = gRTVHeap.GetCPUDescriptorHandleForHeapStart();
for (int i = 0; i < 2; i++) {
ID3D12Resource* buffer = nullptr;
gSwapChain.GetSwapChain()->GetBuffer(i, IID_PPV_ARGS(&buffer));
gColorRTs[i].InitializeFromExisting(buffer);
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle;
rtvHandle.ptr = rtvHeapStart.ptr + i * gRTVDescriptorSize;
gRTVs[i].InitializeAt(device, gColorRTs[i].GetResource(), rtvHandle, nullptr);
D3D12Texture& backBuffer = gSwapChain.GetBackBuffer(i);
CPUDescriptorHandle rtvCpuHandle = gRTVHeap.GetCPUDescriptorHandle(i);
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = { rtvCpuHandle.ptr };
gRTVs[i].InitializeAt(device, backBuffer.GetResource(), rtvHandle, nullptr);
}
// Create DSV
D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = D3D12DepthStencilView::CreateDesc(Format::D24_UNorm_S8_UInt);
gDSV.InitializeAt(device, gDepthStencil.GetResource(), gDSVHeap.GetCPUDescriptorHandleForHeapStart(), &dsvDesc);
CPUDescriptorHandle dsvCpuHandle = gDSVHeap.GetCPUDescriptorHandle(0);
D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = { dsvCpuHandle.ptr };
gDSV.InitializeAt(device, gDepthStencil.GetResource(), dsvHandle, &dsvDesc);
// Create command allocator and list
gCommandAllocator.Initialize(device, CommandQueueType::Direct);
gCommandList.Initialize(device, CommandQueueType::Direct, gCommandAllocator.GetCommandAllocator());
// Create fence
gFence.Initialize(device, 0);
if (!gVertexShader.CompileFromFile(L"Res/Shader/sphere.hlsl", "MainVS", "vs_5_1")) {
Log("[ERROR] Failed to compile vertex shader");
return false;
}
Log("[INFO] Vertex shader compiled, bytecode size: %zu", gVertexShader.GetBytecodeSize());
Log("[INFO] D3D12 initialized successfully");
return true;
}
if (!gPixelShader.CompileFromFile(L"Res/Shader/sphere.hlsl", "MainPS", "ps_5_1")) {
Log("[ERROR] Failed to compile pixel shader");
return false;
}
Log("[INFO] Pixel shader compiled, bytecode size: %zu", gPixelShader.GetBytecodeSize());
// Initialize rendering resources
bool InitRendering() {
Log("[INFO] InitRendering: Starting...");
ID3D12Device* device = gDevice.GetDevice();
Log("[INFO] InitRendering: Got device");
D3D12_DESCRIPTOR_RANGE descriptorRange = D3D12RootSignature::CreateDescriptorRange(
D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 1, 0);
D3D12_ROOT_PARAMETER rootParameters[2];
rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
rootParameters[0].Descriptor.ShaderRegister = 0;
rootParameters[0].Descriptor.RegisterSpace = 0;
rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
rootParameters[1].DescriptorTable.NumDescriptorRanges = 1;
rootParameters[1].DescriptorTable.pDescriptorRanges = &descriptorRange;
D3D12_STATIC_SAMPLER_DESC samplerDesc = D3D12RootSignature::CreateStaticSampler(
0,
D3D12RootSignature::CreateSamplerDesc(
FilterMode::Linear,
TextureAddressMode::Clamp,
D3D12_FLOAT32_MAX
),
ShaderVisibility::Pixel
);
D3D12_ROOT_SIGNATURE_DESC rsDesc = D3D12RootSignature::CreateDesc(
rootParameters, 2,
&samplerDesc, 1,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT
);
if (!gRootSignature.Initialize(device, rsDesc)) {
Log("[ERROR] Failed to initialize root signature");
return false;
}
D3D12_INPUT_ELEMENT_DESC inputElements[] = {
D3D12PipelineState::CreateInputElement("POSITION", 0, Format::R32G32B32A32_Float, 0, 0),
D3D12PipelineState::CreateInputElement("TEXCOORD", 0, Format::R32G32B32A32_Float, 0, 16),
};
D3D12_SHADER_BYTECODE emptyGs = {};
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.pRootSignature = gRootSignature.GetRootSignature();
psoDesc.VS = gVertexShader.GetD3D12Bytecode();
psoDesc.PS = gPixelShader.GetD3D12Bytecode();
psoDesc.GS = emptyGs;
psoDesc.InputLayout.NumElements = 2;
psoDesc.InputLayout.pInputElementDescs = inputElements;
psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
psoDesc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
psoDesc.SampleDesc.Count = 1;
psoDesc.SampleDesc.Quality = 0;
psoDesc.SampleMask = 0xffffffff;
psoDesc.NumRenderTargets = 1;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
psoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
psoDesc.RasterizerState.FrontCounterClockwise = FALSE;
psoDesc.RasterizerState.DepthClipEnable = TRUE;
psoDesc.DepthStencilState.DepthEnable = FALSE;
psoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
psoDesc.BlendState.RenderTarget[0].BlendEnable = FALSE;
psoDesc.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_ONE;
psoDesc.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_ZERO;
psoDesc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
psoDesc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
psoDesc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO;
psoDesc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
psoDesc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
if (!gPipelineState.Initialize(device, psoDesc)) {
Log("[ERROR] Failed to initialize pipeline state");
return false;
}
// Generate sphere geometry
Log("[INFO] Generating sphere geometry...");
std::vector<Vertex> vertices;
std::vector<UINT16> indices;
std::vector<UINT32> indices;
GenerateSphere(vertices, indices, 1.0f, 32);
gIndexCount = (UINT)indices.size();
Log("[INFO] Generated %d vertices, %d indices", vertices.size(), indices.size());
// Create vertex buffer
gVertexBuffer.Initialize(device, CommandQueueType::Direct,
vertices.data(), (UINT)(sizeof(Vertex) * vertices.size()),
ResourceStates::VertexAndConstantBuffer);
gVertexBuffer.SetName("VertexBuffer");
// Create index buffer
gIndexBuffer.Initialize(device, CommandQueueType::Direct,
indices.data(), (UINT)(sizeof(UINT16) * indices.size()),
ResourceStates::IndexBuffer);
gIndexBuffer.SetName("IndexBuffer");
// Load texture
Log("[INFO] Loading texture...");
if (!LoadTexture("Res/Image/earth_d.jpg", gDiffuseTexture, gDiffuseSRV, device, gSRVHeap)) {
Log("[WARN] Failed to load texture, continuing without it");
if (!gVertexBuffer.InitializeWithData(device, gCommandList.GetCommandList(), vertices.data(), (UINT)(sizeof(Vertex) * vertices.size()), D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)) {
Log("[ERROR] Failed to initialize vertex buffer");
return false;
}
gVertexBuffer.SetStride(sizeof(Vertex));
gVertexBuffer.SetBufferType(BufferType::Vertex);
// Skip shader compilation for debug
Log("[INFO] Skipping shader compilation for debug");
Log("[INFO] Skipping root signature for debug");
Log("[INFO] Skipping pipeline state for debug");
if (!gIndexBuffer.InitializeWithData(device, gCommandList.GetCommandList(), indices.data(), (UINT)(sizeof(UINT32) * indices.size()), D3D12_RESOURCE_STATE_INDEX_BUFFER)) {
Log("[ERROR] Failed to initialize index buffer");
return false;
}
gIndexBuffer.SetBufferType(BufferType::Index);
// Initialize matrices
PerspectiveMatrix(gProjectionMatrix, 45.0f * 3.14159f / 180.0f, (float)gWidth / (float)gHeight, 0.1f, 100.0f);
float eye[3] = { 0.0f, 0.0f, 5.0f };
float eye[3] = { 0.0f, 0.0f, 3.0f };
float target[3] = { 0.0f, 0.0f, 0.0f };
float up[3] = { 0.0f, 1.0f, 0.0f };
LookAtMatrix(gViewMatrix, eye, target, up);
IdentityMatrix(gModelMatrix);
InvertMatrix(gIT_ModelMatrix, gModelMatrix);
MultiplyMatrix(gTempMatrix, gViewMatrix, gModelMatrix);
MultiplyMatrix(gMVPMatrix, gProjectionMatrix, gTempMatrix);
TransposeMatrix(gTransposedMatrix, gMVPMatrix);
Log("[INFO] Rendering resources initialized");
gMVPBuffer.InitializeWithData(device, gCommandList.GetCommandList(), gTransposedMatrix, sizeof(gTransposedMatrix), D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
if (!LoadTexture("Res/Image/earth.png", gDiffuseTexture, gDiffuseSRV, device, gSRVHeap, gCommandList.GetCommandList(), gCommandAllocator, gCommandQueue)) {
Log("[ERROR] Failed to load texture");
return false;
}
Log("[INFO] D3D12 initialized successfully");
return true;
}
// Wait for GPU
void WaitForGPU() {
gCommandQueue.WaitForIdle();
}
// Execute command list
void ExecuteCommandList() {
gCommandList.Close();
void* commandLists[] = { gCommandList.GetCommandList() };
gCommandQueue.ExecuteCommandLists(1, commandLists);
gFenceValue += 1;
}
// Begin rendering
void BeginRender() {
gCurrentRTIndex = gSwapChain.GetCurrentBackBufferIndex();
// Transition render target
gCommandList.TransitionBarrier(gColorRTs[gCurrentRTIndex].GetResource(),
D3D12Texture& currentBackBuffer = gSwapChain.GetBackBuffer(gCurrentRTIndex);
gCommandList.TransitionBarrier(currentBackBuffer.GetResource(),
ResourceStates::Present, ResourceStates::RenderTarget);
// Set render targets
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle;
rtvHandle.ptr = gRTVHeap.GetCPUDescriptorHandleForHeapStart().ptr + gCurrentRTIndex * gRTVDescriptorSize;
D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = gDSVHeap.GetCPUDescriptorHandleForHeapStart();
CPUDescriptorHandle rtvCpuHandle = gRTVHeap.GetCPUDescriptorHandle(gCurrentRTIndex);
CPUDescriptorHandle dsvCpuHandle = gDSVHeap.GetCPUDescriptorHandle(0);
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = { rtvCpuHandle.ptr };
D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = { dsvCpuHandle.ptr };
gCommandList.SetRenderTargetsHandle(1, &rtvHandle, &dsvHandle);
// Set viewport and scissor
Viewport viewport = { 0.0f, 0.0f, (float)gWidth, (float)gHeight, 0.0f, 1.0f };
Rect scissorRect = { 0, 0, gWidth, gHeight };
gCommandList.SetViewport(viewport);
gCommandList.SetScissorRect(scissorRect);
// Clear
float clearColor[] = { 0.1f, 0.1f, 0.2f, 1.0f };
float clearColor[] = { 0.0f, 0.0f, 1.0f, 1.0f };
gCommandList.ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr);
gCommandList.ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
}
// Render scene
void RenderScene() {
// Simplified rendering - just like minimal test
// (Add actual rendering code later once basic test passes)
}
// End rendering
void EndRender() {
gCommandList.TransitionBarrier(gColorRTs[gCurrentRTIndex].GetResource(),
D3D12Texture& currentBackBuffer = gSwapChain.GetBackBuffer(gCurrentRTIndex);
gCommandList.TransitionBarrier(currentBackBuffer.GetResource(),
ResourceStates::RenderTarget, ResourceStates::Present);
}
// Take screenshot
void TakeScreenshot() {
ID3D12Resource* backBuffer = gColorRTs[gCurrentRTIndex].GetResource();
D3D12Screenshot::Capture(gDevice.GetDevice(), &gCommandQueue, backBuffer, "screenshot.ppm", gWidth, gHeight);
Log("[INFO] Screenshot saved to screenshot.ppm");
}
// Main entry
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
// Initialize logger
Logger::Get().Initialize();
Logger::Get().AddSink(std::make_unique<ConsoleLogSink>());
Logger::Get().SetMinimumLevel(LogLevel::Debug);
Log("[INFO] D3D12 Render Model Test Starting");
Log("[INFO] D3D12 Sphere Test Starting");
// Register window class
WNDCLASSEX wc = {};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = L"D3D12Test";
wc.lpszClassName = L"D3D12SphereTest";
if (!RegisterClassEx(&wc)) {
MessageBox(NULL, L"Failed to register window class", L"Error", MB_OK);
Log("[ERROR] Failed to register window class");
return -1;
}
// Create window
RECT rect = { 0, 0, gWidth, gHeight };
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
gHWND = CreateWindowEx(0, L"D3D12Test", L"D3D12 Render Model Test",
gHWND = CreateWindowEx(0, L"D3D12SphereTest", L"D3D12 Sphere Test",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
rect.right - rect.left, rect.bottom - rect.top,
NULL, NULL, hInstance, NULL);
if (!gHWND) {
MessageBox(NULL, L"Failed to create window", L"Error", MB_OK);
Log("[ERROR] Failed to create window");
return -1;
}
// Initialize D3D12
if (!InitD3D12()) {
MessageBox(NULL, L"Failed to initialize D3D12", L"Error", MB_OK);
Log("[ERROR] Failed to initialize D3D12");
return -1;
}
// Initialize rendering resources
if (!InitRendering()) {
MessageBox(NULL, L"Failed to initialize rendering", L"Error", MB_OK);
return -1;
}
// Show window
ShowWindow(gHWND, nShowCmd);
UpdateWindow(gHWND);
// Main loop
MSG msg = {};
int frameCount = 0;
const int targetFrameCount = 30;
@@ -535,54 +511,62 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
// Reset command list for this frame
if (frameCount > 0) {
gCommandQueue.WaitForPreviousFrame();
}
gCommandAllocator.Reset();
gCommandList.Reset();
// Render
BeginRender();
RenderScene();
EndRender();
// Execute
ExecuteCommandList();
gCommandList.SetRootSignature(gRootSignature.GetRootSignature());
gCommandList.SetPipelineState(gPipelineState.GetPipelineState());
// Present
gSwapChain.Present(0, 0);
ID3D12DescriptorHeap* heaps[] = { gSRVHeap.GetDescriptorHeap() };
gCommandList.SetDescriptorHeaps(1, heaps);
gCommandList.SetGraphicsRootConstantBufferView(0, gMVPBuffer.GetResource()->GetGPUVirtualAddress());
gCommandList.SetGraphicsRootDescriptorTable(1, gSRVHeap.GetGPUDescriptorHandleForHeapStart());
gCommandList.SetPrimitiveTopology(PrimitiveTopology::TriangleList);
gCommandList.SetVertexBuffer(0, gVertexBuffer.GetResource(), 0, gVertexBuffer.GetStride());
gCommandList.SetIndexBuffer(gIndexBuffer.GetResource(), 0, Format::R32_UInt);
Log("[DEBUG] DrawIndexed with %d indices", gIndexCount);
gCommandList.DrawIndexed(gIndexCount, 1, 0, 0, 0);
frameCount++;
if (frameCount >= targetFrameCount) {
Log("[INFO] Reached target frame count %d - taking screenshot!", targetFrameCount);
// Wait for GPU and take screenshot
ExecuteCommandList();
WaitForGPU();
TakeScreenshot();
bool screenshotResult = D3D12Screenshot::Capture(
gDevice,
gCommandQueue,
gSwapChain.GetBackBuffer(gCurrentRTIndex),
"sphere.ppm"
);
if (screenshotResult) {
Log("[INFO] Screenshot saved to sphere.ppm");
} else {
Log("[ERROR] Screenshot failed");
}
break;
}
EndRender();
ExecuteCommandList();
gSwapChain.Present(0, 0);
}
}
// Wait for GPU to finish
WaitForGPU();
// Shutdown (simplified)
// gPipelineState.Shutdown();
// gRootSignature.Shutdown();
// gVertexShader.Shutdown();
// gGeometryShader.Shutdown();
// gPixelShader.Shutdown();
// gVertexBuffer.Shutdown();
// gIndexBuffer.Shutdown();
// gDiffuseTexture.Shutdown();
// gSRVHeap.Shutdown();
gCommandList.Shutdown();
gCommandAllocator.Shutdown();
gFence.Shutdown();
gSwapChain.Shutdown();
gDevice.Shutdown();
Logger::Get().Shutdown();
Log("[INFO] D3D12 Render Model Test Finished");
Log("[INFO] D3D12 Sphere Test Finished");
return 0;
}
}