A Direct3D 12 depth offset semantic implementation method based on shader compensation

By abstracting kernel-level hardware capabilities and compensating for shaders, the performance loss and compatibility issues when the GPU does not support the VK_EXT_depth_bias_control extension are resolved. This achieves efficient conversion of D3D12 depth offset to Vulkan, improving both performance and compatibility.

CN121833044BActive Publication Date: 2026-06-09北京麟卓信息科技有限公司

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
北京麟卓信息科技有限公司
Filing Date
2026-03-13
Publication Date
2026-06-09

AI Technical Summary

Technical Problem

When the GPU does not support the VK_EXT_depth_bias_control extension, existing pure software simulation solutions suffer from significant performance loss, inefficient PSO management, and poor cross-GPU compatibility, failing to meet the requirements for efficient VKD3D operation.

Method used

By abstracting kernel-level hardware capabilities, managing user-mode PSO, and fine-grained shader compensation, the core functionality of VK_EXT_depth_bias_control is replicated to achieve efficient conversion from D3D12 depth bias to Vulkan. This includes building an adaptation strategy library, creating fixed PSO templates and dynamic variants, binding shader variants, and submitting drawing instructions to the GPU for execution.

Benefits of technology

Without modifying the GPU driver, an efficient conversion from D3D12 depth offset to Vulkan was achieved, reducing GPU load, improving performance, and enhancing cross-GPU compatibility.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121833044B_ABST
    Figure CN121833044B_ABST
Patent Text Reader

Abstract

The application discloses a Direct3D 12 depth offset semantic implementation method based on shader compensation, and when GPU does not support VK_EXT_depth_bias_control, the system starts after the kernel level detects GPU depth offset characteristics, and builds an adaptive strategy and stores it in the kernel state buffer; after VKD3D and application start, the first history buffer and three-level PSO cache are created by VKD3D; when the application creates a shader and creates a D3D12 PSO, the VKD3D extracts parameters, compiles a Vulkan shader module, analyzes depth offset parameters, queries an adaptive strategy, and generates a corresponding type of shader variant; a PSO fixed template is built, a cache key is generated to query a PSO dynamic variant in the three-level PSO cache, a PSO dynamic variant is bound when a pipeline state is set in the application, and after a drawing instruction is submitted, a Vulkan command buffer is submitted to the GPU to complete rendering.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of computer software development technology, specifically relating to a method for implementing Direct3D12 depth offset semantics based on shader compensation. Background Technology

[0002] VKD3D is an open-source project that simulates Direct3D 12 (hereinafter referred to as D3D12) based on the Vulkan 1.3 standard. Its core workflow is to translate D3D12 API calls on the Windows platform into Vulkan API calls on the Linux platform.

[0003] Depth offset is a core method in 3D graphics rendering for resolving depth conflicts in coplanar polygons (Z-fighting) and optimizing shadow mapping, among other advanced rendering effects. In the D3D12 standard, depth offset is defined through the `D3D12_RASTERIZER_DESC` structure, which includes three core parameters: a fixed depth offset value (DepthBias), an offset factor related to the surface slope (SlopeScaleDepthBias), and an offset clamping threshold (DepthBiasClamp). Furthermore, these parameters can be dynamically modified during rendering using interfaces such as `ID3D12GraphicsCommandList::SetDepthBias` and `ID3D12GraphicsCommandList::RSSetViewports`. While the Vulkan 1.3 core specification provides support for basic depth offsets, it has significant limitations: First, it lacks native support for offset clamping thresholds, making it impossible to directly implement threshold restrictions on offsets; second, dynamic parameter modification only supports `depthBiasConstantFactor` and `depthBiasSlopeFactor`, and the parameter precision and effective range deviate from D3D12 semantics; third, the pipeline state object (PSO) is an immutable object, and frequent modification of depth offset parameters can easily lead to PSO explosion, causing a surge in memory consumption and performance degradation.

[0004] The VK_EXT_depth_bias_control extension feature is designed to address the aforementioned issues. It dynamically configures all depth offset parameters using the vkCmdSetDepthBias2EXT command and precisely maps D3D12 depth offset semantics using the VkPipelineDepthBiasStateCreateInfoEXT structure, becoming a hard dependency of VKD3D. However, when the GPU does not support this extension, existing pure software simulation solutions suffer from significant performance overhead (full fragment shader computation increases GPU load by over 30%), inefficient PSO management, and poor cross-GPU compatibility, failing to meet the requirements for efficient VKD3D operation. Summary of the Invention

[0005] In view of this, the present invention provides a Direct3D 12 depth bias semantic implementation method based on shader compensation. Without modifying the GPU driver, it replicates the core function of VK_EXT_depth_bias_control through kernel-level hardware capability abstraction, user-mode PSO management and fine-grained shader compensation, and achieves efficient conversion of D3D12 depth bias to Vulkan.

[0006] This invention provides a method for implementing Direct3D 12 depth offset semantics based on shader compensation, which specifically includes the following steps:

[0007] When the GPU does not support the VK_EXT_depth_bias_control extension, the system detects the GPU's depth bias characteristics after startup, constructs an adaptation strategy that includes static and dynamic strategies, and stores it in the kernel-mode cache. The adaptation strategy includes Vulkan constant offset, Vulkan slope factor, shader clamping threshold, whether hardware offset is enabled, and strategy flag. After VKD3D and D3D12 applications start, VKD3D creates a first history buffer that stores the actual depth offset and hash value of the D3D12 device and a three-level PSO cache that stores the PSO dynamic variant handle. The PSO fixed template contains pipeline states that do not change with depth offset.

[0008] When a D3D application creates a D3D12 shader and then creates a D3D12 PSO with a pipeline descriptor filled with the shader, VKD3D intercepts the creation request and compiles it to generate a Vulkan shader module. The module encapsulates the fixed depth offset value, the offset factor associated with the surface slope, the offset clamping threshold, the depth offset enable flag, and the rasterization state associated configuration into a first depth offset state. It then calculates the hash value of the depth offset parameters and adds it to the first history buffer. Based on the first depth offset state and the process ID, it retrieves the adaptation strategy from the kernel-mode cache, determines the shader variant type, and constructs the shader variant.

[0009] VKD3D creates a Vulkan PSO object containing a fixed PSO template and dynamic PSO variants, binds the fixed PSO template to the Vulkan shader module, and matches the dynamic PSO variant handle in the three-level PSO cache based on the fixed PSO template identifier and the adaptation strategy identifier. When the D3D application sets up the pipeline state, VKD3D binds the dynamic PSO variant to the Vulkan command buffer. When submitting the drawing, the pre-built Vulkan command buffer is submitted to the GPU hardware graphics execution queue, and the GPU completes the rendering.

[0010] Furthermore, when matching the PSO dynamic variant handle in the three-level PSO cache based on the PSO fixed template identifier and the adaptation strategy identifier, if there is no cache miss, all pipeline states in the PSO fixed template that do not change with depth offset are reused and filled into the structure for creating the Vulkan graphics rendering pipeline. Then, according to the output field of the adaptation strategy, the dynamically differentiated pipeline states in the PSO dynamic variant that are only related to depth offset are configured. The matching shader variant is determined according to the adaptation strategy, and the PSO fixed template is bound to the shader variant. The PSO fixed template identifier and the adaptation strategy identifier are used as the cache key of the PSO dynamic variant, and the PSO dynamic variant is added to the three-level PSO cache. A pipeline creation request is submitted to the GPU to generate a Vulkan PSO dynamic variant handle.

