Direct3d 11 features

Тесселяция

В D3D11 добавляется 3 дополнительных стадии конвейера визуализации, целью введения которых является эффективная тесселяция поверхностей.

Конвейер D3D11 включает три новых стадии между стадиями вершинного и геометрического шейдера. Две из них являются программируемыми (стадии оболочечного (hull shader) и domain шейдеров) и одна — конфигурируемая (стадия тесселяции).

Представленный конвейер оперирует сетками, заданными поверхностными патчами. Основными примитивами D3D11 являются треугольные и квадратные патчи. Форма каждого патча определяется числом контрольных точек. В вершинном шейдере эти точки трансформируются, скинятся и (или) морфятся последовательно.

Стадия тесселятора представлена фиксированным набором функции (хорошо конфигурируема), которые используют параметр тесселяции для подразбиения патча на несколько треугольников или квадов. Тесселятор не имеет доступа к контрольным точкам — все решения о разбиении принимаются на основе конфигурационных и тесселяционных параметров, передаваемых из оболочечного шейдера. Каждая вершина после стадии тесселяции передаётся в domain шейдер, причём передаются только координаты параметризации (parametrization coordinates).

Domain shader оперирует parametrization coordinates патча для каждой вершины раздельно, хотя имеется возможность получить доступ к трансформированным контрольным точкам для всего патча. Domain шейдер отправляет всю информацию о вершине (позицию, текстурные координаты, и т. п.) в геометрический шейдер (или на стадию клипирования, если геометрический шейдер не задан). По сути дела, он оценивает представление поверхности в каждой точке. На данной стадии может быть применён метод карт смещения (displacement mapping).

Другие решения проблемы с Direct3D

В случае, если после проведенных мер ошибка «Не удалось найти на вашем ПК устройство Direct3D» снова возникает – нужно проверить компьютер на наличие вирусов и других подобных проблем. Для этого лучше всего воспользоваться специальными утилитами. Для простой чистки компьютера от мусора подойдет программа CCleaner. Она чистит не только ненужные файлы и папки, но и файловый реестр от неиспользуемых ключей, которые тоже могут быть причиной различных ошибок в системе.

Запустите глубокое сканирование в вашем установленном антивирусе. После завершения удалите все файлы, которые попали под подозрение. Если это файлы целых приложений, попробуйте удалить их и запустить Dota 2. Отлично проводит сканирование утилита ESET Online Scanner. Для ее работы нужно скачать небольшой пакет (около 7 Мб) и запустить его работу. Подобная утилита 360 Total Security также работает, не конфликтуя с вашим установленным антивирусом.

В установленном антивирусе необходимо найти хранилище вирусов. Здесь содержатся все файлы, которые программа считает вредными и опасными для вашей системы. Вполне возможно, что сюда попали файлы игры и по причине их недоступности ошибка «не найдено устройство Direct3D на компьютере» продолжает появляться при запуске Dota 2. Если такие файлы здесь находятся, их необходимо удалить из хранилища, а игру добавить в доверенные приложения. После того, как вы испробуете все рекомендуемые выше методы, но результатов не будет – остаются только переустановка игры. Если и это не поможет, тогда необходимо переустановить операционную систему.

Summary

Article Name
Не удалось обнаружить устройство Direct3D

Description
Компьютерная онлайн-игра Dota 2 является очень популярной по всему миру. Запуская ее, пользователи иногда сталкиваются с ошибкой «Не удалось обнаружить устройство Direct3D». При закрытии окна закрывается и лаунчер, а при повторном запуске игрок наблюдает ту же картину. Различные манипуляции, в том числе запуск с правами администратора никаких результатов не дают. Что делать в этой ситуации – читайте далее в этой статье.

Author

Publisher Name
Игорь

Publisher Logo

Background

D3D11On12 works systematically. Each D3D11 API call goes through the typical runtime validation and makes its way to the driver. At the driver layer, the special 11on12 driver records state and issues render operations to D3D12 command lists. These command lists are submitted as necessary (for example, a query or resource might require commands to be flushed) or as requested by Flush. Creating a D3D11 object typically results in the corresponding D3D12 object being created. Some fixed function render operations in D3D11 such as or are not supported in D3D12, and so D3D11On12 emulates them using shaders and additional resources.

