Direct3D 11.3 Functional Specification

Version 1.17 - 6/20/2025


Full Table of Contents at end of document.

Condensed Table of Contents

  • 1 Introduction
  • 2 Rendering Pipeline Overview
  • 3 Basics
  • 4 Rendering Pipeline
  • 5 Resources
  • 6 Multicore
  • 7 Common Shader Internals
  • 8 Input Assembler Stage
  • 9 Vertex Shader Stage
  • 10 Hull Shader Stage
  • 11 Tessellator
  • 12 Domain Shader Stage
  • 13 Geometry Shader Stage
  • 14 Stream Output Stage
  • 15 Rasterizer Stage
  • 16 Pixel Shader Stage
  • 17 Output Merger Stage
  • 18 Compute Shader Stage
  • 19 Stage-Memory I/O
  • 20 Asynchronous Notification
  • 21 System Limits on Various Resources
  • 22 Shader Instruction Reference
  • 23 System Generated Values Reference
  • 24 System Interpreted Values Reference
  • 25 Appendix
  • 26 Constant Listing (Auto-generated)



  • 1 Introduction


    Chapter Contents

    (back to top)

    1.1 Purpose
    1.2 Audience
    1.3 Topics Covered
    1.4 Topics Not Covered
    1.5 Not Optimized for Smooth Reading
    1.6 How D3D11.3 Fits into this Unified Spec


    1.1 Purpose

    This document describes hardware requirements for Direct3D 11.3 (D3D11.3).

    1.2 Audience

    It is assumed that the reader is familiar with real-time graphics, modern Graphics Processing Unit (GPU) design issues and the general architecture of Microsoft Windows Operating Systems, as well their planned release roadmap.

    The target audience for this spec are the implementers, testers and documenters of hardware or software components that would be considered part of a D3D11.3-compliant system. In addition, software developers who are vested in the details about medium-term GPU hardware direction will find interesting information.

    1.3 Topics Covered

    Topics covered in this spec center on definition of the hardware architecture being targeted by the D3D11.1 Graphics Pipeline, in a form that attempts to be agnostic to any single vendor's hardware implementation. Included will be some references to how the Graphics Pipeline is controlled through a Device Driver Interface (DDI), and occasionally depictions of API usage as needed to illustrate points.

    Occasionally, boxed text such as this appears in the spec to indicate justification for decisions, explain history about a feature, provide clarifications or general remarks about a topic being described, or to flag an unresolved issues. These shaded boxes DO NOT provide a complete listing of all such trivia, however. Note that on each revision of this spec, all changes made for that revision are summarized in a separate document typically distributed with the spec.

    1.4 Topics Not Covered

    The exact relationship and interactions between topics covered in the Graphics Pipeline with other Operating System components is not covered.

    GPU resource management, GPU process scheduling, and low-level Operating System driver/kernel architecture are not covered.

    High-level GPU programming concepts (such as high level shading languages) are not covered.

    Little to no theory or derivation of graphics concepts, techniques or history is provided. Equally rare for this spec is any attempt to characterize what sorts of things applications software developers might do using the functionality provided by D3D11.3. There are exceptions, but do not expect to gain much more than an understanding of the "facts" about D3D11.3 from this spec.

    1.5 Not Optimized for Smooth Reading

    Beware, there is little flow to the content in this spec, although there are plenty of links from place to place.


    1.6 How D3D11.3 Fits into this Unified Spec

    This document is the product of starting with the full D3D11.2 functional spec and adding in relevant WindowsNext D3D11.3 features.

    Each Chapter in this spec begins with a summary of the changes from D3D10 to D3D10.1 to D3D11 to D3D11.1 to D3D11.2 to D3D11.3 for that Chapter. A table of links to all of the Chapter delta summaries can be found here(25.2).

    To find D3D11.3 changes specifically (which includes changes for optional new features and clarifications/corrections that affect all feature levels, look for "[D3D11.3]" in the chapter changelists (or simply search the doc for it).



    2 Rendering Pipeline Overview


    Chapter Contents

    (back to top)

    2.1 Input Assembler (IA) Overview
    2.2 Vertex Shader (VS) Overview
    2.3 Hull Shader (HS) Overview
    2.4 Tessellator (TS) Overview
    2.5 Domain Shader (DS) Overview
    2.6 Geometry Shader (GS) Overview
    2.7 Stream Output (SO) Overview
    2.8 Rasterizer Overview
    2.9 Pixel Shader (PS) Overview
    2.10 Output Merger (OM) Overview
    2.11 Compute Shader (CS) Overview


    Summary of Changes in this Chapter from D3D10 to D3D11.3

    Back to all D3D10 to D3D11.3 changes.(25.2)


    D3D11.1 hardware, like previous generations, can be designed with shared programmable cores. A farm of Shader cores exist on the GPU, able to be scheduled across the functional blocks comprising the D3D11.1 Pipeline, depicted below.


    2.1 Input Assembler (IA) Overview

    The Input Assembler (IA) introduces triangles, lines, points or Control Points (for Patches) into the graphics Pipeline, by pulling source geometry data out of 1D Buffers(5.3.4).

    Vertex data can come from multiple Buffers, accessed in an "Array-of-Structures" fashion from each Buffer. The Buffers are each bound to an individual input slot and given a structure stride. The layout of data across all the Buffers is specified by an Input Declaration, in which each entry defines an "Element" with: an input slot, a structure offset, a data type, and a target register (for the first active Shader in the Pipeline).

    A given sequence of vertices is constructed out of data fetched from Buffers, in a traversal directed by a combination of fixed-function state and various Draw*() API/DDI calls. Various primitive topologies are available to make the sequence of vertex data represent a sequence of primitives. Example topologies are: point-list, line-list, triangle-list, triangle-strip, 8 control-point patch-list.

    Vertex data can be produced in one of two ways. The first is "Non-Indexed" rendering, which is the sequential traversal of Buffer(s) containing vertex data, originating at a start offset at each Buffer binding. The second method for producing vertex data is "Indexed" rendering, which is sequential traversal of a single Buffer containing scalar integer indices, originating at a start offset into the Buffer. Each index indicates where to fetch data out of Buffer(s) containing vertex data. The index values are independent of the characteristics of the Buffers they are referring to; Buffers are described by a declaration as mentioned earlier. So the task accomplished by "Non-Indexed" and "Indexed" rendering, each in their own way, is producing addresses from which to fetch vertex data in memory, and subsequently assemble the results into vertices and primitives.

    Instanced geometry rendering is enabled by allowing the sequential traversal, in either Non-indexed or Indexed rendering, to loop over a range within each Vertex Buffer (Non-Indexed case) or Index Buffer (Indexed case). Buffer-bindings can be identified "Instance Data" or "Vertex Data", indicating how to use the bound Buffer while performing instanced rendering. The address generated by "Non-Indexed" or "Indexed" rendering is used to fetch "Vertex Data", accounting also for looping when doing Instanced rendering. "Instance Data", on the other hand, is always sequentially traversed starting from a per-Buffer offset, at a frequency equal to one step per instance (e.g. one step forward after the number of vertices in an instance are traversed). The step rate for "Instance Data" can also be chosen to be a subharmonic of the instance frequency (i.e. one step forward every other instance, every third instance etc.).

    Another use of the Input Assembler is that it can read Buffers that were written to from the Stream Output(2.7) stage. Such a scenario necessitates a particular type of Draw, DrawAuto(8.9). DrawAuto enables the Input Assembler to know how much data was dynamically written to a Stream Output Buffer without CPU involvement.

    In addition to producing vertex data from Buffers, the IA can auto-generate scalar counter values such as: VertexID(8.16), PrimitiveID(8.17) and InstanceID(8.18), for input to shader stages in the graphics pipeline.

    In "Indexed" rendering of strip topologies, such as triangle strips, a mechanism is provided for drawing multiple strips with a single Draw*() call (i.e. 'cut'ting strips).

    Specific operational details of the IA are provided here(8).


    2.2 Vertex Shader (VS) Overview

    The Vertex Shader stage processes vertices, performing operations such as transformations, skinning, and lighting. Vertex Shaders always operate on a single input vertex and produce a single output vertex. This stage must always be active.

    Specific operational details of Vertex Shaders are provided here(9).


    2.3 Hull Shader (HS) Overview

    The Hull Shader operates once per Patch (can only be used with Patces from the IA). It can transform input Control Points that make up a Patch into Output Control Points, and it can perform other setup for the fixed-function Tessellator stage (outputting TessFactors, which are numbers that indicate how much to tessellate).

    Specific operational details of the Hull Shader are provided here(10).


    2.4 Tessellator (TS) Overview

    The Tessellator is a fixed function unit whose operation is defined by declarations in the Hull Shader. It operates once per Patch output by the Hull Shader. The Hull shader outputs TessFactors which are numbers that tell the Tessellator how much to tessellate (generate geometry and connectivity) over the domain of the Patch.

    Specific operational details of the Tessellator provided here(11).


    2.5 Domain Shader (DS) Overview

    The Domain Shader is invoked once per vertex generated by the Tessellator. Each invocation is identified by its coordinate on a generic domain, and the role of the Domain Shader is to turn that coordinate into something tangible (such as a point in 3D space) for use downstream. Each Domain Shader invocation for a Patch also sees shared input of all the Hull Shader output (such as output Control Points).

    Specific operational details of the Domain Shader are provided here(12).


    2.6 Geometry Shader (GS) Overview

    The Geometry Shader runs application-specified Shader code with vertices as input and the ability to generate vertices on output. The Geometry Shader's inputs are the vertices for a full primitive (two vertices for lines, three vertices for triangles, a single vertex for point, or all Control Points for a Patch if it reaches the GS with Tessellation disabled). Some types of primitives can also include the vertices of edge-adjacent primitive (an additional two vertices for a line, an additional three for a triangle).

    Another input is a PrimitiveID auto-generated by the IA. This allows per-face data to be fetched or computed if desired.

    The Geometry Shader stage is capable of outputting multiple vertices forming a single selected topology (GS output topologies available are: tristrip, linestrip, pointlist). The number of primitives emitted can vary freely within any invocation of the Geometry Shader, though the maximum number of vertices that could be emitted must be declared statically. Strip lengths emitted from a GS invocation can be arbitrary (there is a 'cut'(22.8.1) command).

    Output may be fed to rasterizer and/or out to vertex Buffers in memory. Output fed to memory is expanded to individual point/line/triangle lists (the same way they would get passed to the rasterizer).

    Algorithms that can be implemented in the Geometry Shader include:

    Specific operational details of the Geometry Shader are provided here(13).


    2.7 Stream Output (SO) Overview

    Vertices may be streamed out to memory just before arriving at the Rasterizer. This is like a "tap" in the Pipeline, which can be turned on even as data continues to flow down to the Rasterizer. Data sent out via Stream Output is concatenated to Buffer(s). These Buffers may on subsequent passes be recirculated as Pipeline inputs.

    One constraint about Stream Output is that it is tied to the Geometry Shader, in that both must be created together (though either can be "NULL"/"off"). The particular memory Buffer(s) being Streamed out are not tied to this GS/SO pair though. Only the description of which parts of vertex data to feed to Stream Output are tied to the GS.

    One use for Stream Output is for saving ordered Pipeline data that will be reused. For example a batch of vertices might be "skinned" by passing the vertices into the Pipeline as if they are independent points (just to visit all of them once), applying "skinning" operations on each vertex, and streaming out the results to memory. The saved out "skinned" vertices are now available for use in subsequent passes as input.

    Since the amount of output written through Stream Output can be unpredictably dynamic, a special type of Draw command, DrawAuto(8.9), is necessary. DrawAuto enables the Input Assembler to know how much data was dynamically written to a Stream Output Buffer without CPU involvement. In addition, Queries are necessary to mitigate Stream Output overflow(20.4.10), as well as retrieve how much data was written(20.4.9) to the Stream Output Buffers.

    Specific operational details of the Stream Output are provided here(14).


    2.8 Rasterizer Overview

    The rasterizer is responsible for clipping, primitive setup, and determining how to invoke Pixel Shaders. D3D11.3 does not view this as a "stage" in the Pipeline, but rather an interface between Pipeline stages which happens to perform a significant set of fixed function operations, many of which can be adjusted by software developers.

    The rasterizer always assumes input positions are provided in clip-space, performs clipping, perspective divide and applies viewport scale/offset.

    Specific operational details of the Rasterizer are provided here(15).


    2.9 Pixel Shader (PS) Overview

    Input data available to the Pixel Shader includes vertex attributes that can be chosen, on a per-Element basis, to be interpolated with or without perspective correction, or be treated as constant per-primitive.

    The Pixel Shader can also be chosen to be invoked either once per pixel or once per covered sample within the pixel.

    Outputs are one or more 4-vectors of output data for the current pixel or sample, or no color (if pixel is discarded).

    The Pixel Shader has some other inputs and outputs available as well, similar to the kind of inputs and outputs the Compute Shader can use, allowing, for instance, the ability to write to scattered locations.

    Specific operational details of Pixel Shaders are provided here(16).


    2.10 Output Merger (OM) Overview

    The final step in the logical Pipeline is visibility determination, through stencil or depth, and writing or blending of output(s) to RenderTarget(s), which may be one of many Resource Types(5).

    These operations, as well as the binding of output resources (RenderTargets), are defined at the Output Merger.

    Specific operational details of the Output Merger are provided here(17).


    2.11 Compute Shader (CS) Overview

    The Compute Shader allows the GPU to be viewed as a generic grid of data-parallel processors, without any graphics baggage from the graphics pipeline. The Compute Shader has explicit access to fast shared memory to facilitate communication between groups of shader invocations, and the ability to perform scattered reads and writes to memory. The availablility of atomic operations enables unique access to shared memory addresses. The Compute Shader is not part of the Graphics Pipeline (all the previously discussed shader stages). The Compute Shader exists on its own, albeit on the same device as all the other Shader Stages. To invoke this shader, Dispatch*() APIs are called instead of Draw*().

    Specific operational details of Compute Shaders are provided here(18).


    3 Basics


    Chapter Contents

    (back to top)

    3.1 Floating Point Rules
    3.2 Data Conversion
    3.3 Coordinate Systems
    3.4 Rasterization Rules
    3.5 Multisampling


    Summary of Changes in this Chapter from D3D10 to D3D11.3

    Back to all D3D10 to D3D11.3 changes.(25.2)


    3.1 Floating Point Rules


    Section Contents

    (back to chapter)

    3.1.1 Overview
    3.1.2 Term: Unit-Last-Place (ULP)
    3.1.3 32-bit Floating Point

    3.1.3.1 Partial Listing of Honored IEEE-754 Rules
    3.1.3.2 Complete Listing of Deviations or Additional Requirements vs. IEEE-754
    3.1.4 64-bit (Double Precision) Floating Point
    3.1.5 16-bit Floating Point
    3.1.6 11-bit and 10-bit Floating Point


    3.1.1 Overview

    D3D11 supports several different floating point representations for storage. However, all floating point computations in D3D11, whether in Shader programs written by application developers or in fixed function operations such as texture filtering or RenderTarget blending, are required to operate under a defined subset of the IEEE 754 32-bit single precision floating point behavior.

    3.1.2 Term: Unit-Last-Place (ULP)

    One ULP is the smallest representable delta from one value in a numeric representation to an adjacent value. The absolute magnitude of this delta varies with the magnitude of the number in the case of a floating point number. If, hypothetically, the result of an arithmetic operation were allowed to have a tolerance 1 ULP from the infinitely precise result, this would allow an implementation that always truncated its result (without rounding), resulting in an error of at most one unit in the last (least significant) place in the number representation. On the other hand, it would be much more desirable to require 0.5 ULP tolerance on arithmetic results, since that requires the result be the closest possible representation to the infinitely precise result, using round to nearest-even.

    3.1.3 32-bit Floating Point

    3.1.3.1 Partial Listing of Honored IEEE-754 Rules

    Here is a summary of expected 32-bit floating point behaviors for D3D11. Some of these points choose a single option in cases where IEEE-754 offers choices. This is followed by a listing of deviations or additions to IEEE-754 (some of which are significant). Refer to IEEE-754 for topics not mentioned.

    3.1.3.2 Complete Listing of Deviations or Additional Requirements vs. IEEE-754

    3.1.4 64-bit (Double Precision) Floating Point

    Double-precision floating-point support is optional, however all double-precision floating point instructions listed in this spec (here (arithmetic)(22.14), here (conditional)(22.15), here (move)(22.16) and here (type conversion)(22.17) ) must be implemented if double support is enabled.

    Double-precision floating-point usage is indicated at compile time by declaring shadel model 5_a. Support for Shader Model 5.0a will be reportable by drivers and discoverable by users via an API.

    When supported, double-precision instructions match IEEE 754R behavior requirements (with the exception of double precision reciprocal(22.14.5) which is permitted 1.0 ULP tolerance and the exact result if representable).

    An exception to the 4-vector register convention exists for double-precision floating-point instructions, which operate on pairs of doubles. Double-precision floating-point values are in IEEE 754R format. One double is stored in .xy with the least significant 32 bits in x, and the most significant 32 bits in y. Similarly the second double is stored in .zw with the least significant 32 bits in z, and the most significant 32 bits in w.

    The permissible swizzles for double operations are .xyzw, .xyxy, .zwxy, .zwzw. The permissible write masks for double operations are .xy, .zw, and .xyzw.

    Support for generation of denormalized values is required for double-precision data (no flush-to-zero behavior). Likewise, instructions do not read denormalized data as a signed zero - they honor the denorm value.

    3.1.5 16-bit Floating Point

    Several resource formats in D3D11 contain 16-bit representations of floating point numbers. This section describes the float16 representation.

    Format:

    A float16 value, v, made from the format above takes the following meaning:

    32-bit floating point rules also hold for 16-bit floating point numbers, adjusted for the bit layout described above.

    The exceptions are:

    3.1.6 11-bit and 10-bit Floating Point

    A single resource format in D3D11 contains 11-bit and 10-bit representations of floating point numbers. This section describes the float11 and float10 representations.

    Format:

    A float11/float10 value, v, made from the format above takes the following meaning:

    32-bit floating point rules also hold for 11-bit and 10-bit floating point numbers, adjusted for the bit layout described above.

    The exceptions are:


    3.2 Data Conversion


    Section Contents

    (back to chapter)

    3.2.1 Overview
    3.2.2 Floating Point Conversion
    3.2.3 Integer Conversion

    3.2.3.1 Terminology
    3.2.3.2 Integer Conversion Precision
    3.2.3.3 SNORM -> FLOAT
    3.2.3.4 FLOAT -> SNORM
    3.2.3.5 UNORM -> FLOAT
    3.2.3.6 FLOAT -> UNORM
    3.2.3.7 SRGB -> FLOAT
    3.2.3.8 FLOAT -> SRGB
    3.2.3.9 SINT -> SINT (With More Bits)
    3.2.3.10 UINT -> SINT (With More Bits)
    3.2.3.11 SINT -> UINT (With More Bits)
    3.2.3.12 UINT -> UINT (With More Bits)
    3.2.3.13 SINT or UINT -> SINT or UINT (With Fewer or Equal Bits)
    3.2.4 Fixed Point Integers
    3.2.4.1 FLOAT -> Fixed Point Integer
    3.2.4.2 Fixed Point Integer -> FLOAT


    3.2.1 Overview

    This section describes the rules for various data conversions in D3D11. Other relevant information regarding data conversion is in the Data Invertability(19.1.2) section.

    3.2.2 Floating Point Conversion

    Whenever a floating point conversion between different representations occurs, including to/from non-floating point representations, the following rules apply.

    These are rules for converting from a higher range representation to a lower range representation:

    These are rules for converting from a lower precision/range representation to a higher precision/range representation:

    3.2.3 Integer Conversion

    3.2.3.1 Terminology

    The following set of terms are subsequently used to characterize various integer format conversions.

    TermDefinition
    SNORMSigned normalized integer, meaning that for an n-bit 2's complement number, the maximum value means 1.0f (e.g. the 5-bit value 01111 maps to 1.0f), and the minimum value means -1.0f (e.g. the 5-bit value 10000 maps to -1.0f). In addition, the second-minimum number maps to -1.0f (e.g. the 5-bit value 10001 maps to -1.0f). There are thus two integer representations for -1.0f. There is a single representation for 0.0f, and a single representation for 1.0f. This results in a set of integer representations for evenly spaced floating point values in the range (-1.0f...0.0f), and also a complementary set of representations for numbers in the range (0.0f...1.0f)
    UNORMUnsigned normalized integer, meaning that for an n-bit number, all 0's means 0.0f, and all 1's means 1.0f. A sequence of evenly spaced floating point values from 0.0f to 1.0f are represented. e.g. a 2-bit UNORM represents 0.0f, 1/3, 2/3, and 1.0f.
    SINTSigned integer. 2's complement integer. e.g. an 3-bit SINT represents the integral values -4, -3, -2, -1, 0, 1, 2, 3.
    UINTUnsigned integer. e.g. a 3-bit UINT represents the integral values 0, 1, 2, 3, 4, 5, 6, 7
    FLOATA floating-point value in any of the representations defined by D3D11.
    SRGBSimilar to UNORM, in that for an n-bit number, all 0's means 0.0f and all 1's means 1.0f. However unlike UNORM, with SRGB the sequence of unsigned integer encodings between all 0's to all 1's represent a nonlinear progression in the floating point interpretation of the numbers, between 0.0f to 1.0f. Roughly, if this nonlinear progression, SRGB, is displayed as a sequence of colors, it would appear as a linear ramp of luminosity levels to an "average" observer, under "average" viewing conditions, on an "average" display. For complete detail, refer to the SRGB color standard, IEC 61996-2-1, at IEC (International Electrotechnical Commission)

    Note that the terms above are also used as Format Name Modifiers(19.1.3.2), where they describe both how data is layed out in memory and what conversion to perform in the transport path (potentially including filtering) from memory to/from a Pipeline unit such as a Shader. See the Formats(19.1) section to see exactly how these names are used in the context of resource formats.

    What follows are descriptions of conversions from various representations described above to other representations. Not all permutations are shown, but at least all the ones that show up in D3D11 somewhere are shown.

    3.2.3.2 Integer Conversion Precision

    Unless otherwise specified for specific cases, all conversions to/from integer representations to float representations described below must be done exactly. Where float arithmetic is involved, FULL IEEE-754 precision is required (1/2 ULP(3.1.2) of the infinitely precise result), which is stricter than the general D3D11 Floating Point Rules(3.1).

    3.2.3.3 SNORM -> FLOAT

    Given an n-bit integer value representing the signed range [-1.0f to 1.0f], conversion to floating-point is as follows:

    3.2.3.4 FLOAT -> SNORM

    Given a floating-point number, conversion to an n-bit integer value representing the signed range [-1.0f to 1.0f] is as follows:

    This conversion is permitted tolerance of 0.6f ULP(3.1.2) (on the integer side). This means that after converting from float to integer scale, any value within 0.6f ULP(3.1.2) of a representable target format value is permitted to map to that value. The additional Data Invertability(19.1.2) requirement ensures that the conversion is nondecreasing across the range and all output values are attainable.

    Requiring exact (1/2 ULP) conversion precision is acknowledged to be too expensive.

    3.2.3.5 UNORM -> FLOAT

    3.2.3.6 FLOAT -> UNORM

    This conversion is permitted tolerance of 0.6f ULP(3.1.2) (on the integer side). This means that after converting from float to integer scale, any value within 0.6f ULP(3.1.2) of a representable target format value is permitted to map to that value. The additional Data Invertability(19.1.2) requirement ensures that the conversion is nondecreasing across the range and all output values are attainable.

    Requiring exact (1/2 ULP) conversion precision is acknowledged to be too expensive.

    3.2.3.7 SRGB -> FLOAT

    The following is the ideal SRGB to FLOAT conversion.

    This conversion will be permitted a tolerance of 0.5f ULP(3.1.2) (on the SRGB side). The procedure for measuring this tolerance, given that it is relative to the SRGB side even though the result is a FLOAT, is to convert the result back into SRGB space using the ideal FLOAT -> SRGB conversion specified below, but WITHOUT the rounding to integer, and taking the floating point difference versus the original SRGB value to yield the error. There are a couple of exceptions to this tolerance, where exact conversion is required: 0.0f and 1.0f (the ends) must be exactly achievable.

    3.2.3.8 FLOAT -> SRGB

    The following is the ideal FLOAT -> SRGB conversion.

    Assuming the target SRGB color component has n bits:

    This conversion is permitted tolerance of 0.6f ULP(3.1.2) (on the integer side). This means that after converting from float to integer scale, any value within 0.6f ULP(3.1.2) of a representable target format value is permitted to map to that value. The additional Data Invertability(19.1.2) requirement ensures that the conversion is nondecreasing across the range and all output values are attainable.

    Requiring exact (1/2 ULP) conversion precision is acknowledged to be too expensive.

    3.2.3.9 SINT -> SINT (With More Bits)

    To convert from SINT to an SINT with more bits, the MSB bit of the starting number is "sign-extended" to the additional bits available in the target format.

    3.2.3.10 UINT -> SINT (With More Bits)

    To convert from UINT to an SINT with more bits, the number is copied to the target format's LSBs and additional MSB's are padded with 0.

    3.2.3.11 SINT -> UINT (With More Bits)

    To convert from SINT to UINT with more bits: If negative, the value is clamped to 0. Otherwise the number is copied to the target format's LSBs and additional MSB's are padded with 0.

    3.2.3.12 UINT -> UINT (With More Bits)

    To convert from UINT to UINT with more bits the number is copied to the target format's LSBs and additional MSB's are padded with 0.

    3.2.3.13 SINT or UINT -> SINT or UINT (With Fewer or Equal Bits)

    To convert from a SINT or UINT to SINT or UINT with fewer or equal bits (and/or change in signedness), the starting value is simply clamped to the range of the target format.

    3.2.4 Fixed Point Integers

    Fixed point integers are simply integers of some bit size that have an implicit decimal point at a fixed location. The ubiquitous "integer" data type is a special case of a fixed point integer with the decimal at the end of the number. Fixed point number representations are characterized as: i.f, where i is the number of integer bits and f is the number of fractional bits. e.g. 16.8 means 16 bits integer followed by 8 bits of fraction. The integer part is stored in 2's complement, at least as defined here (though it can be defined equally for unsigned integers as well). The fractional part is stored in unsigned form. The fractional part always represents the positive fraction between the two nearest integral values, starting from the most negative. Exact details of fixed point representation, and mechanics of conversion from floating point numbers are provided below.

    Addition and subtraction operations on fixed point numbers are performed simply using standard integer arithmetic, without any consideration for where the implied decimal lies. Adding 1 to a 16.8 fixed point number just means adding 256, since the decimal is 8 places in from the least significant end of the number. Other operations such as multiplication, can be performed as well simply using integer arithmetic, provided the effect on the fixed decimal is accounted for. For example, multiplying two 16.8 integers using an integer multiply produces a 32.16 result.

    Fixed point integer representations are used in a couple of places in D3D11:

    3.2.4.1 FLOAT -> Fixed Point Integer

    The following is the general procedure for converting a floating point number n to a fixed point integer i.f, where i is the number of (signed) integer bits and f is the number of fractional bits:

    Note: Sign of zero is preserved.

    For D3D11 implementations are permitted 0.6f ULP(3.1.2) tolerance in the integer result vs. the infinitely precise value n*2^f after the last step above.

    The diagram below depicts the ideal/reference float to fixed conversion (including round-to-nearest-even), yielding 1/2 ULP accuracy to an infinitely precise result, which is more accurate than required by the tolerance defined above. Future D3D versions will require exact conversion like this reference.

    Specific choices of bit allocations for fixed point integers are listed in the places in the D3D11 spec where they are used.

    3.2.4.2 Fixed Point Integer -> FLOAT

    Assume that the specific fixed point representation being converted to float does not contain more than a total of 24 bits of information, no more than 23 bits of which is in the fractional component. Suppose a given fixed point number, fxp, is in i.f form (i bits integer, f bits fraction). The conversion to float is akin to the following pseudocode:

    float result = (float)(fxp >> f) +              // extract integer
                   ((float)(fxp & (2f - 1)) / (2f)); // extract fraction
    

    Although the situation rarely, if ever arises, consider that a number that originates as fixed point, gets converted to float32, and then gets converted back to fixed point will remain identical to its original value. This holds provided that bit representation for the fixed point number does not contain more information than can be represented in a float32. This lossless conversion property does not hold when making the opposite round-trip, starting from float32, moving to fixed-point, and back; indeed lossy conversion is in fact the "point" of converting from float32 to fixed-point in the first place.

    One final note on round-trip conversion. Observe that when the float32 number -2.75 is converted to fixed-point, it becomes -3 +0.25, that is, the integer part is negative but the fixed point part, considered by itself, is positive. When that is converted back to float32, it becomes -2.75 again, since floating point stores negative numbers in sign-magnitude form, instead of in two's complement form.


    3.3 Coordinate Systems


    Section Contents

    (back to chapter)

    3.3.1 Pixel Coordinate System
    3.3.2 Texel Coordinate System
    3.3.3 Texture Coordinate Interpretation


    3.3.1 Pixel Coordinate System

    The Pixel Coordinate System defines the origin as the upper-left corner of the RenderTarget. Pixel centers are therefore offset by (0.5f,0.5f) from integer locations on the RenderTarget. This choice of origin makes rendering screen-aligned textures trivial, as the pixel coordinate system is aligned with the texel coordinate system.

    D3D9 and prior had a terrible Pixel Coordinate System where the origin was the center of the top left pixel on the RenderTarget. In other words, the origin was (0.5,0.5) away from the upper left corner of the RenderTarget. There was the nice property that Pixel centers were at integer locations, but the fact this was misaligned with the texture coordinate system frequently burned unsuspecting developers. Further, with Multisample rendering, thre was a 1/2 pixel wide region of the RenderTarget along the top and left edge that the viewport could not cover. D3D11 allows applications that want to emulate this behavior to specify a fractional offset to the top left corner of the viewport (-0.5,-0.5).

    3.3.2 Texel Coordinate System

    The texel coordinate system has its origin at the top-left corner of the texture. See the "Texel Coordinate System" diagram below. This is consistent with the Pixel Coordinate System.

    3.3.3 Texture Coordinate Interpretation

    The memory load instructions like sample(22.4.15) or ld(22.4.6) have a couple of ways texture coordinates are interpreted (normalized float, or scaled integer respectively). The "Texture Coordinate Interpretation" diagram below describes how these interpretations get mapped to specific texel(s), for point and linear sampling. The diagram does not illustrate address wrapping, which occurs after the shown equations for computing texel locations. The addressing math shown in this diagram is only a general guideline, and exact definition of texel selection arithmetic is provided in the Texture Sampling(7.18) section, including the role of Fixed Point(3.2.4.1) snapping of precision in the addressing process.


    3.4 Rasterization Rules


    Section Contents

    (back to chapter)

    3.4.1 Coordinate Snapping
    3.4.2 Triangle Rasterization Rules

    3.4.2.1 Top-Left Rule
    3.4.3 Aliased Line Rasterization Rules
    3.4.3.1 Interaction With Clipping
    3.4.4 Alpha Antialiased Line Rasterization Rules
    3.4.5 Quadrilateral Line Rasterization Rules
    3.4.6 Point Rasterization Rules


    3.4.1 Coordinate Snapping

    Consider a set of vertices going through the Rasterizer, after having gone through clipping, perspective divide and viewport scale. Suppose that any further primitive expansion has been done (e.g. rectangular lines can be drawn by implementations as 2 triangles, described later). After the final primitives to be rasterized have been obtained, the x and y positions of the vertices are snapped to exactly n.8 fixed point integers. Any front/back culling is applied (if applicable) after vertices have been snapped. Interpolation of pixel attributes is set up based on the snapped vertex positions of primitives being rasterized.

    3.4.2 Triangle Rasterization Rules

    Any pixel sample locations which fall inside the triangle are drawn. An example with a single sample per pixel (at the center) is shown below. If a sample location falls exactly on the edge of the triangle, the Top-Left Rule applies, to ensure that adjacent triangles do not overdraw. The Top-Left rule is described below.

    3.4.2.1 Top-Left Rule

    Top edge: If an edge is exactly horizontal, and it is above the other edges of the triangle in pixel space, then it is a "top" edge.

    Left edge: If an edge is not exactly horizontal, and it is on the left side of the triangle in pixel space, then it is a "left" edge. A triangle can have one or two left edges.

    Top-Left Rule: If a sample location falls exactly on the edge of a triangle, the sample is inside the triangle if the edge is a "top" edge or a "left" edge. If two edges from the same triangle touch the pixel center, then if both edges are "top" or "left" then the sample is inside the triangle.

    3.4.3 Aliased Line Rasterization Rules

    Rasterization rules for infinitely-thin lines, with no antialiasing, are described below.

    3.4.3.1 Interaction With Clipping

    One futher implication of these line rasterization rules is that lines that are geometrically clipped to the viewport extent may set one less pixel than lines that are rendered to a larger 2D extent with the pixels outside the viewport discarded. (This is due to the handling of the line endpoints.)

    Since geometric clip to the viewport is neither required nor disallowed, aliased line rendering is allowed to differ in viewport-edge pixels due to geometric clipping.

    3.4.4 Alpha Antialiased Line Rasterization Rules

    The alpha-based antialiased rasterization of a line (defined by two end vertices) is implemented as the visualization of a rectangle, with the line's two vertices centered on two opposite "ends" of the rectangle, and the other two edges separated by a width (in D3D11 width is only 1.0f). No accounting for connected line segments is done. The region of intersection of this rectangle with the RenderTarget is estimated by some algorithm, producing "Coverage" values [0.0f..1.0f] for each pixel in a region around the line. The Coverage values are multiplied into the Pixel Shader output o0.a value before the Output Merger Stage. Undefined results are produced if the PS does not output o0.a. D3D11 exposes no controls for this line mode.

    It is deemed that there is no single "best" way to perform alpha-based antialiased line rendering. D3D11 adopts as a guideline the method shown in the diagram below. This method was derived empirically, exhibiting a number of visual properties deemed desirable. Hardware need not exactly match this algorithm; tests against this reference shall have "reasonable" tolerances, guided by some of the principles listed further below, permitting various hardware implementations and filter kernel sizes. None of this flexibility permitted in hardware implementation, however, can be communicated up through D3D11 to applications, beyond simply drawing lines and observing/measuring how they look.

    The following is a listing of the "nice" properties that fall out of the above algorithm, which in general will be expected of hardware implementations (admittedly many of which are likely difficult to test):

    Note that the wider the filter kernel an implementation uses, the blurrier the line, and thus the more sensitive the resulting perceived line intensity is to display gamma. The reference implmentation's kernel is quite large, at 3x3 pixel units about each pixel.

    3.4.5 Quadrilateral Line Rasterization Rules

    Quadrilateral lines take 2 endpoints and turn them into a simple rectangle with width 1.4f, drawn with triangles. The attributes at each end of the line are duplicated for the 2 vertices at each end of the rectangle.

    This mode is not supported with center sample patterns (D3D11_CENTER_MULTISAMPLE_PATTERN) where there is more than one sample overlapping the center of the pixel, in which case results of drawing this style of line are undefined. See here(19.2.4.1).

    The width of 1.4f is an arbitrarily aesthetic choice, used in previous versions of D3D. With no good reason to change, it was left the same.

    3.4.6 Point Rasterization Rules

    For the purpose of rasterization, a point is represented as a square of width 1 oriented to the RenderTarget. Actual implementation may vary, but output behavior should be identical to what is described here. The coordinate for a point indentifies where the center of the square is located. Pixel coverage for points follows Triangle Rasterization Rules, interpreted as though a point is composed of 2 triangles in a Z pattern, with attributes duplicated at the 4 vertices. Cull modes do not apply to points.


    3.5 Multisampling


    Section Contents

    (back to chapter)

    3.5.1 Overview
    3.5.2 Warning about the MultisampleEnable State
    3.5.3 Multisample Sample Locations And Reconstruction
    3.5.4 Effects of Sample Count > 1

    3.5.4.1 Sample-Frequency Execution and Rasterization
    3.5.4.1.1 Invariance Property
    3.5.5 Centroid Sampling of Attributes
    3.5.6 Target Independent Rasterization
    3.5.6.1 Forcing Rasterizer Sample Count
    3.5.6.2 Rasterizer Behavior with Forced Rasterizer Sample Count
    3.5.6.3 Support on Feature Levels 10_0, 10_1, 11_0
    3.5.6.4 UAV-Only Rasterization with Multisampling
    3.5.7 Pixel Shader Derivatives


    3.5.1 Overview

    Multisample Antialiasing seeks to fight geometry aliasing, without necessarily dealing with surface aliasing (leaving that as a shading problem, e.g. texture filterng). This is accomplished by performing pixel coverage tests and depth/stencil tests at multiple sample locations per pixel, backed by storage for each sample, while only performing pixel shading calculations once for covered pixels (broadcasting Pixel Shader output across covered samples). It is also possible to request Pixel Shader invocations to occur at sample-frequency rather than at pixel-frequency.

    3.5.2 Warning about the MultisampleEnable State

    The MultisampleEnable Rasterizer State remains as an awkward leftover from D3D9. It no longer does what the name implies; it no longer has any bearing on multisampling; it only controls line rendering behavior now. The state should have been renamed/refactored, but the opportunity was missed in D3D11. For a detailed discussion about what this state actually does now, see State Interaction With Point/Line/Triangle Rasterization Behavior(15.14).

    3.5.3 Multisample Sample Locations And Reconstruction

    Specifics about sample locations and reconstruction functions for multisample antialiasing are dependent on the chosen Multisample mode, which is outside the scope of this section. See Multisample Format Support(19.2), and Specification of Sample Positions(19.2.4).

    3.5.4 Effects of Sample Count > 1

    Rasterization behavior when sample count is greater than 1 is simply that primitive coverage tests are done for each sample location within a pixel. If one or more sample locations in a pixel are covered, the Pixel Shader is run once for the pixel in Pixel-Frequency mode, or in Sample-Frequency mode once for each covered sample that is also in the Rasterizer SampleMask. Pixel-frequency execution produces a single set of Pixel Shader output data that is replicated to all covered samples that pass their individual depth/stencil tests and blended to the RenderTarget per-sample. Sample-frequency execution produces a unique set of Pixel Shader output data per covered sample (and in SampleMask), each output getting blended 1:1 to the corresponding RenderTarget sample if its depth/stencil test passes.

    3.5.4.1 Sample-Frequency Execution and Rasterization

    Note that points(3.4.6) and quadrilateral lines(3.4.5) are functionally equivalent to drawing their area with triangles. So Sample-Frequency execution is easily defined for all of these primitives. For points, the samples covered by the point area (and in the RasterizerState's SampleMask) each get Pixel Shader invocations with attributes replicated from its single vertex (except one parameter is available that is varying - an ID identifying each sample from the total set of samples in the pixel). For quadrilateral lines, the two end vertices define how attributes interpolate along the length, staying constant across the perpendicular. Again, the samples covered by the area of the primitive (and in the SampleMask) each get a Pixel Shader invocations in Sample-Frequency execution mode, with unique input attributes per sample, including an ID identifying which sample it is.

    Alpha-Antialiased Lines(3.4.4) and Aliased Lines(3.4.3) are algorithms that inherently do not deal with discrete sample locations within a pixel's area, and thus it is illegal/undefined to request Sample-Frequency execution for these primitives, unless the sample count is 1, which is identical to Pixel-Frequency execution.

    3.5.4.1.1 Invariance Property

    Consider a Pixel Shader that operates only on pixel-frequency inputs (e.g. all attributes have one of the following interpolation modes(16.4): constant, linear, linear_centroid, linear_noperspective or linear_noperspective_centroid). Implementations need only execute the shader once per pixel and replicate the results to all samples in the pixel. Now suppose code is added to the shader that generates new outputs based on reading sample-frequency inputs. The existing pixel-frequency part of the shader behaves identically to before. Even though the shader will now execute at sample-frequency (so the new outputs can vary per-sample), each invocation produces the same result for the original outputs.

    Though this example happens to separate out the different interpolation frequencies to highlight their invariance, of course it is perfectly valid in general for shader code to mix together inputs with any different interpolation modes.

    3.5.5 Centroid Sampling of Attributes

    When a sample-frequency interpolation mode(16.4) is not needed on an attribute, pixel-frequency interpolation-modes such as linear evaluate at the pixel center. However with sample count > 1 on the RenderTarget, attributes could be interpolated at the pixel center even though the center of the pixel may not be covered by the primitive, in which case interpolation becomes "extrapolation". This "extrapolation" can be undesirale in some cases, so short of going to sample-frequency interpolation, a compromise is the centroid interpolation mode.

    Centroid behaves exactly as follows:


    3.5.6 Target Independent Rasterization

    The term Conservative Rasterization has been used to describe basically a GPU rasterizer assist for shader computed antialiasing. This concept has not been actually implemented in GPUs, at least that are known, but the following short discussion of Conservative Rasterization somewhat motivates the alternative that is specified here - Target Independent Rasterization. Note that as of D3D11.3, hardware has evolved to support Conservative Rasterization(15.17).

    Consider how multisampling works in D3D (or GPU rasterization in general). Each pixel has “sample” positions which cause Pixel Shaders to be invoked when primitives (e.g. triangles) cover the samples. For multisampling, a single Pixel Shader invocation occurs when at least one sample in a pixel is covered. Alternatively, D3D10.1+ also allows the shader to request that the Pixel Shader be invoked for each covered sample – this has historically been called “supersampling”.

    The downside to these antialiasing approaches is they are based on a discrete number of samples. The more samples the better, but there are still holes in the pixel area between the sample points in which geometry rendered there does not contribute to the image.

    Conservative Rasterization, instead, would ideally invoke the Pixel Shader if the area of a primitive (e.g. triangle) being rendered has any chance of intersecting with the pixel’s square area. It would then be up to shader code to compute whatever measure of pixel area intersection it desires. It may be acceptable for the rasterization to be “conservative” in that triangles/primitives are simply rasterized with a fattened screen space area that could include some pixels with no actual coverage – it doesn’t really matter since the shader will be computing the actual coverage.

    The win is that the number of Pixel Shader invocations is reasonably bounded to the triangle extents (as opposed to rendering bounding rectangles), and the output can be “perfect” antialiasing if desired. This is particularly the case if also utilizing some other features in D3D11 that allow arbitrary length lists to be recorded per pixel.

    However, the complexity of the shader code required to compute an analytic coverage solution with Conservative Rasterization might be too high for the benefit. An alternative scheme, Target Independent Rasterization is defined here, under the more mundane heading 'Forcing Rasterizer Sample Count' below. First though, some discussion about how Target Independent Rasterization can help in at least one scenario - path rendering in Direct2D.

    A common usage scenario of Direct2D is to stroke and/or fill anti-aliased paths. The semantics of the Direct2D anti-aliasing scheme are different from MSAA. The key difference is when the resolve step occurs. With MSAA the resolve step typically happens once per frame. With Direct2D anti-aliasing the resolve step occurs after each path is rendered. To work around these semantic differences the Windows 7 version of Direct2D performs rasterization on the CPU. When a path is to be filled or stroked, an expensive CPU-based algorithm computes the percentage of each pixel that is covered by the path. The GPU is used to multiply the path color by the coverage and blend the results with the existing render target contents. This approach is heavily CPU-bound.

    Target Independent Rasterization enables Direct2D to move the rasterization step from the CPU to the GPU while still preserving the Direct2D anti-aliasing semantics. Rendering of anti-aliased paths will be performed in 2 passes on the GPU. The first pass will write per-pixel coverage to an intermediate render target texture. Paths will be tessellated into non-overlapping triangles. The GPU will be programmed to use Target Independent Rasterization and additive blending during the first pass. The pixel shader used in the first pass will simply count the number of bits set in the coverage mask and output the result normalized to [0.0,1.0]. During the second pass the GPU will read from the intermediate texture and write to the application’s render target. This pass will multiply the path color by the coverage computed during the first pass.

    In some cases, it will be faster for Direct2D to tessellate paths into potentially overlapping triangles. In these cases, the 1st pass will set the ForcedSampleCount to 16 and simply output the coverage mask to the intermediate (R16_UINT). The blender would be setup to do a bitwise OR, or XOR operation (depending on the scenario). The second pass would read this 16-bit value from the intermediate, count the number of bits set, and modulate the color being written to the render target.

    There are 2 fallbacks that could be used to implement this algorithm on GPUs that do not support Target Independent Rasterization. The first fallback would render the scene N times, with alpha = 1/N and additive blending for the first step of the algorithm. This would produce the same results, but at the cost of resorting to multipass rendering to to mimic the effect of supersampling at the rasterizer. The second fallback would use MSAA to implement the first pass of the algorithm. Both fallbacks are bound by memory bandwidth (render target writes). Using Target Independent Rasterization would significantly reduce the memory bandwidth requirements of this algorithm.

    3.5.6.1 Forcing Rasterizer Sample Count

    Overriding the Rasterizer sample count means defining the multisample pattern at the Rasterizer independent of what RenderTargetViews(5.2) (or UnorderedAccessView(5.3.9)s) may be bound at the Output Merger (and their associated sample count / Quality Level).

    The ForcedSampleCount state setting is located in the Rasterizer State(15.1) object.

        UINT ForcedSampleCount; // Valid values for Target Independent Rasterization (TIR): 0, 1, 4, 8, 16
                                // Valid values for UAV(5.3.9) only render: 0, 1, 4, 8, 16
                                // 0 means don't force sample count.
    

    Devices must support all the standard sample patterns up to and including 16 for the ForcedSampleCount. This is even if the device does not support that many samples in RenderTarget / DepthStencil resources.

    Investigations show that the 16 sample standard D3D pattern performs favorably with Direct2D's original software based rasterization pattern, which had the significant disadvantage of using a regular grid layout, even though it was 64 samples.

    3.5.6.2 Rasterizer Behavior with Forced Rasterizer Sample Count

    With a forced sample count/pattern selected at the rasterizer (ForcedSampleCount > 0), pixels are candidates for shader invocation based on the selected sample pattern, independent of the RTV ("output") sample count. The burden is then on shader code to make sense of the possible mismatch between rasterizer and output storage sample count, given the defined semantics.

    Here are the behaviors with ForcedSampleCount > 0.

    The above functionality is required for Feature Level 11_1 hardware.

    3.5.6.3 Support on Feature Levels 10_0, 10_1, 11_0

    D3D10.0 - D3D11.0 hardware (and Feature Level 10_0 - 11_0) supports ForcedSampleCount set to 1 (and any sample count for RTV) along with the described limitations (e.g. no depth/stencil).

    For 10_0, 10_1, and 11_0 hardware, when ForcedSampleCount is set to 1, line rendering cannot be configured to 2-triangle (quadrilateral) based mode (i.e. the MultisampleEnable state cannot be set to true). This limitation isn't present for 11_1 hardware. Note the naming of the 'MultisampleEnable' state is misleading since it no longer has anything to do with enabling multisampling; instead it is now one of the controls along with AntialiasedLineEnable for selecting line rendering mode.

    This limited form of Target Indepdendent Rasterization, ForcedSampleCount = 1, closely matches a mode that was present in D3D10.0 but due to API changes became unavailable for D3D10.1 and D3D11 (and Feature Levels 10_1 and 11_0). In D3D10.0 this mode was the center sampled rendering even on an MSAA surface that was available when MultisampleEnable was set to false (and this could be toggled by toggling MultisampleEnable). In D3D10.1+, MultisampleEnable no longer affects multisampling (despite the name) and only controls line rendering behavior. It turns out some software, such as Direct2D, depended on this mode to be able to render correctly on MSAA surfaces. As of D3D11.1, D2D can use ForcedSampleCount = 1 to bring back this mode consistently on all D3D10+ hardare and Feature Levels. D3D10.0 also supported depth testing in this mode as well, but it is not worth exposing that given it D2D did not expose it, and the full D3D11.1 definition of the feature doesn't work with depth/stencil.

    3.5.6.4 UAV-Only Rasterization with Multisampling

    D3D11 allows rasterization with only UAVs bound, and no RTVs/DSVs. Even though UAVs can have any/different sizes, essentially, the viewport/scissor identify the pixel dimensions. Before this feature, when rendering with only UAVs bound, the rasterizer was limited to a single sample only.

    UAV(5.3.9)-only rendering with multisampling at the rasterizer is possible by keying off the ForcedSampleCount state described earlier, with the sample patterns limited to 0, 1, 4, 8 and 16. (The UAVs themselves are not multisampled in terms of allocation.) A setting of 0 is equivalent to the setting 1 - single sample rasterization.

    Shaders can request pixel-frequency invocation with UAV-only rendering, but requesting sample-frequency invocation is invalid (produces undefined shading results).

    The SampleMask Rasterizer State does not affect rasterization behavior at all here.

    On D3D11.0 hardware, ForcedSampleCount can be 0, 1, 4 and 8 with UAV only Rasterization. D3D11.1 hardware additionally supports 16.

    Attempting to render with unsupported ForcedSampleCount produces undefined rendering results - though if a ForcedSampleCount is chosen that could never be valid for TIR or UAV-only rendering the runtime will fail the Rasterizer State object creation immediately.

    3.5.7 Pixel Shader Derivatives

    Pixel Shaders always run in minimum 2x2 quanta to be able to support derivative calculations, regardless of the RenderTarget sample count. These Pixel Shader derivative calculations, used in texture filtering operations, but also available directly in shaders, are calculated by taking deltas of data in adjacent pixels. This requires data in each pixel has been sampled with unit spacing horizontally or vertically.

    RenderTarget sample counts > 1 do not affect derivative calculation methods. If derivatives are requested on an attribute that has been Centroid sampled, the hardware calculation is not adjusted, and therefore incorrect derivatives will often result. What the Shader expects to be a derivative wrt a unit distance in the x or y direction in RenderTarget space will actually be the rate of change with respect to some other direction vector, which also probably isn't unit length.

    The point here is that it is the application's responsibility to exhibit caution when requesting derivative from Centroid sampled attributes, ideally never requesting them at all. Centroid sampling can be useful for situations where it is critical that a primitive's interpolated attributes are not "extrapolated", but this comes with some tradeoffs: First, centroid sampled attributes may appear to jump around as a primitive edge moves over a pixel, rather than changing continuously. Secondly, derivative calculations on the attributes become unreliable or difficult to use correctly (which also hurts texture sampling operations that derive LOD from derivatives).

    Under sample-frequency execution, a 2x2 quad of Pixel Shaders executes for each sample index where that sample is covered in at least one of the pixels participating in the 2x2 quad. This allows derivatives to be calculated in the usual way since any given sample is located one unit apart horizonally or vertically from the corresponding sample in the neighboring pixels.

    It is left to the application's shader author to decide how to adjust for the fact that derivatives calculated from spacings of one unit may need to be scaled in some way to reflect higher frequency shader execution, depending on the sample pattern/count.

    Further important discussion of Pixel Shader derivatives is under Interaction of Varying Flow Control With Screen Derivatives(16.8).


    4 Rendering Pipeline


    Chapter Contents

    (back to top)

    4.1 Minimal Pipeline Configurations
    4.2 Fixed Order of Pipeline Results
    4.3 Shader Programs
    4.4 The Element


    Summary of Changes in this Chapter from D3D10 to D3D11.3

    Back to all D3D10 to D3D11.3 changes.(25.2)

    The rendering Pipeline encapsulates all state related to the rendering of a primitive. This includes a sequence of pipeline stages as well as various state objects.


    4.1 Minimal Pipeline Configurations


    Section Contents

    (back to chapter)

    4.1.1 Overview
    4.1.2 No Buffers at Input Assembler
    4.1.3 IA + VS (+optionally GS) + No PS + Writes to Depth/Stencil Enabled
    4.1.4 IA + VS (+optionally GS) + PS (incl. Rasterizer, Output Merger)
    4.1.5 IA + VS + SO
    4.1.6 No RenderTarget(s) and/or Depth/Stencil and/or Stream Output
    4.1.7 IA + VS + HS + Tessellation + DS + ...
    4.1.8 Compute alone
    4.1.9 Minimal Shaders


    4.1.1 Overview

    Not all Pipeline Stages must be active. This section clarifies this concept by illustrating some minimal configurations that can produce useful results. The Graphics pipeline is accessed by Draw* calls from the API. The alternative pipeline, Compute, is accessed by issuing Dispatch* calls from the API.

    For the Graphics pipepine, the Input Assembler is always active, as it produces pipeline work items. In addition, the Vertex Shader is always active. Relying on the presence of the Vertex Shader at all times simplifies data flow permutations very significantly, versus allowing the Input Assembler with its limited programming flexibility to feed any pipeline stage.

    Note that even though the Vertex Shader must always be active in the Graphics pipeline, in scenarios where applications really don't want to have a Vertex Shader, and must simply implement it as a trivial or nearly trivial sequence of mov's from inputs to outputs, the short length and simplicity of such "passthrough" shaders should not be a problem for hardware implementations to practically hide the cost of, one way or another.

    4.1.2 No Buffers at Input Assembler

    A minimal use of the Input Assembler is to not have any input Buffers bound (vertex or index data). The Input Assembler can generate counters such as VertexID(8.16), InstanceID(8.18) and PrimitiveID(8.17), which can identicy vertices/primitives generated in the pipeline by Draw*(), or DrawIndexed*() (if at least an Index Buffer is bound). Thus Shaders can minimally drive all their processing based on the IDs if desired, including fetching appropriate data from Buffers or Textures.

    4.1.3 IA + VS (+optionally GS) + No PS + Writes to Depth/Stencil Enabled

    If the shader stage before the rasterizer outputs position, and Depth/Stencil writes are enabled, the rasterizer will simply perform the fixed-function depth/stencil tests and updates to the Depth/Stencil buffer, even if there is no Pixel Shader active. No Pixel Shader means no updates to RenderTargets other than Depth/Stencil.

    4.1.4 IA + VS (+optionally GS) + PS (incl. Rasterizer, Output Merger)

    The Input Assembler + Vertex Shader (required) can drive the Pixel Shader directly (GS does not have to be used, but can be). If an application seeks to write data to RenderTarget(s), not including Depth/Stencil which were explained earlier, the Pixel Shader must be active. This implicitly Output Merger as well, though as described further below, there's no requirement that RenderTargets need to be bound just because rasterization is occuring.

    4.1.5 IA + VS + SO

    The Input Assembler (+required VS) can feed Stream Output directly with no other stages active. Note that as described in the Stream Output Stage(14) section, Stream Output is tied to the Geometry Shader, however a "NULL" Geometry Shader can be specified, allowing the outputs of the Vertex Shader to be sent to Stream Output with no other stages active.

    4.1.6 No RenderTarget(s) and/or Depth/Stencil and/or Stream Output

    Whether or not the Pixel Shader is active, it is always legal to NOT have any output targets bound (and/or have output masks defined so that no output targets are written). Likewise for Stream Output. This might be interesting for performance tests which don't include output memory bandwidth (and which might examine feedback statistics such as shader invocation counts, which is itself a form of pipeline output anyway).

    The Input Assembler (+required VS) can feed Stream Output directly with no other stages active. Note that as described in the Stream Output Stage(14) section, Stream Output is tied to the Geometry Shader, however a "NULL" Geometry Shader can be specified, allowing the outputs of the Vertex Shader to be sent to Stream Output with no other stages active.

    4.1.7 IA + VS + HS + Tessellation + DS + ...

    Take any of the configurations above, and HS + Tessellator + DS can be inserted after the VS. The presence of the DS is what implises the presence of the Tessellator before it.

    4.1.8 Compute alone

    When the Compute Shader runs, it runs by itself. The state for both the Graphics pipeline shaders and Compute Shader can be simultaneously bound. The selection of which pipeline to use is Draw* invokes Graphics and Dispatch* invokes Compute.

    4.1.9 Minimal Shaders

    All vertex shaders must have a minimum of one input and one output, which can be as little as one scalar value. Note that System Generated Values such as VertexID(8.16) and InstanceID(8.18) count as input.


    4.2 Fixed Order of Pipeline Results

    The rendering Pipeline is designed to allow hardware to execute tasks at various stages in parallel. However observable rendering results must match results produced by serial processing of tasks. Whenever a task in the Pipeline could be performed either serially or in parallel, the results produced by the Pipeline must match serial operation. That is, the order that tasks enter the Pipeline is the order that tasks are observed to be propagated all the way through to completion. If a task moving through the Pipeline generates additional sub-tasks, those sub-tasks are completed as part of completing the spawning task, before any subsequent tasks are completed. Note that this does not prevent hardware from executing tasks out of order or in parallel if desirable, just as long as results are buffered appropriately such that externally visible results reflect serial execution.

    One exception to this fixed ordering is with Tessellation. With the fixed function Tessellation stage, implementations are free to generate points and topology in any order as long as that order is consistent given the same input on the same device. Vertices can even be generated multiple times in the course of tessellating a patch, as long as the Tessellator output topology is not point (in which case only the unique points in the patch must be generated). This tessellator exception is discussed here(11.7.9).

    Another exception to the fixed ordering of pipeline results is any access to an Unordered Transaction View of a Resource (for example via the Compute Shader or Pixel Shader). These types of Views explicitly allow unordered results, leaving the burden to applications to make careful choices of atomic instructions to access Unordered Transaction Views if deterministic and implementation invariant output is desired.


    4.3 Shader Programs

    A Shader object encapsulates a Shader program for any type of Shader unit. All shaders have a common binary format and basically have the following typical layout. A helpful reference for this is the source code accompanying the Reference Rasterizer, which includes facilities for parsing the shader binary.

    The Tessellation related shaders have a significantly different structure, particularly the Hull Shader, which appears as multiple phases of shaders concatenated together (not depicted here).

    version
    input declarations
    output declarations
    resource declarations
    code
    
    version
        describes the Shader type: Vertex Shader(vs),
        Hull Shader (hs), Domain Shader (ds),
        Geometry Shader (gs), Pixel Shader (ps),
        Compute Shader (cs).
        Example: vs_5_0, ps_5_0
    input declarations
        declare which input registers are read
        Example:
            dcl_input v[0]
            dcl_input v[1].xy
            dcl_input v[2]
    output declarations
        declare which output registers are written
        Example:
            dcl_output o[0].xyz
            dcl_output o[1]
            dcl_output o[2].xw
    resource declarations
        Example:
            dcl_resource t0, Buffer, UNORM
            dcl_resource t2, Texture2DArray, FLOAT
    code
        This Shader section contains executable instructions.
    

    4.4 The Element


    Section Contents

    (back to chapter)

    4.4.1 Overview
    4.4.2 Elements in the Pipeline
    4.4.3 Passing Elements Through Pipeline Interfaces

    4.4.3.1 Memory-to-Stage Interface
    4.4.3.2 Stage-to-Stage Interface
    4.4.3.2.1 Varying Frequencies of Operation
    4.4.3.3 Stage-to-Memory Interface
    4.4.4 System Generated Values
    4.4.5 System Interpreted Values
    4.4.6 Element Alignment


    4.4.1 Overview

    From the perspective of individual D3D11.3 Pipeline stages accessing and interpreting memory, all memory layouts (e.g. Buffer, Texture1D/2D/3D/Cube) are viewed as being composed of "Elements". An individual Element represents a vector of anywhere from 1 to 4 values. An Element could be an R8G8B8A8 packing of data, a single 8-bit integer value, 4 float32 values, etc. In particular, an Element is any one of the DXGI_FORMAT_* formats(19.1), e.g. DXGI_FORMAT_R8G8B8A8 (DXGI stands for "DirectX Graphics Infrastructure", a software component outside the scope of this specification which happens to own the list of DirectX formats going forward). Filtering may be involved in the process of fetching an Element from a texture, and this simply involves looking at multiple values for a given Element in memory and blending them in some fashion to produce an Element that is returned to the Shader.

    Buffers in memory can be made up of structures of Elements (as opposed to being a collection of a single Element). For example a Buffer could represent an array of vertices, each vertex containing several elements, such as: position, normal and texture coordinates. See the Resources(5) section for full detail.

    4.4.2 Elements in the Pipeline

    The concept of "Elements" does not only apply to resources. Elements also characterize data passing from one Pipeline stage to the next. For example the outputs of a Vertex Shader (Elements making up a vertex) are typically read into a subsequent Pipeline stage as input data, for instance into a Geometry Shader. In this scenario, the Vertex Shader writes values to output registers, each of which represents an individual Element. The subsequent Shader (Geometry Shader in this example) would see a set of input registers each initialized with an Element out of the set of input data.

    4.4.3 Passing Elements Through Pipeline Interfaces

    There are various types of data interfaces in the hardware Pipeline through which Elements pass. This section describes the interfaces in generic terms, and characterizes how Elements of data pass through them. Specific descriptions for each of the actual interfaces in the Pipeline are provided throughout the spec, in a manner consistent with the principles outlined here. The overall theme here is that data mappings through all interfaces are always direct, without any linkage resolving required.

    4.4.3.1 Memory-to-Stage Interface

    The first type of interface is Memory-to-Stage, where an Element from a Resource (Texture/Buffer) is being fetched into the some part of the Pipeline, possibly the "top" of the Pipeline (Input Assembler(8)), or the "side", meaning a fetch driven from within a Shader Stage. At the point of binding of memory Resources to these interfaces, a number is given to each Element that is bound, representing which input (v#) or texture (t#) "register" at the particular interface refers to the Element. Note that there is no linkage resolving done on behalf of the application; the Shader assumes which "registers" will refer to particular Elements in memory, and so when memory is bound to the interface, it must be bound (or declared, in cases where multiple Elements come from the same Resource in memory) at the "register" expected by the Shader.

    For Memory-to-Stage interfaces, Elements always provide to the Shader 4 components of data, with defaults provided for Elements in memory containing fewer than 4 components (though this can be masked to be any subset of the 4 components in the Shader if desired).

    For interfaces on the "side", where memory Resources are bound to Shader Stages so they can be fetched from via Shader code, the set of binding points (t# registers in the Shader) cannot be dynamically indexed within the Shader program without using flow control.

    On the other hand, the interface at the "top" of the Pipeline (the input v# registers of the first active Shader Stage) can be dynamically indexed as an array from Shader code. The Elements in v# registers being indexed must have a declaration(22.3.30) specifying each range that is to be indexed, where each range specifies a contiguous set of Elements/v# registers, ranges do not overlap, and the components declared for each Element in a given range are identical across the range.

    4.4.3.2 Stage-to-Stage Interface

    The second type of interface is Stage-to-Stage, where one Pipeline Stage outputs a set of 4 component Elements (written to output o# registers) to the subsequent active Pipeline Stage, which receives Elements in its input v# registers. The mapping of output registers in one Stage to input registers in the next Stage is always direct; so a value written to o3 always goes to v3 in the subsequent Stage. Any subset of the 4 components of any Element can be declared rather than the whole thing.

    If more Elements or components within Elements are output than are expected/declared for input by the subsequent Stage, the extra data gets discarded / becomes undefined. If fewer Elements or components within Elements are output than are expected/declared for input by the subsequent Stage, the missing data is undefined.

    Similar to the Memory-to-Stage interface at the "top" of the Pipeline, which feeds the input v# registers of the first active Pipeline Stage, at a Stage-to-Stage interface, writes to output Elements (o#) and at the subsequent Stage, reads from input elements (v#) can each be dynamically indexed as arrays from code at the respective Shaders. The Elements in o# registers being indexed must have a declaration(22.3.30) for each range, specifying a contiguous set of Elements/o# registers, without overlapping, and with the same component masks declared for each Element in a given range. The same applies to input v# registers at the subsequent stage (the array declarations for the input v# registers in the Shader are independent/orthogonal to the array declarations for o# in the previous Shader).

    4.4.3.2.1 Varying Frequencies of Operation

    There is a detail which is mostly orthogonal to the the Stage-to-Stage interface discussion above: the frequency of operation at subsequent Stages varies, in addition to different amounts of data different Stages can input. For example the Geometry Shader(13) inputs all the vertices for a primitive. The Pixel Shader(16) can choose to have its inputs inperpolated from vertices, or take the data from one. The point of the above discussion is only to describe the mechanism for Element transport through the interfaces independently of these varying frequencies of operation between Stages.

    4.4.3.3 Stage-to-Memory Interface

    The final type of interface is Stage-to-Memory, where a Pipeline Stage outputs a set of 4 component Elements (written to output o# registers) on a path out to memory. These interfaces (e.g. to RenderTargets or Stream Output) are somewhat the converse of the Memory-to-Stage Interface. Each memory Resource representing one or more Elements of output identifies each Element by a number #, corresponding directly to an output o# register. There is no linkage resolving done on behalf of the application; the application must associate target memory for Element output directly with each o# register that will provide it. Details on specifying these associations are unique for the different Stage-to-Memory interfaces (RenderTargets, Stream Output).

    If a Stage-to-Memory interface outputs more Elements or components within Elements than there are destination memory bindings to accommodate, the extra data is discarded. If a Stage-to-Memory interface outputs fewer Elements or components within Elements than there are destination memory bindings expecting to be written, undefined data will be output (i.e. no defaults). At RenderTarget output, there are various means to mask what data gets output, most interesting of which is depth testing, but that is outside the scope of this discussion.

    At the RenderTarget output interface (which is Pixel Shader(16) output), dynamic indexing of the o# registers is not supported. For the other Stage-to-Memory interface, Stream Output, indexing of outputs is permissible. Stream Output shares the output o# registers used for Stage-to-Stage output in the Geometry Shader(13) Stage, where indexing is permitted as defined for the Stage-to-Stage interface.

    4.4.4 System Generated Values

    There are various hardware generated values which can each be made available when for input to certain Shader Stages by declaring them for input to a component of an input register. A listing of each System Generated Value in D3D11.3 can be found in the System Generated Value Reference(23), but in addition, here are links to descriptions of some (not all) of the System Generated Values: VertexID(8.16), InstanceID(8.18), PrimitiveID(8.17), IsFrontFace(15.12).

    In the Hull Shader(10), Domain Shader(12) and Geometry Shader(13), PrimitiveID is a special case that has its own input register, but for all other cases of inputting hardware generated values into Shaders, (including the PrimitiveID into the Pixel Shader(16)), the Shader must declare a scalar component of one of its input v# registers as one of the System Generated Values to receive each input value. If that v# register also has some components provided by a the previous Stage or Input Assembler(8), the hardware generated value can only be placed in one of the components after the rest of the data. For example if the Input Assembler provides v0.xz, then VertexID might be declared for v0.w (since w is after z), but not v0.y. There cannot be overlap between the target for generated values and the target for values arriving from an upstream Stage or the Input Assembler.

    Hardware generated values that are input into the generic v# registers can only be input into the first active Pipeline Stage in a given Pipeline configuration that understands the particular value; from that point on it is the responsibility of the Shader to manually pass the values down if desired through output o# registers. If multiple Stages in the pipeline request a hardware generated value, only the first stage receives it, and at the subsequent stages, the declaration is ignored (though a prudent Shader programmer would pass down the value manually to correspond with the naming).

    Since VertexID(8.16), InstanceID(8.18) are both meaningful at a vertex level, and IDs generated by hardware can only be fed into the the first stage that understands them, these ID values can only be fed into the Vertex Shader. PrimitiveID(8.17) generated by hardware can only be fed into the Hull Shader, Domain Shader, as well as whichever of the follwing is the first remaining active stage: Geometry Shader or Pixel Shader.

    It is not legal to declare a range of input registers as indexable(22.3.30) if any of the registers in the range contains a System Generated Value.

    From the API point of view, System Generated Values and System Interpreted Values (below) may be exposed to developers as just once concept: "System Values" "SV_*".

    4.4.5 System Interpreted Values

    In many cases, hardware must be informed of the meaning of some of the application-provided or computed data moving through the D3D11.3 Pipeline, so the hardware may perform a fixed function operation using the data. The most obvious example is "position", which is interpreted by the Rasterizer (just before the Pixel Shader). Data flowing through the D3D11.3 Pipeline must be identified as a System Interpreted Value at the output interface between Stages where the hardware is expected to make use of the data. For the case where the Input Assembler(8) is the only Stage present in a Pipeline configuration before the place where the hardware is expected to interpret some data, the Input Assembler(8) has a mechanism for identifying System Interpreted Values to the relevant (components of) Elements it declares.

    A listing of each System Interpreted Value in D3D11.3 can be found in the System Interpreted Values Reference(24). Each System Interpreted Value has typically one place in the Pipeline where it is meaningful to the hardware. Also, there may be constraints on how many components in an Element need to be present (such as .xyzw for "position" going to the Rasterizer).

    If data produced by the Input Assembler or by the output o# registers of any Stage is identified as a System Interpreted Value at a point in the pipeline where the hardware has no use for interpreting the data, the label is silently ignored (and the data simply flows to the next active Stage uninterpreted). For example if the Input Assembler labels the xyzw components of one of the Elements it is producing as "position", but the first active Pipeline Stage is the Vertex Shader, the hardware ignores the label, since there is nothing for hardware to do with a "position" going into the Vertex Shader.

    Just because data is tagged as a System Interpreted Value, telling hardware what to do with it, does not mean the hardware necessarily "consumes" the data. Any data flowing through the Pipeline (System Interpreted Value or not) can typically be input into the next Pipeline Stage's Shader regardless of whether the hardware did something with the data in between. In other words, output data identified as a System Interpreted Value is available to the subsequent Shader Stage if it chooses to input the data, no differently from non-System Interpreted Values. If there are exceptions, they would be described in the System Interpreted Value Reference(24). One catch is that if a given Pipeline Stage, or the Input Assembler, identifies a System Interpreted Value (e.g. "clipDistance"), and the next Shader Stage declares it wants to input that value, it must not only declare as input the appropriate register # and component(s), but also identify the input as the same System Interpreted Value (e.g. "clipDistance"). Mismatching declarations results in undefined behavior. e.g. Identifying an output o3.x as "clipDistance", but not naming a declared input at the next stage v3.x as "clipDistance" is bad. Of course, in this example it would be legal for the subsequent Shader to not declare v3.x for input at all.

    It is not legal to declare a range of input or output registers as indexable(22.3.30) if any of the registers in the range contains a System Interpreted Value, with the exception of System Interpeted Values for the Tessellator, which have their own indexing rules - see the Hull Shader(10) specification.

    Note that there is no mechanism in the hardware to identify things that the hardware does not care about, such as "texture coordinate" or "color". At a high level in the software stack, full naming of all data may or may not be present to assist in authoring and/or discoverability, but these issues are outside the scope of anything that hardware or drivers need to know about.

    Note that while it may seem redundant to label System Interpreted Values at both the place producing the values as well as the next stage inputting it (in the case where the next stage actually wants to input it), this helps hardware/drivers isolate the compilation step for Shader programs at different Stages from any dependency on each other, in the event the driver needs to rename registers to fit hardware optimally, in a way that is transparent to the application.

    From the API point of view, System Generated Values and System Interpreted Values (above) may be exposed to developers as just once concept, "System Values" "SV_*".

    4.4.6 Element Alignment

    In many cases in D3D11.3, an offset for an Element is required, a stride for a structure (e.g. vertex) is required, or an initial offset for a Buffer is required. All of these types of values have the following alignment restrictions:

    Example byte alignments for some of the formats(19.1) which can be used in structures (e.g. vertex buffers) or as elements in index buffers:

    However, these alignment rules do not apply to Buffer offsets when creating Views on Buffers. These Buffer offsets have more stringent requirements, detailed in the View section(5.2).

    There is also some similar discussion, focused on memory accesses common to UAVs(5.3.9), SRVs and Thread Group Shared Memory in the Memory Addressing and Alignment Issues(7.13) section.

    None of these rules are validated (except in debug mode) and violations will result in undefined behavior.


    5 Resources


    Chapter Contents

    (back to top)

    5.1 Memory Structure
    5.2 Resource Views
    5.3 Resource Types and Pipeline Bindings
    5.4 Resource Creation
    5.5 Resource Dimensions
    5.6 Resource Manipulation
    5.7 Resource Discard
    5.8 Per-Resource Mipmap Clamping
    5.9 Tiled Resources


    Summary of Changes in this Chapter from D3D10 to D3D11.3

    Back to all D3D10 to D3D11.3 changes.(25.2)

    Several different Resource Types (arrangements of memory storage) are available for input or output by various Pipeline stages. The available Resource Types are: Buffer(5.3.4) (Typically a Structured(5.1.3) or "Unstructured(5.1.2) region of memory), Texture1D(5.3.5) (Homogeneous array of 1D Textures), Texture2D(5.3.6) (Homogeneous array of 2D Textures), Texture3D(5.3.7) (Volume Texture), and TextureCube(5.3.8) (3D enclosure). The Resource Type, in general, determines many characteristics, like whether the memory is Structured(5.1.3), where the Resource may be bound to in the graphics pipeline, how many mip levels there are, what the sampling behavior is, and other possible restrictions/properties on the Resource. Resources are built up of one or more Subresources, which each are a generalized 3D quantity of data which degenerates to store 2D and 1D quantities of data. The arrangement of Subresources to build up a Resource is tied to the Resource Type and dimensions.

    There are also distinctions in how a Resource is bound to the graphics pipeline. The binding location can also be thought of as accepting either Buffers directly or accepting Views of Resources. Each binding location which accepts Views requires a unique View type for that location - e.g. Render Target View or Shader Resource View.

    The size for mipmap slice subresources 1..n are computed sequentially from the size of the largest subresource (subresource 0, where for each mipped dimension:

            mipslice N+1 size = floor( mipslice N size / 2)
    

    The following diagram depicts Resources, their Subresource arrangement, and how they are sampled from within shaders. While the following diagram depicts deep mip mapping, it is valid to create Resources less than the maximum amount of mip levels.



    5.1 Memory Structure


    Section Contents

    (back to chapter)

    5.1.1 Overview
    5.1.2 Unstructured Memory
    5.1.3 Structured Buffers
    5.1.4 Raw Buffers
    5.1.5 Prestructured+Typeless Memory
    5.1.6 Prestructured+Typed Memory


    5.1.1 Overview

    When a Resource is allocated, it's memory structure can generally be classified either as Unstructured, Prestructured+Typeless, or Prestructured+Typed.

    5.1.2 Unstructured Memory

    Only the Buffer Resource(5.3.4) construction may be created as "Unstructured". Unstructured identifies the Resource as a single contiguous block of memory with no mipmaps, nor array slices. Unstructured Resources generally must have the memory structure defined when the Resource is bound to the graphics pipeline (providing types and offsets for the Element(s) in the Resource, as well as an overall stride). This memory structure can change freely, since it is late-bound to the Resource at the graphics pipeline binding location.

    The same Unstructured Resource may be bound to multiple slots in the graphics Pipeline with different memory interpretations at each location, as long as the Resource is only being read from at each binding. The same Unstructured Resource may not be bound to read and write stages of the pipeline simultaneously for a single Draw/Dispatch operation.

    Unstructured Resources do not have mipmaps nor array slices. See the Resource Binding Table(5.3.1) for descriptions of where Buffers (the only Resources that can be Unstructured) can be bound in the Pipeline.

    5.1.3 Structured Buffers

    Only the Buffer Resource(5.3.4) construction may be created as "Structured". Structured identifies the Resource as a single contiguous block of memory with no mipmaps, nor array slices, but it does have a structure size (stride), so that it represents an array of structures. Implementations can take advantage of knowing there is a fixed structure size in they way they lay out the memory physically (hidden from the application).

    A number of application scenarios require the ability to write a structure of data out to an index in an array. E.g. Generating an unordered collection of output data in an Append buffer(5.3.10). Hardware may be optimized for smaller reads and writes than the stride of a data. Consider a group of 16 shader threads where each thread wants to write out the first 4 bytes of a structure. If the structure is only 4 bytes, the 16 threads will collectively write out 16 consecutive 32-bit locations, which tends to be fast. But if the structure is larger – say 64 bytes, then the 16 threads will each issue a write that is spaced 64 bytes apart. Then when reading the data back in a later pass, the same problem will be reoccur. Reads will be issued with a spacing equal to the stride of the structure, with larger structures likely to have more of a performance issue.

    Due to the reads and the writes having similar access patterns it would be better to have the data layout in memory match the access pattern that occurs. Since the actual access pattern is hardware specific as well as the performance characteristics of reads spaced by stride boundaries, the design pattern of textures is followed to allow for better performance by hiding the physical layout of the memory.

    The same Structured Resource may be bound to multiple slots in the graphics Pipeline, as long as the Resource is only being read from at each binding. The same Structured Resource may not be bound to read and write stages of the pipeline simultaneously for a single Draw/Dispatch operation.

    Structured Resources do not have mipmaps nor array slices. See the Resource Binding Table(5.3.1) for descriptions of where Buffers (the only Resources that can be Structured) can be bound in the Pipeline.

    5.1.4 Raw Buffers

    Sometimes a convenient way to access the contents of a Buffer is to treat it simply as a huge bag of bits. The Raw view comes close to this, by allowing access to a Buffer in the form of 32-bit aligned addressing and accessing of data in chunks of 1-4 32-bit values, with no type.

    Raw access to a Buffer is indicated when creating either a Shader Resource View(5.2) (SRV) or Unordered Access View(5.3.9) (UAV), with the flag D3D11_BUFFER_SRV_FLAG_RAW (SRV) or D3D11_BUFFER_UAV_FLAG_RAW (UAV).

    To be able to create a RAW View, the underlying resource had to have been created with D3D11_RESOURCE_MISC_ALLOW_RAW_VIEWS.

    This flag cannot be combined with D3D11_RESOURCE_MISC_STRUCTURED_BUFFER. Also, a Buffer created with D3D11_BIND_CONSTANT_BUFFER cannot also specify D3D11_RESOURCE_MISC_ALLOW_RAW_VIEWS. This is not a limitation, since Constant Buffers already have a constraint that they cannot be accessed with any other View in the first place.

    Other than those invalid cases, specifying D3D11_RESOURCE_MISC_ALLOW_RAW_VIEWS when creating a Buffer does not limit any functionality versus not having it – e.g. the Buffer can be used for non-RAW access in any number of ways possible with D3D. Specifying the D3D11_RESOURCE_MISC_ALLOW_RAW_VIEWS flag only increases available functionality – it is just giving the system an early indication that the Buffer may participate in RAW style access in addition to other uses.

    5.1.5 Prestructured+Typeless Memory

    Any Resource type may be created as "Prestructured+Typeless". A structure size is provided, plus bit widths of components (but not the types of those components), and also dimensions (in units of structures) appropriate for the Resource type. This is unlike a Structured Buffer, which only specifies a structure size/stride and no definition of the contents of the structure. Before the Resource is bound to the pipeline, Resource Views must be created which will fully qualify the component's types. These Resource Views also allow the Resource to be decomposed into smaller compatible subgroupings of the Subresources. For example, a fully mipped DXGI_FORMAT_R32G32B32A32_TYPELESS Texture3D with a width of four, a height of three, and a depth of five, would have three mip levels. To use this texture, a Resource View would have to fully qualify the format of the Resource, possible to DXGI_FORMAT_R32G32B32A32_UINT. In addition, the Resource View could also regroup only the two least detailed mip levels or select only a particular mip level. This allows the original Resource to be manipulated as if it were a Resource made up of only a few Subresources within the original Resource. The full details of Resource Views(5.2) is described later.

    The benefit of Prestructured+Typeless Resources is that memory may be used as weakly typed storage, enabling limited reuse or reinterpretation of the memory, as long as the component bit counts remain the same. The same Prestructured+Typeless Resource may be bound to multiple slots in the graphics pipeline with Views of different fully qualified formats at each location. This forces bit representations of formats to be well-defined with respect to each other.

    For example, a Resource created with the format R32G32B32A32_TYPELESS may be used as R32G32B32A32_FLOAT and R32G32B32A32_UINT at different locations in the pipeline simultaneously.

    5.1.6 Prestructured+Typed Memory

    Any Resource type may be created as "Prestructured+Typed", also known as creating the Resource with a fully-qualified type or format. In general, this may allow Resource optimizations, especially when the Resource is created with flags indicating that the Resource cannot be Mapped/ Locked by the application.

    Special resource formats, such as Block Compression Formats(19.5), have the characteristic that in order to read an individual Element in the resource, there is not a unique location in the resource that corresponds to the Element. Some sort of decompression or decoding of data from locations in the resource that are not unique to a particular Element is required during the read process in order to resolve what an individual Element is (even when no filtering is being applied). Complex formats like this must be created as part of a "Prestructured+Typed" resource.

    "Prestructured+Typed" and "Prestructured+Typeless" resources support mipmapping, as the combination of Resource type, dimensions and structure size provided during resource creation supply enough information to allocate all memory in the layout required. Additionally, Resource Views created against Prestructured+Typed Resources must have indentical Resource Formats as the Prestructured+Typed Resource.


    5.2 Resource Views


    Section Contents

    (back to chapter)

    5.2.1 Overview
    5.2.2 Shader Resource View Support for Raw and Structured Buffers
    5.2.3 Clearing Views

    5.2.3.1 Clearing RenderTarget and DepthStencil Views
    5.2.3.2 Clearing Unordered Access Views
    5.2.3.3 Alternative: ClearView
    5.2.3.3.1 ClearView Rect mapping to surface area


    5.2.1 Overview

    In order to indirectly bind a Resource to certain stages of the graphics pipeline, Resource Views must be used. In addition, since some Resources may be created as "Prestructured+Typeless", the View provides the final opportunity to fully qualify the Resource component's types. The Resource Views also allow the Resource to be decomposed into smaller compatible subgroupings of the Mip Slices, Array Slices, and Subresources. This means that the effective dimensions and array sizes of the Views will, naturally, always be less than or equal to the original Resource. Each stage of the pipeline requires a unique type of View, and each type of View may have it's own custom set of state parameters that are needed to complete the process of binding a particular Resource to the graphics pipeline stage. All necessary restrictions to the basic Resource have already been done through the Pipeline Bind Flags during Resource creation. These Resource Views are directly bound to the pipeline, instead of the Resource objects, themselves.

    A resource view is distinct from the underlying resource from which the view was created, so where views are used, the view properties (number of mipmaps, number of array elements, type, etc.) are always used in place of the properties of the original resource. Thus, for example, a render target array index of zero always indicates the first array element in the view, even if the first array element in the view is not the first array element in the underlying resource. Out of range behaviors are also always with respect to the view properties where views are used.

    Each unique View type has certain restrictions associated with the bind location of the graphics pipeline stage. For example, Render Target Views of Buffers may have a maximum width of 16384. This maximum is smaller than the maximum size of a Buffer (min(max(128,0.25f * (Amount of Dedicated VRAM)),2048) MB), so only a subsection of large Buffers may be bound as a Render Target at a time. In addition, Render Target Views of Texture3D may have a maximum array size of 2048. This fortunately matches the maximum W dimension size of a Texture3D (2048).

    When Views are created of Buffers, restrictions are placed on the View's starting offset in the Buffer. If represented as a byte offset, the offset must be a multiple of the View Element Size. Another way to comply with this restriction is by specifying the Buffer offset in an integral number of View Elements. In addition, there exists another restriction on Buffer View creation. Views of the R32G32B32 element type cannot be created on a Buffer which had the Pipeline Bind flag of IAVERTEXINPUT, IAINDEXINPUT, CONSTANTBUFFER, or STREAMOUTPUT set. This prevents an R32G32B32 element from being used simultaneously as vertex and texture data.

    To characterize the kind of decomposition that Shader Resource Views are capable of, here's a complete listing of the number of Views that are possible with a Texture2D Resource that was created fully mipped with the most detailed LOD: width = 4, height = 4, arraysize = 3.

    1. MostDetailedMip: 0 (w:4,h:4), MipLevels: 3, FirstArraySlice: 0, ArraySize: 3
    2. MostDetailedMip: 0 (w:4,h:4), MipLevels: 3, FirstArraySlice: 0, ArraySize: 2
    3. MostDetailedMip: 0 (w:4,h:4), MipLevels: 3, FirstArraySlice: 1, ArraySize: 2
    4. MostDetailedMip: 0 (w:4,h:4), MipLevels: 3, FirstArraySlice: 0, ArraySize: 1
    5. MostDetailedMip: 0 (w:4,h:4), MipLevels: 3, FirstArraySlice: 1, ArraySize: 1
    6. MostDetailedMip: 0 (w:4,h:4), MipLevels: 3, FirstArraySlice: 2, ArraySize: 1
    7. MostDetailedMip: 0 (w:4,h:4), MipLevels: 2, FirstArraySlice: 0, ArraySize: 3
    8. MostDetailedMip: 0 (w:4,h:4), MipLevels: 2, FirstArraySlice: 0, ArraySize: 2
    9. MostDetailedMip: 0 (w:4,h:4), MipLevels: 2, FirstArraySlice: 1, ArraySize: 2
    10. MostDetailedMip: 0 (w:4,h:4), MipLevels: 2, FirstArraySlice: 0, ArraySize: 1
    11. MostDetailedMip: 0 (w:4,h:4), MipLevels: 2, FirstArraySlice: 1, ArraySize: 1
    12. MostDetailedMip: 0 (w:4,h:4), MipLevels: 2, FirstArraySlice: 2, ArraySize: 1
    13. MostDetailedMip: 1 (w:2,h:2), MipLevels: 2, FirstArraySlice: 0, ArraySize: 3
    14. MostDetailedMip: 1 (w:2,h:2), MipLevels: 2, FirstArraySlice: 0, ArraySize: 2
    15. MostDetailedMip: 1 (w:2,h:2), MipLevels: 2, FirstArraySlice: 1, ArraySize: 2
    16. MostDetailedMip: 1 (w:2,h:2), MipLevels: 2, FirstArraySlice: 0, ArraySize: 1
    17. MostDetailedMip: 1 (w:2,h:2), MipLevels: 2, FirstArraySlice: 1, ArraySize: 1
    18. MostDetailedMip: 1 (w:2,h:2), MipLevels: 2, FirstArraySlice: 2, ArraySize: 1
    19. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 0, ArraySize: 3
    20. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 0, ArraySize: 2
    21. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 1, ArraySize: 2
    22. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 0, ArraySize: 1
    23. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 1, ArraySize: 1
    24. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 2, ArraySize: 1
    25. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 0, ArraySize: 3
    26. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 0, ArraySize: 2
    27. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 1, ArraySize: 2
    28. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 0, ArraySize: 1
    29. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 1, ArraySize: 1
    30. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 2, ArraySize: 1
    31. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 0, ArraySize: 3
    32. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 0, ArraySize: 2
    33. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 1, ArraySize: 2
    34. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 0, ArraySize: 1
    35. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 1, ArraySize: 1
    36. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 2, ArraySize: 1

    The Views bound at the Render Target, Depth Stencil and Unordered Access binding locations in the pipeline have futher restrictions, in that they can only choose a Mip Slice, aka. select only one mip level. Here's a listing of the possible decomposition that can occur with Render Target, Depth Stencil and Unordered Access Views of the same Resource used in the previous example:

    1. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 0, ArraySize: 3
    2. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 0, ArraySize: 2
    3. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 1, ArraySize: 2
    4. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 0, ArraySize: 1
    5. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 1, ArraySize: 1
    6. MostDetailedMip: 0 (w:4,h:4), MipLevels: 1, FirstArraySlice: 2, ArraySize: 1
    7. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 0, ArraySize: 3
    8. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 0, ArraySize: 2
    9. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 1, ArraySize: 2
    10. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 0, ArraySize: 1
    11. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 1, ArraySize: 1
    12. MostDetailedMip: 1 (w:2,h:2), MipLevels: 1, FirstArraySlice: 2, ArraySize: 1
    13. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 0, ArraySize: 3
    14. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 0, ArraySize: 2
    15. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 1, ArraySize: 2
    16. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 0, ArraySize: 1
    17. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 1, ArraySize: 1
    18. MostDetailedMip: 2 (w:1,h:1), MipLevels: 1, FirstArraySlice: 2, ArraySize: 1

    5.2.2 Shader Resource View Support for Raw and Structured Buffers

    The following DDIs indicate the way Shader Resource Views (SRVs) are created, allowing read-only access to Raw and Structured Buffers in any shader stage.

    Making an SRV of a Raw buffer allows it to be declared for read in any shader stage by the ld_raw instruction. This is accomplished by specifying a flag on creation of the Buffer View requesting Raw access (D3D11_DDI_BUFFEREX_SRV_FLAG_RAW) shown below.

    In contrast, if the underlying Buffer was created as a Structured Buffer, then any SRV of the Buffer inherits the Structured semantics. In this case all shader stages can declare the resource for read by the ld_structured instruction. Note that unlike _RAW views (where the View decides that the Buffer will be "viewed" as RAW), nothing about the creation of a View of a Structured Buffer needs to indicate that it is structured, because once the Structured property is assigned to a Buffer on creation of the resource (including a structure stride), all Views on the Buffer are automatically Structured.

    typedef struct D3D11DDIARG_BUFFER_SHADERRESOURCEVIEW
    {
        UINT     FirstElement;
        UINT     NumElements;
    } D3D11DDIARG_BUFFER_SHADERRESOURCEVIEW;
    
    
    // BufferEx - Ex means extra pararameters
    typedef struct D3D11DDIARG_BUFFEREX_SHADERRESOURCEVIEW
    {
        UINT     FirstElement;
        UINT     NumElements;
        UINT     Flags; // See D3D11_DDI_BUFFEREX_SRV_FLAG* below
    } D3D11DDIARG_BUFFER_SHADERRESOURCEVIEW;
    #define D3D11_DDI_BUFFEREX_SRV_FLAG_RAW         0x00000001
    
    typedef struct D3D11DDIARG_CREATESHADERRESOURCEVIEW
    {
        D3D11DDI_HRESOURCE    hDrvResource;
        DXGI_FORMAT           Format;
        D3D11DDIRESOURCE_TYPE ResourceDimension;
    
        union
        {
            D3D11DDIARG_BUFFER_SHADERRESOURCEVIEW    Buffer;
            D3D11DDIARG_TEX1D_SHADERRESOURCEVIEW     Tex1D;
            D3D11DDIARG_TEX2D_SHADERRESOURCEVIEW     Tex2D;
            D3D11DDIARG_TEX3D_SHADERRESOURCEVIEW     Tex3D;
            D3D11DDIARG_TEXCUBE_SHADERRESOURCEVIEW   TexCube;
            D3D11DDIARG_BUFFEREX_SHADERRESOURCEVIEW  BufferEx;
        };
    } D3D11DDIARG_CREATESHADERRESOURCEVIEW;
    

    5.2.3 Clearing Views

    Clearing is an optimized operation to enable filling Render Target, Depth Stencil and Unordered Access Views with certain clear values.

    5.2.3.1 Clearing RenderTarget and DepthStencil Views

    The floating point values passed in through the DDI must be converted to the fully qualified format type of the View desired to be cleared. The standard type conversion rules(3.2) indicate how to convert to most values; but these conversion rules do not explicitly handle the case where the destination fixed point format contains more integer bits than the floating point format mantissa. When converting these floating point values to a format such as DXGI_FORMAT_R32G32B32A32_UINT or _SINT, the closest value is chosen. When the original floating point absolute value is larger than 2^24, the least significant bits of the destination are to be filled with 0's for _UINT and positive _SINT; or 1's for negative _SINT values.

    The full extent of the resource view is always cleared. Viewport and scissor are not applied.

    Depth clear values outside of the range specified in viewport range(15.6.1) will not be passed to the DDI.

        // part of user mode Device interface:
        STDMETHOD_( void, ClearRenderTarget )(
            D3D10DDI_HDEVICE hDevice,
            D3D11DDI_HRENDERTARGETVIEW hRenderTargetView,
            FLOAT ColorRGBA[ 4 ] );
        STDMETHOD_( void, ClearDepthStencil )(
            D3D10DDI_HDEVICE hDevice,
            D3D11DDI_HDEPTHSTENCILVIEW hDepthStencilView,
            UINT DSFlags, FLOAT Depth, UINT8 Stencil );
    

    5.2.3.2 Clearing Unordered Access Views

    For UnorderedAccessViews(5.3.9), there are a couple of ways to Clear the View.

    ClearUnorderedAccessViewUint(...) clears a UAV with bit-precise values, copying the lower ni bits from each array element i to the corresponding channel, where ni is the number of bits in the ith channel of the resource Format (for example, R8G8B8_FLOAT has 8 bits for the first 3 channels). This works on any UAV with no format conversion. For RAW Buffer and Structured Buffer Views, only the first array element’s value is used.

    ClearUnorderedAccessViewFloat(...) clears a UAV with a float value. It only works on FLOAT, UNORM, and SNORM UAVs, with format conversion from FLOAT to *NORM where appropriate. On other UAVs, the operation is invalid and the call will not reach the driver.

        // part of user mode Device interface:
        STDMETHOD_( void, ClearUnorderedAccessViewUint)(
            D3D10DDI_HDEVICE hDevice,
            D3D11DDI_HRENDERTARGETVIEW hRenderTargetView,
            UINT Values[ 4 ] );
        STDMETHOD_( void, ClearUnorderedAccessViewFloat)(
            D3D10DDI_HDEVICE hDevice,
            D3D11DDI_HDEPTHSTENCILVIEW hDepthStencilView,
            FLOAT Values[ 4 ] );
    

    5.2.3.3 Alternative: ClearView

    View clearing command, implemented however the driver sees is the most efficient way. The primary distinction here versus the other Clears described above in D3D11 is that this takes a list of rects (an empty list clears the entire surface). This method only works on RTV, UAV, or any Video View of a Texture2D surface (runtime drops invalid calls). All array slices in the view get the same clear applied (any rects apply to each array slice).

    The driver or hardware is responsible for clamping rects to the surface extents.

    Color values are converted/clamped to the destination format as appropriate per D3D conversion rules. E.g. if the format of the view is R8G8B8A8_UNORM, inputs are clamped to 0.0f to 1.0f (NaN to 0).

    If the format is integer, such as R8G8B8A8_UINT, inputs are taken as integral floats, so 235.0f maps to 235 (fractions rounded to zero, out of range/INF values clamped to target range, NaN to 0).

    typedef VOID ( APIENTRY* PFND3D11_1DDI_CLEARVIEW )(
        D3D10DDI_HDEVICE hDevice,
        D3D11DDI_HANDLETYPE viewType, // View type that supports this clear
                                      // (RTV, UAV or any Video view).
                                      // Must be a Texture2D{Array} resource only
        VOID* hView,
        const FLOAT[4] color, // interpretation of color is view / format specific
        const D3D10_DDI_RECT* pRect, // Rect is subject to aligment constraints based on format being cleared.
                                    // e.g. Subsampled video formats require rect extents snapped to full sample boundary
                                    // NULL means clear the entire view.
        UINT numRects
         );
    
    Color Mappings for RTVs and UAVs:
    Color[0]: R
    Color[1]: G
    Color[2]: B
    Color[3]: A
    (e.g. An RTV of the Y plane of an NV12 surface, of format R8_*, would take the color from R.  An RTV of the UV plane of an NV12 surface, of format R8G8_*, would take the color from RG.)
    
    Color Mappings for Video Views:
    Color[0]: Y
    Color[1]: U/Cb
    Color[2]: V/Cr
    Color[3]: A
    

    For Video Views with YUV or YCbBr formats, no color space conversion happens – and in cases where the format name doesn’t indicate _UNORM vs. _UINT etc., _UINT is assumed (so input 235.0f maps to 235 as described above).

    This feature is required to be supported for all D3D10+ hardware in D3D11.1 drivers and for D3D9 drivers maps to the already existing functionality there. The D3D9 equivalent honored the scissor rect, so emulation of ClearView on the D3D9 DDI will unset scissor / clear / reset scissor to achieve the intended behavior of ClearView (e.g. this scissor manipulation isn't needed on the new D3D11.1 ClearView DDI which ignores scissor/viewports by definition.).

    Having this Clear with rects provides parity with D3D9 where there was a similar Clear that in particular was used for video. With Video added to D3D11 (outside the scope of this spec), adding this ClearView provides parity with D3D9.

    Direct2D will be another user of this for rendering scenarios that map to a fill.

    5.2.3.3.1 ClearView Rect mapping to surface area

    For RTVs and UAVS: The space the ClearView rects apply on is that of the view format (as opposed to the surface format, which for video surfaces can be different sizes). This is consistent with how Viewports and rendering work on those views. e.g. for a 64x64 YUYV surface, an RTV with the format R8G8B8A8_UINT appears in shaders (and to RSSetViewports()) as having dimensions 32x64 RGBA values. ClearView’s rects apply to the same space. The “color” coming into ClearView is just maps to the channels in the view (RGBA) ignoring the video layout. So a single clear color could really mean “stripes” of color if interpreted in video space. That’s not interesting to do, but it just falls out and isn’t worth bothering to validate out – the user who makes D3D views of video surfaces has to know they are operating on the raw memory via D3D – be it shaders or APIs like ClearView.

    By contrast, ClearView on Video Views (the views that are used with the video pipeline and not D3D Rasterization) operate on logical surface dimensions. So a 64x64 YUYV surface appears as though it is that size, and so rects passed into ClearView are in that full 64x64 space (not 32x64). It is undefined to request clearing non-aligned rects (covering only half of the pixel pairs). The color passed into ClearView is just a single YUV value that is appropriately replicated for subsampled pixels by the driver. Video Views hide the memory layout from the API user, so they do not have to worry about what type of subsampling is going on (an exception is the alignment of the rect bounds).


    5.3 Resource Types and Pipeline Bindings


    Section Contents

    (back to chapter)

    5.3.1 Overview
    5.3.2 Performant Readback
    5.3.3 Conversion Resource Copies/ Blts
    5.3.4 Buffer

    5.3.4.1 Buffer: Pipeline Binding: Input Assembler Vertex Data
    5.3.4.2 Buffer Pipeline Binding: Input Assembler Index Data
    5.3.4.3 Buffer Pipeline Binding: Shader Constant Input
    5.3.4.3.1 Partial Constant Buffer Updates
    5.3.4.3.2 Offsetting Constant Buffer Bindings
    5.3.4.4 Buffer Pipeline Binding: Shader Resource Input
    5.3.4.5 Pipeline Binding: Stream Output
    5.3.4.6 Pipeline Binding: RenderTarget Output
    5.3.4.7 Pipeline Binding: Unordered Access
    5.3.5 Texture1D
    5.3.5.1 Pipeline Binding: Shader Resource Input
    5.3.5.2 Pipeline Binding: RenderTarget Output
    5.3.5.3 Pipeline Binding: Depth/ Stencil Output
    5.3.6 Texture2D
    5.3.6.1 Pipeline Binding: Shader Resource Input
    5.3.6.2 Pipeline Binding: RenderTarget Output
    5.3.6.3 Pipeline Binding: Depth/ Stencil Output
    5.3.7 Texture3D
    5.3.7.1 Pipeline Binding: Shader Resource Input
    5.3.7.2 Pipeline Binding: RenderTarget Output
    5.3.8 TextureCube
    5.3.8.1 Pipeline Binding: Shader Resource Input
    5.3.8.2 Pipeline Binding: RenderTarget Output
    5.3.8.3 Pipeline Binding: Depth/ Stencil Output
    5.3.9 Unordered Access Views
    5.3.9.1 Creating the Underlying Resource for a UAV
    5.3.9.2 Creating an Unordered Access View (UAV) at the DDI
    5.3.9.3 Binding an Unordered Access View at the DDI
    5.3.9.4 Hazard Tracking
    5.3.9.5 Limitations on Typed UAVs
    5.3.10 Unordered Count and Append Buffers
    5.3.10.1 Creating Unordered Count and Append Buffers
    5.3.10.2 Using Unordered Count and Append Buffers
    5.3.11 Video Views


    5.3.1 Overview

    All Resources must be qualified with a set of Pipeline Bind flags at creation time to indicate where in the graphics pipeline the Resource may be bound. Binding a Resource at a certain pipeline location imposes certain restrictions on the Resource for it's entire lifetime. Naturally, Resources may be bound at more than one location in the pipeline (even simultaneously within certain restrictions), but the Resource must satisfy all the restrictions that each Pipeline Bind flag imposes. Certain pipeline locations only accept Resource Views(5.2) to be bound to them. In such a case, the presence of the Pipeline Bind flag indicates that Resource Views can be created against the Resource in order to bind the Resource to such a pipeline location. Sometimes Pipeline Bind flags impose restrictions which conflict with each other, so such Pipeline Usage flags are naturally mutually exclusive. Otherwise, explicit mention is given when one Pipeline Bind flag prevents the usage of other Pipeline Bind flags.

    The following table indicates which Resource Types may be bound to which available graphics Pipeline locations. A single entire Resource may not be able to have itself bound entirely to both an input and output Pipeline stage during a Draw operation. However, it is possible to refer to discrete components of the Resource, with Resource Views(5.2), allowing the same Resource to be bound as an input and output simultaneously, as long as the different Views do not share the same Subresources. For example: A two-dimensional mipped Resource created with the appropriate Pipeline Bind flags may have Subresources bound as Shader Resource Inputs, and a mutually exclusive Subresource from the same Resource bound as a RenderTarget Output, by using different Views.

    Resource Type Input Assembler Vertex or Index Shader Resource Input Shader Constant Input Stream Output RenderTarget Output Depth/ Stencil Output
    Buffer UVUUV
    Texture1D V VV
    Texture2D V VV
    Texture3D V V
    TextureCube V VV

    5.3.2 Performant Readback

    Any Resource that is used as an output for the graphics pipeline cannot be mapped/ locked. This is not meant to block an application from viewing the contents of such a Resource. It is expected that to read the contents of such Resources in a performant manner, the contents must be copied to a Resource which is able to be mapped/ locked for CPU read access. Typically, the Resource which is able to be mapped/ locked will not be marked with any Pipeline Bind flags, and as such is expected to be a driver allocated system memory Resource which is allocated in such a fashion to be compatible with the hardware DMA engine. The Resource is also expected to be allocated for performant CPU reads. This enables an asynchronous performant read back for the CPU.

    5.3.3 Conversion Resource Copies/ Blts

    The Performant Readback(5.3.2) scenario highlights the need that for any device-dependent memory arrangement, used to optimize GPU Resources which cannot be mapped/ locked, there is always a performant ability to convert the memory arrangement into the device-independent memory arrangement that will be used to satisfy the map/ lock. This principle also relates to input Resources that cannot be mapped/ locked. Since non-mappable/ non-lockable input Resources may use a device-dependent memory arrangement and still be updated with UpdateSubresourceUP(5.6.8), CopyResource(5.6.3), and CopySubresourceRegion(5.6.2). Therefore, there is a need for a performant ability to convert the device-indepenedent memory arrangement into any device-dependent memory arrangement.

    5.3.4 Buffer

    The Buffer is the only Resource which can be created as Unstructured(5.1.2). When the Buffer is bound to the graphics Pipeline, it's memory interpretation generally must also be bound to the graphics Pipeline along with it (providing types and offsets for the Element(s) in the Resource, as well as an overall stride). Sometimes this information is bound or described separately.

    A Buffer has neither multiple mip levels nor multiple array slices, so a Buffer is made up of only a single Subresource. Buffers can be bound at multiple places in the pipeline simulatenously during a Draw call as long the Buffer is only read from at each location. If the Buffer is being written to, then the Buffer may only be bound to one location in the pipeline during a Draw call.

    5.3.4.1 Buffer: Pipeline Binding: Input Assembler Vertex Data

    When a Buffer has been created with the Pipeline Bind flag indicating that it may be used as an Input Assembler Vertex Input, the Buffer may be contain multiple types of data per vertex. This data type, offset, and stride binding is done when the Resource is bound to the Pipeline.

    5.3.4.2 Buffer Pipeline Binding: Input Assembler Index Data

    When a Buffer has been created with the Pipeline Bind flag indicating that it may be used as an Input Assembler Index Input, and the Buffer is bound as an Index Input, at the time of binding, the format must be specified as one of: R16_UINT, or R32_UINT.

    5.3.4.3 Buffer Pipeline Binding: Shader Constant Input

    When a Buffer has been created with the Pipeline Bind flag indicating that it may be used as a Shader Constant Input, the format of the Buffer is assumed to be R32G32B32A32_TYPELESS when bound as a Shader Constant Input. The Buffer size viewable from a shader is restricted to hold a maximum of 4096 elements. The overall buffer size can be larger - see Offsetting Constant Buffer Bindings(5.3.4.3.2). The usage of Constant Buffers within the shaders is expected to make Shader execution more efficient than using ld(22.4.6) or sample(22.4.15) with a Shader Resource within the Shader. Constant Input is read into a Shader given an integer array index to fetch a single Element. This is similar to point sampling of a texture; as there is no filtering. Constant Input is only needed to store Shader constants which could change between Draw() calls, as opposed to Immediate Constants or an Immediate Constant Buffer, which is are embedded into a Shader.

    A Shader Constant Resource is expected to be optimized for moving constant data from the CPU to the graphics adapter, and as such, may not be able to be mapped/ locked, allowing the CPU to read the contents of the Buffer directly. Therefore, the Resource may only be CPUWRITE (write-only) or not mappable/ lockable. In addition, if the Resource is mappable/ lockable, Map/ Lock must be called with DISCARDRESOURCE. NOOVERWRITE is not valid on Shader Constant Resources either. The Resource may still be used with CopyResource(5.6.3) and CopySubresourceRegion(5.6.2). All other Pipeline Bind flags are prevented from being used, disallowing constant buffers to be vertex buffers, streamed out to or rendered to, etc.

    5.3.4.3.1 Partial Constant Buffer Updates

    Map() allows NO_OVERWRITE for Constant Buffers. This was disallowed before D3D11.1.

    Similarly, UpdateSubresource1() adds the ability to perform partial Constant Buffer updates. So the pDstBox parameter does not have to be null NULL when updating Constant Buffers via UpdateSubresource1(). Either NO_OVERWRITE or DISCARD flags must be specified for a partial update, and the extents of the pDstBox parameter must be aligned to 16 byte (full constant) boundaries or the call is dropped.

    Before the first call with NO_OVERWRITE on a deferred context, a DISCARD must be done on the same context (via Copy*()/Update*()/Map() API flag or Discard*() API). This is not required on immediate contexts if the application knows the GPU is finished with the resource (though discard can be used if not).

    This feature is required to be supported for all D3D10+ hardware with D3D11.1 drivers.

    This allows applications to partially go back to a DX9 style convention where they have the ability to set invidivual constants in a Constant Buffer if they like (albeit with the new simplifying NO_OVERWRITE limitation - the updates can't conflict with existing constant references that may be in flight on the GPU). The restriction to not allow partial Constant Buffer updates when Constant Buffers were added to D3D10 was intended to simplify the system handling of shader constants on the assumption that applications could simply organize their constant data in to groups, each with its own Constant Buffer, organized by frequency of update. The impression seems to be that in many cases this restriction was a net performance loss for applications, hence this proposed change to at least partially loosen up Constant Buffer updates.

    5.3.4.3.2 Offsetting Constant Buffer Bindings

    A common desire for high performance game engines is to collect a large batch of Constant Buffer updates for constants to be referenced by separate Draw*() calls, each needing their own constants, all at once. This is facilitated by allowing the application to create a large Buffer and then pointing individual shaders to regions within it (kind of like a View, but without having to make a whole object to describe the view).

    Constant Buffers are allowed to be created larger than the maximum Constant Buffer size that an individual shader can reference, which is at most 4096 16-byte elements - 65kB. Each "element" is one 4-component Shader Constant.

    The Constant Buffer Resource size is limited only by the size of memory allocation the system is capable of handling (limits defined elsewhere, and more than large enough for the purpose of the discussion here).

    When a Constant Buffer larger than 4096 elements in size is bound to the pipeline via *SetShaderConstants() APIs [e.g. VSSetShaderConstants()], it appears to the shader as if it is only 4096 elements in size.

    Variants of the *SetShaderConstants() APIs, *SetShaderConstants1() allow a "FirstConstant" and "NumConstants" to be specified along with the binding. When the shader accesses a Constant Buffer bound this way it will appear as if it starts at the specified "FirstConstant" offset (where 1 means 16 bytes) and has a size defined by NumConstants (number of 16 byte Constants). This is basically a lightweight "View" of a region of a larger Constant Buffer.

    FirstConstant must be a multiple of 16 constants.

    NumConstants must be a multiple of 16 constants, in the range [0..4096].

    If any part of the range defined by FirstConstant and ConstantCount falls off the underlying resource, accesses to those addresses count as out of bounds reads from the shader, which is defined to return 0 for all components.

    This feature is required to be supported for all D3D10+ hardware in D3D11.1 drivers and is emulated by the runtime on Feature Level 9_x running on D3D9 drivers.

    5.3.4.4 Buffer Pipeline Binding: Shader Resource Input

    When a Buffer has been created with the Pipeline Bind flag indicating that it may be used as a Shader Resource Input and it is a typed Buffer (the view specifies a format type), it may be read from within shaders with the load(22.4.6). See the description of this instruction for detail. To use a typed Buffer as a Shader Resource Input, it must be bound at one of the available 128 slots for input Resources, by first creating the appropriate View for this particular stage of the graphics pipeline. It is fine for the same Buffer to be bound to multiple slots simultaneously, possibly even with different Element formats or inital offsets. However at each binding, only a single Element type is permitted, and the data stride is implied to be equal the Element size. In other words, "Array-of-structure" style layouts cannot be described for typed Buffers bound at Shader Resource Input. Structured Buffers allow array-of-structures access, though without any automatic format conversion for elements.

    Just like Typed Buffers, Raw and Structured Buffers can be bound to the pipeline via Shader Resource Views for reading into shaders via ld_raw(22.4.10) and ld_structured(22.4.12) instructions, respectively.

    5.3.4.5 Pipeline Binding: Stream Output

    Details of the usage of such a Resource are described in the Streaming Output section(14). There are two types of bindings available for Stream Output Buffers, one that treats a single output Buffer as a Multiple-Element Buffer (array-of-structures), while the other permits multiple output Buffers each treated as Single-Element Buffers (structure-of-arrays). Single-Element Buffer output is expected to be used typically for recirculation (subsequently) as a Shader Resource Input, but this can also be used as Input Assembler Vertex Input. Multiple-Element Buffer output is only intended to be used for recirculating data (subsequently) back as Input Assembler Vertex Input (since Multiple-Element Buffer access is not currently available in Shaders).

    If the Resource has the Input Assembler Vertex Input Pipeline Bind flag specified, the Resource may also be used with DrawAuto(8.9).

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.4.6 Pipeline Binding: RenderTarget Output

    When a Buffer has been created with the Pipeline Bind flag indicating that it may be used as a RenderTarget Output, this Pipeline Bind flag indicates that Render Target Views may be created with this Resource.

    Constraints when a Buffer is used as RenderTarget output: it cannot be paired with any Depth/Stencil Output (i.e. no depth buffering); it can only have a single Element defined, with a data stride implied to be equal to the Element width; the View is limited to a maximum width of 16384 (multiple Views with different offsets would be needed to leverage the entire Buffer). In all other regards, a Buffer render target output is identical to the Texture1D case.

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.4.7 Pipeline Binding: Unordered Access

    When the Unordered Access Pipeline Bind has been indicated, Unordered Access Views may be created for use at the Compute Shader or Pixel Shader.

    5.3.5 Texture1D

    A Texture1D is a homogeneous array of 1D Textures. The array is homogeneous in the sense that each Texture has the same data format and dimensions (including miplevels). The entire array of Textures are created atomically. The memory for the entire Resource need not be contiguous. A Texture1D may not be created as Unstructured(5.1.2), but may be created as Prestructured+Typeless Memory(5.1.5) or as Prestructured+Typed Memory(5.1.6). As illustrated by the diagram(5) and binding configurations(5.3.1), a Texture1D may be decomposed into sub-groups of Mip Slices, Array Slices, and Subresources in order to refer to discrete components of the Resource to accomplish certain operations. The decomposition for graphics Pipeline Binding is achieved through the usage of Views for each stage of the pipeline.

    Like other Resources, a Texture1D must be qualified with a set of flags at creation indicating where in the graphics pipeline the Resource may be bound. Naturally, the Resource may be bound at more than one location in the pipeline, but the Resource must've been created with the restrictions that each Pipeline Usage flag indicates. Sometimes Pipeline Bind flags have restrictions which conflict with each other, so such Pipeline Bind flags are mutually exclusive.

    5.3.5.1 Pipeline Binding: Shader Resource Input

    When the Texture1D has been created with the Pipeline Bind flag indicating that it may be used as a Shader Resource Input, the Texture1D Resource may be read from within shaders with the ld(22.4.6) or sample(22.4.15) instructions, after they are bound to the pipeline through the usage of Views. See the descriptions of these instructions for details. Each Element from a Texture1D to be read into a Shader counts towards a limit on the total number of elements addressable from Resources (128). Texture1D Resources are addressed from the Shader with a 1D coordinate plus a 2nd coordinate specifying which Array Slice in the Texture1D to fetch from. The 2nd coordinate, if provided as floating point data, is rounded (nearest even), producing an integral array index. Typical 1D filtering occurs on the Array Slice chosen by the 2nd coordinate.

    5.3.5.2 Pipeline Binding: RenderTarget Output

    When a Texture1D Mip Slice is bound as a RenderTarget Output, through the usage of Views, it is allowable to use either an accompanying Texture1D Depth/ Stencil of the same dimensions. For example, if the most detailed Mip Slice View of a Texture1D (width=6, arraysize=8) is bound as a RenderTarget Output; an effective Texture1D View of (width=6, arraysize=8) may be used as a Depth/ Stencil. Also, the particular Array Slice in the Texture1D to render is chosen, from the Geometry Shader stage, by declaring a scalar component output data as the System Interpreted Value "renderTargetArrayIndex". If such a value is not present in primitive data reaching the rasterizer, the default is to render to Array Slice 0.

    Rasterization to Texture1D resources is identical to rasterizing to a Texture2D resource with a y dimension of 1, thus both x and y coordinates are honored and only rendering that covers the Nx1 area of these resources will update them.

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.5.3 Pipeline Binding: Depth/ Stencil Output

    When the Texture1D has been created with the Pipeline Bind flag indicating that it may be used as a Depth/ Stencil Output, the Texture1D Resource may only be one of a few Resource Formats (essentially only those which have a 'D' component or those TYPELESS formats which can be converted to a format with a 'D' component), such as D32_FLOAT or R32_TYPELESS, etc.

    Resources created with this Pipeline Bind flag cannot also be used as a RenderTarget (the two flags are mutually exclusive).

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. In addition, Depth/ Stencil Resources cannot be a destination for CopyResource(5.6.3), CopySubresourceRegion(5.6.2), nor UpdateSubresourceUP(5.6.8) operations. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.6 Texture2D

    A Texture2D is a homogeneous array of 2D Textures. The array is homogeneous in the sense that each Texture has the same data format and dimensions (including miplevels). The entire array of Textures are created atomically. The memory for the entire Resource need not be contiguous. A Texture2D may not be created as Unstructured(5.1.2), but may be created as Prestructured+Typeless Memory(5.1.5) or as Prestructured+Typed Memory(5.1.6). As illustrated by the diagram(5) and binding configurations(5.3.1), a Texture2D may be decomposed into sub-groups of Mip Slices, Array Slices, and Subresources in order to refer to discrete components of the Resource to accomplish certain operations. The decomposition for graphics Pipeline Binding is achieved through the usage of Views for each stage of the pipeline.

    Like other Resources, a Texture2D must be qualified with a set of flags at creation indicating where in the graphics Pipeline the Resource may be bound. Naturally, the Resource may be bound at more than one location in the Pipeline, but the Resource must've been created with the restrictions that each Pipeline Bind flag indicates. Sometimes Pipeline Bind flags have restrictions which conflict with each other, so such Pipeline Bind flags are mutually exclusive.

    5.3.6.1 Pipeline Binding: Shader Resource Input

    When the Texture2D has been created with the Pipeline Bind flag indicating that it may be used as a Shader Resource Input, the Texture2D Resource may be read from within shaders with the ld(22.4.6) or sample(22.4.15) instructions, after they are bound to the pipeline through the usage of Views. See the descriptions of these instructions for details. Each Element from a Texture2D to be read into a Shader counts towards a limit on the total number of elements addressable from Resources (128). Texture2D Resources are addressed from the Shader with a 2D coordinate plus a 3rd coordinate specifying which Array Slice in the Texture2D to fetch from. The 3rd coordinate, if provided as floating point data, is rounded (nearest even), producing an integral array index. Typical 2D filtering occurs on the Array Slice chosen by the 3rd coordinate.

    5.3.6.2 Pipeline Binding: RenderTarget Output

    When a Texture2D Mip Slice View is bound as a RenderTarget Output, through the usage of Views, it is allowable to use either an accompanying effective Texture2D Depth/ Stencil View of the same dimensions. For example, if the most detailed Mip Slice View of a Texture2D (width=6, height=4, arraysize=8) is bound as a RenderTarget Output; an effective Texture2D View of (width=6, height=4, arraysize=8) may be used as a Depth/ Stencil. Also, the particular Array Slice in the Texture2D to render is chosen, from the Geometry Shader stage, by declaring a scalar component of output data as the System Interpreted Value "renderTargetArrayIndex". If such a value is not present in primitive data reaching the rasterizer, the default is to render to Array Slice 0.

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.6.3 Pipeline Binding: Depth/ Stencil Output

    When the Texture2D has been created with the Pipeline Bind flag indicating that it may be used as a Depth/ Stencil Output, the Texture2D Resource may only be one of a few Resource Formats (essentially only those which have a 'D' component or those TYPELESS formats which can be converted to a format with a 'D' component), such as D32_FLOAT or R32_TYPELESS, etc.

    Resources created with this Pipeline Bind flag cannot also be used as a RenderTarget (the two flags are mutually exclusive).

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. In addition, Depth/ Stencil Resources cannot be a destination for CopyResource(5.6.3), CopySubresourceRegion(5.6.2), nor UpdateSubresourceUP(5.6.8) operations. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.7 Texture3D

    A Texture3D is a 3D grid data layout, supporting mipmaps; and is also known as a Volume Texture. The entire Resource is created atomically. The memory for the entire Resource need not be contiguous. A Texture3D may not be created as Unstructured(5.1.2), but may be created as Prestructured+Typeless Memory(5.1.5) or as Prestructured+Typed Memory(5.1.6). As illustrated by the diagram(5) and binding configurations(5.3.1), a Texture3D may be decomposed into sub-groups of Mip Slices, Array Slices, and Subresources in order to refer to discrete components of the Resource to accomplish certain operations. The decomposition for graphics Pipeline Binding is achieved through the usage of Views for each stage of the pipeline.

    5.3.7.1 Pipeline Binding: Shader Resource Input

    When the Texture3D has been created with the Pipeline Bind flag indicating that it may be used as a Shader Resource Input, the Texture3D Resource may be read from within shaders with the ld(22.4.6) or sample(22.4.15) instructions, after they are bound to the pipeline through the usage of Views. See the descriptions of these instructions for details. Each Element from a Texture3D to be read into a Shader counts towards a limit on the total number of elements addressable from Resources (128). Texture3D Resources are addressed from the Shader with a 3D coordinate. Typical 3D filtering occurs with this coordinate.

    5.3.7.2 Pipeline Binding: RenderTarget Output

    When a Texture3D Mip Slice is bound as a RenderTarget Output, through the usage of Views, the Texture3D behaves identically to a Texture2D with n Array Slices where n is the depth (3rd dimension) of the Texture3D. The particular z slice in the Texture3D to render is chosen, from the Geometry Shader stage stage, by declaring a scalar component of output data as the System Interpreted Value "renderTargetArrayIndex". If such a value is not present in primitive data reaching the rasterizer, the default is to render\ to z=0.

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.8 TextureCube

    A TextureCube has 6 faces, each of which is like a square Texture2D, including mipmaps. The entire Resource is created atomically. The memory for the entire Resource need not be contiguous. A Texture3D may not be created as Unstructured(5.1.2), but may be created as Prestructured+Typeless Memory(5.1.5) or as Prestructured+Typed Memory(5.1.6). As illustrated by the diagram(5) and binding configurations(5.3.1), a TextureCube may be decomposed into sub-groups of Mip Slices, Array Slices (each representing a face), and Subresources in order to refer to discrete components of the Resource to accomplish certain operations. The decomposition for graphics Pipeline Binding is achieved through the usage of Views for each stage of the pipeline.

    TextureCubes can also represent an array of cubes, which means a multiple of 6 faces. Used as a Cube Array, the "array" dimension selects which Cube to use. However, the same resource can also be viewed as a 2D Array, in which case each face of each Cube appears as a single location along the "array" dimension.

    5.3.8.1 Pipeline Binding: Shader Resource Input

    When the TextureCube has been created with the Pipeline Bind flag indicating that it may be used as a Shader Resource Input, the TextureCube{Array} Resource may be read from within shaders after they are bound to the pipeline through the usage of Views. The View can expose the TextureCube{Array} as an array of TextureCubes starting from any face (from the perspective of a sequence of 2D faces), then spanning a multiple of 6 faces, such that each 6 faces appears as a location on the array axis. Alternatively, the TextureCube can be viewed as a 2D Array spanning any contiguous set of faces in the resource where each face is a slice, hiding the "Cube-ness" of the resource. Each Element from a TextureCube resource to be read into a Shader counts towards a limit on the total number of elements addressable from Resources (128). TextureCube Resources viewed as a Cube are addressed from the Shader with a 3D vector pointing out from the center of the TextureCube, and as a Cube Array, an additional coordinate provides the Array Slice. If the Array Slice is provided as a floating point number, is is rounded to nearest even.

    5.3.8.2 Pipeline Binding: RenderTarget Output

    When a TextureCube{Array} Mip Slice is bound as a RenderTarget Output, the TextureCube behaves identically to a Texture2DArray, such that any contiguous subset of the faces in the array participate in the View. The particular Array slice in the View to render to is chosen from the Geometry Shader stage, by declaring a scalar component of output data as the System Interpreted Value "renderTargetArrayIndex". If such a value is not present in primitive data reaching the rasterizer, the default is to render to Array Slice0.

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    5.3.8.3 Pipeline Binding: Depth/ Stencil Output

    When the TextureCube{Array} has been created with the Pipeline Bind flag indicating that it may be used as a Depth/ Stencil Output, the Resource may only be one of a few Resource Formats (essentially only those which have a 'D' component or those TYPELESS formats which can be converted to a format with a 'D' component), such as D32_FLOAT or R32_TYPELESS, etc. In addition, when rendering using such a Depth/ Stencil TextureCube (viewed as a Texture2DArray Depth Stencil View), only equally sized RenderTarget Views are compatable for use as a RenderTarget Output.

    Resources created with this Pipeline Bind flag cannot also be used as a RenderTarget (the two flags are mutually exclusive).

    Since this is an output stage, Resources with this Pipeline Bind flag are not able to be mapped/ locked for CPU access ever. In addition, Depth/ Stencil Resources cannot be a destination for CopyResource(5.6.3), CopySubresourceRegion(5.6.2), nor UpdateSubresourceUP(5.6.8) operations. This doesn't prevent Resources completely from being viewed by the CPU, as there are performant(5.3.2) methods for viewing the contents of the Resource.

    typedef struct D3D10DDI_HSHADERRESOURCEVIEW
    {
        void* m_pDrvPrivate;
    } D3D10DDI_HSHADERRESOURCEVIEW;
    
    typedef struct D3D10DDIARG_BUFFER_SHADERRESOURCEVIEW
    {
        union
        {
            UINT FirstElement; // Nicer name // < ResourceWidth / ElementSize
            UINT ElementOffset;
        };
        union
        {
            UINT NumElements; // Nicer name // <= ( ResourceWidth / ElementSize - ElementOffset )
            UINT ElementWidth;
        };
    } D3D10DDIARG_BUFFER_SHADERRESOURCEVIEW;
    
    typedef struct D3D11DDIARG_BUFFEREX_SHADERRESOURCEVIEW
    {
        union
        {
            UINT FirstElement;  // Nicer name   // < ResourceWidth / ElementSize
            UINT ElementOffset;
        };
        union
        {
            UINT NumElements;   // Nicer name // <= ( ResourceWidth / ElementSize - ElementOffset )
            UINT ElementWidth;
        };
        UINT     Flags; // See D3D11_DDI_BUFFEREX_SRV_FLAG_* below
    } D3D11DDIARG_BUFFEREX_SHADERRESOURCEVIEW;
    #define D3D11_DDI_BUFFEREX_SRV_FLAG_RAW         0x00000001
    
    
    typedef struct D3D10DDIARG_TEX1D_SHADERRESOURCEVIEW
    {
        UINT     MostDetailedMip; // < Resource MipLevels
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     MipLevels; // <= ( Resource MipLevels - MostDetailedMip )
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D10DDIARG_TEX1D_SHADERRESOURCEVIEW;
    
    typedef struct D3D10DDIARG_TEX2D_SHADERRESOURCEVIEW
    {
        UINT     MostDetailedMip; // < Resource MipLevels
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     MipLevels; // <= ( Resource MipLevels - MostDetailedMip )
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D10DDIARG_TEX2D_SHADERRESOURCEVIEW;
    
    typedef struct D3D10DDIARG_TEX3D_SHADERRESOURCEVIEW
    {
        UINT     MostDetailedMip; // < Resource MipLevels
        UINT     MipLevels; // <= ( Resource MipLevels - MostDetailedMip )
    } D3D10DDIARG_TEX3D_SHADERRESOURCEVIEW;
    
    
    typedef struct D3D10DDIARG_TEXCUBE_SHADERRESOURCEVIEW
    {
        UINT     MostDetailedMip;
        UINT     MipLevels;
    } D3D10DDIARG_TEXCUBE_SHADERRESOURCEVIEW;
    
    typedef struct D3D10_1DDIARG_TEXCUBE_SHADERRESOURCEVIEW
    {
        UINT MostDetailedMip; // < Resource MipLevels
        UINT MipLevels; // <= ( Resource MipLevels - MostDetailedMip )
        UINT First2DArrayFace; // <= ( Resource ArraySize - 5 )
        UINT NumCubes; // multiple of 6 faces that must fit in resource after First2DArrayFace
    } D3D10_1DDIARG_TEXCUBE_SHADERRESOURCEVIEW;
    
    typedef struct D3D11DDIARG_CREATESHADERRESOURCEVIEW
    {
        D3D10DDI_HRESOURCE    hDrvResource;
        DXGI_FORMAT           Format; // Fully qualified
        D3D10DDIRESOURCE_TYPE ResourceDimension;
    
        union
        {
            D3D10DDIARG_BUFFER_SHADERRESOURCEVIEW    Buffer;
            D3D10DDIARG_TEX1D_SHADERRESOURCEVIEW     Tex1D;
            D3D10DDIARG_TEX2D_SHADERRESOURCEVIEW     Tex2D;
            D3D10DDIARG_TEX3D_SHADERRESOURCEVIEW     Tex3D;
            D3D10_1DDIARG_TEXCUBE_SHADERRESOURCEVIEW TexCube;
            D3D11DDIARG_BUFFEREX_SHADERRESOURCEVIEW  BufferEx;
        };
    } D3D11DDIARG_CREATESHADERRESOURCEVIEW;
    
        // part of user mode Device interface:
        STDMETHOD_( SIZE_T, CalcPrivateShaderResourceViewSize )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATESHADERRESOURCEVIEW* pCreateShaderResourceView );
        STDMETHOD( CreateShaderResourceView )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATESHADERRESOURCEVIEW* pCreateShaderResourceView,
            D3D10DDI_HSHADERRESOURCEVIEW hDrvShaderResourceView );
        STDMETHOD_( void, DestroyShaderInput )( D3D10DDI_HDEVICE hDrvDevice,
            D3D10DDI_HSHADERRESOURCEVIEW hDrvShaderResourceView );
    
    
    typedef struct D3D10DDI_HRENDERTARGETVIEW
    {
        void* m_pDrvPrivate;
    } D3D10DDI_HRENDERTARGETVIEW;
    
    typedef struct D3D10DDIARG_BUFFER_RENDERTARGETVIEW
    {
        union
        {
            UINT FirstElement; // Nicer name // < ResourceWidth / ElementSize
            UINT ElementOffset;
        };
        union
        {
            UINT NumElements; // Nicer name // <= ( ResourceWidth / ElementSize - ElementOffset )
            UINT ElementWidth;
        };
    } D3D10DDIARG_BUFFER_RENDERTARGETVIEW;
    
    typedef struct D3D10DDIARG_TEX1D_RENDERTARGETVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D10DDIARG_TEX1D_RENDERTARGETVIEW;
    
    typedef struct D3D10DDIARG_TEX2D_RENDERTARGETVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D10DDIARG_TEX2D_RENDERTARGETVIEW;
    
    typedef struct D3D10DDIARG_TEX3D_RENDERTARGETVIEW
    {
        UINT     MipSlice;
        UINT     FirstW; // < Resource MipSlice W dimension
        UINT     WSize; // <= ( Resource MipSlice W dimension - FirstW )
    } D3D10DDIARG_TEX3D_RENDERTARGETVIEW;
    
    typedef struct D3D10DDIARG_TEXCUBE_RENDERTARGETVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // as 2DArray
        UINT     ArraySize; // as 2DArray
    } D3D10DDIARG_TEXCUBE_RENDERTARGETVIEW;
    
    typedef struct D3D10DDIARG_CREATERENDERTARGETVIEW
    {
        D3D10DDI_HRESOURCE    hDrvResource;
        DXGI_FORMAT           Format; // Fully qualified
        D3D10DDIRESOURCE_TYPE ResourceDimension;
    
        union
        {
            D3D10DDIARG_BUFFER_RENDERTARGETVIEW  Buffer;
            D3D10DDIARG_TEX1D_RENDERTARGETVIEW   Tex1D;
            D3D10DDIARG_TEX2D_RENDERTARGETVIEW   Tex2D;
            D3D10DDIARG_TEX3D_RENDERTARGETVIEW   Tex3D;
            D3D10DDIARG_TEXCUBE_RENDERTARGETVIEW TexCube;
        };
    } D3D10DDIARG_CREATERENDERTARGETVIEW;
    
        // part of user mode Device interface:
        STDMETHOD_( SIZE_T, CalcPrivateRenderTargetViewSize )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D10DDIARG_CREATERENDERTARGETVIEW* pCreateRenderTargetView );
        STDMETHOD( CreateRenderTargetView )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D10DDIARG_CREATERENDERTARGETVIEW* pCreateRenderTargetView,
            D3D10DDI_HRENDERTARGETVIEW hDrvRenderTargetView );
        STDMETHOD_( void, DestroyRenderTargetView )( D3D10DDI_HDEVICE hDrvDevice,
            D3D10DDI_HRENDERTARGETVIEW hDrvRenderTargetView );
    
    typedef struct D3D10DDI_HDEPTHSTENCILVIEW
    {
        void* m_pDrvPrivate;
    } D3D10DDI_HDEPTHSTENCILVIEW;
    
    typedef struct D3D10DDIARG_TEX1D_DEPTHSTENCILVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D10DDIARG_TEX1D_DEPTHSTENCILVIEW;
    
    typedef struct D3D10DDIARG_TEX2D_DEPTHSTENCILVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D10DDIARG_TEX2D_DEPTHSTENCILVIEW;
    
    typedef struct D3D10DDIARG_TEXCUBE_DEPTHSTENCILVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // as 2DArray
        UINT     ArraySize; // as 2DArray
    } D3D10DDIARG_TEXCUBE_DEPTHSTENCILVIEW;
    
    typedef enum D3D11_DDI_CREATEDEPTHSTENCILVIEW_FLAG
    {
        D3D11_DDI_CREATE_DSV_READ_ONLY_DEPTH   = 0x01L,
        D3D11_DDI_CREATE_DSV_READ_ONLY_STENCIL = 0x02L,
        D3D11_DDI_CREATE_DSV_FLAG_MASK         = 0x03L,
    } D3D11_DDI_CREATEDEPTHSTENCILVIEW_FLAG;
    
    typedef struct D3D11DDIARG_CREATEDEPTHSTENCILVIEW
    {
        D3D10DDI_HRESOURCE    hDrvResource;
        DXGI_FORMAT           Format; // Fully qualified
        D3D10DDIRESOURCE_TYPE ResourceDimension;
        UINT                  Flags;
    
        union
        {
            D3D10DDIARG_TEX1D_DEPTHSTENCILVIEW   Tex1D;
            D3D10DDIARG_TEX2D_DEPTHSTENCILVIEW   Tex2D;
            D3D10DDIARG_TEXCUBE_DEPTHSTENCILVIEW TexCube;
        };
    } D3D11DDIARG_CREATEDEPTHSTENCILVIEW;
    
        // part of user mode Device interface:
        STDMETHOD_( SIZE_T, CalcPrivateDepthStencilViewSize )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATEDEPTHSTENCILVIEW* pCreateDepthStencilView );
        STDMETHOD( CreateDepthStencilView )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATEDEPTHSTENCILVIEW* pCreateDepthStencilView,
            D3D10DDI_HDEPTHSTENCILVIEW hDrvDepthStencilView );
        STDMETHOD_( void, DestroyDepthStencilView )( D3D10DDI_HDEVICE hDrvDevice,
            D3D10DDI_HDEPTHSTENCILVIEW hDrvDepthStencilView );
    
    typedef struct D3D11DDI_HUNORDEREDACCESSVIEW
    {
        void* m_pDrvPrivate;
    } D3D11DDI_HUNORDEREDACCESSVIEW;
    
    typedef struct D3D11DDIARG_BUFFER_UNORDEREDACCESSVIEW
    {
        UINT     FirstElement; // < ResourceWidth / ElementSize
        UINT     NumElements; // <= ( ResourceWidth / ElementSize - ElementOffset )
        UINT     Flags; // See D3D11_DDI_BUFFER_UAV_FLAG* below
    } D3D11DDIARG_BUFFER_UNORDEREDACCESSVIEW;
    #define D3D11_DDI_BUFFER_UAV_FLAG_RAW         0x00000001
    #define D3D11_DDI_BUFFER_UAV_FLAG_APPEND      0x00000002
    #define D3D11_DDI_BUFFER_UAV_FLAG_COUNTER     0x00000004
    
    typedef struct D3D11DDIARG_TEX1D_UNORDEREDACCESSVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D11DDIARG_TEX1D_UNORDEREDACCESSVIEW;
    
    typedef struct D3D11DDIARG_TEX2D_UNORDEREDACCESSVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice; // < Resource ArraySize
        UINT     ArraySize; // <= ( Resource ArraySize - FirstArraySlice )
    } D3D11DDIARG_TEX2D_UNORDEREDACCESSVIEW;
    
    typedef struct D3D11DDIARG_TEX3D_UNORDEREDACCESSVIEW
    {
        UINT     MipSlice;
        UINT     FirstW; // < Resource MipSlice W dimension
        UINT     WSize; // <= ( Resource MipSlice W dimension - FirstW )
    } D3D11DDIARG_TEX3D_UNORDEREDACCESSVIEW;
    
    typedef struct D3D11DDIARG_CREATEUNORDEREDACCESSVIEW
    {
        D3D10DDI_HRESOURCE    hDrvResource;
        DXGI_FORMAT           Format; // Fully qualified
        D3D10DDIRESOURCE_TYPE ResourceDimension; // Runtime will never set this to TexCube
    
        union
        {
            D3D11DDIARG_BUFFER_UNORDEREDACCESSVIEW    Buffer;
            D3D11DDIARG_TEX1D_UNORDEREDACCESSVIEW     Tex1D;
            D3D11DDIARG_TEX2D_UNORDEREDACCESSVIEW     Tex2D;
            D3D11DDIARG_TEX3D_UNORDEREDACCESSVIEW     Tex3D;
        };
    } D3D11DDIARG_CREATEUNORDEREDACCESSVIEW;
    
        // part of user mode Device interface:
        STDMETHOD_( SIZE_T, CalcPrivateUnorderedAccessViewSize )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATEUNORDEREDACCESS* pCreateUnorderedAccessView );
        STDMETHOD( CreateUnorderedAccessView )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATEUNORDEREDACCESSVIEW* pCreateUnorderedAccessView,
            D3D10DDI_HUNORDEREDACCESSVIEW hDrvUnorderedAccessView );
        STDMETHOD_( void, DestroyDepthStencilView )( D3D10DDI_HDEVICE hDrvDevice,
            D3D10DDI_HUNORDEREDACCESSVIEW hDrvUnorderedAccessView );
    
    

    5.3.9 Unordered Access Views

    Unordered Access Views (UAVs) can be bound at the Output Merger(17) (available to all graphics shader stages from there) and Compute Shader(18) stage.

    At the Output Merger, there is the constraint that the total of the number of o# slots (Render Target Views - RTVs) and u# slots (UAVs) that may be bound simultaneously is at most 64, where no more than 8 can be RTVs. The way this is enforced, for simplicity, is that all o# (RTV) slots that are declared must have a slot # that is less than the minimum # of the u# (UAV) slots that are declared. So it is valid for a Pixel Shader to declare o0, o1, u4 and u63, but it is not valid for a Pixel Shader to declare o0, u3, and o4.

    Separating o# from u# this way minimizes future dependence on the fact that they happen to live in the same bind space in D3D11, if that turns out not to be desirable.

    The UAVs bound at the Output Merger are visible to all graphics stages (a shared set of UAV bindings). So multiple graphics shader stages can access the same UAVs simultaneously.

    Certain shader stages, like the Vertex Shader or Domain Shader (with Tessellation), are implemented by hardware using shader result caches. So if nearby primitives share the same vertex, the results of the corresponding shader invocation for that vertex may be retrieved from a result cache rather than re-executing the shader. The presence of these result caches and their behavior is hardware specific. Previously, without the ability for the unique shader invocations to have side-effects, the user had no way of knowing or depending on any caching taking place, beyond observing some performance wins if the caching worked well. With UAVs available to all shaders (enabling shaders to write arbitrarily to the UAV memory), any hardware-specific shader result caching will be visible, and the burden is left to the application developer to avoid depending on any given hardware's behavior. In particular, the behavior of such caching would not take into account any UAV accesses that take place; the hash key for shader result caching is simply the inputs for a given shader invocation independent of what may be read from UAVs during the shader invocation (which may not occur at all if there is a cache hit).

    There is no guarantee that UAV accesses issued from within or across shader stages executing within a given Draw*(), or issued from the Compute Shader within Dispatch*(), finish in the order issued. All UAV accesses are finished at the end of the Draw*()/Dispatch*() though.

    The Compute Shader has its own separate set of 64 slots where only UAVs may be bound, independent of the set of RTV+UAV bindpoints for the graphics stages.

    In D3D11.0, the number of UAVs was limited to 8 at the Compute Shader and 8 combined RTV+UAV at the Pixel Shader. There have since been requests to increase this limit. In addition, there have been requests to have some sort of logging ability available to all shader stages, at least for debugging purposes. Being able to access UAVs from every graphics Shader Stage permits this.

    Dynamic indexing of UAV registers (i.e. dynamically indexing # in u#) is not permitted.

    Shader Instructions (defined elsewhere) which are accessing UAVs simply take a u# as a parameter, much like instructions that are sampling from textures take a t# as a parameter.

    5.3.9.1 Creating the Underlying Resource for a UAV

    The D3D11 Resource types that can have a UAV on them are Texture1D{Array}, Texture2D{Array}, Texture3D and Buffer. When the Resource is created at the API/DDI, the bind flag D3D11_{DDI_}BIND_UNORDERED_ACCESS must be specified in order for subsequent creation of UAVs on the resource to be valid.

    The D3D11_BIND_UNORDERED_ACCESS flag may be combined with any of the following bind flags:

    The D3D11_BIND_UNORDERED_ACCESS flag may NOT be combined with any of the following bind flags:

    The constraints combining D3D11_BIND_UNORDERED_ACCESS with other flags on Resource Creation, such as Usage (dynamic, staging etc) are the same as existing constraints present specified for D3D11_BIND_RENDER_TARGET.

    The Sample Count on the resource must be 1, and the Sample Quality must be 0.

    Note in the DDI, the names above become D3D11_DDI_BIND_*.

    5.3.9.2 Creating an Unordered Access View (UAV) at the DDI

    typedef struct D3D11DDIARG_CREATEUNORDEREDACCESSVIEW
    {
        D3D11DDI_HRESOURCE   hDrvResource;
        DXGI_FORMAT          Format;
        D3D11DDIRESOURCE_TYPE ResourceDimension;
    
        union
        {
            D3D11DDIARG_BUFFER_UNORDEREDACCESSVIEW  Buffer;
            D3D11DDIARG_TEX1D_UNORDEREDACCESSVIEW   Tex1D;
            D3D11DDIARG_TEX2D_UNORDEREDACCESSVIEW   Tex2D;
            D3D11DDIARG_TEX3D_UNORDEREDACCESSVIEW   Tex3D;
        };
    } D3D11DDIARG_CREATEUNORDEREDACCESSVIEW;
    

    The Format parameter must be compatible with the format the Resource was created with, and can be any format that supports being bound at the RenderTarget except for SRGB formats. Additional restrictions on the Format for Buffer views are discussed shortly below.

    The D3D11DDIARG_*_UNORDEREDACESSVIEW parameters, describing the view parameters based on resource dimension, are as follows:

    typedef struct D3D11DDIARG_BUFFER_UNORDEREDACCESSVIEW
    {
        UINT     FirstElement;
        UINT     NumElements;
        UINT     Flags; // see D3D11_DDI_BUFFER_UAV_FLAG* below
    } D3D11DDIARG_BUFFER_UNORDEREDACCESSVIEW;
    #define D3D11_DDI_BUFFER_UAV_FLAG_RAW    0x00000001
    #define D3D11_DDI_BUFFER_UAV_FLAG_STRUCTURED 0x00000002
    

    The _RAW_FLAG allows the shader to access the buffer simply as a 1D array of untyped 32-bit data. The Format must be specified as R32_TYPELESS when this flag is used. The underlying Buffer must have been created with D3D11_DDI_MISC_FLAG_ALLOW_RAW_VIEWS (D3D11_MISC_FLAG_ALLOW_RAW_VIEWS at the API).

    The _STRUCTURED flag (mutually exclusive to _RAW) requires that the Buffer was created as a Structured Buffer. The Format for a structured buffer must be specified as DXGI_FMT_UNKNOWN. The type information for the structured buffer will be inherited from the buffer resource.

    The absence of _RAW and _STRUCTURED flags means the Buffer View is Typed, so the Format of the view can be specified as freely as any with other UAV dimension (1D, 2D, 3D).

    When a UAV or SRV is Raw, the FirstElement parameter (defining the start of the view) must result in a 128bit aligned offset, otherwise the creation of the View will fail. Knowing the base address of a view is conveniently aligned enables various optimizations/assumptions in hardware given accesses from a shader that are offsets from the base of the view (where the offsets are often literals in the shader).

    typedef struct D3D11DDIARG_TEX1D_UNORDEREDACCESSVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice;
        UINT     ArraySize;
    } D3D11DDIARG_TEX1D_UNORDEREDACCESSVIEW;
    
    typedef struct D3D11DDIARG_TEX2D_UNORDEREDACCESSVIEW
    {
        UINT     MipSlice;
        UINT     FirstArraySlice;
        UINT     ArraySize;
    } D3D11DDIARG_TEX2D_UNORDEREDACCESSVIEW;
    
    typedef struct D3D11DDIARG_TEX3D_UNORDEREDACCESSVIEW
    {
        UINT     MipSlice;
        UINT     FirstW;
        UINT     WSize;
    } D3D11DDIARG_TEX3D_UNORDEREDACCESSVIEW;
    

    5.3.9.3 Binding an Unordered Access View at the DDI

    The D3D11 OMSetRenderTargets API/DDI accepts both RenderTargetViews, DepthStencilView, and UnorderedAccessViews at the same time. This affects the Graphics side of the pipeline, not the Compute side. Here is the DDI:

    typedef VOID ( APIENTRY* PFND3D11DDI_SETRENDERTARGETS )(
        D3D10DDI_HDEVICE, // device handle
        CONST D3D11DDI_HRENDERTARGETVIEW*, // array of RenderTargetViews,
        UINT, // index of first RTV to set
        UINT, // number of RTVs being set (all others unbound)
        D3D10DDI_HDEPTHSTENCILVIEW, // DepthStencilView
        CONST D3D11DDI_HUNORDEREDACCESSVIEW*, // array of UnorderedAccessViews,
        UINT*, // Array of Append buffer offsets (relevant only for
               // UAVs which have the Append flag (otherwise ignored).
               // -1 means keep current offset.  Any other value sets
               // the hidden counter for that Appendable UAV.
        UINT, // index of first start of UAVs to set
        UINT, // number of UAVs being set (all others unbound)
        UINT, // the first UAV in the set of updated UAVs (including NULL bindings)
        UINT // the number of UAVs in the set of updated UAVs (including NULL bindings)
     )
    

    There is a separate CSSetUnorderedAccessViews API/DDI that accepts UnorderedAccessViews to be bound for the Compute side of the device. It is similar to the above, except doesn’t include RenderTargets.

    The last two parameters, UAVRangeStart and UAVRangeSize exist at the DDI level and not at the OMSetRenderTargets API level. The Direct3D 11 runtime tracks the set of bound UAVs which have changed (which may be different from the set of bound UAVs overall) whereby the driver may use this information for optimization purposes.

    5.3.9.4 Hazard Tracking

    UAVs have the same precedence in Hazard Tracking as RTVs and SO Targets:

    If a subresource is ever bound as an output (RTV/UAV/SO Target), subsequently unbound, and then bound as a shader input, a ReadAfterWriteHazard DDI is called. Drivers can use this as a hint as to when a rendering flush may be required. There are additional situations where Read After Write hazards are reported given the two pipelines – Graphics and Compute, in particular resources moving from output binding on one side to input binding on the other side, as well Compute outputs moving to Compute input. Note UAVs are considered as "output", since if an application only needs to read a resource, it should be bound as an input instead.

    5.3.9.5 Limitations on Typed UAVs

    There is a significant and unfortunate limitation in many hardware designs that had to be built into D3D. While Typed UAVs support many formats – essentially any format that can be a RenderTarget - the majority of these formats only support being written as a UAV, but not read at the same time.

    Shader Resource Views are of course always available in any shader stage when only read-only access from arbitrary locations in a Typed resource is needed. Conversely, it is useful that if write-only access to arbitrary locations in a Typed resource is needed, UAVs support that scenario.

    However, simultaneous reading and writing to a UAV within a single Draw* or Dispatch* operation is only supported if the UAV’s Type is R32_UINT/_SINT/_FLOAT. In particular, the ld_uav_typed IL instruction for reading from a typed UAV is limited to R32_UINT/_SINT/_FLOAT formats. E.g. a UAV with a type such as R8G8B8A8_UNORM_SRGB cannot be read from (but it can be written).

    D3D has a partial workaround for this inability to simultaneously read+write from Typed UAVs. The purpose is to make tasks such as editing an image in-place simpler, given the circumstances.

    D3D allows Texture1D/2D/3D resources created with any of the following small set of 32-bit per element formats to have UAVs created from them with R32_UINT/_SINT/_FLOAT as the type:

    Once an R32_* UAV is created, it allows arbitrary reading and writing to the UAV’s memory in-place. The catch is there is no type conversion since the format is R32_*, meaning reads and writes simply move raw data unaltered between a shader and memory. Since the desire of the application is that the memory is really interpreted as some format like DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, the application is responsible for manually performing type conversion in the shader code upon reads and writes to the R32_* UAV.

    The upside is that because the original resource was created with one of the _TYPELESS formats listed above, it allows other views such as Shader Resource Views or Render Target Views to be created using the actual format that the application intended – such as DXGI_FORMAT_R8G8B8A8_UNORM_SRGB. These properly typed views can then benefit from the fixed-function hardware type conversion upon reading and writing to the format during texture filtering on read or blending on writes, even though these were not available to the UAV, where manual type conversion code had to be done in the shader.

    The formats supporting this casting to R32_* are limited those for which the hardware really makes no difference in memory layout versus R32_*, but excluding a few that have complex encoding cost such as DXGI_FORMAT_R11G11B10_FLOAT. If this ability to cast to R32_* UAVs was not included in D3D, applications would have to perform a copy rendering pass to move data from an R32_* resource where the image editing occurred to a separate resource that has the desired type (e.g. R10G10B10A2_UNORM), which is a waste of memory.

    5.3.10 Unordered Count and Append Buffers

    Unordered Append Buffers enable a usage pattern whereby Pixel Shader and Compute Shaders can write structures of data to memory in variable quantity, in an unordered way. Hardware can take advantage of knowing this type of operation is going on, producing optimized performance.

    5.3.10.1 Creating Unordered Count and Append Buffers

    For Structured Buffers that have been created with the Bind flag: D3D11_DDI_BIND_UNORDERED_ACCESS, Unordered Access Views can be created with one of the optional flags D3D11_DDI_BUFFER_UAV_FLAG_COUNTER or D3D11_DDI_BUFFER_UAV_FLAG_APPEND. The latter flag gives up some flexibility for (possibly) performance – described later.

    Creating a Structured Buffer UAV with UAV_FLAG_COUNTER causes the driver to allocate storage for a single hidden 32-bit unsigned integer counter associated with the UAV (as opposed to being associated with the underlying resource), initialized to 0. Multiple UAVs created on the same Buffer with this flag will thus have multiple independent counters.

    Shaders can atomically increment or decrement this count (but not do both in one shader) and use the returned index to indicate which structure index in the UAV to access. If the _COUNTER flag is used, count values (representing struct index) returned to the shader may be saved for use later after the shader has completed, for example for linked lists.

    If the _APPEND flag is used when creating the UAV, a counter is created like with the _COUNTER flag, except the counter values returned to a shader invocation when incrementing or decrementing the count are only valid for the lifetime of the shader invocation. So the shader can use the index during the shader invocation to access the corresponding struct index in the UAV, but the hardware is permitted to reorder the struct layout from the point of view of anything outside the shader invocation, or after the shader invocation is complete. This is for cases where an application is simply generating struct records and it does not care that the order of the records is maintained. However if the application goes out of its way to examine the buffer (such as copying from it or using some other type of View) the hardware will have to pack the records into the range of struct locations corresponding to the number of times shader invocations incremented the counter on a given UAV. Even though the data will appear packed, the structs may be reordered. Some hardware will take advantage of not having to maintain the order to provide better access performance.

    5.3.10.2 Using Unordered Count and Append Buffers

    When Pixel Shaders and Compute Shaders bind UAVs that have _COUNT or _APPEND usage specified, an initial value for the View’s hidden counter must be provided as part of the bind call. Specifying -1 means maintain the current counter value already in the Buffer. Any other value sets the counter value.

    When an Append UAV is bound to the pipeline, the instructions that can access it are restricted to the following:

    imm_atomic_alloc(22.17.17) store_structured(22.4.13) imm_atomic_consume(22.17.18) ld_structured(22.4.12)

    For an Append UAV, the HLSL compiler can use imm_atomic_alloc to obtain an "address" and then use a sequence of store_* commands to write out data a unique location in the unordered output to the UAV.

    Conversely, the HLSL compiler can use imm_atomic_consume to obtain an "address" that already has data and then use a sequence of ld_* commands to read back data from a unique location in the UAV.

    For Append UAVs, the count values returned by imm_atomic_alloc and imm_atomic_consume are hidden from the shader by the HLSL compiler, which exposes simply the ability to Append() structs or Consume() structs (not both in the same shader).

    For Count UAVs, where the returned count value may be stored, any instructions capable of accessing Structured Buffers are permitted from the shader, in addition to all of the instructions listed above. Unlike Append UAVs, the HLSL compiler exposes the count values returned by imm_atomic_alloc and imm_atomic_consume for access in the shader – allowing the value to be saved.

    The counter behind imm_atomic_alloc and imm_atomic_consume has no overflow or underflow clamping, and there is no feedback given to the shader as to whether overflow/underflow happened (wrapping of the counter). The only thing the counter really accomplishes is a way of generating unique addresses that is conveniently bundled with the UAV.

    It is invalid for a single shader, or multiple shaders in flight on a GPU, to have the presence of both imm_atomic_alloc and imm_atomic_consume instructions operating on the same UAV. For a single shader, compilation fails if these operations (however they appear in HLSL) are mixed. The GPU must guarantee that Shader invocations from separate Draw*/Dispatch operations do not run out of sequence when there is a possibility that an alloc/consume hazard could exist.

    The counter associated with a Count/Append UAV is somewhat like the counters that are associated with Stream Output buffers (note a Buffer cannot be both a Stream Output and Count/Append Buffer), although those counters have slightly different semantics. There is an API/DDI CopyStructureCount which allows the hidden count in a Count/Append UAV to be copied to another Buffer. This can serve as the vertex count parameter to Draw*InstancedIndirect, allowing data that has been written to an Append Buffer to be recirculated back into the GPU without CPU knowledge of the exact quantity involved.

    When Append/Count UAVs are bound to the pipeline the application can specify what the initial counter value should be, or choose to maintain the existing count value.

    For an Append UAV, since the storage is unordered, when binding the UAV to the pipeline as a UAV or any other tpe of view (e.g. SRV), the contents of any struct entries in the UAV beyond the count value become undefined, and any contents within the count value are maintained, but may be reordered. It is fine for multiple different types of UAVs to overlap, but the application has to beware of the effect that the unordered nature of Append UAVs may have (when bound/used) on other overlapping views of the same memory. It is safest for an application not to mix usage of overlapping UAVs with expectations of data order being maintained in between.

    Count UAVs do not create any such ordering issues, since by definition applications are allowed to save count values as references to specific locations in the UAV.

    For some implementations, Append UAVs will behave identically to Count UAVs (e.g. no reordering). Still, if the application does not care about the ordering of records being maintained in the UAV, it does not hurt (and can only help on some implementations) to make use of the constrained Append semantics for generating and subsequently consuming unordered collections of items.

    5.3.11 Video Views

    As of the D3D11.1 API/DDI, Video Resources can have SRV/RTV/UAVs created so that D3D shaders can process them. The way the underlying Video Resource shows up in D3D as an ID3D11Resource* is described in separate D3D11 Video specs. This section covers how given an ID3D11Resource* to a Video Resource, SRV/RTV/UAVs can be created in D3D.

    These Video Resources will be either Texture2D or Texture2DArray, so the ViewDimension in the VIEW_DESC structure must match. Additionally, the format of the underlying Video Resource restricts the formats that the View can use.

    The following table describes all the combinations of Video Resource and View(s) that can be made from them. Note that multiple views of different parts of the same surface can be created, and depending on the format they may have different sizes from each other. A few video formats do not support D3D SRV/UAV/RTVs at all: DXGI_FORMAT_420_OPAQUE, _AI44, _IA44, _P8 and _A8P8. Further details on all the video formats is provided in the D3D11 Video DDI spec.

    Runtime read+write conflict prevention logic (which stops a resource from being bound as an SRV and RTV/UAV at the same time) treats Views of different parts of the same Video surface as conflicting for simplicity. It doesn’t seem interesting to allow the case of reading from luma while simultaneously rendering to chroma in the same surface, for example, even though it may be possible in hardware.

    Video Resource
    Format
    (DXGI_FORMAT_*)
    Valid View Format
    (DXGI_FORMAT_*)
    Meaning Mapping to
    View Channel
    View Types
    Supported
    AYUV
    (This is the most
    common YUV
    4:4:4 format)
    R8G8B8A8_{UNORM|UINT},
    or for UAVs, an
    additional choice: R32_UINT
    Straightforward mapping of the entire
    surface in one view.

    Using R32_UINT for UAVs allows both
    read and write (as opposed
    to just write for the other format)
    V->R8,
    U->G8,
    Y->B8,
    A->A8
    SRV,
    RTV,
    UAV
    YUY2
    (This is the most
    common YUV
    4:2:2 format)
    R8G8B8A8_{UNORM|UINT},
    or for UAVs, an
    additional choice: R32_UINT
    Straightforward mapping of the entire
    surface in one view.

    Using R32_UINT for UAVs allows both read
    and write (as opposed to just write for the
    other format)
    Y0->R8,
    U0->G8,
    Y1->B8,
    V0->A8
    SRV,
    UAV
    R8G8_B8G8_UNORM In this case the width of the view will
    appear to be twice the R8G8B8A8 view would
    be, with hardware reconstruction of RGBA done
    automatically on read (and before filtering).
    This has been in D3D hardware for a long time
    (legacy) though it likely is not interesting any more.
    Y0->R8,
    U0->G8[0],
    Y1->B8,
    V0->G8[1]
    SRV
    NV12
    (This is the most
    common YUV
    4:2:0 format)
    R8_{UNORM|UINT} Luminance Data View Y->R8 SRV,
    RTV,
    UAV
    R8G8_{UNORM|UINT} Chrominance Data View
    (width and height are each 1/2
    of luminance view)
    U->R8,
    V->G8
    SRV,
    RTV,
    UAV
    NV11
    (This is the most
    common YUV
    4:1:1 format)
    R8_{UNORM|UINT} Luminance Data View Y->R8 SRV,
    RTV,
    UAV
    R8G8_{UNORM|UINT} Chrominance Data View
    (width and height are each 1/4
    of luminance view)
    U->R8,
    V->G8
    SRV,
    RTV,
    UAV
    P016
    (This is a 16 bit per
    channel planar
    4:2:0 format)
    R16_{UNORM|UINT} Luminance Data View Y->R16 SRV,
    RTV,
    UAV
    R16G16_{UNORM|UINT},
    or for UAVs, an
    additional choice: R32_UINT
    Chrominance Data View
    (width and height are each 1/2
    of luminance view)

    Using R32_UINT for UAVs allows both read and
    write (as opposed to just write for the other format)
    U->R16,
    V->G16
    SRV,
    RTV,
    UAV
    P010
    (This is a 10 bit per
    channel planar
    4:2:0 format)
    R16_{UNORM|UINT} Luminance Data View

    D3D does not enforce or care whether or not the
    lowest 6 bits are 0 (given this is a 10 bit format
    using 16 bits) – application shader code would have
    to enforce this manually if desired. From the D3D
    point of view, this is format is no different than P016.
    Y->R16 SRV,
    RTV,
    UAV
    R16G16_{UNORM|UINT,
    or for UAVs, an
    additional choice: R32_UINT
    Chrominance Data View
    (width and height are each 1/2 of luminance view)

    Using R32_UINT for UAVs allows both read and write
    (as opposed to just write for the other format)

    Same comment as above about this 10 bit format using
    16 bits.
    U->R16,
    V->G16
    SRV,
    RTV,
    UAV
    Y216
    (This is a 16 bit per
    channel packed
    4:2:2 format)
    R16G16B16A16_{UNORM|UINT} Straightforward mapping of the entire surface
    in one view.
    Y0->R16,
    U->G16,
    Y1->B16,
    V->A16
    SRV,
    UAV
    Y210
    (This is a 10 bit per
    channel packed
    4:2:2 format)
    R16G16B16A16_{UNORM|UINT} Straightforward mapping of the entire surface
    in one view.

    D3D does not enforce or care whether or not the
    lowest 6 bits are 0 (given this is a 10 bit format
    using 16 bits) – application shader code would have
    to enforce this manually if desired. From the D3D
    point of view, this is format is no different than Y216.
    Y0->R16,
    U->G16,
    Y1->B16,
    V->A16
    SRV,
    UAV
    Y416
    (This is a 16 bit per
    channel packed
    4:4:4 format)
    R16G16B16A16_{UNORM|UINT} Straightforward mapping of the entire surface
    in one view.
    U->R16,
    Y->G16,
    V->B16,
    A->A16
    SRV,
    UAV
    Y410
    (This is a 10 bit per
    channel packed
    4:4:4 format)
    R10G10B10A2_{UNORM|UINT},
    or for UAVs, an
    additional choice: R32_UINT
    Straightforward mapping of the entire surface
    in one view. Using R32_UINT for UAVs allows both
    read and write (as opposed to just write for the
    other format).
    U->R10,
    Y->G10,
    V->B10,
    A->A2
    SRV,
    UAV


    5.4 Resource Creation


    5.4.1 Overview

    Resources have the following properties in common, specified at Resource creation:

    Resources are made up of one of more Subresources. These Subresources share a common lifespan with each other and the Resource. In other words, the Resource and Subresources are atomically allocated and destroyed. However, some operations occur at the Subresource level, versus the Resource level. Subresources are three dimensional entities (with height, width, depth, pitch, and slice pitch), but degenerate into two and one dimensional entities for a certain Resource. For ex. a fully mipped Texture2D Resource creation with a width of two, a height of two, and an array size of two will have four Subresources that can be individually referenced for certain operations. Two Subresources have a width of two, height of two, and depth of one. These two Subresources are the most detailed mip level. The additional two Subresources have a width of one, height of one, and depth of one. Each Subresource is allowed to have it's own address, so the Resource may have somewhere between one and four disjoint allocations to satisfy the previous example. Each Subresource inherits the properties of the Resource, and Subresources may not be part of multiple Resources.

    typedef enum D3D10DDIRESOURCE_TYPE
    {
        D3D10DDIRESOURCE_BUFFER      = 1,
        D3D10DDIRESOURCE_TEXTURE1D   = 2,
        D3D10DDIRESOURCE_TEXTURE2D   = 3,
        D3D10DDIRESOURCE_TEXTURE3D   = 4,
        D3D10DDIRESOURCE_TEXTURECUBE = 5,
    #if D3D11DDI_MINOR_HEADER_VERSION >= 1
        D3D11DDIRESOURCE_BUFFEREX    = 6,
    #endif
    } D3D10DDIRESOURCE_TYPE;
    
    typedef struct D3D10DDI_MIPINFO
    {
        UINT TexelWidth;
        UINT TexelHeight;
        UINT TexelDepth;
        UINT PhysicalWidth;
        UINT PhysicalHeight;
        UINT PhysicalDepth;
    } D3D10DDI_MIPINFO;
    
    typedef struct D3D10_DDIARG_SUBRESOURCE_UP
    {
        VOID*   pSysMem;
        UINT  SysMemPitch;
        UINT  SysMemSlicePitch;
    } D3D10_DDIARG_SUBRESOURCE_UP;
    
    typedef struct D3D11DDI_HRESOURCE
    {
        void* m_pDrvPrivate;
    } D3D11DDI_HRESOURCE;
    
    // Bits for D3D11DDI_CREATERESOURCE::BindFlags
    
    typedef enum D3D10_DDI_RESOURCE_BIND_FLAG
    {
        D3D10_DDI_BIND_VERTEX_BUFFER     = 0x00000001L,
        D3D10_DDI_BIND_INDEX_BUFFER      = 0x00000002L,
        D3D10_DDI_BIND_CONSTANT_BUFFER   = 0x00000004L,
        D3D10_DDI_BIND_SHADER_RESOURCE   = 0x00000008L,
        D3D10_DDI_BIND_STREAM_OUTPUT     = 0x00000010L,
        D3D10_DDI_BIND_RENDER_TARGET     = 0x00000020L,
        D3D10_DDI_BIND_DEPTH_STENCIL     = 0x00000040L,
        D3D10_DDI_BIND_PIPELINE_MASK     = 0x0000007FL,
    
        D3D10_DDI_BIND_PRESENT           = 0x00000080L,
        D3D10_DDI_BIND_MASK              = 0x000000FFL,
    
    #if D3D11DDI_MINOR_HEADER_VERSION >= 1
        D3D11_DDI_BIND_UNORDERED_ACCESS  = 0x00000100L,
    
        D3D11_DDI_BIND_PIPELINE_MASK     = 0x0000017FL,
        D3D11_DDI_BIND_MASK              = 0x000001FFL,
    #endif
    } D3D10_DDI_RESOURCE_BIND_FLAG;
    
    // Bits for D3D11DDI_CREATERESOURCE::MapFlags
    typedef enum D3D10_DDI_CPU_ACCESS
    {
        D3D10_DDI_CPU_ACCESS_WRITE          = 0x00000001L,
        D3D10_DDI_CPU_ACCESS_READ           = 0x00000002L,
        D3D10_DDI_CPU_ACCESS_MASK          = 0x00000003L,
    } D3D10_DDI_CPU_ACCESS;
    
    // Bits for D3D11DDI_CREATERESOURCE::Usage
    typedef enum D3D10_DDI_RESOURCE_USAGE
    {
        D3D10_DDI_USAGE_DEFAULT    = 0,
        D3D10_DDI_USAGE_IMMUTABLE  = 1,
        D3D10_DDI_USAGE_DYNAMIC    = 2,
        D3D10_DDI_USAGE_STAGING    = 3,
    } D3D10_DDI_RESOURCE_USAGE;
    
    // Bits for D3D11DDI_CREATERESOURCE::MiscFlags
    typedef enum D3D10_DDI_RESOURCE_MISC_FLAG
    {
        D3D10_DDI_RESOURCE_AUTO_GEN_MIP_MAP             = 0x00000001L,
        D3D10_DDI_RESOURCE_MISC_SHARED                  = 0x00000002L,
        // Reserved for D3D11_RESOURCE_MISC_TEXTURECUBE   0x00000004L,
        D3D10_DDI_RESOURCE_MISC_DISCARD_ON_PRESENT      = 0x00000008L,
    #if D3D11DDI_MINOR_HEADER_VERSION >= 1
        D3D11_DDI_RESOURCE_MISC_DRAWINDIRECT_ARGS       = 0x00000010L,
        D3D11_DDI_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS  = 0x00000020L,
        D3D11_DDI_RESOURCE_MISC_BUFFER_STRUCTURED       = 0x00000040L,
        D3D11_DDI_RESOURCE_MISC_RESOURCE_CLAMP          = 0x00000080L,
    #endif
        // Reserved for D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX 0x00000100L,
        // Reserved for D3D11_RESOURCE_MISC_GDI_COMPATIBLE 0x00000200L,
        D3D10_DDI_RESOURCE_MISC_REMOTE                  = 0x00000400L,
    } D3D10_DDI_RESOURCE_MISC_FLAG;
    
    typedef struct D3D11DDIARG_CREATERESOURCE
    {
        CONST D3D10DDI_MIPINFO*              pMipInfoList;
        CONST D3D10_DDIARG_SUBRESOURCE_UP*   pInitialDataUP; // non-NULL if Usage has invariant
        D3D10DDIRESOURCE_TYPE                ResourceDimension; // Part of old Caps1
    
        UINT                                 Usage; // Part of old Caps1
        UINT                                 BindFlags; // Part of old Caps1
        UINT                                 MapFlags;
        UINT                                 MiscFlags;
    
        DXGI_FORMAT                          Format; // Totally different than D3DDDIFORMAT
        DXGI_SAMPLE_DESC                     SampleDesc;
        UINT                                 MipLevels;
        UINT                                 ArraySize;
    
        // Can only be non-NULL, if BindFlags has D3D10_DDI_BIND_PRESENT bit set; but not always.
        // Presence of structure is an indication that Resource could be used as a primary (ie. scanned-out),
        // and naturally used with Present (flip style). (UMD can prevent this- see dxgiddi.h)
        // If pPrimaryDesc absent, blt/ copy style is implied when used with Present.
        DXGI_DDI_PRIMARY_DESC*               pPrimaryDesc;
    
        UINT                                 ByteStride; // 'StructureByteStride' at API
    } D3D11DDIARG_CREATERESOURCE;
    
        // part of user mode Device interface:
        STDMETHOD_( SIZE_T, CalcPrivateResourceSize )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATERESOURCEIN* pCreateResourceIn );
        STDMETHOD( CreateResource )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_CREATERESOURCEIN* pCreateResourceIn,
            D3D11DDI_HRESOURCE hDrvResource );
        STDMETHOD_( void, DestroyResource )( D3D10DDI_HDEVICE hDrvDevice,
            D3D11DDI_HRESOURCE hDrvResource );
    

    5.4.2 Creating a Structured Buffer

    A structured buffer(5.1.3) is created by specifying both a new misc flag and the stride of the structure.

    The only D3D11 Resource type that can have a structure defined is the Buffer type. When the Resource is created at the API, the misc flag D3D11_RESOURCE_MISC_STRUCTURED_BUFFER and a structure stride in bytes must be specified.

    The StructureByteStride can be at most 2048 bytes.

    The D3D11_RESOURCE_MISC_STRUCTURED_BUFFER flag cannot be combined with D3D11_RESOURCE_MISC_ALLOW_RAW_VIEWS (described elsewhere).

    The D3D11_RESOURCE_MISC_STRUCTURED_BUFFER flag may be combined with any of the following bind flags:

    The D3D11_RESOURCE_MISC_STRUCTURED_BUFFER flag may NOT be combined with any of the following bind flags:

    Buffers that define a structure cannot be used with the InputAssembler, either for vertex or index data. Structured buffers also cannot be bound as a stream output target or render target.

    If the D3D11_RESOURCE_MISC_STRUCTURED_BUFFER is not set, then StructureByteStride parameter to the Buffer creation must be 0. If not, the runtime will fail the creation call.

    If the D3D11_RESOURCE_MISC_STRUCTURED_BUFFER is set, then StrideInBytes must be non-zero and ByteWidth must be evenly divisible by StructureByteStride . If either condition is not true when creating a structured buffer, the create call will be failed by the runtime.

    5.5 Resource Dimensions

    Resource size dimensions (Width, Height, Depth) are always specified in pixel units. Size dimensions are restricted only for subsampled and block compressed formats (see Formats(19.1) section), and are otherwise restricted only to positive integers. Furthermore, the size dimensions of a Resource have no bearing on what functionality is available for the resource (such as filtering support).

    Resource pitches are always expressed in bytes, and indicate the memory delta between the start of pixel rows or array slices, with the only exception being block compressed formats, where the pitch is defined as between between 'block' rows instead of pixel rows. Pitch values are restricted only to non-negative integers, intentionally including zero for which the first row will be replicated to all rows.

    Size dimensions for lower level mipmapped resources are computed by the Direct3D runtime based on the size of the level zero map. These computed dimensions are adjusted upward as necessary to adhere to physical size dimension restrictions for subsampled and block compressed formats - refer to the discusson of physical and virtual dimensions in Block Compressed Formats(19.5) and Sub-Sampled Formats(19.4).


    5.6 Resource Manipulation


    Section Contents

    (back to chapter)

    5.6.1 Mapping

    5.6.1.1 Map Flags
    5.6.1.2 Map() NO_OVERWRITE on Dynamic Buffers used as Shader Resource Views
    5.6.1.3 Map() on DEFAULT Buffers used as SRVs or UAVs
    5.6.2 CopySubresourceRegion
    5.6.2.1 CopySubresourceRegion with Same Source and Dest
    5.6.2.2 CopySubresourceRegion Tileable Copy Flag
    5.6.3 CopyResource
    5.6.4 Staging Surface CPU Read Performance (primarily for ARM CPUs)
    5.6.5 Structured Buffer: CopyResource, CopySubresourceRegion
    5.6.6 Multisample Resolve
    5.6.7 FlushResource
    5.6.8 UpdateSubresourceUP
    5.6.9 UpdateSubresource and CopySubresourceRegion with NO_OVERWRITE or DISCARD


    5.6.1 Mapping

    Mapping/ locking is done at the Subresource level, instead of the Resource level. Mapping means granting CPU access to the Subresource's storage or contents. Typically, the user mode driver must invoke the Lock callback to achieve this operation. The application subsequently relinquishes direct access to mapped Subresources by unmapping them. Only one Map for a given Subresource is allowed (even for non-overlapping regions) and no accelerator operations on a Subresource may be ongoing while a Map is outstanding on that Subresource. However, multiple Subresources of the same Resource may be Mapped at the same time. Each Map method returns a structure that contains a pointer to the storage backing the Resource, and pitch values representing the distances between rows or planes of data, depending on the Subresource dimensionality. The returned pointer always points to the top-left byte (U = 0, V = 0, W = 0) to the mapped Subresource. The layout is similar to that of a multidimensional 'C' array, where the Subresource can be considered to be the following 'C' declaration:

    Pixel_Type Subresource [ W ][ V ][ U ];
    

    with the additional characteristic that the driver is allowed to specify the byte pitch between each row (or block-row for BC formats) and each depth slice.

    When returning a pointer to the mapped resource, the pointer must be 16-byte aligned. This restriction allows applications to perform SSE-optimized operations on the data natively, without realignment or copy (example usages include CPU geometry and texture processing).

    // D3D11.3 Mapping/ Locking:
    // One, more, or none: CPUREAD, CPUWRITE
    // Exclusively one or none: RANGEVALID, AREAVALID, BOXVALID
    // Exclusively one or none: DISCARDRESOURCE
    
    // Bits for D3D11DDIARG_MAPIN::Flags
    #define D3D11DDILOCK_CPUREAD
    #define D3D11DDILOCK_CPUWRITE
    #define D3D11DDILOCK_RANGEVALID
    #define D3D11DDILOCK_AREAVALID
    #define D3D11DDILOCK_BOXVALID
    #define D3D11DDILOCK_DISCARDRESOURCE
    #define D3D11DDILOCK_NOOVERWRITE
    
    typedef struct D3D11DDIARG_MAPIN
    {
        D3D11DDI_HRESOURCE hResource;   // in: resource identifier
        UINT32            Subresource; // in: zero based subresource index
        UINT32            Flags;       // in: flags
    } D3D11DDIARG_LOCKIN;
    
    typedef struct D3D11DDIARG_MAPOUT
    {
        void*  pSurfData;  // out: pointer to memory
        SIZE_T Pitch;      // out: pitch of memory
        SIZE_T SlicePitch; // out: slice pitch of memory
    } D3D11DDIARG_MAPOUT;
    
    typedef struct D3D11DDIARG_UNMAPIN
    {
        D3D11DDI_HRESOURCE hResource;   // in: resource identifier
        UINT32            Subresource; // in: zero based subresource index
    } D3D11DDIARG_UNMAPIN;
    
        // part of user mode Device interface:
        STDMETHOD( Map )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_MAPIN* pMapIn, D3D11DDIARG_MAPOUT* pMapOut ) = 0;
        STDMETHOD( Unmap )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_UNMAPIN* pUnmapIn ) = 0;
    

    5.6.1.1 Map Flags

    5.6.1.2 Map() NO_OVERWRITE on Dynamic Buffers used as Shader Resource Views

    Map() allows NO_OVERWRITE for Buffers with DYNAMIC usage and the SHADER_RESOURCE (shader input) bind flag. Before D3D11.1 this was disallowed (though DISCARD was allowed).

    Before the first call with NO_OVERWRITE on a deferred context, a DISCARD must be done on the same context (via Copy*()/Update*()/Map() API flag or Discard*() API). This is not required on immediate contexts if the application knows the GPU is finished with the resource (though discard can be used if not).

    This feature is required to be supported for all D3D10+ hardware with D3D11.1 drivers.

    The background here is that Map() NO_OVERWRITE used to be allowed on Dynamic Index Buffers or Vertex Buffers. Game developers would use this to perform a sliding window of successive buffer updates while rendering follows along. The driver would not have to rename the surface and the GPU did not have to flush rendering while it referenced the Buffer even as the application updated other parts of it.

    Increasingly developers have found reasons to pass the same sort of data into shaders directly (via Shader Resource View) to take advantage of the extra flexibility versus the fixed function semantics of Vertex and Index Buffers at the Input Assembler. As of D3D10, Map() NO_OVERWRITE was not allowed on DYNAMIC Buffers with the Shader Resource bind flag, however. This was simply an oversight, hindering the ability to efficiently feed vertex/index style data directly to shaders.

    5.6.1.3 Map() on DEFAULT Buffers used as SRVs or UAVs

    Map() can be called on Buffers with DEFAULT usage and SHADER_RESOURCE and/or UNORDERED_ACCESS bind flags.

    The Buffer can have MiscFlags BUFFER_ALLOW_RAW_VIEWS, BUFFER_STRUCTURED or nothing.

    Before D3D11.2 this was disallowed. As of D3D11.2, this feature is required to be supported for Feature Level 11.0+ devices with WDDM1.3+ drivers.

    The goal here was to reduce the number of copies required to transfer Buffer data to and from the GPU. Previously, to allow CPU access of the data generated in a DirectCompute computation, an app had to perform an intermediate copy to a STAGING resource. This was due to the fact that only STAGING resources could be directly accessed by the CPU. The need for this copy resulted in a measureable performance hit on bandwidth-intensive DirectCompute scenarios.

    This feature exposed the ability to create Default buffers marked with D3D11_CPU_ACCESS_FLAGs, as long as their creation description matched the specific configuration options described. These restrictions were designed merely to scope down the investigation and development work to fit within budget while enabling the core scenario, not because hardware necessarily has the same degree of constraint.

    5.6.2 CopySubresourceRegion

    This function allows sub-region copying of data from one Subresource to another. No stretch, color key, blend, nor format conversion. However, format types of each Subresource need not be exactly equal to each other, as the Resource may be Prestructured+Typeless Memory(5.1.5), which is also supported. For example, a R32_FLOAT Texture can be copied to an R32_UINT Texture, as both of these formats are in the same R32_TYPELESS group. Conceptually, the interpreted value of texels changes during this type of copy; but the raw value of memory happens to be equal. This function also works when both Subresources are Unstructured Memory(5.1.2) also, except that the regions to copy will be in raw bytes, versus pixel or Element units.

    In addition, the Subresources need not be of equal size; but the source and destination regions must fit entirely within the Subresources. The source and destination Subresources must not be the same Subresources.

    Resources which can be used as Depth/ Stencil cannot partipate in this operation as a destination; but they can as a source. Multisampled Resources cannot partcipate in Copy operations.

    typedef struct D3D11DDIARG_COPYSUBRESOURCEREGIONIN
    {
        D3D11DDI_HRESOURCE hDstResource;   // in: resource identifier
        UINT32             DstSubresource; // in: zero based subresource index
        POINT3D            DstPoints;      // in: Destination Offset
        D3D11DDI_HRESOURCE hSrcResource;   // in: resource identifier
        UINT32             SrcSubresource; // in: zero based subresource index
        CONST D3D11_BOX*   SrcBox;         // in: Source Region
    } D3D11DDIARG_COPYSUBRESOURCEREGIONIN;
    
        // part of user mode Device interface:
        STDMETHOD( CopySubresourceRegion )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_COPYSUBRESOURCEREGIONIN* pCopySubresourceRegionIn ) = 0;
    

    5.6.2.1 CopySubresourceRegion with Same Source and Dest

    CopySubresourceRegion*() allow the source and dest to be the same resource, with D3D11.1 drivers. The driver must handle overlapping copies.

    This feature is required to be supported for all D3D10+ hardware with D3D11.1 runtime+drivers. When the application uses feature level 9.x all drivers support this with the D3D11.1 runtime.

    5.6.2.2 CopySubresourceRegion Tileable Copy Flag

    CopySubresourceRegion*() allows a new TILEABLE flag when the source is a currently bound RenderTarget (flag ignored otherwise). This is intended for tile / deferred rendering GPUs (no impact on the copy for non-tiled rendering GPUs). The flag indicates that if the GPU happens to be processing only given tile of a RenderTarget at a time (where the RenderTarget is the source in the copy), the GPU can break the copy call to occur per-tile along with the surrounding rendering calls batched for the scene, without having to flush the scene for all tiles.

    The application is guaranteeing that future access to the destination of the copy will only be used for 1:1 cycling of that data back into the same pixel location of the affected RenderTarget (which remains bound). Said another way, the application is guaranteeing that when a tiling GPU replays batched rendering commands to produce any given tile, there will be no visible effect (e.g. to commands earlier in the batch) of the copy having already occured for previously processed tiles.

    The source and dest don't have to be the same size resource; this flag is relevant to just the region being copied.

    When the application is finished using the target of the TILEABLE copy for recirculating back to the original surface, DiscardResource() should be called if the contents are no longer needed (but this is not strictly required). For some implementations, knowing the end of life of the data in the scratch surface could allow the entire copy to be optimized away into leaving the data in fast tile memory and never having to write it out to GPU memory.

    If an application violates the 1:1 property when using the TILEABLE flag on CopySubresourceRegion, such as reading into a different pixel, or into a shader stage other than the Pixel Shader in the second pass, the the data being read is undefined (it will have been generated by an unknown rendering pass by the application or uninitilized).

    If the RenderTarget gets unbound, any copies from it that happened with the TILEABLE flag while bound lose the TILEABLE property after the RenderTarget unbinding.

    This feature is available for all D3D9+ hardware with D3D11.1 drivers (D3D9 portion of the DDI for D3D9 hardware and both D3D9 and D3D11.1 portions of the DDI for D3D10+ hardware).

    This feature will be exposed only to customers of Direct3D within the Windows OS, at least initially, given the narrowly focused application.

    An example of a valid scenario (Direct2D will do something similar to this, and likely other Windows components):

    The example does not work if additional copies are inserted from surface to surface (the length of the cycle can't be extended) - doing so just means the TILEABLE flag loses its value and the GPU will likely have to flush the scene. Behavior should be correct here but performance gains may be lost. In general just because the TILEABLE flag is used on a Copy doesn't mean there will not be a mid-scene flush - that could happen for other reasons, typically changing of RenderTargets. The tileable flag just means there is one less trigger for mid-scene flushes.

    5.6.3 CopyResource

    This function allows copying of an entire Resource, assuming the Resources are identical types and dimensions. No stretch, color key, blend, nor format conversion. However, format types of each Subresource need not be exactly equal to each other, as the Resource may be Prestructured+Typeless Memory(5.1.5), which is also supported. For example, a R32_FLOAT Texture can be copied to an R32_UINT Texture, as both of these formats are in the same R32_TYPELESS group. Conceptually, the interpreted value of texels changes during this type of copy; but the raw value of memory happens to be equal. This function also works when both Resources are Unstructured Memory(5.1.2).

    Resources which can be used as Depth/ Stencil cannot partipate in this operation as a destination; but they can as a source. Multisampled Resources cannot partcipate in Copy operations. This operation also impacts heavily on performant readback and upload scenarios.(5.3.2)

    typedef struct D3D11DDIARG_COPYRESOURCEIN
    {
        D3D11DDI_HRESOURCE hDstResource; // in: resource identifier
        D3D11DDI_HRESOURCE hSrcResource; // in: resource identifier
    } D3D11DDIARG_COPYRESOURCEIN;
    
        // part of user mode Device interface:
        STDMETHOD( CopyResource )( D3D10DDI_HDEVICE hDrvDevice,
            CONST D3D11DDIARG_COPYRESOURCEIN* pCopyResourceIn ) = 0;
    

    5.6.4 Staging Surface CPU Read Performance (primarily for ARM CPUs)

    On the ARM CPU, cache coherency isn’t provided when the GPU writes to system memory, so a GPU driver would normally be tempted to put a staging (D3D CPU memory) surface in uncached memory (which is slow for CPU access) to avoid incorrect values being read from the cache. However, the Win8 Video Memory Manager will manually flush the CPU cache on ARM when data has been copied from the GPU to a staging surface – so GPU drivers can safely use cacheable memory for STAGING surfaces (yielding good performance on CPU reads). VidMM will also flush CPU caches for the opposite case as well - before the GPU reads from a STAGING surface.

    At the D3D11.1 DDI, when a STAGING surface is created, the CPU_ACCESS flags (READ and/or WRITE) are mapped directly down through the DDI, so there it is obvious to drivers when the cacheable memory choice should be made (when WRITE is not set). For the D3D9 DDI (which all drivers for all hardware feature levels must implement), the mapping from D3D11's CPU_ACCESS flags to the D3D9 DDI’s is described in the separate API/DDI spec - see PFND3DDDI_CREATERESOURCE - the situation is SYSTEMMEMORY surfaces that don't have the WriteOnly flag set at the D3D9 DDI.

    A note for User Mode drivers: The driver must not cache Map on surfaces that rely on the software enforced coherency described above (i.e. surface is cacheable but mapped into an aperture segment which doesn’t support CacheCoherency). The driver must explicitly call LockCb and UnlockCb at every Map for such surfaces to give an opportunity to VidMm to apply the proper memory barrier. Failing to do so will result in the surface getting corrupted over time.

    5.6.5 Structured Buffer: CopyResource, CopySubresourceRegion

    CopyResource and CopySubresourceRegion allow either or both the source and destination to be structured buffers. It is possible to copy from linear to structured, structured to linear, and structured to structured. If copying between structured buffers, the strides must be the same or the runtime will fail the copy operation. If the region to copy is not specified as complete structures, then the runtime will fail the copy operation.

    When the either the source or destination is linear and the other is structured, it is up to the driver to do rearrange the layout if necessary. If structured buffers are stored linearly, then the copy operation is a straightforward copy. If not stored linearly, then any tiling or other reorganization must occur as part of the copy operation.

    5.6.6 Multisample Resolve

    Only multisample render targets are able to be resolved to a single-sampled resource. Naturally, the source must be a multisampled render target, while the destination must be a single-sampled resource restricted such that it resides in video memory. For example, the destination cannot be a dynamic or system-memory friendly Resource. Thus the destination Resource must be USAGE_DEFAULT. The algorithm to resolve multiple samples to one pixel is implementation dependent. Resolve shares some of the restrictions of Copy, such as both Resources must be the same type (ie. Texture2D), and no strecting. Only a whole Subresource can be resolved, so both Subresources must be the same dimensions. Format conversion is not desired for ResolveSubresource either. However, due to typeless Resources, there is an interesting interaction with either Resource Format. If each Resource is prestructured+typed, then both Resources must have the same Format; and that must match the passed in ResolveFormat (ie. all R32_FLOAT). If one Resource is prestructured+typeless, then the prestructured+typed Resource's format must be compatable with the typeless format; and the ResolveFormat must match the prestructured