[0011] Furthermore, the Vulkan architecture for creating the graphics rendering pipeline includes Vulkan shader modules, vertex input layout, input assembly state, rasterization fill mode, culling mode, multisampling state, depth and stencil test mode, color blending state, pipeline layout, and rendering channels.

[0012] Furthermore, the specific steps of configuring the pipeline state of the PSO dynamic variant that is only related to the depth offset according to the output field of the adaptation strategy are as follows: if whether to enable hardware offset is TRUE, then enable hardware depth offset in the PSO dynamic variant and enable the dynamic depth offset state bit; otherwise, disable hardware depth offset and mark all depth offset logic as implemented by shaders; fill the PSO dynamic variant with the converted Vulkan constant offset and the converted Vulkan slope factor as the default values ​​of constant offset and slope factor of the depth offset state, mark the shader variant type that the PSO dynamic variant needs to be bound to, and bind the shader clamping threshold and slope compensation coefficient to the pipeline layout of the PSO dynamic variant.

[0013] Furthermore, the method of matching the PSO dynamic variant handle in the three-level PSO cache based on the PSO fixed template identifier and the adaptation strategy identifier is as follows: the cache key of the PSO dynamic variant is composed of the PSO fixed template identifier and the adaptation strategy identifier. The cache is queried in the three-level PSO cache in the order from the first-level cache to the second-level cache and then to the third-level cache. If the first-level cache is hit, the PSO dynamic variant handle is returned. If the second-level cache is hit, the PSO dynamic variant handle is updated to the first-level cache header and the PSO dynamic variant handle is returned. If the third-level cache is hit, the PSO object is created based on the cache creation information without reassembling the pipeline state. After creation, the PSO object is synchronously updated to the first-level cache and the second-level cache and the PSO dynamic variant handle is returned.

[0014] Furthermore, the method for determining the shader variant type and constructing the shader variant is as follows: the shader variant type includes a basic variant, a clamping compensation variant, and a full compensation variant. The basic variant has no depth offset compensation logic and is used in scenarios where the hardware fully supports depth offset. The clamping compensation variant inserts depth offset clamping logic and is used in scenarios where the hardware does not support clamping. The full compensation variant inserts slope correction logic and depth offset clamping logic simultaneously and is used in scenarios where the hardware depth offset capability is weak. Based on the shader variant type, the corresponding SPIR-V instruction is inserted before the depth value output position by the Vulkan shader module to form the shader variant.

[0015] Furthermore, the depth offset clamping logic is as follows: using the Vulkan native fixed depth offset value obtained by parsing the shader code, the vertex shader pre-calculated triangle screen space area, and the slope-related offset value corrected by the fragment shader, the fixed depth offset and the slope-related offset are merged to obtain the final total offset to be applied; the total offset is strictly limited to a set range by the clamping function, which is determined by the depth offset clamping parameters passed in by the application.

[0016] Furthermore, the slope correction logic is as follows: in the vertex shader, the screen space area of ​​the triangle is pre-calculated based on the vertex coordinates in clip space and the actual projection position of the vertex in screen space, and interpolated to each pixel of the triangle during the rasterization stage; in the fragment shader, the D3D12 standard slope value is obtained by dividing the pre-calculated triangle screen space area by the total pixel area of ​​the current viewport, and the D3D12 slope-related depth offset value is calculated by the hardware precision compensation coefficient and the converted slope scaling depth offset, and then added to the fixed offset to obtain the corrected slope.

[0017] Furthermore, a low-latency system call is registered to enable user-mode VKD3D to access the kernel-mode policy cache. Specifically, after the kernel receives an adaptation policy query request, it allows the VKD3D process to call the low-latency system call if the process's permissions are verified. After calculating the hash value of the D3D12 depth offset state, a matching item is searched in the kernel-mode policy cache. If the cache hits, the adaptation policy is returned directly; otherwise, static policy matching is performed to match the corresponding policy from the static policy library or to generate a dynamic policy. The newly generated adaptation policy is stored in the kernel-mode policy cache. The obtained adaptation policy is then copied from kernel-mode to user-mode memory and returned to VKD3D.

[0018] Furthermore, the dynamic strategy is dynamically generated by the parameter mapping algorithm, specifically: calculating the range ratio of the D3D12 parameters to the hardware native parameters, generating a parameter scaling factor based on the range ratio to scale the D3D12 parameters to the effective range of the hardware, setting the shader clamping flag to TRUE and recording the conversion value of the clamping threshold if the hardware does not support the offset clamping threshold, and generating a slope compensation coefficient for shader correction if the hardware slope factor accuracy is insufficient.

[0019] Beneficial effects:

[0020] This invention, when the GPU does not support the VK_EXT_depth_bias_control extension, detects GPU depth offset-related characteristics through kernel-level probing after system startup, and encapsulates and stores the results in the GPU. A global database indexed by PCIe device IDs is used to construct a two-level adaptation strategy system, including static and dynamic strategy libraries. The generated adaptation strategies are stored in the kernel-mode cache, and low-latency system calls are registered for VKD3D access. After VKD3D and D3D12 applications start, VKD3D creates a depth offset parameter history buffer, a three-level PSO cache, and a hash table storing fixed PSO templates. When a D3D application creates a shader and initiates a D3D12 PSO creation request, VKD3D intercepts the request, extracts and compiles the Vulkan shader module, parses the depth offset parameters, queries the kernel for adaptation strategies, and generates shader variants of the corresponding type. VKD3D constructs fixed PSO templates, generates cache keys, and queries the three-level PSO cache level by level. If no match is found, a dynamic PSO variant is created and cached. When the application sets the pipeline state, the dynamic PSO variant is bound, and after submitting the drawing command, the Vulkan command buffer is submitted to the GPU for execution, completing the rendering output. Attached Figure Description

[0021] Figure 1 This is a flowchart illustrating a method for implementing Direct3D 12 depth offset semantics based on shader compensation, provided by the present invention. Detailed Implementation

[0022] The present invention will be described in detail below with reference to the accompanying drawings and embodiments.

[0023] This invention provides a method for implementing Direct3D 12 depth offset semantics based on shader compensation. The core idea is as follows: When the GPU does not support the VK_EXT_depth_bias_control extension, after system startup, the kernel hierarchically detects GPU depth offset-related characteristics, encapsulates the results and stores them in a global database indexed by the GPU PCIe device ID, constructs a two-level adaptation strategy system including a static strategy library and a dynamic strategy library, stores the generated adaptation strategy in the kernel-mode cache, and registers low-latency system calls for VKD3D access; after VKD3D and the D3D12 application start, VKD3D creates a depth offset parameter history buffer, a three-level PSO cache, and a hash table storing fixed PSO templates; the D3D application creates shaders and initiates D3D12. When a PSO creation request is made, VKD3D intercepts the request, extracts and compiles the Vulkan shader module, parses the depth offset parameters, queries the kernel for the adaptation strategy, and generates a shader variant of the corresponding type. VKD3D builds a fixed PSO template, generates a cache key, and queries the three-level PSO cache level by level. If the key is not found, a dynamic PSO variant is created and cached. When the application sets the pipeline state, the dynamic PSO variant is bound. After submitting the drawing command, the Vulkan command buffer is submitted to the GPU for execution to complete the rendering output.