For interop, it’s important to understand how D3D11On12 interacts with the D3D12 objects that the app has created and provided. In order to ensure that work happens in the correct order, the D3D11 immediate context must be flushed before additional D3D12 work can be submitted to that queue. It’s also important to ensure that the queue given to D3D11On12 must be drainable at all times. That means that any waits on the queue must eventually be satisfied, even if the D3D11 render thread blocks indefinitely. Be wary not to take a dependency on when D3D11On12 inserts flushes or waits, as this may change with future releases. Additionally, D3D11On12 tracks and manipulates resource states on its own. The only way to ensure coherency of state transitions is to make use of the acquire/release APIs to manipulate the state tracking to match the app’s needs.

Create the cube renderer

In this example, we organize the scene renderer class with the following methods:

  • CreateDeviceDependentResources: Called whenever the scene must be initialized or restarted. This method loads your initial vertex data, textures, shaders, and other resources, and constructs the initial constant and vertex buffers. Typically, most of the work here is done with ID3D11Device methods, not ID3D11DeviceContext methods.
  • CreateWindowSizeDependentResources: Called whenever the window state changes, such as when resizing occurs or when orientation changes. This method rebuilds transform matrices, such as those for your camera.
  • Update: Typically called from the part of the program that manages immediate game state; in this example, we just call it from the Main class. Have this method read from any game-state information that affects rendering, such as updates to object position or animation frames, plus any global game data like light levels or changes to game physics. These inputs are used to update the per-frame constant buffers and object data.
  • Render: Typically called from the part of the program that manages the game loop; in this case, it’s called from the Main class. This method constructs the graphics pipeline: it binds shaders, binds buffers and resources to shader stages, and invokes drawing for the current frame.

These methods comprise the body of behaviors for rendering a scene with Direct3D using your assets. If you extend this example with a new rendering class, declare it on the main project class. So this:

becomes this:

Again, note that this example assumes that the methods have the same signatures in your implementation. If the signatures have changed, review the Main loop and make the changes accordingly.

Let’s take a look at scene-rendering methods in more detail.

Memory Management Library

A memory management helper library is available for download that you can integrate into your app to more closely match D3D11 memory management behavior. As a D3D11 style management library, it is most effective with apps that are still using a committed resource style allocation strategy. In particular, the library should be seen as a stepping stone that will get you most of the way back to D3D11 performant memory management when in memory constrained scenarios (for example, low-end memory cards, 4k, ultra settings, and so on). D3D12 APIs do enable techniques that let you get even better memory efficiency over D3D11, though these techniques can be challenging and time consuming to implement.

Note that this library is a work in progress and may change over time. Use the links below to access the library, and samples.

The D3D12 Residency Starter Library

Implement the Update method

The Update method is called once per game loop — in this example, it is called by the main class’s method of the same name. It has a simple purpose: update scene geometry and game state based on the amount of elapsed time (or elapsed time steps) since the previous frame. In this example, we simply rotate the cube once per frame. In a real game scene, this method contains a lot more code for checking game state, updating per-frame (or other dynamic) constant buffers, geometry buffers, and other in-memory assets accordingly. Since communication between the CPU and GPU incurs overhead, make sure you only update buffers that have actually changed since the last frame — your constant buffers can be grouped, or split up, as needed to make this more efficient.

In this case, Rotate updates the constant buffer with a new transformation matrix for the cube. The matrix will be multiplied per-vertex during the vertex shader stage. Since this method is called with every frame, this is a good place to aggregate any methods that update your dynamic constant and vertex buffers, or to perform any other operations that prepare the objects in the scene for transformation by the graphics pipeline.

Dynamic Shader Linking

Rendering systems must deal with significant complexity when they manage shaders, while providing the opportunity to optimize shader code. This becomes an even greater challenge because shaders must support a variety of different materials in a rendered scene across various hardware configurations. To address this challenge, shader developers have often resorted to one of two general approaches. They have either created fully featured large, general-purpose shaders that can be used by a wide variety of scene items, which trade off some performance for flexibility, or created individual shaders for each geometry stream, material type, or light type combination needed.

These large, general-purpose shaders handle this challenge by recompiling the same shader with different preprocessor definitions, and the latter method uses brute-force developer power to achieve the same result. The shader permutation explosion has often been a problem for developers who must now manage thousands of different shader permutations within their game and asset pipeline.

