Replace bgfx with bespoke RHI#39
Draft
jayrulez wants to merge 20 commits into
Draft
Conversation
Introduce draconic::shell: the OS/windowing service (IShell, IWindow, IWindowManager, and the input device interfaces) as the primary module 'shell' with 'shell:window' and 'shell:input' partitions. Add two backends as separate libraries: - shell.null: a headless IShell (create/destroy/resize windows, no-op input) for tests, tools, and headless hosts. - shell.desktop: an SDL3-based IShell covering Win32/X11/Wayland/Cocoa windowing, input, and native-handle export for RHI surface creation. Each backend ships a doctest suite. Enable SDL_JOYSTICK and SDL_HIDAPI so the desktop backend's SDL_INIT_GAMEPAD (gamepad input) succeeds.
…ut modules Move windowing and input onto the new shell: the SDL3 desktop backend now owns window creation, native-handle export, and input, so the old draco::platform (SDL native-handle extraction) and draco::input (global SDL input) modules are removed. RHI no longer depends on platform: it defines its own rhi::NativeWindowType and init() takes it, keeping the renderer self-contained. RenderSample runs entirely on shell.desktop (createShell, mainWindow()->native() for RHI init, shell->input() for camera/mouse control, shell->processEvents()/isRunning() for the loop) and links Shell_Desktop. CameraController takes input by value (CameraInput) instead of reaching into a global input module. Draconic no longer re-exports platform/input, and the CMake wiring (Runtime, Rendering RHI, Scene Camera, Samples) is updated accordingly.
Give the sample its own subdirectory so more samples can be added as sibling folders. Samples/cpp/CMakeLists.txt now just dispatches via add_subdirectory; the RenderSample target and its shader/texture steps move to Samples/cpp/Render/CMakeLists.txt unchanged.
Track the main window by id instead of returning m_live[0]: destroying and flushing the main window while another window remains open no longer promotes that window to 'main' (which made isRunning() revive). mainWindow() now returns null once the initial window is gone, and NullShell::isRunning() stops when the main window is closed or destroyed, matching the documented contract. Make destroyWindow() a genuine no-op for windows the manager does not own, checked by pointer identity rather than id: windows from different managers can share an id, and acting on a foreign window would close it and make flushDestroyed() erase the wrong owned entry. Add headless regression tests for both: destroying the main window with a second window open (no promotion, no isRunning revival) and destroyWindow rejecting a foreign window whose id collides with an owned one.
Add the MSVC linker equivalent (/WHOLEARCHIVE:$<TARGET_FILE:SDL3::SDL3-static>) of the existing --whole-archive / -force_load handling. SDL3 is linked statically with joystick/HIDAPI enabled, so without whole-archive inclusion the linker can drop its constructor-registered input drivers and gamepad support disappears at runtime.
windows(), mainWindow(), and getWindow() are pure reads but were declared non-const while events() was const. Const-qualify them (they still return non-const IWindow* / span<IWindow* const>, the same pattern as events()), so read-only callers no longer have to defeat constness: NullShell::isRunning() and SDL3Shell::isRunning() drop their const_cast on the window manager and call mainWindow() directly.
m_gamepads held raw SDL3Gamepad* allocated with new and freed by hand in removeGamepad()/releaseDevices(), pairing each delete with an SDL_CloseGamepad(). Give SDL3Gamepad a destructor that closes its SDL_Gamepad and store std::vector<std::unique_ptr<SDL3Gamepad>>, so the container owns the whole device. removeGamepad() and releaseDevices() now just erase/clear, removing every manual free (and the risk that a future early-return skips one). Ordering is unchanged: releaseDevices() clears the list before SDL_Quit, and the later destructor sees an empty list.
Contributor
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Aligns the shell module with the engine's draco:: namespace convention (core, rhi). Module name and API are unchanged; only the enclosing namespace moves.
…ernion to Core Drop the bgfx rendering stack entirely: delete the Rendering and Scene modules, the bx/bimg/bgfx submodules and their ThirdParty build tooling, the shader compilation (cmake/Shaders.cmake), and rewire Runtime/Engine/Draconic so the engine builds on Core + Shell + SDL3 only. RenderSample becomes a shell-only placeholder that opens a window and pumps events until closed. Core/Math kept its one bx dependency (Transform's TRS matrix build), so replace it with native math: add core.math.matrix4 (4x4 row-major, row-vector convention: identity/translation/scale/rotation/perspective/ortho/lookAt, multiply, transpose, transformPoint/Direction/Point2D, determinant, inverse) and core.math.quaternion (fromAxisAngle, Hamilton product, conjugate/dot/inverse/normalize/rotateVector/slerp, rotationMatrix). Rewrite Transform to position/rotation(Quaternion)/scale with an inline toMatrix() and a lerp helper, removing bx from Core entirely. Added missing math helpers used by these types (sin/cos/tan/acos/sqrt, scalar and Vector2/3/4 nearlyEqual, Vector3::zero/one) and added Matrix4/Quaternion/Transform unit tests.
Introduce the rhi module: a backend-agnostic GPU render-hardware-interface, as the primary module 'rhi' with partitions for enums, texture formats, core types, forward declarations, resource/descriptor structs, resources, command recording, extensions (mesh shader / ray tracing), queue, swap chain, and the Backend/Adapter/Device factory. Interface only - concrete backends (Null, Validation, Vulkan, DX12) land as separate modules. Add a small Status/ErrorCode facility to Core (core.status, re-exported via core.defs) for the interface's status-code returns; value-or-error paths use std::expected. Uses this engine's conventions throughout: draco::rhi namespace, camelCase methods/functions/constants (types and enum values stay PascalCase), and std container types (std::vector/span/optional/u8string). Wired via add_modules_library(Rendering/RHI) into Runtime.
Headless no-op RHI backend implementing every rhi interface with stubs: a NullDevice that creates/destroys resources, a mappable NullBuffer backed by host memory, no-op command encoders, and a createNullBackend() entry point. Unsupported extensions (mesh shaders, ray tracing) degrade to NotSupported rather than crash. Intended for headless testing, CI, and tools. Includes a doctest suite covering adapter enumeration, device/resource creation, buffer mapping, and extension degradation. Allocations use new/delete for now (the engine's Slice-based allocator does not compose with polymorphic base-pointer frees; revisit with the GPU backends).
The validation backend (rhi.validation) wraps any RHI backend and checks API usage before forwarding: encoder state machines (recording / in-pass / finished), non-null resource arguments, pipeline-bound-before-draw, viewport/scissor set before draw, monotonic fence signaling, swap chain acquire/present balance, and per-device live-resource leak tracking. Validated wrappers unwrap to the inner objects before forwarding, so an inner backend only ever sees its own types.
The Vulkan backend (rhi.vk) implements the full RHI surface on Vulkan 1.3+ dynamic rendering: adapter enumeration with preference ordering, logical device and queue setup, all resource/pipeline/bind-group creation, command encoders (render/compute/bundle passes), swap chains with platform surfaces (Win32/X11/Wayland), transfer batches, and the mesh-shader and ray-tracing extensions. Requires the Vulkan loader (find_package(Vulkan)); the loader is a private dependency since the headers live in the module's global fragment. Includes a platform-agnostic smoke test that initializes the backend, enumerates adapters, and creates a device. It never touches surfaces, so it runs anywhere a loader is present and skips the device step gracefully when no adapter is available.
The DX12 backend (rhi.dx12) implements the full RHI surface on D3D12: adapter enumeration via DXGI, device/queue setup, all resource/pipeline/bind-group creation, descriptor heap management (CPU staging + GPU-visible ring), command encoders (render/compute/bundle passes with copy-on-bind descriptor staging), swap chains, transfer batches, and the mesh-shader and ray-tracing extensions. Windows only: registration is guarded by if(WIN32) and links the D3D12/DXGI system libraries privately. Includes a platform-agnostic smoke test (built only on Windows) that initializes the backend, enumerates adapters, and creates a device. Not yet compiled — this box has no D3D12 toolchain; the port is to be validated on Windows.
- DxBackend: sortAdaptersByPreference casing to match Device.cppm - DxRenderBundleEncoder: PascalCase delegate calls to camelCase - Math.test: qualify std::cos to resolve overload ambiguity
The shaders module wraps DXC (IDxcCompiler3) to compile HLSL to SPIR-V or DXIL. It loads dxcompiler at runtime (LoadLibrary/dlopen) rather than linking it, so nothing hard-links the compiler. The public compile types (ShaderStage, CompileOptions, CompileResult, ShaderFlags + variant key) are self-contained: the compiler produces bytecode and has no RHI dependency — the RHI-coupled variant cache is a separate module (shaders.system, not yet ported). Draco::DXCHeaders (ThirdParty/DXC) carries the DXC include dir plus DRACO_DXC_PATH, the absolute path the compiler falls back to for the runtime library. The prebuilt DXC runtime libraries themselves are not committed here. Test compiles a trivial vertex shader to SPIR-V (checks the magic number) and confirms a bad shader reports an error instead of crashing — passes against the vendored DXC on Linux.
The sample framework (samples.rhi.framework) is the shared base for the RHI samples, relocated into Samples/cpp/RHI so it is scoped to RHI samples only. SampleApp brings up an SDL3 window (shell.desktop), a Vulkan or DX12 backend (validation-wrapped), device, graphics queue, and swap chain, then runs an event/resize/render loop calling the subclass's onInit/onRender/onResize/onShutdown. DepthBuffer is a recreate-on-resize depth target; ShaderHelpers compiles HLSL to a ShaderModule, picking SPIR-V or DXIL by device type and applying Vulkan binding shifts. The framework re-exports rhi + shell so samples import one module. DX12 is compiled in only on Windows (DRACO_HAS_DX12). Individual samples are added on top of this.
Ports the 30 numbered RHI samples (Triangle through RenderBundles) plus the Smoketest, verbatim apart from the namespace (draco::) and camelCase API changes. They exercise the RHI across vertex/index buffers, textures, uniform buffers, compute, bind groups, blending, instancing, depth, mipmaps, MSAA, MRT, wireframe, samplers, blit, queries, readback, multi-queue, bindless, batch upload, mesh shaders, ray tracing, stencil, cube maps, occlusion queries, multi-draw-indirect, dynamic offsets, 3D textures, procedural RT, resolve, and render bundles. Each sample is one Main.cpp on the shared framework; a draco_add_rhi_sample() helper wires each executable with the whole-archive SDL link so its static video/input drivers survive. Math types are qualified under draco::math (Vector, Matrix4, Quaternion, degToRad). Build only: they open an SDL3 window and need a GPU/display, so they are not run in CI.
Commit the prebuilt DXC runtime libraries (dxcompiler + dxil, for win-x64 and linux-x86_64) that the shaders module loads at runtime via DRACO_DXC_PATH. Tracking them directly keeps a fresh checkout self-contained: the samples compile HLSL at runtime and need dxcompiler present.
The shader system (shaders.system) is a compile-on-demand cache for shader variants on top of the RHI-free shaders compiler. A shader is registered by name per stage; getVariant(name, stage, flags) turns the flags into #defines, compiles the permutation via DXC, creates a GPU ShaderModule, and caches it by (nameHash, stage, flags). Compile failures are not cached, so a later request retries after a fix. invalidateShader drops and destroys a shader's variants and bumps a monotonic version the PSO cache can poll. Variants are keyed in a std::unordered_map via a hash functor for the variant key. Needs the RHI to create modules, so it is a separate library from the base shaders module. Test compiles real SPIR-V via DXC and creates modules on the Null backend, covering flags-to-defines, caching, distinct variants, and invalidation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This is a WIP PR that replaces bgfx with a bespoke WebGPU-inspired RHI that supports a Vulkan and DX12 backend.
It compounds on the shell PR, but will be rebased once the shell PR is merged.