[0024] This invention provides a method for implementing Direct3D 12 depth offset semantics based on shader compensation, the processing flow of which is as follows: Figure 1 As shown, the specific steps include:

[0025] Step 1: After system startup, the depth offset characteristics of the GPU are detected hierarchically, including basic characteristics, parameter range and accuracy, and vendor-specific behaviors. The results are encapsulated into a depth offset structure and stored in the kernel's global database indexed by the GPU PCIe device ID. A two-tiered adaptation strategy is constructed, consisting of a static strategy library and a dynamic strategy library. The static strategy library stores adaptation rules for mainstream GPU architectures, while the dynamic strategy library stores adaptation strategies for GPU models not covered in the static strategy library, dynamically generated by the parameter mapping algorithm. The adaptation strategy includes core fields such as the converted Vulkan constant offset, the converted Vulkan slope factor, shader clamping threshold, whether hardware offset is enabled, and strategy identifier, and is stored in the kernel-mode strategy cache. A low-latency system call is registered to enable user-mode VKD3D to access the strategy cache.

[0026] Among them, the basic characteristics are the GPU's support status for basic features such as dynamic depth offset and depth clamping. The parameter range and precision are the core parameters such as the maximum constant offset, minimum constant offset, maximum slope factor, offset parameter precision bits and parameter type of the hardware native depth offset. Vendor-specific behaviors include the implicit hardware behaviors of different architectures, such as the slope factor amplification coefficient of the AMD GCN architecture.

[0027] The static strategy library dynamically generated by the parameter mapping algorithm does not include GPU model adaptation strategies. Specifically, it calculates the range ratio of D3D12 parameters to hardware native parameters, generates a parameter scaling factor based on the range ratio, and scales the D3D12 parameters to the effective range of the hardware. If the hardware does not support the offset clamping threshold, it sets the shader clamping flag to TRUE and records the conversion value of the clamping threshold. If the hardware slope factor is not accurate enough, it generates a slope compensation coefficient for shader correction.

[0028] Specifically, the registration of low-latency system calls enables user-mode VKD3D to access the policy cache. After receiving an adaptation policy query request, the kernel allows the VKD3D process to call the low-latency system call if its permissions are verified. After calculating the hash value of the D3D12 depth offset state, a match is searched in the kernel-mode policy cache. If a cache hit occurs, the adaptation policy is returned directly; otherwise, static policy matching is performed to match the corresponding policy from the static policy library or to generate a dynamic policy. The newly generated adaptation policy is then stored in the kernel-mode policy cache. Finally, the obtained adaptation policy is copied from kernel-mode to user-mode memory and returned to VKD3D.

[0029] Step 2: After the VKD3D and D3D12 applications start, VKD3D constructs a global device context that stores the default depth offset state of the D3D12 device, a command list context that stores the actual depth offset state of the D3D12 device, and a drawing call context that caches the current command list's depth offset state snapshot. It also creates a depth offset parameter history buffer that stores the structure and corresponding hash value of the most recently used actual depth offset of the D3D12 device. A three-level PSO cache is created, including a first-level cache storing recently used PSO handles, a second-level cache storing all created PSO variants, and a third-level cache storing PSO handles that have not yet been created. Finally, a first hash table is created to store fixed PSO templates. Each fixed PSO template contains pipeline states in Vulkan PSO that do not change with depth offset, and each fixed PSO template has a unique template identifier.

[0030] To optimize subsequent PSO caching and hardware adaptation efficiency, VKD3D maintains a historical buffer for depth offset parameters, which adopts a circular queue structure. The hash value of newly captured parameters is calculated and compared with the historical buffer. If a match is found, it is marked as a reuse parameter, and the reuse count is recorded for subsequent PSO pre-creation priority sorting. The buffer adopts the Least Recently Used (LRU) eviction policy to remove parameter records that have not been used for more than 100 frames, thereby reducing memory usage.

[0031] The PSO fixed template contains pipeline states in Vulkan PSO that do not change with depth offset, such as shader modules, vertex input layout, depth and stencil test modes, rasterization fill modes, etc.

[0032] Step 3: When the D3D application creates a D3D12 shader, it compiles the HLSL code into the D3D12 standard DXIL shader bytecode, then fills the pipeline descriptor with the DXIL shader bytecode, and fills in other core states such as rasterization state and vertex layout. Finally, it creates a D3D12 PSO with the pipeline descriptor filled with shaders as parameters.

[0033] After VKD3D intercepts the D3D12 PSO creation request, it extracts the D3D12 DXIL shader bytecode already created by the application from the pipeline descriptor, compiles it into a Vulkan shader module, determines the output position of the depth value, extracts the embedded fixed depth offset value, the offset factor associated with the surface slope, the offset clamping threshold, the depth offset enable flag, and the rasterization state associated configuration, encapsulates the verified parameters into the first depth offset state and adds it to the global device context, calculates the hash value of the depth offset parameter containing the fixed depth offset value, the offset factor associated with the surface slope, and the offset clamping threshold, adds it to the depth offset parameter history buffer, and marks the number of reuses.

[0034] The adaptation policy query request, constructed from the first depth offset state and the process ID, is sent to the kernel. The adaptation policy is retrieved from the kernel-mode policy cache. The shader variant type is determined based on the adaptation policy. Then, based on the variant type, the corresponding SPIR-V instruction is inserted before the depth value output position by the Vulkan shader module to form a shader variant. A unique shader variant identifier is assigned to the shader variant and stored in the shader variant database.

[0035] The shader variants include the base variant, the clamping compensation variant, and the full compensation variant. The base variant has no depth offset compensation logic and is used in scenarios where the hardware fully supports depth offset. The clamping compensation variant inserts depth offset clamping logic and is used in scenarios where the hardware does not support clamping. The full compensation variant inserts slope correction logic and depth offset clamping logic simultaneously and is used in scenarios where the hardware depth offset capability is weak.

[0036] The depth offset clamping logic inserted in the fragment shader is as follows: the Vulkan native fixed depth offset value obtained by parsing the shader code, the vertex shader pre-calculated triangle screen space area, and the slope-related offset value corrected by the fragment shader are used to merge the fixed depth offset and the slope-related offset to obtain the final total offset to be applied, replicating the native depth offset calculation formula of D3D12; the total offset is strictly limited to a set range by the clamping function, which is determined by the depth offset clamping parameters passed in by the application.

[0037] The slope correction logic is as follows: In the vertex shader, the screen space area of ​​the triangle is pre-calculated based on the vertex coordinates in clip space and the actual projection position of the vertex in screen space. During the rasterization stage, this area is hardware interpolated to each pixel of the triangle to ensure that all fragments within the triangle receive the same area value, fully aligning with the primitive-level calculation logic of D3D12. In the fragment shader, the pre-calculated screen space area of ​​the triangle is divided by the total pixel area of ​​the current viewport to obtain the standard slope value defined by the D3D12 specification. The slope-related depth offset value conforming to the D3D12 specification is calculated using the hardware precision compensation coefficient and the converted slope scaling depth offset. Finally, the corrected slope is obtained by adding the corrected slope value to the fixed offset.

[0038] Furthermore, the present invention optimizes the generated SPIR-V instructions, such as constant folding and dead code elimination, to reduce the number of shader instructions.