Direct3D 11 and shader model 5 introduce object-oriented language constructs and provide runtime support of shader linking to help developers program shaders.

See Dynamic Linking for additional information.

Limitations

The D3D11On12 layer implements a very large subset of the D3D11 API, but there are some known gaps (in addition to bugs in the implementation that can cause incorrect rendering).

As of Windows 10, version 1809 (10.0; Build 17763), as long as D3D11On12 is running on a driver that supports Shader Model 6.0 or later, then it can run shaders that use interfaces. In earlier versions of Windows, the shader interfaces feature is not implemented in D3D11On12, and attempting to use the feature will cause errors and debug messages.

As of Windows 10, version 1803 (10.0; Build 17134), swap chains are supported on D3D11On12 devices. In earlier versions of Windows, they are not.

D3D11On12 has not been optimized for performance. There will likely be moderate CPU overhead compared to a standard D3D11 driver, minimal GPU overhead, and there is known to be significant memory overhead. Therefore it is not recommended to use D3D11On12 for complicated 3D scenes, and it is instead recommended for simple scenes, or 2D rendering.

Force the sample count to create a rasterizer state

Direct3D 11.1 lets you specify a force sample count when you create a rasterizer state.

This Direct3D 11.1 feature consists of the following API.

ID3D11Device1::CreateRasterizerState1

Note

If you want to render with the sample count forced to 1 or greater, you must follow these guidelines:

  • Don’t bind depth-stencil views.
  • Disable depth testing.
  • Ensure the shader doesn’t output depth.
  • If you have any render-target views bound (D3D11_BIND_RENDER_TARGET) and you forced the sample count to greater than 1, ensure that every render target has only a single sample.
  • Don’t operate the shader at sample frequency. Therefore, ID3D11ShaderReflection::IsSampleFrequencyShader returns FALSE.

Otherwise, rendering behavior is undefined. For info about how to configure depth-stencil, see Configuring Depth-Stencil Functionality.

Уровни функций Direct3D Direct3D feature levels

В Direct3D появился новый механизм определения аппаратной поддержки — уровни функций.Direct3D has a new mechanism for determining hardware support called feature levels. Благодаря уровням функций становится проще узнать о возможностях графического адаптера, поскольку можно запросить четко определенный набор функций GPU.Feature levels simplify the task of figuring out what the graphics adapter can do by allowing you to request a well-defined set of GPU functionality. Например, уровень «9 _ 1» применяет функциональные возможности графических адаптеров Direct3D 9, включая Shader Model 2. x.For example, the 9_1 feature level implements the functionality provided by Direct3D 9 graphics adapters, including shader model 2.x. Поскольку 9 _ 1 является самым низким уровнем функций, можно рассчитывать, что все устройства поддерживают шейдер вершин и шейдер пикселей, которые были теми же этапами, что и программируемая модель шейдера Direct3D 9.Since 9_1 is the lowest feature level, you can expect all devices to support a vertex shader and a pixel shader, which were the same stages supported by the Direct3D 9 programmable shader model.

Ваша игра будет использовать D3D11CreateDevice для создания устройства и контекста устройства Direct3D.Your game will use D3D11CreateDevice to create the Direct3D device and device context. Вызывая эту функцию, вы предоставляете список уровней функций, которые поддерживает ваша игра.When you call this function you provide a list of feature levels that your game can support. На основе этого списка функция вернет самый высокий поддерживаемый уровень функций.It will return the highest supported feature level from that list. Например, если в игре можно использовать текстуры BC4/BC5 (компонент оборудования DirectX 10), в список поддерживаемых функций необходимо включить по меньшей мере 9 _ 1 и 10 _ 0.For example if your game can use BC4/BC5 textures (a feature of DirectX 10 hardware), you would include at least 9_1 and 10_0 in the list of supported feature levels. Если игра выполняется на устройствах с DirectX 9 и BC4/BC5, то D3D11CreateDevice вернет 9 _ 1.If the game is running on DirectX 9 hardware and BC4/BC5 textures can’t be used, then D3D11CreateDevice will return 9_1. Затем ваша игра может переключиться на другой формат текстур (и более мелкие текстуры).Then your game can fall back to a different texture format (and smaller textures).

