diff --git a/debian/README.md b/debian/README.md new file mode 100644 index 0000000..ca629fa --- /dev/null +++ b/debian/README.md @@ -0,0 +1,18 @@ +# ruis-render-directx — debian directory + +This directory does **not** contain a Debian package. + +`ruis-render-directx` is the DirectX 12 renderer for ruis and is **Windows-only**: +it requires the DirectX 12 / Windows SDK headers, the D3D12 runtime and an +HLSL compiler, so it cannot be packaged for Debian/Ubuntu (or any other +Linux distribution). + +The directory still exists because **the debian changelog/version is the +primary location for the version** of this renderer: the CI +(`myci-deb-version.sh` / `myci-deb-version.ps1`) reads the version from +`debian/changelog` and applies it to the msys2/vcpkg/doxygen/pkg-config +packages, even though only the Windows builds of them are actually produced. + +* `changelog` — the placeholder Debian changelog holding the project + version (the first line of the file is parsed by the ci tooling; keep the + `(major.minor.patch[-rev])` form in that line). diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..c7aa329 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,5 @@ +ruis-render-directx (1.0.0-1) unstable; urgency=medium + + * initial version. + + -- Ivan Gagis Sat, 29 Nov 2026 01:00:00 +0200 diff --git a/src/ruis/render/directx/context.cpp b/src/ruis/render/directx/context.cpp index cfef8aa..5a05256 100644 --- a/src/ruis/render/directx/context.cpp +++ b/src/ruis/render/directx/context.cpp @@ -25,6 +25,7 @@ along with this program. If not, see . #include #include #include +#include #include @@ -59,10 +60,16 @@ context::context( // maps the framework's normalized viewport coordinates (x right, y down, // zero at the top-left, right/bottom edges at (1, 1)) to the DirectX NDC. // - // In the DirectX NDC -1 -1 corresponds to the top-left corner, 1 1 to the - // bottom-right corner, and z points away from the viewer (same orientation - // as the framework, so no axis flip is needed). - m.set_identity().translate(-1, -1).scale(2, 2); + // DirectX identity matrix: + // viewport edges: left = -1, right = 1, top = 1, bottom = -1 + // z-axis away from the viewer + m.set_identity() + // x-axis right, y-axis down, z-axis away + .scale(1, -1, 1) + // viewport edges: left = 0, top = 0 + .translate(-1, -1) + // viewport edges: right = 1, bottom = 1 + .scale(2, 2); return parameters{m}; }() ), @@ -182,7 +189,7 @@ void context::create_swapchain() IDXGISwapChain1* sc = nullptr; check_hresult( dxgi_factory->CreateSwapChainForHwnd( - reinterpret_cast(this->device), + reinterpret_cast(this->queue), this->surface_ref.get().get_hwnd(), &desc, nullptr, @@ -348,7 +355,7 @@ void context::wait_for_gpu() } // wait for the frame that rendered to the back buffer we are about to reuse const auto i = int(this->frame_index); - if (this->frame_pending[i]) { + if (i >= 0 && i < int(this->back_buffer_count) && this->frame_pending[i]) { const auto res = WaitForSingleObject(this->frame_fence_events[i], 10000); // 10s timeout if (res != WAIT_OBJECT_0) { throw std::runtime_error("directx context wait_for_gpu: the frame fence did not complete in time"); @@ -367,16 +374,21 @@ void context::ensure_frame_began() this->ensure_swapchain_valid(); if (this->swapchain != nullptr) { - // wait for the GPU to finish with the back buffer we are about to overwrite, - // then advance to the next back buffer + // the swapchain tells us which back buffer we are about to render to + this->frame_index = this->swapchain->GetCurrentBackBufferIndex(); + // wait for the GPU to finish with the back buffer we are about to overwrite this->wait_for_gpu(); - this->frame_index = (this->frame_index + 1) % this->back_buffer_count; } // reset the command allocator and the command list (the GPU has finished with - // the work recorded in them) - check_hresult(this->command_allocator->Reset(), "command allocator Reset"); - check_hresult(this->command_list->Reset(this->command_allocator, nullptr), "command list Reset"); + // the work recorded in them); a freshly created pair is already in the reset + // state and some runtimes reject Reset() on it until the first work has + // completed + if (!this->frame_first_begin) { + check_hresult(this->command_allocator->Reset(), "command allocator Reset"); + check_hresult(this->command_list->Reset(this->command_allocator, nullptr), "command list Reset"); + } + this->frame_first_begin = false; this->frame_begun = true; } @@ -393,7 +405,7 @@ void context::present_frame() // signal the fence for this back buffer (waited on before it is reused) const auto value = this->frame_fence->GetCompletedValue() + 1; - this->frame_fence->Signal(value); + check_hresult(this->queue->Signal(this->frame_fence, value), "queue Signal (frame fence)"); const auto i = int(this->frame_index); check_hresult( this->frame_fence->SetEventOnCompletion(value, this->frame_fence_events[i]), @@ -585,6 +597,16 @@ void context::enable_depth(bool enable) this->depth_enabled = enable; } +DXGI_FORMAT context::current_rtv_format() const +{ + if (this->current_fb != nullptr && this->current_fb->color != nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") + const auto& tex = static_cast(*this->current_fb->color); + return to_dxgi_format_8bit(tex.ri_format); + } + return DXGI_FORMAT_B8G8R8A8_UNORM; +} + uint32_t context::get_blend_key() const { // pack the blend state into a key for the pipeline cache: @@ -602,27 +624,8 @@ uint32_t context::get_blend_key() const ID3DBlob* context::compile_shader(const char* hlsl, const char* entry_point, const char* profile) { - ID3DBlob* blob = nullptr; - ID3DBlob* err_blob = nullptr; - check_hresult( - D3DCompile( - hlsl, - strlen(hlsl), - "ruis-render-directx.hlsl", - nullptr, - nullptr, - entry_point, - profile, - 0, - 0, - &blob, - &err_blob - ), - "D3DCompile" - ); - if (err_blob != nullptr) { - err_blob->Release(); - } + // the shared helper throws with the compiler's error message on failure + auto* blob = compile_hlsl_blob(hlsl, entry_point, profile); this->shader_blobs.emplace_back(blob); return blob; } @@ -635,12 +638,13 @@ ID3D12PipelineState* context::build_pipeline( ) { // compile the shaders to DXIL (the blobs are kept alive in shader_blobs) - auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_6_0"); - auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_6_0"); + auto* vs_blob = this->compile_shader(vertex_hlsl, "main", "vs_5_1"); + auto* fs_blob = this->compile_shader(fragment_hlsl, "main", "ps_5_1"); // ---- the vertex input layout ---- - // all vertices are stored as float4 (4 floats) in the vertex buffer; the a1 - // attribute (if present) is the tail of the float4 (its format is shader-specific) + // each buffer of the vertex array holds float4 (4 floats) vertices with the + // same stride; the a1 attribute (if present) reads the first few floats of the + // second buffer (its format is shader-specific) const auto a1 = shader_kind(key.shader_kind); auto input_layout_elements = std::vector{ {.SemanticName = "POSITION", @@ -653,11 +657,11 @@ ID3D12PipelineState* context::build_pipeline( if (has_a1) { input_layout_elements.push_back( D3D12_INPUT_ELEMENT_DESC{ - .SemanticName = "TEXCOORD", + .SemanticName = a1_semantic(a1), .SemanticIndex = 0, .Format = a1_format(a1), .InputSlot = 1, - .AlignedByteOffset = UINT(vertex_stride_bytes), + .AlignedByteOffset = 0, .InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA } ); @@ -696,17 +700,24 @@ ID3D12PipelineState* context::build_pipeline( depth_stencil.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; depth_stencil.BackFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; + // ---- the pipeline ---- + // Culling / winding: same settings as the Vulkan and OpenGL renderers + // (cull the back face, front face counter-clockwise). For triangle-strip + // primitives the rasterizer automatically adjusts the winding of the + // second and fourth (and so on) triangles so that all triangles in the + // strip have the same facing orientation; the quad indices in ruis do + // not need to be consistent-oriented (see renderer.hpp). const auto pipeline_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC{ .pRootSignature = this->root_signature, - .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), vs_blob->GetBufferSize()}, - .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), fs_blob->GetBufferSize()}, + .VS = D3D12_SHADER_BYTECODE{vs_blob->GetBufferPointer(), UINT(vs_blob->GetBufferSize())}, + .PS = D3D12_SHADER_BYTECODE{fs_blob->GetBufferPointer(), UINT(fs_blob->GetBufferSize())}, .BlendState = blend, .SampleMask = 0xFFFFFFFF, .RasterizerState = D3D12_RASTERIZER_DESC{ .FillMode = D3D12_FILL_MODE_SOLID, - .CullMode = D3D12_CULL_MODE_NONE, - .FrontCounterClockwise = FALSE, + .CullMode = D3D12_CULL_MODE_BACK, + .FrontCounterClockwise = TRUE, .DepthBias = 0, .DepthBiasClamp = 0.0f, .SlopeScaledDepthBias = 0.0f, @@ -721,20 +732,52 @@ ID3D12PipelineState* context::build_pipeline( .IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, .PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, .NumRenderTargets = 1, - .RTVFormats = {DXGI_FORMAT_UNKNOWN}, // the actual format depends on the render target - .DSVFormat = DXGI_FORMAT_UNKNOWN, // the actual format depends on the depth texture + .RTVFormats = {static_cast(key.rtv_format)}, + .DSVFormat = use_depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_UNKNOWN, .SampleDesc = {.Count = 1, .Quality = 0}, .NodeMask = 0 }; ID3D12PipelineState* pso = nullptr; - check_hresult( - this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)), - "CreateGraphicsPipelineState" - ); + const auto hr = this->device->CreateGraphicsPipelineState(&pipeline_desc, IID_PPV_ARGS(&pso)); + check_hresult(hr, "CreateGraphicsPipelineState"); return pso; } +// NOTE: D3D12 did not support triangle fans for a long time, but the later +// DirectX versions re-introduced it. So the support cannot be assumed from the +// headers or the SDK version: it must be checked on the device at runtime via +// CheckFeatureSupport (D3D12_FEATURE_DATA_D3D12_OPTIONS15 / TriangleFanSupported). +bool context::triangle_fan_supported() const +{ + if (!this->triangle_fan_supported_checked) { +#if defined(D3D12_FEATURE_D3D12_OPTIONS15) && defined(D3D12_FEATURE_DATA_D3D12_OPTIONS15) + D3D12_FEATURE_DATA_D3D12_OPTIONS15 options{}; + const auto hr = this->device->CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS15, + &options, + sizeof(options) + ); + this->triangle_fan_supported_cache = SUCCEEDED(hr) && options.TriangleFanSupported != FALSE; +#else + // this toolchain does not declare OPTIONS15 at all: treat triangle fan as + // unsupported (the check is conservative) + this->triangle_fan_supported_cache = false; +#endif + this->triangle_fan_supported_checked = true; + } + return this->triangle_fan_supported_cache; +} + +// runtime gate for the triangle fan mode: if the device reports that triangle fan is +// not supported, throw instead of failing silently deeper in the render pipeline +void context::check_topology_supported(ruis::render::vertex_array::mode m) const +{ + if (m == ruis::render::vertex_array::mode::triangle_fan && !this->triangle_fan_supported()) { + throw std::runtime_error("Unsupported: triangle_fan primitive topology"); + } +} + ID3D12PipelineState* context::get_or_create_pipeline( shader_kind kind, // bool textured, @@ -748,7 +791,8 @@ ID3D12PipelineState* context::get_or_create_pipeline( .blend_key = this->get_blend_key(), .depth_enabled = uint32_t(this->depth_enabled ? 1 : 0), .textured = uint32_t(textured ? 1 : 0), - .topology = uint32_t(topology) + .topology = uint32_t(topology), + .rtv_format = uint32_t(this->current_rtv_format()) }; const auto it = this->pipelines.find(key); @@ -776,30 +820,34 @@ void context::draw_indexed( this->command_list->SetPipelineState(pso); this->command_list->IASetPrimitiveTopology(to_topology(va.rendering_mode)); - // the vertex buffer (the first buffer of the vertex array; the vertex data of - // all buffers is expected to have the same float4 layout) + // the vertex buffers (one per slot; all buffers have the same float4 layout) { utki::assert(!va.buffers.empty(), SL); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") - const auto& vb = static_cast(va.buffers.front().get()); - const auto vbv = D3D12_VERTEX_BUFFER_VIEW{ - .BufferLocation = vb.gpu_va, - .SizeInBytes = UINT(vb.byte_size), - .StrideInBytes = UINT(vertex_stride_bytes) - }; - this->command_list->IASetVertexBuffers(0, 1, &vbv); + std::vector views(va.buffers.size()); + for (size_t i = 0; i < va.buffers.size(); ++i) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") + const auto& vb = static_cast(va.buffers[i].get()); + views[i] = D3D12_VERTEX_BUFFER_VIEW{ + .BufferLocation = vb.gpu_va, + .SizeInBytes = UINT(vb.byte_size), + .StrideInBytes = UINT(vertex_stride_bytes) + }; + } + this->command_list->IASetVertexBuffers(0, UINT(views.size()), views.data()); } - // the index buffer + // the index buffer (an empty index buffer has no GPU resource) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") const auto& ib = static_cast(va.indices.get()); - const auto ibv = D3D12_INDEX_BUFFER_VIEW{ - .BufferLocation = ib.gpu_va, - .SizeInBytes = UINT(UINT64(ib.index_count) * (ib.index_format == DXGI_FORMAT_R16_UINT ? 2 : 4)), - .Format = ib.index_format - }; - this->command_list->IASetIndexBuffer(&ibv); + if (ib.index_count > 0) { + const auto ibv = D3D12_INDEX_BUFFER_VIEW{ + .BufferLocation = ib.gpu_va, + .SizeInBytes = UINT(UINT64(ib.index_count) * (ib.index_format == DXGI_FORMAT_R16_UINT ? 2 : 4)), + .Format = ib.index_format + }; + this->command_list->IASetIndexBuffer(&ibv); + } } // the per-draw uniforms (root 32-bit constants) @@ -843,11 +891,13 @@ void context::draw_indexed( this->command_list->RSSetScissorRects(1, &scissor_desc); } - // the draw call + // the draw call (skipped for an empty index buffer) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the renderer owns the object; the base-class reference comes from the ruis API") const auto& ib = static_cast(va.indices.get()); - this->command_list->DrawIndexedInstanced(ib.index_count, 1, 0, 0, 0); + if (ib.index_count > 0) { + this->command_list->DrawIndexedInstanced(ib.index_count, 1, 0, 0, 0); + } } } @@ -875,7 +925,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); check_hresult( this->device->CreateCommittedResource( - &default_heap_properties(), + &readback_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, @@ -892,7 +942,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende const auto desc = make_buffer_desc(row_pitch * h, D3D12_RESOURCE_FLAG_NONE); check_hresult( this->device->CreateCommittedResource( - &upload_heap_properties(), + &default_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, @@ -941,7 +991,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende this->wait_for_gpu(); // read the data back (the row pitch is the one the buffer was allocated with) - std::vector pixels(row_pitch * h); + std::vector pixels(SIZE_T(row_pitch * h)); { const auto pitch = row_pitch; D3D12_RANGE read_range{0, SIZE_T(pitch * h)}; @@ -950,7 +1000,7 @@ rasterimage::image_variant context::readback_framebuffer_color(const ruis::rende auto* dst = pixels.data(); auto* src = static_cast(mapped); for (UINT y = 0; y < h; ++y) { - std::memcpy(dst, src, row_pitch); + std::memcpy(dst, src, SIZE_T(row_pitch)); dst += row_pitch; src += pitch; } diff --git a/src/ruis/render/directx/context.hpp b/src/ruis/render/directx/context.hpp index b0465a7..cb652a1 100644 --- a/src/ruis/render/directx/context.hpp +++ b/src/ruis/render/directx/context.hpp @@ -53,11 +53,13 @@ struct pipeline_key { uint32_t depth_enabled = 0; uint32_t textured = 0; uint32_t topology = 0; // D3D12_PRIMITIVE_TOPOLOGY + uint32_t rtv_format = 0; // DXGI_FORMAT (the current render target format) bool operator==(const pipeline_key& o) const { return this->shader_kind == o.shader_kind && this->blend_key == o.blend_key && - this->depth_enabled == o.depth_enabled && this->textured == o.textured && this->topology == o.topology; + this->depth_enabled == o.depth_enabled && this->textured == o.textured && + this->topology == o.topology && this->rtv_format == o.rtv_format; } }; @@ -77,6 +79,7 @@ struct pipeline_key_hash { hash_combine(h, std::hash()(k.depth_enabled)); hash_combine(h, std::hash()(k.textured)); hash_combine(h, std::hash()(k.topology)); + hash_combine(h, std::hash()(k.rtv_format)); return h; } }; @@ -147,6 +150,10 @@ class context : public ruis::render::context // the packed key of the current blend state (for pipeline selection) uint32_t get_blend_key() const; + // the DXGI_FORMAT of the current render target (the swapchain for the + // screen, the color texture for a frame buffer) + DXGI_FORMAT current_rtv_format() const; + // get or create a pipeline state object for the given shader + current state ID3D12PipelineState* get_or_create_pipeline( shader_kind kind, // @@ -156,6 +163,14 @@ class context : public ruis::render::context const char* fragment_hlsl ); + // whether the device supports the triangle fan primitive topology (queried once, lazily). + // NOTE: triangle fan was not supported by earlier D3D12, but later DirectX versions + // re-introduced it, so support must be checked on the device, not assumed. + bool triangle_fan_supported() const; + + // throw std::runtime_error if the requested topology is not supported + void check_topology_supported(ruis::render::vertex_array::mode m) const; + // begin a frame (acquire the back buffer, reset the command list). Idempotent // within a frame. void ensure_frame_began(); @@ -219,6 +234,11 @@ class context : public ruis::render::context // ---- current frame state ---- bool frame_begun = false; + bool frame_first_begin = true; // a fresh command allocator rejects Reset() on some runtimes + + // lazily queried triangle fan support cache (thread-safe enough: the render calls come from one thread) + mutable bool triangle_fan_supported_checked = false; + mutable bool triangle_fan_supported_cache = false; // ---- renderer state ---- ruis::render::frame_buffer* current_fb = nullptr; // the current framebuffer (nullptr = screen) diff --git a/src/ruis/render/directx/directx.cpp b/src/ruis/render/directx/directx.cpp index a1eb137..04d282d 100644 --- a/src/ruis/render/directx/directx.cpp +++ b/src/ruis/render/directx/directx.cpp @@ -21,12 +21,13 @@ along with this program. If not, see . #include "directx.hpp" +#include #include #include namespace ruis::render::directx { -std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) +ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile) { ID3DBlob* blob = nullptr; ID3DBlob* err_blob = nullptr; @@ -45,20 +46,24 @@ std::vector compile_hlsl(const char* source, const char* entry_point, c ); if (FAILED(hr)) { const auto err = err_blob != nullptr ? reinterpret_cast(err_blob->GetBufferPointer()) : ""; - const auto msg = std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err; - if (err_blob != nullptr) { - err_blob->Release(); - } - throw std::runtime_error(msg); + if (err_blob != nullptr) { err_blob->Release(); } + if (blob != nullptr) { blob->Release(); } + throw std::runtime_error(std::string("HLSL compilation failed (") + entry_point + " " + profile + "): " + err); } + if (err_blob != nullptr) { err_blob->Release(); } + return blob; +} +std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile) +{ + // compile the shader and copy the bytecode out of the returned blob + // (the caller keeps the blob alive for the lifetime of the pipeline; + // this public helper only needs the bytecode) + auto* blob = compile_hlsl_blob(source, entry_point, profile); const auto size = blob->GetBufferSize(); std::vector bytecode(size); std::copy_n(static_cast(blob->GetBufferPointer()), size, bytecode.begin()); blob->Release(); - if (err_blob != nullptr) { - err_blob->Release(); - } return bytecode; } diff --git a/src/ruis/render/directx/directx.hpp b/src/ruis/render/directx/directx.hpp index 7b20c69..64e1662 100644 --- a/src/ruis/render/directx/directx.hpp +++ b/src/ruis/render/directx/directx.hpp @@ -51,9 +51,9 @@ inline void check_hresult(HRESULT hr, const char* what) /** * @brief The shared draw uniforms, bound as a root constant buffer view. * - * The matrix is stored in row-major order, which is the same order that - * r4::matrix4 uses and the default packing order of a row-major float4x4 in - * HLSL, so the matrix is copied directly from r4 without any transposition. + * The matrix is stored in column-major order, matching the default packing + * of a float4x4 in an HLSL cbuffer (r4 stores row-major), so the matrix is + * transposed on write. */ struct draw_uniforms { float matrix[4][4]; @@ -64,9 +64,11 @@ static_assert(sizeof(draw_uniforms) == 16 * sizeof(float) + 4 * sizeof(float)); inline void write_draw_uniforms(draw_uniforms* u, const r4::matrix4& m, const r4::vector4& color) { + // r4 stores row-major, HLSL expects column-major: transpose first + auto t = m.tposed(); for (uint32_t r = 0; r < 4; ++r) { for (uint32_t c = 0; c < 4; ++c) { - u->matrix[r][c] = m[r][c]; + u->matrix[r][c] = t[r][c]; } } u->color[0] = color.x(); @@ -148,10 +150,11 @@ inline DXGI_FORMAT to_dxgi_format_8bit(rasterimage::format f) } // D3D12_RESOURCE_STATE_DEPTH_STENCIL was removed from the new SDK; -// it is the same combination of states as before -inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = // - D3D12_RESOURCE_STATE_DEPTH_WRITE | // - D3D12_RESOURCE_STATE_DEPTH_READ; +// the depth-stencil resources of this renderer are only written through the +// depth-stencil view, so they are created in the (single) depth-write state. +// (Read-only states cannot be combined with write states, so DEPTH_WRITE | DEPTH_READ +// would be invalid.) +inline constexpr auto D3D12_RESOURCE_STATE_DEPTH_STENCIL = D3D12_RESOURCE_STATE_DEPTH_WRITE; inline const D3D12_HEAP_PROPERTIES& default_heap_properties() { @@ -159,7 +162,7 @@ inline const D3D12_HEAP_PROPERTIES& default_heap_properties() static const auto props = D3D12_HEAP_PROPERTIES{ .Type = D3D12_HEAP_TYPE_DEFAULT, .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, - .MemoryPoolPreference = D3D12_MEMORY_POOL_L0, + .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, .CreationNodeMask = 0, .VisibleNodeMask = 0 }; @@ -212,7 +215,21 @@ inline const D3D12_HEAP_PROPERTIES& upload_heap_properties() static const auto props = D3D12_HEAP_PROPERTIES{ .Type = D3D12_HEAP_TYPE_UPLOAD, .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, - .MemoryPoolPreference = D3D12_MEMORY_POOL_L0, + .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, + .CreationNodeMask = 0, + .VisibleNodeMask = 0 + }; + return props; +} + +// a readback heap (CPU-readable; the resources created in this heap are +// only ever copy destinations) +inline const D3D12_HEAP_PROPERTIES& readback_heap_properties() +{ + static const auto props = D3D12_HEAP_PROPERTIES{ + .Type = D3D12_HEAP_TYPE_READBACK, + .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, .CreationNodeMask = 0, .VisibleNodeMask = 0 }; @@ -237,8 +254,20 @@ inline D3D12_RESOURCE_BARRIER transition_barrier( return b; } -// compile an HLSL shader source at runtime (via the D3D compiler); -// the returned blob contains the DXIL bytecode +/** + * @brief Compile one HLSL shader source at runtime (via the D3D compiler). + * @param source the HLSL source + * @param entry_point the entry point + * @param profile the target profile (e.g. "vs_5_1") + * @return the compiled blob; the caller owns it and must release it. + * @throws std::runtime_error carrying the compiler's error message on failure. + */ +ID3DBlob* compile_hlsl_blob(const char* source, const char* entry_point, const char* profile); + +/** + * @brief Compile one HLSL shader source at runtime and return the DXIL bytecode. + * @throws std::runtime_error carrying the compiler's error message on failure. + */ std::vector compile_hlsl(const char* source, const char* entry_point, const char* profile); } // namespace ruis::render::directx diff --git a/src/ruis/render/directx/factory.cpp b/src/ruis/render/directx/factory.cpp index dfcf8ff..03a75d7 100644 --- a/src/ruis/render/directx/factory.cpp +++ b/src/ruis/render/directx/factory.cpp @@ -77,15 +77,15 @@ factory::factory(const utki::shared_ref& surface) : // const auto static_sampler = D3D12_STATIC_SAMPLER_DESC{ .Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR, - .AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - .AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - .AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + .AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER, + .AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER, + .AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER, .MipLODBias = 0.0f, - .MaxAnisotropy = 1, + .MaxAnisotropy = 0, .ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER, .BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, .MinLOD = 0.0f, - .MaxLOD = 0.0f, + .MaxLOD = D3D12_FLOAT32_MAX, .ShaderRegister = 0, .RegisterSpace = 0, .ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL @@ -101,13 +101,17 @@ factory::factory(const utki::shared_ref& surface) : // ID3DBlob* blob = nullptr; ID3DBlob* error_blob = nullptr; - check_hresult( - D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_1, &blob, &error_blob), - "D3D12SerializeRootSignature" - ); + const auto hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, &error_blob); + std::string err_text; if (error_blob != nullptr) { + const auto ptr = reinterpret_cast(error_blob->GetBufferPointer()); + err_text = (ptr != nullptr) ? std::string(ptr) : std::string(); error_blob->Release(); } + check_hresult( + FAILED(hr) ? hr : S_OK, + FAILED(hr) && !err_text.empty() ? err_text.c_str() : "D3D12SerializeRootSignature" + ); check_hresult( this->device->CreateRootSignature( 0, @@ -178,8 +182,13 @@ void factory::one_shot(std::function cmd) cons } } - check_hresult(this->upload_allocator->Reset(), "upload allocator Reset"); - check_hresult(this->upload_command_list->Reset(this->upload_allocator, nullptr), "upload command list Reset"); + // a freshly created allocator and command list are already in the reset state; + // some runtimes reject Reset() on them until the first work has completed + if (!this->upload_first_shot) { + check_hresult(this->upload_allocator->Reset(), "upload allocator Reset"); + check_hresult(this->upload_command_list->Reset(this->upload_allocator, nullptr), "upload command list Reset"); + } + this->upload_first_shot = false; cmd(this->upload_command_list); @@ -188,7 +197,7 @@ void factory::one_shot(std::function cmd) cons const auto lists = std::array{{this->upload_command_list}}; this->queue->ExecuteCommandLists(1, lists.data()); - this->upload_fence->Signal(++this->upload_fence_value); + check_hresult(this->queue->Signal(this->upload_fence, ++this->upload_fence_value), "queue Signal (upload fence)"); check_hresult( this->upload_fence->SetEventOnCompletion(this->upload_fence_value, this->upload_fence_event), "fence SetEvent" @@ -405,7 +414,7 @@ void factory::upload_texture(texture_2d* t) const &upload_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload) ), @@ -425,7 +434,7 @@ void factory::upload_texture(texture_2d* t) const auto* dst = static_cast(mapped); const auto* src = t->deferred_data.data(); for (UINT64 y = 0; y < h; ++y) { - std::memcpy(dst + y * pitch, src + y * row_bytes, row_bytes); + std::memcpy(dst + y * pitch, src + y * row_bytes, SIZE_T(row_bytes)); } upload->Unmap(0, nullptr); } diff --git a/src/ruis/render/directx/factory.hpp b/src/ruis/render/directx/factory.hpp index c916f9a..eca4276 100644 --- a/src/ruis/render/directx/factory.hpp +++ b/src/ruis/render/directx/factory.hpp @@ -169,6 +169,7 @@ class factory : public ruis::render::factory // work), but they advance this internal submission state mutable uint64_t upload_fence_value = 0; mutable bool upload_submitted = false; + mutable bool upload_first_shot = true; // a fresh command allocator rejects Reset() on some runtimes }; } // namespace ruis::render::directx diff --git a/src/ruis/render/directx/index_buffer.cpp b/src/ruis/render/directx/index_buffer.cpp index a05a76d..0c2886b 100644 --- a/src/ruis/render/directx/index_buffer.cpp +++ b/src/ruis/render/directx/index_buffer.cpp @@ -57,6 +57,14 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT { const auto byte_size = data.size(); + this->index_format = fmt; + this->index_count = count; + + // an empty index buffer does not need a GPU resource + if (byte_size == 0) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the factory is owned by the renderer; the base-class reference comes from the ruis API") auto& dx_f = static_cast(this->factory.get()); auto* device = dx_f.device; @@ -78,9 +86,6 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT this->gpu_va = this->resource->GetGPUVirtualAddress(); } - this->index_format = fmt; - this->index_count = count; - // ---- upload the data ---- { ID3D12Resource* upload = nullptr; @@ -91,7 +96,7 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT &upload_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload) ), @@ -106,13 +111,13 @@ void index_buffer::upload(utki::span data, DXGI_FORMAT fmt, UINT dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { const auto barrier1 = - transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); cmd->ResourceBarrier(1, &barrier1); cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(byte_size)); const auto barrier2 = transition_barrier( this->resource, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER + D3D12_RESOURCE_STATE_INDEX_BUFFER ); cmd->ResourceBarrier(1, &barrier2); }); diff --git a/src/ruis/render/directx/shaders/shader_common.cpp b/src/ruis/render/directx/shaders/shader_common.cpp index 9503a3b..fcb7abb 100644 --- a/src/ruis/render/directx/shaders/shader_common.cpp +++ b/src/ruis/render/directx/shaders/shader_common.cpp @@ -58,6 +58,10 @@ void directx_shader_render( } } + // NOTE: triangle fan was unsupported by earlier D3D12, but later DirectX versions + // re-introduced it. Do not assume support: check the device and throw if unsupported. + ctx.check_topology_supported(va.rendering_mode); + // the per-draw uniforms (root constants) draw_uniforms u{}; write_draw_uniforms(&u, m, color); diff --git a/src/ruis/render/directx/shaders/shader_common.hpp b/src/ruis/render/directx/shaders/shader_common.hpp index 91f5d99..7fe03b3 100644 --- a/src/ruis/render/directx/shaders/shader_common.hpp +++ b/src/ruis/render/directx/shaders/shader_common.hpp @@ -21,6 +21,8 @@ along with this program. If not, see . #pragma once +#include + #include #include #include @@ -65,6 +67,18 @@ constexpr DXGI_FORMAT a1_format(shader_kind k) } } +// the semantic name of the a1 attribute (used in the vertex input layout) +constexpr const char* a1_semantic(shader_kind k) +{ + switch (k) { + case shader_kind::pos_clr: + return "COLOR"; + default: + // the textured shaders and the luminance shader declare it as TEXCOORD + return "TEXCOORD"; + } +} + // map the VAO's rendering mode to a DirectX primitive topology inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) { @@ -72,7 +86,15 @@ inline D3D12_PRIMITIVE_TOPOLOGY to_topology(ruis::render::vertex_array::mode m) case ruis::render::vertex_array::mode::triangles: return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; case ruis::render::vertex_array::mode::triangle_fan: +#if defined(D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN) return D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN; +#else + // NOTE: earlier D3D12 did not support triangle fans, but later + // DirectX versions re-introduced it. This toolchain does not even + // declare the topology constant (e.g. mingw64 headers), so it + // cannot be mapped: treat it as unsupported. + throw std::runtime_error("Unsupported: triangle_fan primitive topology"); +#endif case ruis::render::vertex_array::mode::line_loop: return D3D_PRIMITIVE_TOPOLOGY_LINELIST; // D3D12 has no line loop; use a line list case ruis::render::vertex_array::mode::triangle_strip: diff --git a/src/ruis/render/directx/shaders/shader_src.hpp b/src/ruis/render/directx/shaders/shader_src.hpp index ea38d7f..0a556cf 100644 --- a/src/ruis/render/directx/shaders/shader_src.hpp +++ b/src/ruis/render/directx/shaders/shader_src.hpp @@ -22,7 +22,7 @@ along with this program. If not, see . /* * The HLSL sources of the renderer's shaders. * They are compiled to DXIL at runtime with the D3D compiler (see - * directx::compile_hlsl()). + * directx::compile_hlsl_blob(), which is what the renderer uses). * * The per-draw uniforms (the transformation matrix and the color) are passed * as root 32-bit constants in register b0: first a float4x4 matrix (16 floats), @@ -45,18 +45,24 @@ namespace ruis::render::directx { // ============== color ========= static const char* hlsl_shader_color_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; float4 main(float4 pos : POSITION) : SV_POSITION { - return draw_matrix * pos; + return mul(draw_matrix, pos); } )HLSL"; static const char* hlsl_shader_color_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; float4 main() : SV_Target { @@ -68,8 +74,11 @@ float4 main() : SV_Target // ============== pos_clr ======= static const char* hlsl_shader_pos_clr_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; struct VS_OUT { @@ -80,14 +89,19 @@ struct VS_OUT VS_OUT main(float4 pos : POSITION, float4 col : COLOR) { VS_OUT o; - o.pos = draw_matrix * pos; + o.pos = mul(draw_matrix, pos); o.col = col; return o; } )HLSL"; static const char* hlsl_shader_pos_clr_fragment = R"HLSL( -float4 main(float4 col : COLOR) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float4 col : COLOR) : SV_Target { return col; } @@ -97,8 +111,11 @@ float4 main(float4 col : COLOR) : SV_Target // ============== pos_tex ======= static const char* hlsl_shader_pos_tex_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; struct VS_OUT { @@ -109,20 +126,28 @@ struct VS_OUT VS_OUT main(float4 pos : POSITION, float2 uv : TEXCOORD) { VS_OUT o; - o.pos = draw_matrix * pos; + o.pos = mul(draw_matrix, pos); o.uv = uv; return o; } )HLSL"; static const char* hlsl_shader_pos_tex_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; Texture2D tex0 : register(t0); SamplerState samp0 : register(s0); -float4 main(float2 uv : TEXCOORD) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target { return tex0.Sample(samp0, uv) * draw_color; } @@ -140,13 +165,21 @@ static const char* hlsl_shader_color_pos_tex_fragment = hlsl_shader_pos_tex_frag static const char* hlsl_shader_color_pos_tex_alpha_vertex = hlsl_shader_pos_tex_vertex; static const char* hlsl_shader_color_pos_tex_alpha_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; Texture2D tex0 : register(t0); SamplerState samp0 : register(s0); -float4 main(float2 uv : TEXCOORD) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float2 uv : TEXCOORD) : SV_Target { return float4(draw_color.xyz, draw_color.w * tex0.Sample(samp0, uv).r); } @@ -156,8 +189,11 @@ float4 main(float2 uv : TEXCOORD) : SV_Target // ============== color_pos_lum = static const char* hlsl_shader_color_pos_lum_vertex = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; struct VS_OUT { @@ -168,17 +204,25 @@ struct VS_OUT VS_OUT main(float4 pos : POSITION, float lum : TEXCOORD) { VS_OUT o; - o.pos = draw_matrix * pos; + o.pos = mul(draw_matrix, pos); o.lum = lum; return o; } )HLSL"; static const char* hlsl_shader_color_pos_lum_fragment = R"HLSL( -RootConstants[1] draw_matrix : register(b0); -RootConstants[1] draw_color : register(b16); +cbuffer DrawConstants : register(b0) +{ + float4x4 draw_matrix; + float4 draw_color; +}; -float4 main(float lum : TEXCOORD) : SV_Target +// NOTE: the VS outputs SV_POSITION at hardware register 0 and any +// arbitrary semantic (e.g. TEXCOORD/COLOR) at register 1. The fragment shader +// must declare SV_POSITION as an (unused) input so its arbitrary semantic +// lines up at the same hardware register as the VS output; otherwise pipeline +// creation fails with E_INVALIDARG ("mismatched hardware registers"). +float4 main(float4 pos : SV_POSITION, float lum : TEXCOORD) : SV_Target { return float4(draw_color.xyz, draw_color.w * lum); } diff --git a/src/ruis/render/directx/texture_2d.cpp b/src/ruis/render/directx/texture_2d.cpp index fd6749d..f256adc 100644 --- a/src/ruis/render/directx/texture_2d.cpp +++ b/src/ruis/render/directx/texture_2d.cpp @@ -156,7 +156,7 @@ texture_2d::texture_2d( const auto barrier2 = transition_barrier( this->resource, D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ); cmd->ResourceBarrier(1, &barrier2); }); @@ -232,7 +232,7 @@ void texture_2d::record_upload_commands(ID3D12GraphicsCommandList* cmd, ID3D12Re const auto barrier2 = transition_barrier( this->resource, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ); cmd->ResourceBarrier(1, &barrier2); } diff --git a/src/ruis/render/directx/vertex_buffer.cpp b/src/ruis/render/directx/vertex_buffer.cpp index b61238c..3622851 100644 --- a/src/ruis/render/directx/vertex_buffer.cpp +++ b/src/ruis/render/directx/vertex_buffer.cpp @@ -21,6 +21,7 @@ along with this program. If not, see . #include "vertex_buffer.hpp" +#include #include #include "factory.hpp" @@ -37,6 +38,11 @@ vertex_buffer::vertex_buffer( ), byte_size(padded_data.size() * sizeof(float)) { + // an empty vertex buffer does not need a GPU resource + if (this->byte_size == 0) { + return; + } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast, "the factory is owned by the renderer; the base-class reference comes from the ruis API") auto& dx_f = static_cast(this->factory.get()); auto* device = dx_f.device; @@ -44,6 +50,13 @@ vertex_buffer::vertex_buffer( // ---- the vertex buffer (default heap) ---- { const auto desc = make_buffer_desc(UINT64(this->byte_size), D3D12_RESOURCE_FLAG_NONE); + char vbuf_msg[128] = {0}; + std::snprintf( + vbuf_msg, + sizeof(vbuf_msg), + "CreateCommittedResource (vertex buffer, size=%u)", + UINT(this->byte_size) + ); check_hresult( device->CreateCommittedResource( &default_heap_properties(), @@ -53,7 +66,7 @@ vertex_buffer::vertex_buffer( nullptr, IID_PPV_ARGS(&this->resource) ), - "CreateCommittedResource (vertex buffer)" + vbuf_msg ); this->gpu_va = this->resource->GetGPUVirtualAddress(); } @@ -68,7 +81,7 @@ vertex_buffer::vertex_buffer( &upload_heap_properties(), D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload) ), @@ -83,7 +96,7 @@ vertex_buffer::vertex_buffer( dx_f.one_shot([&](ID3D12GraphicsCommandList* cmd) { const auto barrier1 = - transition_barrier(upload, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_barrier(upload, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_SOURCE); cmd->ResourceBarrier(1, &barrier1); cmd->CopyBufferRegion(this->resource, 0, upload, 0, UINT64(this->byte_size)); const auto barrier2 = transition_barrier(