[0039] Step 4: VKD3D creates the corresponding Vulkan PSO object, which includes a fixed PSO template and a dynamic PSO variant. The fixed PSO template is composed of pipeline states that do not change with depth offset. A template identifier is assigned to the fixed PSO template, added to the first hash table, and the fixed PSO template is bound to the created Vulkan shader module. The cache key of the dynamic PSO variant is composed of the fixed PSO template identifier and the adaptation strategy identifier. The cache is searched in the three-level PSO cache in the order from the first-level cache to the second-level cache and then to the third-level cache. If the first-level cache is hit, the PSO dynamic variant handle is returned, and step 6 is executed. If the second-level cache is hit, the PSO dynamic variant handle is updated to the first-level cache header and the PSO dynamic variant handle is returned, and step 6 is executed. If the third-level cache is hit, the PSO object is created based on the cache creation information without reassembling the pipeline states. After creation, the PSO object is synchronously updated to the first-level cache and the second-level cache, and the PSO dynamic variant handle is returned, and step 6 is executed. If none of the three-level PSO caches are hit, step 5 is executed to create the dynamic PSO variant.

[0040] Step 5: Reuse all pipeline states in the PSO fixed template that do not change with depth offset, and populate them into the Vulkan graphics rendering pipeline structure, including Vulkan shader modules, vertex input layout, input assembly state, rasterization fill mode, culling mode, multisampling state, depth and stencil test mode, color blending state, pipeline layout, rendering channels, and other fixed pipeline configurations; then configure the dynamically differentiated pipeline states in the PSO dynamic variant that are only related to depth offset according to the output field of the adaptation strategy; determine the matching shader variant according to the adaptation strategy, and then bind the PSO fixed template to the shader variant; use the PSO fixed template identifier and the adaptation strategy identifier as the cache key of the PSO dynamic variant, and add the PSO dynamic variant to the three-level PSO cache; submit a pipeline creation request to the GPU to generate a Vulkan PSO dynamic variant handle.

[0041] Specifically, configuring the pipeline state of dynamic differentiation related only to depth offset in the PSO dynamic variant according to the output field of the adaptation strategy is as follows: when whether to enable hardware offset is TRUE, enable hardware depth offset in the PSO dynamic variant and enable the dynamic depth offset status bit; when whether to enable hardware offset is FALSE, disable hardware depth offset and mark all depth offset logic as implemented by shaders; fill the PSO dynamic variant with the converted Vulkan constant offset and the converted Vulkan slope factor as the default values ​​of constant offset and slope factor for the depth offset state to complete hardware range scaling and precision adaptation; mark the shader variant type that the PSO dynamic variant needs to be bound to, and bind the shader clamping threshold and slope compensation coefficient to the pipeline layout of the PSO dynamic variant.

[0042] Step 6: When setting up the pipeline state in the D3D application, VKD3D binds the created PSO dynamic variant to the Vulkan command buffer; when submitting the drawing, the pre-built Vulkan command buffer is submitted to the GPU hardware graphics execution queue, and the GPU executes the commands to complete the rendering output.

[0043] Example:

[0044] This embodiment employs a shader-compensated Direct3D 12 depth offset semantic implementation method provided by the present invention. It enables the normal operation of D3D 12 applications in a GPU hardware environment that does not support the VK_EXT_depth_bias_control extended feature. The specific process includes:

[0045] The full-dimensional capture and context-level management of S1 and D3D12 depth offset parameters: As the conversion layer between D3D12 and Vulkan, VKD3D first needs to complete the full capture and context state management of the D3D12 depth offset related interface calls.

[0046] S1.1, Precise identification of interface calls: VKD3D identifies all calls related to depth offset by overriding the core interfaces of D3D12, including:

[0047] Explicit parameter modification: Capture the ID3D12GraphicsCommandList::SetDepthBias interface call and extract the three parameters passed in: DepthBias, SlopeScaleDepthBias, and DepthBiasClamp.

[0048] Implicit state association: Capture the ID3D12GraphicsCommandList::RSSetViewports and ID3D12GraphicsCommandList::RSSetState interface calls and parse the depth offset parameters embedded in the rasterizer state object (RasterizerState);

[0049] Pipeline State Binding: Capture the ID3D12GraphicsCommandList::SetPipelineState interface call and extract the pre-configured depth offset static parameter in the D3D12 PSO.

[0050] For each interface call, VKD3D records the call sequence, parameter source (explicit setting, pipeline binding, viewport association), and call context (main command list, subcommand list, calculation command list).

[0051] S1.2 Parameter Structured Parsing and Validation: For the captured depth offset parameters, VKD3D performs multi-dimensional validity checks to ensure that the parameters comply with the D3D12 specification and the compatibility requirements of Vulkan hardware.

[0052] Numerical range check: Check whether DepthBias exceeds the range of [-FLT_MAX, FLT_MAX] defined by D3D12, and whether DepthBiasClamp is a non-negative value (as required by the D3D12 specification). If the parameters are abnormal, return the E_INVALIDARG error according to the D3D12 standard.

[0053] Precision adaptation preprocessing: Convert the 64-bit double-precision floating-point parameters of D3D12 to 32-bit single-precision floating-point numbers supported by Vulkan, and record the precision loss value for subsequent shader compensation.

[0054] State correlation verification: Check the linkage between the depth offset enabled state (DepthBiasEnable) and the rasterization state (e.g., when depth testing is disabled, depth offset should automatically become invalid). If there is a conflict, correct the parameters according to the D3D12 behavior logic.

[0055] The validated parameters are encapsulated into a D3D12DepthBiasState structure, which contains five core fields: fixed offset fDepthBias, slope factor fSlopeScale, clamping threshold fClamp, enable flag bEnable, and parameter source identifier uiParamSource.

[0056] S1.3 Hierarchical storage and state inheritance of context: VKD3D constructs a three-level context storage structure to achieve precise management and inheritance of depth offset states, thus addressing the omissions in state inheritance in traditional solutions.

[0057] Global device context: Stores the default depth offset state of the D3D12 device (initial values ​​are DepthBias=0, SlopeScaleDepthBias=0, DepthBiasClamp=0), serving as the base state for all command lists;

[0058] Command list context: Each D3D12 command list (including the main list and sub-lists) maintains an independent D3D12DepthBiasState instance, which initially inherits the state from the global device context and is subsequently updated in real time with API calls;

[0059] Draw call context: For each draw call, a snapshot of the depth offset state of the current command list is temporarily cached to prevent the state from being accidentally modified during the drawing process.

[0060] When a command list copy (ID3D12CommandList::CopyCommands) or a subcommand list execution (ID3D12GraphicsCommandList::ExecuteIndirect) occurs, VKD3D automatically copies the depth offset context depth of the source command list to the target list to ensure consistency of state inheritance.

[0061] S1.4 Parameter History Caching and Reuse Marking: To optimize subsequent PSO caching and hardware adaptation efficiency, VKD3D maintains a depth offset parameter history buffer.

[0062] The buffer adopts a circular queue structure with a capacity of 64 (covering 99% of the game scene parameter switching frequency). It stores the most recently used D3D12DepthBiasState structure and its corresponding hash value. For newly captured parameters, its hash value is calculated and compared with the historical buffer. If a match is found, it is marked as a reuse parameter and the reuse count is recorded for subsequent PSO pre-creation priority sorting. The buffer adopts an LRU (Least Recently Used) eviction policy to remove parameter records that have not been used for more than 100 frames, reducing memory usage.