Если вы решили расширить игру Direct3D 9, добавив поддержку более высоких уровней функций Direct3D, лучше сначала закончить перенос существующего графического кода Direct3D 9.If you decide to extend your Direct3D 9 game to support higher Direct3D feature levels then it’s better to finish porting your existing Direct3D 9 graphics code first. После переноса игры в Direct3D 11 будет проще добавить дополнительные пути отрисовки с более сложной графикой.After you have your game working in Direct3D 11, it’s easier to add additional rendering paths with enhanced graphics.

Подробное объяснение поддержки уровней функций см. в разделе Уровни функций Direct3D.See Direct3D feature levels for a detailed explanation of feature level support. Полный перечень функций Direct3D 11 см. в разделах Функции Direct3D 11 и Функции Direct3D 11.1.See Direct3D 11 Features and Direct3D 11.1 Features for a full list of Direct3D 11 features.

Resource Binding

Views in Direct3D 11 (shader resource views, render target views, and so on), have largely been replaced in Direct3D 12 with the concept of a descriptor. The creation methods still exist in Direct3D 12 (such as CreateShaderResourceView and CreateRenderTargetView), which are called after the descriptor heap has been created, to write the data into the heap. Binding in Direct3D 12 is now handled by descriptor handles described in a root signature, and submitted using the SetGraphicsRootDescriptorTable or SetComputeRootDescriptorTable methods.

Root signatures details mappings between the root signature slot number and descriptor tables, where the descriptor table can contain references to resources available to vertex shaders, pixel shaders, and the other shaders, such as constant buffers, shader resource views and samplers. This flexibility disconnects the HLSL register space from the API binding space in Direct3D 12, unlike Direct3D 11 where there is a one to one mapping between these.

One of the implications of this system is that the app is responsible for renaming descriptor tables, which enables developers to understand the performance cost of changing even a single descriptor per draw call.

A new feature of Direct3D 12 is that an app can control which descriptors are shared between which shader stages. In Direct3D 11 resources such as UAVs are shared between all shader stages. By enabling descriptors to be disabled for certain shader stages, the registers used by descriptors that have been disabled are available to be used by descriptors which are enabled for a particular shader stage.

The following table shows an example root signature.

Root Parameter Slot Descriptor Table Entry
VS Descriptor Range b0-b13
1 VS Descriptor Range t0-t127
2 VS Descriptor Range s0-s16
3 PS Descriptor Range b0-b13
…
14 DS Descriptor Range s0-16
15 Shared Descriptor Range u0-u63

Дополнительные сведения о сопоставленииAdditional mapping info

  • IDirect3DDevice9:: сеткурсорпоситион заменяется на сеткурсорпос.IDirect3DDevice9::SetCursorPosition is replaced by SetCursorPos.
  • IDirect3DDevice9:: сеткурсорпропертиес заменяется на сеткурсор.IDirect3DDevice9::SetCursorProperties is replaced by SetCursor.
  • IDirect3DDevice9:: сетиндицес заменяется ссылку ID3D11DeviceContext:: иасетиндексбуффер.IDirect3DDevice9::SetIndices is replaced by ID3D11DeviceContext::IASetIndexBuffer.
  • IDirect3DDevice9:: сетрендертаржет заменяется ссылку ID3D11DeviceContext:: омсетрендертаржетс.IDirect3DDevice9::SetRenderTarget is replaced by ID3D11DeviceContext::OMSetRenderTargets.
  • IDirect3DDevice9:: сетсЦиссоррект заменяется ссылку ID3D11DeviceContext:: рссетсЦиссорректс.IDirect3DDevice9::SetScissorRect is replaced by ID3D11DeviceContext::RSSetScissorRects.
  • IDirect3DDevice9:: сетстреамсаурце заменяется ссылку ID3D11DeviceContext:: иасетвертексбуфферс.IDirect3DDevice9::SetStreamSource is replaced by ID3D11DeviceContext::IASetVertexBuffers.
  • IDirect3DDevice9:: сетвертексдекларатион заменяется ссылку ID3D11DeviceContext:: иасетинпутлайаут.IDirect3DDevice9::SetVertexDeclaration is replaced by ID3D11DeviceContext::IASetInputLayout.
  • IDirect3DDevice9:: сетвиевпорт заменяется ссылку ID3D11DeviceContext:: рссетвиевпортс.IDirect3DDevice9::SetViewport is replaced by ID3D11DeviceContext::RSSetViewports.
  • IDirect3DDevice9:: шовкурсор заменяется на шовкурсор.IDirect3DDevice9::ShowCursor is replaced by ShowCursor.

