Skip to content

Commit

Permalink
Added texture background for the DX11 core
Browse files Browse the repository at this point in the history
  • Loading branch information
bigfatbrowncat committed Sep 17, 2024
1 parent cf6d940 commit bd2c683
Show file tree
Hide file tree
Showing 12 changed files with 4,382 additions and 43 deletions.
24 changes: 20 additions & 4 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ project(${TARGET})

set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MD") # No idea who removed /Zi flag from the debug conf. Putting it back
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /Zi /MDd") # No idea who removed /Zi flag from the debug conf. Putting it back
add_subdirectory(third_party/DirectX-Headers)

# Demo for DirectX 11

Expand All @@ -17,12 +18,22 @@ add_executable(${EXE_DX11} WIN32
D3DContext.h
D3DContext_DX11.cpp

DDSTextureLoader.h
DDSTextureLoader.cpp

DCompContext.h
DCompContext.cpp D3DContextBase.cpp Base.h GraphicContents.h)
DCompContext.cpp

D3DContextBase.cpp Base.h GraphicContents.h)

target_compile_definitions(${EXE_DX11} PUBLIC WINVER=0x0602 UNICODE _UNICODE USE_DX11)
target_compile_features(${EXE_DX11} PUBLIC cxx_std_20)
target_link_libraries(${EXE_DX11} PUBLIC D3D11 dxgi D3DCompiler Dcomp)
target_link_libraries(${EXE_DX11} PUBLIC D3D11 dxgi dxguid D3DCompiler Dcomp)
add_custom_command(
TARGET ${EXE_DX11} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/grass.dds
$<TARGET_FILE_DIR:${EXE_DX11}>)