[0063] S2. Construction and Refined Querying of the Kernel-Mode Depth Bias Hardware Adaptation Layer (DBHAL): To address the issue of varying depth bias capabilities across different GPU hardware, this invention adds a Depth Bias Hardware Adaptation Layer (DBHAL) to the Linux kernel. Through kernel-level hardware detection, policy generation, and parameter conversion, it provides a unified hardware capability abstraction interface for user space. This step is further broken down into the following sub-steps:

[0064] S2.1, Staged Detection and Modeling of GPU Depth Bias Characteristics: After the GPU driver is loaded, the kernel module vk_depth_bias_adapter.ko triggers a three-level hardware characteristic detection to generate a refined hardware capability model.

[0065] Basic feature detection: Call Vulkan's vkGetPhysicalDeviceFeatures2 interface to obtain the GPU's support status for basic features such as VK_DYNAMIC_STATE_DEPTH_BIAS and VK_FEATURE_DEPTH_CLAMP, and record boolean values ​​such as whether dynamic depth offset bSupportDynamicBias and depth clamping bSupportDepthClamp are supported;

[0066] Parameter range and precision detection: Call the vkGetPhysicalDeviceDepthStencilProperties interface to extract key parameters of the hardware native depth offset, including the maximum constant offset fMaxConstantBias, the minimum constant offset fMinConstantBias, the maximum slope factor fMaxSlopeBias, the offset parameter precision bits uiBiasPrecisionBits, and the parameter type eBiasValueType (including floating-point, fixed-point, and integer).

[0067] Vendor-specific behavior detection: Obtain GPU vendor and architecture information through vkGetPhysicalDeviceProperties2, perform vendor-specific behavior tests for different hardware such as NVIDIA, AMD, and Intel (such as drawing test triangles and reading the offset values ​​of actual hardware applications), and record implicit hardware behaviors (such as the slope factor amplification coefficient of AMD GCN architecture and the depth offset clamping threshold of NVIDIA Ada architecture).

[0068] All detection results are encapsulated into a VkDepthBiasHardwareCapabilities structure, stored in the kernel's gpu_hardware_db global database, and indexed by the GPU's PCIe device ID.

[0069] S2.2 Static loading and dynamic generation of the adaptation strategy library: DBHAL builds a two-level adaptation strategy library based on VkDepthBiasHardwareCapabilities to achieve precise mapping from D3D12 parameters to Vulkan parameters.

[0070] Static strategy library: Built-in adaptation rules for mainstream GPU architectures (such as the slope factor conversion formula for NVIDIA Turing architecture and the constant offset scaling factor for AMD RDNA2 architecture), stored in the kernel's / lib / modules / [kernel-version] / kernel / drivers / gpu / vk_dbhal / static_strategy.db file, which is loaded into memory when the system starts;

[0071] Dynamic strategy generation: For GPU models not covered by the static library, DBHAL dynamically generates adaptation strategies through a parameter mapping algorithm.

[0072] Calculate the range ratio of D3D12 parameters to native hardware parameters (e.g., fRangeRatio = fD3D12MaxBias / fHardwareMaxBias).

[0073] The D3D12 parameters are scaled to the effective range of the hardware based on the ratio (fScaleFactor = 1.0 / fRangeRatio).

[0074] If the hardware does not support DepthBiasClamp, then mark bNeedShaderClamp = true and record the converted value of the clamping threshold;

[0075] If the hardware slope factor is not precise enough, a slope compensation coefficient (fSlopeCompensate = fHardwarePrecision / fD3D12Precision) is generated for subsequent shader correction.

[0076] The final adaptation strategy is encapsulated into a VkDepthBiasAdaptationStrategy structure, which includes core fields such as the converted Vulkan constant offset fVkConstantFactor, the converted Vulkan slope factor fVkSlopeFactor, the shader clamping threshold fShaderClampValue, whether to enable hardware offset bUseHardwareBias, and the strategy unique identifier uiStrategyID.

[0077] S2.3 Implementation of Low-Latency Query Interface from User Space to Kernel Space: To enable efficient access to kernel-space adaptation strategies by user-space VKD3D, DBHAL adds the system call sys_vk_query_depth_bias_strategy and optimizes query performance.

[0078] System call parameter definition:

[0079] long sys_vk_query_depth_bias_strategy(

[0080] pid_t pid, / / Calling process ID

[0081] const struct D3D12DepthBiasState *pD3D12State, / / D3D12 depth offset state

[0082] struct VkDepthBiasAdaptationStrategy *pOutStrategy, / / Output adaptation strategy

[0083] bool bCacheResult / / Whether to cache query results );

[0085] Query process optimization: After receiving a query request, the kernel first verifies the process permissions (only allowing the VKD3D process to call); calculates the hash value of pD3D12State and searches for a match in kernel_strategy_cache (kernel-mode policy cache); if the cache hits, the policy is returned directly; if not, static policy matching or dynamic policy generation is performed; if bCacheResult is true, the newly generated policy is stored in kernel_strategy_cache (cache capacity is 1024, using LRU eviction); pOutStrategy is copied from kernel-mode to user-mode memory and returned to VKD3D.

[0086] Performance optimization: The average response time of system calls is controlled within 1μs, and the overhead of large parameter transmission is further reduced by replacing traditional copying with memory mapping (mmap).

[0087] S3. A refined implementation of the User-Space Dynamic PSO Cache Manager (DPCM): To address the PSO explosion problem, VKD3D introduces the Dynamic PSO Cache Manager (DPCM), which achieves efficient management of Vulkan PSOs through templated, hierarchical caching, and pre-creation mechanisms. This step is further broken down into the following sub-steps:

[0088] S3.1, PSO template splitting and classification management: DPCM splits Vulkan PSOs into two parts: a fixed template and a dynamic variant, eliminating the influence of depth offset parameters on PSO uniqueness.

[0089] PSO Fixed Templates: Contain core states in Vulkan PSO that do not change with depth offset, such as shader modules, vertex input layout, depth and stencil test modes, rasterization fill modes, etc. DPCM assigns a template identifier uiTemplateID to each unique fixed template and stores it in the template_database hash table;

[0090] PSO dynamic variant: contains only states related to depth offset (such as the depth offset enable flag and hardware parameters in VkPipelineDepthStencilStateCreateInfo), and is uniquely identified by a fixed template and adaptation policy ID.

[0091] For example, two D3D12 PSOs that differ only in their depth offset parameter can reuse the same fixed template in Vulkan by simply creating different dynamic variants.

[0092] S3.2 Multi-dimensional generation and conflict resolution of cache keys: DPCM generates a globally unique cache key for each PSO dynamic variant, ensuring the accuracy of cache lookup.

[0093] Cache key composition: The cache key is a 64-bit unsigned integer, composed of the following fields concatenated bit by bit:

[0094] uiTemplateID (24 bits): PSO fixed template identifier;

[0095] uiStrategyID (20 bits): Kernel adaptation strategy identifier;

[0096] uiDynamicStateMask (16-bit): Mask for other dynamic states (such as viewport, clipping rectangle);

[0097] uiVendorID (4 digits): GPU manufacturer identifier (distinguishing between NVIDIA, AMD, and Intel).

[0098] Hash collision resolution: Hash collisions are handled using chaining. A doubly linked list is maintained in each bucket of the pso_cache hash table to store PSO variants with the same cache key but different actual states. These variants are further distinguished by an additional pso_state_checksum.