Управление аппаратным пандусом видеоадаптера с помощью IDirect3DDevice9:: сетгаммарамп заменяется Идксгиаутпут:: сетгаммаконтрол.Control of the video card’s hardware gamma ramp through IDirect3DDevice9::SetGammaRamp is replaced by IDXGIOutput::SetGammaControl. См. раздел Использование гамма-коррекции.See Using gamma correction.

IDirect3DDevice9::P роцессвертицес заменяется функцией потокового вывода для шейдеров Geometry.IDirect3DDevice9::ProcessVertices is replaced by the Stream-Output functionality of Geometry Shaders. См. раздел Начало работы с стадией потокового вывода.See Getting started with the Stream-Output Stage.

Метод IDirect3DDevice9:: сетклипплане для задания пользовательских клипов-плоскостей был заменен на семантику выходных данных шейдера HLSL SV_ClipDistance (см. семантику), доступна в VS_4_0 и выше или в новом атрибуте функции HLSL клиппланес (см. раздел Пользовательские ролики в оборудовании на уровне компонентов 9).The method IDirect3DDevice9::SetClipPlane to set user clip-planes was replaced by either the HLSL SV_ClipDistance vertex shader output semantic (see Semantics), available in VS_4_0 and up, or the new HLSL clipplanes function attribute (see User clip planes on feature level 9 hardware).

IDirect3DDevice9:: сетпалеттинтриес и IDirect3DDevice9:: сеткурренттекстурепалетте являются устаревшими.IDirect3DDevice9::SetPaletteEntries and IDirect3DDevice9::SetCurrentTexturePalette are deprecated. Замените их на шейдер пикселей, который ищет цвета в текстуре R8G8B8A8 256×1.Replace these with a pixel shader that looks up colors in a 256×1 R8G8B8A8 texture instead.

Не рекомендуется использовать функции тесселяции с фиксированными функциями, такие как дравректпатч, дравтрипатч, сетнпатчмодеи делетепатч .Fixed-function tessellation functions like DrawRectPatch, DrawTriPatch, SetNPatchMode, and DeletePatch are deprecated. Замените их программируемыми шейдерами тесселяции конвейера SM 5.0 (если оборудование поддерживает шейдеры тесселяции).Replace these with programmable-pipeline SM5.0 Tessellation shaders (if hardware supports tessellation shaders).

IDirect3DDevice9:: сетфвфи коды фвф больше не поддерживаются.IDirect3DDevice9::SetFVF, and FVF codes, are no longer supported. Перед переносом в макеты D3D11 необходимо перенести из D3D8/D3D9 ФВФ в D3D9 объявления вершин.You should port from D3D8/D3D9 FVF codes to D3D9 Vertex Declarations before porting to D3D11 Input Layouts.

Все типы D3DDECLTYPE , которые не поддерживаются напрямую, могут эмулироваться достаточно эффективно с небольшим количеством побитовых операций в начале шейдера вершин в VS_4_0 и выше.All of the D3DDECLTYPE types that are not directly supported can be emulated fairly efficiently with a small number of bitwise operations at the beginning of a vertex shader in VS_4_0 and up.

Odds and ends

The following table shows a number of features that are similar between Direct3D 11 and 12, but are not identical.

Direct3D 11 Direct3D 12
ID3D11Query ID3D12QueryHeap allows queries to be grouped together, reducing the cost.
ID3D11Predicate Predication is now enabled by having data in a fully transparent buffer. The Direct3D 11 ID3D11Predicate object is replaced by ID3D12Resource::Map, which must follow a call to ResolveQueryData and a GPU sync operation using a fence to wait for the data to be ready. Refer to Predication.
UAV/SO hidden counter The app is responsible for allocation and management of SO/UAV counters. Refer to Stream Output Counters and UAV Counters.
Resource dynamic MinLOD (minium level of detail) This has been moved to the SRV descriptor static MinLOD.
Draw*Indirect/DispatchIndirect Drawing indirect methods are all merged into the one ExecuteIndirect method.
DepthStencil formats are interleaved DepthStencil formats are planar. For example a format of 24 bits of depth, 8 bits of stencil would be stored in the format 24/8/24/8… etc in Direct3D 11, but as 24/24/24… followed by 8/8/8… in Direct3D 12. Note that each plane is its own subresource in D3D12 (refer to Subresources).
ResizeTilePool Reserved resources can be mapped to multiple heaps. When a tile pool would have been grown in D3D11, an additional heap can be allocated in D3D12 instead.