set_target_properties(${EXE_DX11}
PROPERTIES
Expand All @@ -40,12 +51,17 @@ add_executable(${EXE_DX12} WIN32
D3DContext.h
D3DContext_DX12.cpp

DDSTextureLoader12.h
DDSTextureLoader12.cpp

DCompContext.h
DCompContext.cpp D3DContextBase.cpp Base.h GraphicContents.h)

target_compile_definitions(${EXE_DX12} PUBLIC WINVER=0x0602 UNICODE _UNICODE USE_DX12)
add_dependencies(${EXE_DX12} DirectX-Headers)
target_include_directories(${EXE_DX12} PUBLIC ${DirectX-Headers_SOURCE_DIR}/include)
target_compile_definitions(${EXE_DX12} PUBLIC WINVER=0x0602 UNICODE _UNICODE USE_DX12 USING_DIRECTX_HEADERS)
target_compile_features(${EXE_DX12} PUBLIC cxx_std_20)
target_link_libraries(${EXE_DX12} PUBLIC D3D12 dxgi D3DCompiler Dcomp)
target_link_libraries(${EXE_DX12} PUBLIC D3D12 dxgi D3DCompiler Dcomp DirectX-Headers DirectX-Guids)

set_target_properties(${EXE_DX12}
PROPERTIES
Expand Down
8 changes: 6 additions & 2 deletions D3DContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#include <d3d11.h>
#include <dxgi1_2.h>
#elif defined(USE_DX12)
#include <d3d12.h>
#include <directx/d3d12.h>
#include <dxgi1_4.h>
#else
#error "You should set either USE_DX11 or USE_DX12"
Expand All @@ -26,7 +26,7 @@ struct D3DContextBase : public Base {
#else
#error "You should set either USE_DX11 or USE_DX12"
#endif
std::shared_ptr<GraphicContents> contents;
std::shared_ptr<GraphicContents> contents;

IDXGIAdapter* intelAdapter = nullptr;
IDXGIFactory2* dxgiFactory = nullptr;
Expand Down Expand Up @@ -59,6 +59,7 @@ struct D3DContext : public D3DContextBase {
#if defined(USE_DX11)
ID3D11DeviceContext *deviceContext;
IDXGISwapChain1 *swapChain;
ID3D11ShaderResourceView* imageTextureView = nullptr;
void DrawTriangle(int width, int height,
ID3D11Device* device,
ID3D11DeviceContext* device_context,
Expand Down Expand Up @@ -90,6 +91,9 @@ struct D3DContext : public D3DContextBase {
HANDLE g_hSwapChainWaitableObject = nullptr;
ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {};
D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {};
ID3D12Resource* imageTextureView = nullptr;
std::unique_ptr<uint8_t[]> ddsData;
std::vector<D3D12_SUBRESOURCE_DATA> subresources;

private:
struct DrawingCache {
Expand Down
8 changes: 7 additions & 1 deletion D3DContextBase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,14 @@ void D3DContextBase::lookForIntelOutput(const RECT& position) {
for (UINT i = 0; intelAdapter->EnumOutputs(i, &output) != DXGI_ERROR_NOT_FOUND; i++) {
DXGI_OUTPUT_DESC outputDesc;
hr_check(output->GetDesc(&outputDesc));
if (outputDesc.Monitor != nullptr) {
if (outputDesc.Monitor != nullptr /*&&
outputDesc.DesktopCoordinates.left <= position.right &&
outputDesc.DesktopCoordinates.top <= position.bottom &&
outputDesc.DesktopCoordinates.right >= position.right &&
outputDesc.DesktopCoordinates.bottom >= position.bottom*/) {

intelAdapterFirstOutput = output;
//std::cout << i << std::endl;
break;
} else {
output->Release();
Expand Down
44 changes: 28 additions & 16 deletions D3DContext_DX11.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
#include "D3DContext.h"
#include "DDSTextureLoader.h"

#include "d3dcompiler.h"

#include <string>
#include <vector>
#include <stdexcept>
#include <iostream>

using namespace DirectX;

void D3DContext::DrawTriangle(int width, int height,
ID3D11Device* device,
Expand All @@ -16,20 +20,20 @@ void D3DContext::DrawTriangle(int width, int height,

D3D11_BUFFER_DESC vb_desc;
ZeroMemory(&vb_desc, sizeof(vb_desc));
vb_desc.ByteWidth = (UINT)(vertices.size() * sizeof(Vertex));
vb_desc.ByteWidth = (UINT)(vertices.size() * sizeof(TextureVertex));
vb_desc.Usage = D3D11_USAGE_DEFAULT;
vb_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vb_desc.CPUAccessFlags = 0;
vb_desc.MiscFlags = 0;
vb_desc.StructureByteStride = sizeof(Vertex);
vb_desc.StructureByteStride = sizeof(TextureVertex);

D3D11_SUBRESOURCE_DATA vb_data;
ZeroMemory(&vb_data, sizeof(vb_data));
vb_data.pSysMem = &vertices[0];

{
ID3D11Buffer *vertex_buffer;
const UINT stride = sizeof(Vertex);
const UINT stride = sizeof(TextureVertex);
const UINT offset = 0;
device->CreateBuffer(&vb_desc, &vb_data, &vertex_buffer);
device_context->IASetVertexBuffers(0, 1, &vertex_buffer, &stride, &offset);
Expand All @@ -44,14 +48,16 @@ void D3DContext::DrawTriangle(int width, int height,

std::string shader_code = contents->getShader();

hr_check(D3DCompile2(shader_code.c_str(), shader_code.length(),
auto hresult = D3DCompile2(shader_code.c_str(), shader_code.length(),
nullptr,
nullptr, nullptr, "PSMain", "ps_4_0", D3DCOMPILE_DEBUG, 0,
0, nullptr, 0,
&ps, &ps_error));
&ps, &ps_error);

if (ps_error != nullptr) {
throw std::runtime_error("Pixel shader compilation error");
std::string err = "Pixel shader compilation error: ";
err += reinterpret_cast<const char*>( ps_error->GetBufferPointer());
throw std::runtime_error(err);
}

hr_check(device->CreatePixelShader(ps->GetBufferPointer(), ps->GetBufferSize(), nullptr, &pixel_shader));
Expand All @@ -69,11 +75,13 @@ void D3DContext::DrawTriangle(int width, int height,

hr_check(device->CreateVertexShader(vs->GetBufferPointer(), vs->GetBufferSize(), nullptr, &vertex_shader));
device_context->VSSetShader(vertex_shader, nullptr, 0);
device_context->PSSetShaderResources( 0, 1, &imageTextureView );

D3D11_INPUT_ELEMENT_DESC element_desc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
//{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};

hr_check(device->CreateInputLayout(element_desc, sizeof(element_desc) / sizeof(D3D11_INPUT_ELEMENT_DESC), vs->GetBufferPointer(), vs->GetBufferSize(), &input_layout));
Expand All @@ -86,7 +94,7 @@ void D3DContext::DrawTriangle(int width, int height,
if (ps_error != nullptr) ps_error->Release();
}

device_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
device_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);//D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

{
D3D11_VIEWPORT viewport;
Expand All @@ -112,9 +120,14 @@ void D3DContext::DrawTriangle(int width, int height,
device_context->ClearRenderTargetView(rtv, color);

device_context->OMSetRenderTargets(1, &rtv, nullptr);
device_context->Draw(3, 0);
device_context->Draw((UINT)vertices.size(), 0);

syncIntelOutput();

buffer->Release();
// Discard outstanding queued presents and queue a frame with the new size ASAP.
checkDeviceRemoved(swapChain->Present(0, DXGI_PRESENT_RESTART));

buffer->Release();
rtv->Release();
}

Expand All @@ -133,7 +146,7 @@ D3DContext::D3DContext(std::shared_ptr<GraphicContents> contents): D3DContextBas
nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT,
nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, &deviceContext));

// Create the swap chain.
// Create the swap chain.
DXGI_SWAP_CHAIN_DESC1 scd = {};
// Just use a minimal size for now. WM_NCCALCSIZE will resize when necessary.
scd.Width = 1;
Expand All @@ -147,6 +160,8 @@ D3DContext::D3DContext(std::shared_ptr<GraphicContents> contents): D3DContextBas
scd.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
hr_check(dxgiFactory->CreateSwapChainForComposition(device, &scd, nullptr, &swapChain));

hr_check(CreateDDSTextureFromFile( this->device, L"grass.dds", nullptr, &imageTextureView ));

this->reposition(getFullDisplayRECT());
}

Expand All @@ -158,14 +173,10 @@ void D3DContext::reposition(const RECT& position) {

// A real app might want to compare these dimensions with the current swap chain
// dimensions and skip all this if they're unchanged.
checkDeviceRemoved(swapChain->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, 0));
checkDeviceRemoved(swapChain->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE));

DrawTriangle(width, height, device, deviceContext, swapChain, contents);

syncIntelOutput();

// Discard outstanding queued presents and queue a frame with the new size ASAP.
checkDeviceRemoved(swapChain->Present(0, DXGI_PRESENT_RESTART));
//Sleep(500);
// Wait for a vblank to really make sure our frame with the new size is ready before
// the window finishes resizing.
Expand All @@ -176,6 +187,7 @@ void D3DContext::reposition(const RECT& position) {
}

D3DContext::~D3DContext() {
if (imageTextureView) { imageTextureView->Release(); imageTextureView = nullptr; }
if (swapChain) { swapChain->SetFullscreenState(false, nullptr); swapChain->Release(); swapChain = nullptr; }
if (deviceContext) { deviceContext->Release(); deviceContext = nullptr; }
if (device) { device->Release(); device = nullptr; }
Expand Down
37 changes: 27 additions & 10 deletions D3DContext_DX12.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
#include "D3DContext.h"
//#include "DDSTextureLoader12.h"

#include <d3dcompiler.h>

#include <vector>
#include <string>
#include <iostream>

//using namespace DirectX;

// The debug layer is broken and crashes the app. Don't enable it
//#ifdef _DEBUG
//#define DX12_ENABLE_DEBUG_LAYER
Expand All @@ -32,7 +35,7 @@ void D3DContext::DrawTriangle(int width, int height,
D3D12_RESOURCE_DESC vb_desc = {
.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER,
.Alignment = 0,
.Width = sizeof(Vertex) * vertices.size(),
.Width = sizeof(RGBAVertex) * vertices.size(),
.Height = 1,
.DepthOrArraySize = 1,
.MipLevels = 1,
Expand Down Expand Up @@ -66,8 +69,8 @@ void D3DContext::DrawTriangle(int width, int height,

D3D12_VERTEX_BUFFER_VIEW vertex_buffer_view = {
.BufferLocation = drawing_cache->vertex_buffer->GetGPUVirtualAddress(),
.SizeInBytes = static_cast<UINT>(sizeof(Vertex) * vertices.size()),
.StrideInBytes = sizeof(Vertex)
.SizeInBytes = static_cast<UINT>(sizeof(RGBAVertex) * vertices.size()),
.StrideInBytes = sizeof(RGBAVertex)
};

ID3D12RootSignature *rootSignature;
Expand Down Expand Up @@ -112,6 +115,7 @@ void D3DContext::DrawTriangle(int width, int height,
D3D12_INPUT_ELEMENT_DESC vertexFormat[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
//{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}
};

Expand Down Expand Up @@ -246,11 +250,12 @@ void D3DContext::DrawTriangle(int width, int height,
FLOAT color[] = {0.0f, 0.2f, 0.4f, 1.0f};
graphics_command_list->ClearRenderTargetView(mainRenderTargetDescriptor,
color /*clear_color_with_alpha*/, 0, nullptr);
graphics_command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
graphics_command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//graphics_command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);//D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
graphics_command_list->IASetVertexBuffers(0, 1, &vertex_buffer_view);

// Finally drawing the bloody triangle!
graphics_command_list->DrawInstanced(3, 1, 0, 0);
graphics_command_list->DrawInstanced((UINT)vertices.size(), 1, 0, 0);

barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
Expand All @@ -276,8 +281,8 @@ bool D3DContext::CreateDeviceD3D(/*HWND hWnd*/)
// Setup swap chain
DXGI_SWAP_CHAIN_DESC1 scd = {};
// Just use a minimal size for now. WM_NCCALCSIZE will resize when necessary.
scd.Width = 1;
scd.Height = 1;
scd.Width = 1920;
scd.Height = 1080;
scd.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
scd.SampleDesc.Count = 1;
scd.SampleDesc.Quality = 0;
Expand Down Expand Up @@ -390,7 +395,8 @@ bool D3DContext::CreateDeviceD3D(/*HWND hWnd*/)
void D3DContext::CleanupDeviceD3D()
{
CleanupRenderTarget();
if (swapChain != nullptr) { swapChain->SetFullscreenState(false, nullptr); swapChain->Release(); swapChain = nullptr; }
if (imageTextureView) { imageTextureView->Release(); imageTextureView = nullptr; }
if (swapChain != nullptr) { swapChain->SetFullscreenState(false, nullptr); swapChain->Release(); swapChain = nullptr; }
if (g_hSwapChainWaitableObject != nullptr) { CloseHandle(g_hSwapChainWaitableObject); }
for (auto & i : g_frameContext) {
if (i.CommandAllocator) {
Expand Down Expand Up @@ -490,6 +496,18 @@ D3DContext::FrameContext* D3DContext::WaitForNextFrameResources()

D3DContext::D3DContext(std::shared_ptr<GraphicContents> contents): D3DContextBase(contents), swapChain(nullptr), descriptorHeap(nullptr) {
bool_check(CreateDeviceD3D());

// hr_check(LoadDDSTextureFromFile( this->device, L"grass.dds", &imageTextureView, ddsData, subresources ));
// HRESULT __cdecl LoadDDSTextureFromFile(
// _In_ ID3D12Device* d3dDevice,
// _In_z_ const wchar_t* szFileName,
// _Outptr_ ID3D12Resource** texture,
// std::unique_ptr<uint8_t[]>& ddsData,
// std::vector<D3D12_SUBRESOURCE_DATA>& subresources,
// size_t maxsize = 0,
// _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr,
// _Out_opt_ bool* isCubeMap = nullptr);

this->reposition(getFullDisplayRECT());
}

Expand All @@ -498,9 +516,8 @@ void D3DContext::reposition(const RECT& position) {
int height = position.bottom - position.top;

lookForIntelOutput(position);

CleanupRenderTarget();
checkDeviceRemoved(swapChain->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, 0/*DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT*/));
checkDeviceRemoved(swapChain->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE));//0/*DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT*/));
CreateRenderTarget();

FrameContext* frameCtx = WaitForNextFrameResources();
Expand Down
Loading

0 comments on commit bd2c683

Please sign in to comment.