[0099] S3.3, PSO caching layered management and pre-creation mechanism: DPCM constructs a three-level PSO caching architecture, balancing access speed and cache hit rate:

[0100] Level 1 cache (L1): Capacity is 256, stores recently used PSO handles, adopts a circular buffer structure, access latency <10ns, hit rate target ≥90%;

[0101] Secondary cache (L2): with a capacity of 2048, it stores all created PSO variants, uses a hash table for storage, implements read-write locks through pthread_rwlock_t, and supports multi-threaded concurrent access;

[0102] Level 3 cache (L3): with a capacity of 8192, stores PSO creation information (such as the VkGraphicsPipelineCreateInfo structure), does not actually create PSO objects, and only compiles them dynamically when needed.

[0103] Meanwhile, DPCM implements PSO pre-creation based on the parameter history buffer:

[0104] Analyze the parameter history and extract depth offset parameter combinations that have been reused ≥5 times;

[0105] In VKD3D's idle frames (CPU or GPU load <50%), vkCreateGraphicsPipelines is called asynchronously to create a PSO variant;

[0106] Store the pre-created PSO in the L2 cache and mark it as pre-created. When the drawing call requires it, bind it directly.

[0107] S3.4, PSO Failure Handling and Resource Reclamation: To avoid cache bloat and resource leaks, DPCM implements a refined PSO failure and reclamation mechanism:

[0108] Active invalidation: When the shader module and pipeline layout corresponding to the PSO fixed template are destroyed, DPCM automatically marks all associated dynamic variants as invalid and removes them from the cache;

[0109] Passive reclamation: A dual-threshold LRU reclamation strategy is adopted. When the L2 cache capacity reaches 80%, the least recently used PSO variant is removed; when the capacity reaches 90%, forced reclamation is triggered to release all invalid PSO handles.

[0110] Resource release: When reclaiming a PSO, first call vkDestroyPipeline to release Vulkan resources, and then release the memory of the PSO creation information to ensure no memory leaks.

[0111] S4. Shader-level depth offset precision compensation and variant optimization: When the kernel adaptation strategy flag bNeedShaderClamp=true or the hardware depth offset precision is insufficient, VKD3D inserts compensation logic through the shader translation layer to achieve precise reproduction of D3D12 depth offset semantics.

[0112] S4.1 Automated generation and management of shader variants: The VKD3D HLSL to SPIR-V translation layer adds a depth offset compensation variant generation module to generate multiple variants for each original shader.

[0113] Variant classification:

[0114] Basic variant: No depth offset compensation logic, for scenarios where the hardware fully supports depth offset;

[0115] Clamping compensation variant: Inserts DepthBiasClamp clamping logic for scenarios where the hardware does not support clamping;

[0116] Full compensation variant: Simultaneously inserts slope correction and clamping logic, used in scenarios where hardware depth offset capability is weak.

[0117] Generation process:

[0118] Parse the original HLSL code to locate the output position of the depth value (such as the variable with the SV_Depth semantics).

[0119] According to the kernel adaptation strategy, SPIR-V instructions with compensation logic are inserted before the output depth value;

[0120] A unique shader_variant_id is generated for each variant and stored in the shader_variant_db database;

[0121] The generated SPIR-V code is optimized (e.g., constant folding, dead code elimination) to reduce the number of shader instructions.

[0122] The S4.2 and D3D12 slope calculation logic are accurately reproduced. D3D12 and Vulkan differ in their surface slope calculation methods (D3D12 is based on the triangle screen space area, while Vulkan is based on the pixel derivative). VKD3D implements accurate simulation of the D3D12 slope in the shader:

[0123] Pre-calculation of vertex shader slope:

[0124] / / Calculating the screen space area of ​​a triangle in the vertex shader (basics of D3D12 slope calculation)

[0125] struct VS_OUTPUT {

[0126] float4 pos : SV_POSITION;

[0127] float3 screenPos : TEXCOORD0;

[0128] float triangleArea : TEXCOORD1; / / Store the area of ​​the triangle

[0129] };

[0130] VS_OUTPUT VSMain(VS_INPUT input) {

[0131] VS_OUTPUT output;

[0132] output.pos = mul(input.pos, mvpMatrix);

[0133] output.screenPos = output.pos.xyz / output.pos.w;

[0134] / / Calculate the area of ​​a triangle (using vertex indices to find adjacent vertices)

[0135] float3 v1 = screenPos[gl_VertexIndex % 3];

[0136] float3 v2 = screenPos[(gl_VertexIndex + 1) % 3];

[0137] float3 v3 = screenPos[(gl_VertexIndex + 2) % 3];

[0138] output.triangleArea = length(cross(v2 - v1, v3 - v1)) / 2.0;

[0139] return output;

[0140] }

[0141] Slope correction for fragment shaders:

[0142] / / Calculating the D3D12 standard slope based on the triangle area in the fragment shader

[0143] float slopeD3D12 = output.triangleArea / (screenWidth *screenHeight);

[0144] / / Apply slope scaling factor and compensation coefficient

[0145] float slopeBias = slopeD3D12 * fVkSlopeFactor * fSlopeCompensate;

[0146] S4.3 Depth Offset Clamping and Depth Value Modification Optimization: Depth offset clamping logic is inserted into the fragment shader, and the performance impact of depth value modification is optimized.

[0147] Implementation of the constraint logic:

[0148] / / Calculate the total depth offset value

[0149] float totalBias = fVkConstantFactor + slopeBias;

[0150] / / Apply D3D12 DepthBiasClamp clamp

[0151] totalBias = clamp(totalBias, -fShaderClampValue, fShaderClampValue);

[0152] Performance optimizations for depth value modification:

[0153] Modify gl_FragDepth only when depth offset is enabled to avoid invalid calculations when it is disabled;

[0154] By leveraging Vulkan's VK_EXT_early_fragment_tests extension, deep tests can be performed in advance, reducing the number of fragments for which offsets need to be applied.

[0155] For scenarios with a depth buffer format of D32_SFLOAT, the floating-point depth value is directly modified; for the D24_UNORM_S8_UINT format, it is first converted to a floating-point number and then the offset is applied to avoid precision loss.

[0156] S4.4 Dynamic binding and switching of shader variants: When creating a PSO dynamic variant, DPCM automatically binds the corresponding shader variant according to the kernel adaptation strategy.

[0157] If bNeedShaderClamp = true, bind the clamp compensation variant;

[0158] If the hardware slope accuracy is insufficient, bind a full compensation variant;

[0159] If the hardware fully supports depth offset, bind the base variant.

[0160] Shader variant switching is achieved through PSO binding, without requiring modification to the drawing command flow, ensuring compatibility with the Vulkan command execution process.

[0161] S5 and Vulkan command stream construction, synchronization, and submission optimizations: VKD3D converts the processed depth offset state into a Vulkan command stream and submits it to the GPU, filling gaps in command synchronization, error rollback, batch processing optimization, and other processes.

[0162] S5.1 Fine-grained construction of Vulkan commands: Before drawing calls, VKD3D constructs Vulkan commands in the following order:

[0163] PSO binding: Retrieves the matching PSO variant from DPCM and calls vkCmdBindPipeline to bind it to the current command buffer;

[0164] Dynamic state setting: If bUseHardwareBias = true, call vkCmdSetDepthBias to set the converted Vulkan depth offset parameters (fVkConstantFactor, fVkSlopeFactor).