Porting Shaders

Direct3D 10 Shaders are Authored in HLSL

Direct3D 10 limits the use of assembly language to that of debugging purposes only, therefore any hand written assembly shaders used in Direct3D 9 will need to be converted to HLSL.

Shader Signatures and Linkage

We discussed the requirements for Input Assembly linkage to Vertex shader input signatures earlier in this document (see above). Note that the Direct3D 10 runtime has also tightened the requirements for stage to stage linkage between shaders. This change will affect shader sources where the binding between stages may not have been fully described under Direct3D 9. For example:

* Broken VS — PS Linkage — even though the pixel shader may not be interested in the full matrix, the linkage must specify the full float4x3.

Note, the linkage semantics between stages must match exactly however, the target stages inputs may be a prefix of the values being output. In the example above, the pixel shader could have position and texcoord1 as the only inputs, but it could not have the position and texcoord2 as the only inputs due to the ordering constraints.

HLSL Shader Stage linkages

Linkage between shaders may occur at any of the following points in the pipeline:

  • Input Assembler to Vertex Shader
  • Vertex Shader to Pixel Shader
  • Vertex Shader to Geometry Shader
  • Vertex Shader to Stream Output
  • Geometry Shader to Pixel Shader
  • Geometry Shader to Stream Out

Constant Buffers

For ease of porting content from Direct3D 9 an initial approach to constant management outside of the Effects system might involve the creation of a single constant buffer containing all the required constants. It is important for performance to order constants into buffers by the expected frequency of update. This organization will reduce the amount of redundant constant sets to a minimum.

User clip planes in HLSL on feature level 9 and higher

Starting with Windows 8, you can use the clipplanes function attribute in an HLSL function declaration rather than SV_ClipDistance to make your shader work on feature level 9_x as well as feature level 10 and higher. For more info, see User clip planes on feature level 9 hardware.

Swapchains

The DXGI swap chain is the basis for swap chains in both Direct3D 11 and 12. There are some minor differences, in Direct3D 11 the three types of swap chain are SEQUENTIAL, DISCARD, and FLIP_SEQUENTIAL. For Direct3D 12 there are just two types: FLIP_SEQUENTIAL and FLIP_DISCARD. As noted above, you should be explicitly creating your swapchain via IDXGIFactory4, or later, and using the same interface for any adapter enumeration.

In Direct3D 11 there is automatic backbuffer rotation: only one render target view is needed for back buffer 0. In Direct3D 12 buffer rotation is explicit, there needs to be a render target view for each back buffer. Use the IDXGISwapChain3::GetCurrentBackBufferIndex method to select which one to render to. Again this additional flexibility enables greater parallelization.

Note

While there are numerous ways to set up your application, generally applications have one ID3D12CommandAllocator per swap-chain buffer. This allows the application to proceed to building up a set of commands for the next frame while the GPU renders the previous.

Creating a Core device

In general, to create a Direct3D 12 device, you call the D3D12CreateDevice function, and specify a minimum feature level.

If you specify a feature level of 9 through 12, then the device that’s returned is a feature-rich device, such as a traditional GPU (which supports a superset of the functionality of a Core device). A Core device is never returned for that range of feature levels.

On the other hand, if you specify a Core feature level (for example, D3D_FEATURE_LEVEL::D3D_FEATURE_LEVEL_1_0_CORE), then the device that’s returned could be feature-rich, or it could be a Core device.

If you specify a feature level, then the runtime/debug layer validates that the features your application uses are allowed by that feature level. That set of features is defined later in this topic.

Example Usage

Typical usage of D3D11On12 would be to use D2D to render text or images on top of a D3D12 back buffer. See the D3D11On12 sample for example code. Here is a rough outline of the steps to take to do so:

  • Create a D3D12 device (D3D12CreateDevice) and a D3D12 swap chain (CreateSwapChain with an ID3D12CommandQueue as an input).
  • Create a D3D11On12 device using the D3D12 device and the same command queue as input.
  • Retrieve the swap chain back buffers, and create D3D11 wrapped resources for each of them. The input state used should be the last way that D3D12 used it (e.g. RENDER_TARGET) and the output state should be the way that D3D12 will use it after D3D11 has finished (e.g. PRESENT).
  • Initialize D2D, and provide the D3D11 wrapped resources to D2D to prepare for rendering.