[0165] Viewport and clipping rectangle settings: If the depth offset is associated with the viewport, call vkCmdSetViewports and vkCmdSetScissor to update the viewport state synchronously.

[0166] Draw command submission: Call vkCmdDraw or vkCmdDrawIndexed to execute the drawing. If a shader compensation variant is bound, the GPU will automatically execute the depth offset compensation logic.

[0167] S5.2 Command Buffer State Synchronization and Conflict Resolution: To avoid conflicts between the depth offset state and other Vulkan states, VKD3D implements a command buffer state synchronization mechanism:

[0168] State dirty marking management: Maintain a VkCommandBufferState structure for each command buffer to mark the dirty state (whether it needs to be updated) of states such as depth offset, viewport, and PSO.

[0169] Synchronization timing control: The corresponding vkCmdSet* command is executed only when the state is dirty to avoid duplicate settings;

[0170] Conflict detection and correction: If a conflict is detected between the depth offset enabled state and the depth test disabled state (D3D12 requires that the depth offset is invalid when the depth test is disabled), vkCmdSetDepthBias is automatically called to set the offset parameter to zero and the shader compensation logic is marked as invalid.

[0171] S5.3 Error Rollback and Exception Handling: VKD3D implements a multi-level error rollback strategy to address exceptions such as PSO creation failure and shader compilation errors.

[0172] Level 1 rollback: If PSO creation fails (e.g., parameters exceed hardware limitations), DPCM automatically selects a PSO variant that is fully simulated in software and implements depth offset entirely through shaders;

[0173] Secondary fallback: If the shader compensation variant fails to compile, it is downgraded to a basic depth offset simulation (using only hardware constant offsets, abandoning slope factors and clamping), and a warning is logged.

[0174] Level 3 rollback: If the hardware does not support depth offset at all, disable the depth offset function and return a warning message to the application through the ID3D12InfoQueue interface of D3D12 to ensure that the application does not crash.

[0175] S5.4 Batch processing optimization for drawing calls: VKD3D reduces the overhead of PSO binding and state switching through batch processing of drawing calls.

[0176] Same strategy batch processing: merge drawing calls that use the same depth offset adaptation strategy into a batch, bind PSO only once at the beginning of the batch, and share state within the batch;

[0177] Empty draw call culling: If all depth offset parameters are zero and compensation logic is disabled, the corresponding empty draw call is culled to reduce the number of command submissions;

[0178] Indirect drawing optimization: For the vkCmdDrawIndirect call, the depth offset information in the indirect parameter buffer is parsed in advance, and the corresponding PSO variant is pre-bound.

[0179] This embodiment mainly involves the following definitions:

[0180] DBHAL (Depth Bias Hardware Adaptation Layer): A dedicated module (vk_depth_bias_adapter.ko) added to the Linux kernel. Its functions include GPU depth bias feature detection, adaptation strategy generation, and provision of user-space query interface. Its core is to abstract hardware capabilities into a unified interface to solve the adaptation problem of different GPU depth bias capabilities.

[0181] DPCM (Dynamic PSO Cache Manager): A new user-space module added to VKD3D. Its functions include PSO template splitting, three-level cache management, PSO pre-creation and recycling. Its core is to solve the PSO explosion problem and achieve efficient management and reuse of Vulkan PSO.

[0182] The three-level context storage structure is a D3D12 depth offset state storage system, which includes a global device context (storing the default state of the device), a command list context (each command list has an independent state, inherited from the global context), and a drawing call context (a temporary snapshot before drawing). The core is to ensure the consistency of state inheritance and modification.

[0183] Two-level adaptation strategy library: The adaptation strategy system built in DBHAL includes a static strategy library (with built-in adaptation rules for mainstream GPU architectures, stored in a specified kernel path) and dynamic strategy generation (for GPUs not covered by the static library, strategies are generated in real time through parameter mapping algorithms). The core is to achieve adaptation coverage for all GPU models.

[0184] Three-level PSO caching architecture: The PSO caching system designed in DPCM includes L1 cache (circular buffer, storing the 256 most recent PSO handles), L2 cache (hash table, storing 2048 created PSO variants), and L3 cache (storing creation information for 8192 PSOs, dynamically compiled). The core is to balance cache hit rate and access latency.

[0185] Parameter history buffer: Stores the most recently used D3D12DepthBiasState structure and hash value in a circular queue (capacity 64). It adopts an LRU eviction policy. The core purpose is to provide a highly reusable parameter basis for the pre-creation of PSO in DPCM.

[0186] Dual-threshold LRU eviction strategy: The PSO eviction mechanism proposed in DPCM removes the least recently used variant when the L2 cache capacity reaches 80%, and forcibly evictions all invalid variants when it reaches 90%. The core is to avoid cache bloat and resource leakage.

[0187] Shader compensation variants: The three types of HLSL to SPIR-V shader variants generated include the base variant (no compensation), the clamp compensation variant (inserting DepthBiasClamp logic), and the full compensation variant (inserting slope correction and clamp logic). The core is to adapt to different hardware defect scenarios.

[0188] Command buffer state dirty marking management: In the command synchronization mechanism, the VkCommandBufferState structure is used to mark whether states such as depth offset and PSO need to be updated. The core is to reduce repeated vkCmdSet* commands and improve command flow efficiency.

[0189] Multi-level error rollback strategy: The designed exception handling mechanism includes a first-level rollback (PSO failure to full software simulation), a second-level rollback (shader failure to base offset), and a third-level rollback (hardware incompatibility to disabling functionality). The core is to ensure application stability under extreme scenarios.

[0190] Experiments have verified that this invention achieves efficient simulation of D3D12 depth offset on GPUs that do not support VK_EXT_depth_bias_control through a three-level layered scheme: kernel-mode hardware adaptation, user-mode dynamic management, and precise shader layer compensation.

[0191] Semantic accuracy is achieved through kernel-level parameter transformation and shader-level D3D12 slope logic reproduction. The visual effect of depth offset simulation is 99.9% consistent with the native performance of D3D12 on the Windows platform, completely eliminating rendering errors such as Z-fighting and shadow floating.

[0192] Performance optimization maximizes the use of the GPU's native depth offset capabilities, enabling software compensation only when necessary. Compared to pure software simulation solutions, GPU load is reduced by more than 35%, the number of PSOs is reduced by 80%, and pipeline creation overhead is reduced by 90%.

[0193] Dynamic efficiency: Through kernel-mode policy caching and user-mode PSO pre-creation, the average response time for dynamic modification of depth offset parameters is less than 5μs, which fully meets the real-time requirements of D3D12.

[0194] It boasts broad compatibility, supporting all NVIDIA, AMD, and Intel GPUs without requiring modifications to the driver source code. It also supports Linux kernel version 5.10 and above and can be directly integrated into the VKD3D mainline code.

[0195] Scalability: The kernel-level static policy library supports dynamic updates, allowing adaptation to newly released GPU models by adding new policy files without modifying the core code.

[0196] In summary, the above are merely preferred embodiments of the present invention and are not intended to limit the scope of protection of the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A method for implementing Direct3D 12 depth offset semantics based on shader compensation, characterized in that, Specifically, the following steps are included: When the GPU does not support the VK_EXT_depth_bias_control extension, the system detects the GPU's depth offset characteristics after startup, constructs an adaptation strategy that includes static and dynamic strategies, and stores it in the kernel-mode cache. The adaptation strategy includes Vulkan constant offset, Vulkan slope factor, shader clamping threshold, whether to enable hardware offset, and policy flag; after VKD3D and D3D12 applications start, VKD3D creates a first history buffer that stores the actual depth offset and hash value of the D3D12 device and a three-level PSO cache that stores the PSO dynamic variant handle. The PSO fixed template contains pipeline states that do not change with depth offset. When a D3D application creates a D3D12 shader and then creates a D3D12 PSO with a pipeline descriptor filled with the shader, VKD3D intercepts the creation request and compiles it to generate a Vulkan shader module. The module encapsulates the fixed depth offset value, the offset factor associated with the surface slope, the offset clamping threshold, the depth offset enable flag, and the rasterization state associated configuration into a first depth offset state. It then calculates the hash value of the depth offset parameters and adds it to the first history buffer. Based on the first depth offset state and the process ID, it retrieves the adaptation strategy from the kernel-mode cache, determines the shader variant type, and constructs the shader variant. VKD3D creates a Vulkan PSO object containing a fixed PSO template and dynamic PSO variants, binds the fixed PSO template to the Vulkan shader module, and matches the dynamic PSO variant handle in the three-level PSO cache based on the fixed PSO template identifier and the adaptation strategy identifier. When the D3D application sets up the pipeline state, VKD3D binds the dynamic PSO variant to the Vulkan command buffer. When submitting the drawing, the pre-built Vulkan command buffer is submitted to the GPU hardware graphics execution queue, and the GPU completes the rendering.

2. The Direct3D 12 depth offset semantic implementation method according to claim 1, characterized in that, When matching the PSO dynamic variant handle in the three-level PSO cache based on the PSO fixed template identifier and the adaptation strategy identifier, if there is no cache miss, all pipeline states in the PSO fixed template that do not change with depth offset are reused and filled into the structure for creating the Vulkan graphics rendering pipeline. Then, according to the output field of the adaptation strategy, the dynamically differentiated pipeline states in the PSO dynamic variant that are only related to depth offset are configured. The matching shader variant is determined according to the adaptation strategy, and then the PSO fixed template is bound to the shader variant. The PSO fixed template identifier and the adaptation strategy identifier are used as the cache key of the PSO dynamic variant, and the PSO dynamic variant is added to the three-level PSO cache. A pipeline creation request is submitted to the GPU to generate a Vulkan PSO dynamic variant handle.

3. The Direct3D 12 depth offset semantic implementation method according to claim 2, characterized in that, The Vulkan architecture for creating the graphics rendering pipeline includes the Vulkan shader module, vertex input layout, input assembly state, rasterization fill mode, culling mode, multisampling state, depth and stencil test mode, color blending state, pipeline layout, and rendering channels.

4. The Direct3D 12 depth offset semantic implementation method according to claim 2, characterized in that, The specific steps for configuring the pipeline state of the PSO dynamic variant that is only related to the depth offset according to the output field of the adaptation strategy are as follows: if whether to enable hardware offset is TRUE, then enable hardware depth offset in the PSO dynamic variant and enable the dynamic depth offset state bit; otherwise, disable hardware depth offset and mark all depth offset logic as implemented by shaders; fill the PSO dynamic variant with the converted Vulkan constant offset and the converted Vulkan slope factor as the default values ​​of constant offset and slope factor of the depth offset state, mark the shader variant type that the PSO dynamic variant needs to be bound to, and bind the shader clamping threshold and slope compensation coefficient to the pipeline layout of the PSO dynamic variant.

5. The Direct3D 12 depth offset semantic implementation method according to claim 1, characterized in that, The method for matching PSO dynamic variant handles in the three-level PSO cache based on the PSO fixed template identifier and the adaptation strategy identifier is as follows: The cache key of the PSO dynamic variant is composed of the PSO fixed template identifier and the adaptation strategy identifier. The cache is queried in the three-level PSO cache in the order from the first-level cache to the second-level cache and then to the third-level cache. If the first-level cache is hit, the PSO dynamic variant handle is returned. If the second-level cache is hit, the PSO dynamic variant handle is updated to the first-level cache header and the PSO dynamic variant handle is returned. If the third-level cache is hit, the PSO object is created based on the cache creation information without reassembling the pipeline state. After creation, the PSO object is synchronously updated to the first-level cache and the second-level cache and the PSO dynamic variant handle is returned.

6. The Direct3D 12 depth offset semantic implementation method according to claim 1, characterized in that, The method for determining the shader variant type and constructing the shader variant is as follows: the shader variant type includes a basic variant, a clamping compensation variant, and a full compensation variant. The basic variant is without depth offset compensation logic and is used in scenarios where the hardware fully supports depth offset. The clamping compensation variant is an insertion depth offset clamping logic, used in scenarios where the hardware does not support clamping; The full compensation variant inserts slope correction logic and depth offset clamping logic simultaneously, and is used in scenarios where the hardware depth offset capability is weak. Depending on the shader variant type, the corresponding SPIR-V instruction is inserted before the depth value output position based on the Vulkan shader module to form the shader variant.

7. The Direct3D 12 depth offset semantic implementation method according to claim 6, characterized in that, The depth offset clamping logic is as follows: the Vulkan native fixed depth offset value obtained by parsing the shader code, the vertex shader pre-calculated triangle screen space area, and the slope-related offset value corrected by the fragment shader are used to merge the fixed depth offset and the slope-related offset to obtain the final total offset to be applied; the total offset is strictly limited to a set range by the clamping function, which is determined by the depth offset clamping parameters passed in by the application.

8. The Direct3D 12 depth offset semantic implementation method according to claim 6, characterized in that, The slope correction logic is as follows: In the vertex shader, the screen space area of ​​the triangle is pre-calculated based on the vertex coordinates in clip space and the actual projection position of the vertex in screen space, and interpolated to each pixel of the triangle during the rasterization stage; In the fragment shader, the D3D12 standard slope value is obtained by dividing the pre-calculated triangle screen space area by the total pixel area of ​​the current viewport, and the D3D12 slope-related depth offset value is calculated by the hardware precision compensation coefficient and the converted slope scaling depth offset, and then added to the fixed offset to obtain the corrected slope.

9. The Direct3D 12 depth offset semantic implementation method according to claim 1, characterized in that, Registering a low-latency system call enables user-mode VKD3D to access the kernel-mode policy cache. Specifically, after the kernel receives an adaptation policy query request, it allows the VKD3D process to call the low-latency system call when the verification process permission is verified. After calculating the hash value of the D3D12 depth offset state, a matching item is searched in the kernel-mode policy cache. If the cache hits, the adaptation policy is returned directly. Otherwise, static policy matching is performed to match the corresponding policy from the static policy library or to generate a dynamic policy. The newly generated adaptation policy is then stored in the kernel-mode policy cache. The obtained adaptation strategy is returned to VKD3D via a memory copy from kernel space to user space.

10. The Direct3D 12 depth offset semantic implementation method according to claim 9, characterized in that, The dynamic strategy is dynamically generated by the parameter mapping algorithm. Specifically, it calculates the range ratio of the D3D12 parameters to the hardware native parameters, generates a parameter scaling factor based on the range ratio, and scales the D3D12 parameters to the effective range of the hardware. If the hardware does not support the offset clamping threshold, the shader clamping flag is set to TRUE and the conversion value of the clamping threshold is recorded. If the accuracy of the hardware slope factor is insufficient, a slope compensation coefficient is generated for shader correction.