Then, on each frame, do the following:

  • Render into the current swap chain back buffer using a D3D12 command list, and execute it.
  • Acquire the current back buffer’s wrapped resource (AcquireWrappedResources).
  • Issue D2D rendering commands.
  • Release the wrapped resource (ReleaseWrappedResources).
  • Flush the D3D11 immediate context.
  • Present (IDXGISwapChain1::Present1).

Debug layer

The debug layer provides extensive additional parameter and consistency validation (such as validating shader linkage and resource binding, validating parameter consistency, and reporting error descriptions).

Note

For Windows 10, to create a device that supports the debug layer, enable the «Graphics Tools» optional feature. Go to the Settings panel, under System, Apps & features, Manage optional Features, Add a feature, and then look for «Graphics Tools».

The header required to support the debugging layer, D3D12SDKLayers.h, is included by default from d3d12.h.

When the debug layer lists memory leaks, it outputs a list of object interface pointers along with their friendly names. The default friendly name is «<unnamed>». You can set the friendly name by using the ID3D12Object::SetName method. Typically, you should compile these calls out of your production version.

We recommend that you use the debug layer to debug your apps to ensure that they are clean of errors and warnings. The debug layer helps you write Direct3D 12 code. In addition, your productivity can increase when you use the debug layer because you can immediately see the causes of obscure rendering errors or even black screens at their source. The debug layer provides warnings for many issues. For example:

  • Forgot to set a texture but read from it in your pixel shader.
  • Output depth but have no depth-stencil state bound.
  • Texture creation failed with INVALIDARG.

Set the compiler define D3DCOMPILE_DEBUG to tell the HLSL compiler to include debug information into the shader blob.

For details of all the debug interfaces and methods, refer to the Debug Layer Reference.

For overview information on using the debug layer, refer to Understanding the D3D12 Debug Layer.

Overview of the Major Structural Changes in Direct3D 10

The process of rendering using the Direct3D 10 device is structurally similar to Direct3D 9.

  • Set a vertex stream source
  • Set input layout in Direct3D 10 (set vertex stream declaration in Direct3D 9)
  • Declare primitive topology
  • Set textures
  • Set state objects
  • Set shaders
  • Draw

The Draw call ties the operations together; the ordering of calls prior to the Draw call is arbitrary. The major differences in the Direct3D 10 API design are as follows:

  • Removal of Fixed Function
  • Removal of CAPS bits — Direct3D 10’s base feature set is guaranteed
  • Stricter management of: resource access, device state, shader constants, shader linkage (inputs and outputs to shaders) between stages
  • API entry point name changes reflect the use of virtual GPU memory (Map() instead of Lock()).
  • A debug layer can be added to the device at creation time
  • The primitive topology is now an explicit state (separated from the Draw call)
  • Explicit shader constants are now stored in constant buffers
  • Shader authoring is done entirely in HLSL. The HLSL compiler now resides in the primary Direct3D 10 DLL.
  • New programmable stage — the geometry shader
  • Removal of BeginScene()/EndScene()
  • Common 2D, focus and adapter-management functionality implemented in a new component: DXGI

Removal of Fixed Function

It is sometimes surprising that even in a Direct3D 9 engine that fully exploits the programmable pipeline, there remains a number of areas that depend on the fixed-function (FF) pipeline. The most common areas are usually related to screen-space aligned rendering for UI. It is for this reason that you are likely to need to build a FF emulation shader or set of shaders which provide the necessary replacement behaviors.

This documentation contains a white paper containing replacement shader sources for the most common FF behaviors (see Fixed Function EMU Sample). Some fixed-function pixel behavior including alpha test has been moved into shaders.

Device Object Creation Time Validation

The Direct3D 10 pipeline has been redesigned from the ground up in hardware and software with a primary intention to reduce CPU overhead (at Draw time). To reduce costs, all types of device data have been assigned an object with explicit creation methods provided by the device itself. This enables strict data validation at object creation time instead of during the Draw call as it often does with Direct3D 9.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *