Explanation About Initilizing A DirextX3D Class 关于初始化Direct3D类的解释

目录

DirectX11 Study Note

This article basicialy base on DirectX 11 Tutorials - Series 2 Tutorial 3: Initializing DirectX 11
and Direct3D 11 Graphics in MSDN

The best way to read the article is to read the tutorial first. Check out the documentation here when you encounter an unfamiliar API.

I will wirite the article by the sequence of creating a direct3d graphics, and explanation the important point of every function accroding to MSDN document.

And I will translate content from Engligh to Chinese for a reference.

CreateDXGIFactory -> DXGIFactory -> Primary Adapter -> All DisplayModeList

本文基于[DirectX 11教程 - 系列2教程3:初始化DirectX 11(http://www.rastertek.com/dx11s2tut03.html)
和MSDN中的Direct3D 11图形部分

文章的最佳阅读方式是首先阅读教程,遇到陌生的API时查看这里的文档解释。

我将按创建direct3d图形的顺序编写文章,并根据MSDN文档说明每个函数的重点。

我会将英文的内容翻译成中文供参考。

Before we can initialize Direct3D we have to get the refresh rate from the video card/monitor. Each computer may be slightly different so we will need to query for that information. We query for the numerator and denominator values and then pass them to DirectX during the setup and it will calculate the proper refresh rate.

在我们初始化Direct3D之前,我们必须从视频卡/监视器获得刷新率。每台计算机可能略有不同,因此我们需要查询该信息。我们查询分子和分母值,然后在设置期间将它们传递给DirectX,它将计算适当的刷新率。

If we don't do this and just set the refresh rate to a default value which may not exist on all computers then DirectX will respond by performing a blit instead of a buffer flip which will degrade performance and give us annoying errors in the debug output.

如果我们不这样做并且只是将刷新率设置为默认值,这可能不存在于所有计算机上,那么DirectX将通过执行blit而不是缓冲区翻转来响应,这将降低性能并在调试输出中给出令人讨厌的错误。

Create a DirectX graphics interface factory.创建一个DirectX图形界面工厂

    	// Create a DirectX graphics interface factory.
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if(FAILED(result))
	{
		return false;
	}

CreateDXGIFactory function CreateDXGIFactory函数

Creates a DXGI 1.0 factory that you can use to generate other DXGI objects.

创建可用于生成其他DXGI对象的DXGI 1.0工厂。
Syntax


HRESULT CreateDXGIFactory(
  REFIID riid,
  void   **ppFactory
);

Parameters
riid

Type: REFIID

The globally unique identifier (GUID) of the IDXGIFactory object referenced by the ppFactory parameter.

ppFactory参数引用的IDXGIFactory对象的全局唯一标识符(GUID)。

ppFactory

Type: void**

Address of a pointer to an IDXGIFactory object.

指向IDXGIFactory对象的指针的地址。执行函数之后生成的IDXGIFactory对象便会存在这个地址中。

Return Value

Type: HRESULT

Returns S_OK if successful; otherwise, returns one of the DXGI_ERROR.
如果成功则返回S_OK;否则,返回DXGI_ERROR其中之一。

Remarks
Use a DXGI factory to generate objects that enumerate adapters, create swap chains, and associate a window with the alt+enter key sequence for toggling to and from the fullscreen display mode.

使用DXGI工厂生成枚举适配器,创建swap chains,以及将窗口与alt + enter键相关联,以便全屏显示模式的进出切换。

If the CreateDXGIFactory function succeeds, the reference count on the IDXGIFactory interface is incremented. To avoid a memory leak, when you finish using the interface, call the IDXGIFactory::Release method to release the interface.

如果CreateDXGIFactory函数成功,则IDXGIFactory接口上的引用计数会递增。为避免内存泄漏,在使用完界面后,调用IDXGIFactory :: Release方法释放接口。

Examples
Creating a DXGI 1.0 Factory

创建DXGI 1.0工厂

The following code example demonstrates how to create a DXGI 1.0 factory. This example uses the __uuidof() intrinsic to obtain the REFIID, or GUID, of the IDXGIFactory interface.

以下代码示例演示如何创建DXGI 1.0工厂。此示例使用__uuidof()内在函数来获取IDXGIFactory接口的REFIID或GUID。


IDXGIFactory * pFactory;

HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&pFactory) );


Use the factory to create an adapter 使用工厂创建适配器

Use the factory to create an adapter for the primary graphics interface (video card).

使用工厂为主图形界面(视频卡)创建适配器。

	// Use the factory to create an adapter for the primary graphics interface (video card).
	result = factory->EnumAdapters(0, &adapter);
	if(FAILED(result))
	{
		return false;
	}

IDXGIFactory interface IDXGIFactory接口

An IDXGIFactory interface implements methods for generating DXGI objects (which handle full screen transitions).

IDXGIFactory接口实现了生成DXGI对象(用于处理全屏转换)的方法。

Methods

The IDXGIFactory interface has these methods.

IDXGIFactory接口具有这些方法。

Method Description
IDXGIFactory::EnumAdapters Enumerates the adapters (video cards) 枚举所有适配器(视频卡)

Remarks
Create a factory by calling CreateDXGIFactory.

通过调用CreateDXGIFactory创建工厂。

Because you can create a Direct3D device without creating a swap chain, you might need to retrieve the factory that is used to create the device in order to create a swap chain. You can request the IDXGIDevice interface from the Direct3D device and then use the IDXGIObject::GetParent method to locate the factory. The following code shows how.

因为您可以在不创建交换链的情况下创建Direct3D设备,所以可能需要检索用于创建设备的工厂以创建交换链。您可以从Direct3D设备请求IDXGIDevice接口,然后使用IDXGIObject :: GetParent方法找到工厂。以下代码显示了如何操作。

IDXGIDevice * pDXGIDevice = nullptr;
hr = g_pd3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice);

IDXGIAdapter * pDXGIAdapter = nullptr;
hr = pDXGIDevice->GetAdapter( &pDXGIAdapter );

IDXGIFactory * pIDXGIFactory = nullptr;
pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pIDXGIFactory);

Enumerate the primary adapter output 枚举主适配器输出

Enumerate the primary adapter output (monitor).

枚举主适配器输出(监视器/显示器)。

        AdapterOutput* adapterOutput
	// Enumerate the primary adapter output (monitor).
	result = adapter->EnumOutputs(0, &adapterOutput);
	if(FAILED(result))
	{
		return false;
	}

IDXGIAdapter interface IDXGIAdapter接口

The IDXGIAdapter interface represents a display subsystem (including one or more GPUs, DACs and video memory).

IDXGIAdapter接口代表显示子系统(包括一个或多个GPU,DAC和视频内存)。

Methods
The IDXGIAdapter interface has these methods.

Method Description
IDXGIAdapter::EnumOutputs Enumerate adapter (video card) outputs.
IDXGIAdapter::GetDesc Gets a DXGI 1.0 description of an adapter (or video card).1.0版适配器(或视频卡)的描述

Remarks
A display subsystem is often referred to as a video card, however, on some machines the display subsystem is part of the motherboard.

显示子系统(译注:处理显示的系统)通常被称为视频卡,然而,在一些机器上,显示子系统是主板的一部分。

To enumerate the display subsystems, use IDXGIFactory::EnumAdapters.

要枚举显示子系统,请使用IDXGIFactory :: EnumAdapters。

To get an interface to the adapter for a particular device, use IDXGIDevice::GetAdapter.

要获取特定设备的适配器接口,请使用IDXGIDevice :: GetAdapter。

To create a software adapter, use IDXGIFactory::CreateSoftwareAdapter.

要创建软件适配器(译注:使用CPU模拟GPU),请使用IDXGIFactory :: CreateSoftwareAdapter。

IDXGIAdapter::EnumOutputs method IDXGIAdapter::EnumOutputs 方法

Syntax


HRESULT EnumOutputs(
  UINT        Output,
  IDXGIOutput **ppOutput
);

Parameters

Output

Type: UINT

The index of the output.

输出的索引。

ppOutput

Type:  IDXGIOutput **

The address of a pointer to an IDXGIOutput interface at the position specified by the Output parameter.

由Output参数指定的位置,是一个IDXGIOutput接口的指针的地址。

Return Value
Type: HRESULT

A code that indicates success or failure (see DXGI_ERROR). DXGI_ERROR_NOT_FOUND is returned if the index is greater than the number of outputs.

表示成功或失败的代码(请参阅DXGI_ERROR)。如果索引大于输出端的数量,则返回DXGI_ERROR_NOT_FOUND。

If the adapter came from a device created using D3D_DRIVER_TYPE_WARP, then the adapter has no outputs, so DXGI_ERROR_NOT_FOUND is returned.

如果适配器来自使用D3D_DRIVER_TYPE_WARP创建的设备,然后适配器没有任何输出端,那么返回DXGI_ERROR_NOT_FOUND。

Remarks
Note If you call this API in a Session 0 process, it returns DXGI_ERROR_NOT_CURRENTLY_AVAILABLE.

注意如果在Session 0进程中调用此API,则返回DXGI_ERROR_NOT_CURRENTLY_AVAILABLE。

When the EnumOutputs method succeeds and fills the ppOutput parameter with the address of the pointer to the output interface, EnumOutputs increments the output interface's reference count. To avoid a memory leak, when you finish using the output interface, call the Release method to decrement the reference count.

当EnumOutputs方法成功,并使用指向输出接口的指针的地址填充ppOutput参数时,EnumOutputs会增加输出接口的引用计数。为避免内存泄漏,在使用输出接口完成后,调用Release方法减少引用计数。

EnumOutputs first returns the output on which the desktop primary is displayed. This output corresponds with an index of zero. EnumOutputs then returns other outputs.

EnumOutputs首先返回显示桌面主节点的输出。此输出对应于零索引。然后返回其他输出。

Examples
Enumerating Outputs

枚举输出

Here is an example of how to use EnumOutputs to enumerate all the outputs on an adapter:

以下是如何使用EnumOutputs枚举适配器上的所有输出的示例:


UINT i = 0;
IDXGIOutput * pOutput;
std::vector<IDXGIOutput*> vOutputs;
while(pAdapter->EnumOutputs(i, &pOutput) != DXGI_ERROR_NOT_FOUND)
{
    vOutputs.push_back(pOutput);
    ++i;
}

Get the number for the adapter output (monitor). 获取适配器输出(监视器)的编号。

Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).

获取适合适配器输出(监视器)的DXGI_FORMAT_R8G8B8A8_UNORM显示格式的模式数。


	// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if(FAILED(result))
	{
		return false;
	}

	// Create a list to hold all the possible display modes for this monitor/video card combination.
        //创建一个列表,以保存此监视器/视频卡组合的所有可能的显示模式。
	displayModeList = new DXGI_MODE_DESC[numModes];
	if(!displayModeList)
	{
		return false;
	}

	// Now fill the display mode list structures.
        //现在填写显示模式列表结构
	result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if(FAILED(result))
	{
		return false;
	}

IDXGIOutput interface IDXGIOutput接口

An IDXGIOutput interface represents an adapter output (such as a monitor).

IDXGIOutput接口表示适配器输出(例如监视器)。

Methods

The IDXGIOutput interface has these methods.

DXGIOutput接口具有这些方法。

Method Description
IDXGIOutput::GetDisplayModeList Gets the display modes that match the requested format and other input options.获取与请求的格式和其他输入选项匹配的所有显示模式

Remarks

To see the outputs available, use IDXGIAdapter::EnumOutputs. To see the specific output that the swap chain will update, use IDXGISwapChain::GetContainingOutput.

要查看可用的输出,请使用IDXGIAdapter :: EnumOutputs。要查看交换链将update的特定输出,请使用IDXGISwapChain :: GetContainingOutput。

IDXGIOutput::GetDisplayModeList method IDXGIOutput :: GetDisplayModeList方法

[Starting with Direct3D 11.1, we recommend not to use GetDisplayModeList anymore to retrieve the matching display mode. Instead, use IDXGIOutput1::GetDisplayModeList1, which supports stereo display mode.]

[从Direct3D 11.1开始,我们建议不再使用GetDisplayModeList来检索匹配的显示模式。而是使用IDXGIOutput1 :: GetDisplayModeList1,它支持立体显示模式。

Gets the display modes that match the requested format and other input options.

获取与请求的格式和其他输入选项匹配的显示模式。

Syntax


HRESULT GetDisplayModeList(
  DXGI_FORMAT    EnumFormat,
  UINT           Flags,
  UINT           *pNumModes,
  DXGI_MODE_DESC *pDesc
);

Parameters
EnumFormat

Type: DXGI_FORMAT

The color format (see DXGI_FORMAT).

颜色格式(参见DXGI_FORMAT)。

Flags

Type: UINT

Options for modes to include (see DXGI_ENUM_MODES). DXGI_ENUM_MODES_SCALING needs to be specified to expose the display modes that require scaling. Centered modes, requiring no scaling and corresponding directly to the display output, are enumerated by default.

要包含的模式选项(请参阅DXGI_ENUM_MODES)。需要指定DXGI_ENUM_MODES_SCALING以显示需要缩放的显示模式。默认情况下,枚举模式,不需要缩放并直接对应于显示输出。

pNumModes

Type: UINT

Set pDesc to NULL so that pNumModes returns the number of display modes that match the format and the options. Otherwise, pNumModes returns the number of display modes returned in pDesc.

将pDesc设置为NULL,以便pNumModes返回与格式和选项匹配的显示模式数。否则,pNumModes返回pDesc中返回的显示模式数。

pDesc

Type: DXGI_MODE_DESC*

A pointer to a list of display modes (see DXGI_MODE_DESC); set to NULL to get the number of display modes.

指向显示模式列表的指针(参见DXGI_MODE_DESC);设置为NULL以获取显示模式的数量。

Return Value

Type: HRESULT

Returns one of the following DXGI_ERROR. It is rare, but possible, that the display modes available can change immediately after calling this method, in which case DXGI_ERROR_MORE_DATA is returned (if there is not enough room for all the display modes).

返回以下DXGI_ERROR之一。可能的是,可用的显示模式在调用此方法后可立即更改,在这种情况下,返回DXGI_ERROR_MORE_DATA(如果没有足够的空间用于所有显示模式)。

If GetDisplayModeList is called from a Remote Desktop Services session (formerly Terminal Services session), DXGI_ERROR_NOT_CURRENTLY_AVAILABLE is returned.

如果从远程桌面服务会话(以前称为终端服务会话)调用GetDisplayModeList,则返回DXGI_ERROR_NOT_CURRENTLY_AVAILABLE。

Remarks

In general, when switching from windowed to full-screen mode, a swap chain automatically chooses a display mode that meets (or exceeds) the resolution, color depth and refresh rate of the swap chain. To exercise more control over the display mode, use this API to poll the set of display modes that are validated against monitor capabilities, or all modes that match the desktop (if the desktop settings are not validated against the monitor).

通常,当从窗口模式切换到全屏模式时,交换链会自动选择满足(或超过)交换链的分辨率,颜色深度和刷新率的显示模式。要对显示模式进行更多控制,请使用此API轮询针对监视器功能验证的一组显示模式,或者与桌面匹配的所有模式(如果桌面设置未针对监视器进行验证)。

As shown, this API is designed to be called twice. First to get the number of modes available, and second to return a description of the modes.

如图所示,此API旨在被调用两次。首先获得可用模式的数量,然后返回模式的描述。

UINT num = 0;
DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT;
UINT flags         = DXGI_ENUM_MODES_INTERLACED;

pOutput->GetDisplayModeList( format, flags, &num, 0);

...

DXGI_MODE_DESC * pDescs = new DXGI_MODE_DESC[num];
pOutput->GetDisplayModeList( format, flags, &num, pDescs);


DXGI_MODE_DESC structure DXGI_MODE_DESC结构

Describes a display mode.

描述显示模式。

Syntax


typedef struct DXGI_MODE_DESC {
  UINT                     Width;
  UINT                     Height;
  DXGI_RATIONAL            RefreshRate;
  DXGI_FORMAT              Format;
  DXGI_MODE_SCANLINE_ORDER ScanlineOrdering;
  DXGI_MODE_SCALING        Scaling;
} DXGI_MODE_DESC;

Members
Width

Type: UINT

A value that describes the resolution width. If you specify the width as zero when you call the IDXGIFactory::CreateSwapChain method to create a swap chain, the runtime obtains the width from the output window and assigns this width value to the swap-chain description. You can subsequently call the IDXGISwapChain::GetDesc method to retrieve the assigned width value.

描述分辨率宽度的值。如果在调用IDXGIFactory :: CreateSwapChain方法创建交换链时将宽度指定为零,则运行时从输出窗口获取宽度,并将此宽度值分配给交换链描述。随后,您可以调用IDXGISwapChain :: GetDesc方法来检索指定的宽度值

Height

Type: UINT

A value describing the resolution height. If you specify the height as zero when you call the IDXGIFactory::CreateSwapChain method to create a swap chain, the runtime obtains the height from the output window and assigns this height value to the swap-chain description. You can subsequently call the IDXGISwapChain::GetDesc method to retrieve the assigned height value.

描述分辨率高度的值。如果在调用IDXGIFactory :: CreateSwapChain方法创建交换链时将高度指定为零,则运行时从输出窗口获取高度,并将此高度值分配给交换链描述。随后,您可以调用IDXGISwapChain :: GetDesc方法来检索指定的高度值。

RefreshRate

Type: DXGI_RATIONAL

A DXGI_RATIONAL structure describing the refresh rate in hertz

描述以赫兹为单位的刷新率的DXGI_RATIONAL结构

Format

Type: DXGI_FORMAT

A DXGI_FORMAT structure describing the display format.

描述显示格式的DXGI_FORMAT结构。

ScanlineOrdering

Type: DXGI_MODE_SCANLINE_ORDER

A member of the DXGI_MODE_SCANLINE_ORDER enumerated type describing the scanline drawing mode.

DXGI_MODE_SCANLINE_ORDER枚举类型的成员,描述扫描线绘制模式。

Scaling

Type: DXGI_MODE_SCALING

A member of the DXGI_MODE_SCALING enumerated type describing the scaling mode.

DXGI_MODE_SCALING枚举类型的成员,用于描述缩放模式。


Retrieve using the adapter is the name of the video card and the amount of video memory使用适配器检索视频卡的名称和视频内存量

We now have the numerator and denominator for the refresh rate. The last thing we will retrieve using the adapter is the name of the video card and the amount of video memory.
我们现在有刷新率的分子和分母。我们使用适配器检索做的最后一件事是视频卡的名称和视频内存的数量。


	// Get the adapter (video card) description.
        ///获取适配器(视频卡)说明。
	result = adapter->GetDesc(&adapterDesc);
	if(FAILED(result))
	{
		return false;
	}

	// Store the dedicated video card memory in megabytes.
        //以专用视频卡内存存储,以兆字节为单位。
	m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	// Convert the name of the video card to a character array and store it.
        //将视频卡的名称转换为字符数组并存储它。
	error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128);
	if(error != 0)
	{
		return false;
	}

wcstombs_s, _wcstombs_s_l

Converts a sequence of wide characters to a corresponding sequence of multibyte characters. A version of wcstombs, _wcstombs_l with security enhancements as described in Security Features in the CRT.

将一系列宽字符转换为相应的多字节字符序列。 wcstombs的一个版本,_wcstombs_l,具有安全性增强功能,如CRT中的安全功能所述。


Get the pointer to the back buffer

获取指向后台缓冲区的指针

Sometimes this call to create the device will fail if the primary video card is not compatible with DirectX 11. Some machines may have the primary card as a DirectX 10 video card and the secondary card as a DirectX 11 video card. Also some hybrid graphics cards work that way with the primary being the low power Intel card and the secondary being the high power Nvidia card. To get around this you will need to not use the default device and instead enumerate all the video cards in the machine and have the user choose which one to use and then specify that card when creating the device.

如果主要视频卡与DirectX 11不兼容,有时创建设备的此调用将失败。某些计算机可能将主卡作为DirectX 10视频卡,将辅助卡作为DirectX 11视频卡。此外,一些混合显卡的工作原理是主卡是低功耗的英特尔卡,次要卡的是高功率的Nvidia卡。要解决此问题,您将需要不使用默认设备,而是枚举机器中的所有视频卡,让用户选择使用哪一个,然后在创建设备时指定该卡。

Now that we have a swap chain we need to get a pointer to the back buffer and then attach it to the swap chain. We'll use the CreateRenderTargetView function to attach the back buffer to our swap chain.

现在我们有一个交换链,我们需要获得一个指向后缓冲区的指针,然后将它附加到交换链。我们将使用CreateRenderTargetView函数将后台缓冲区附加到交换链。

	// Get the pointer to the back buffer.
        //获取指向后台缓冲区的指针。
	result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
	if(FAILED(result))
	{
		return false;
	}

IDXGISwapChain::GetBuffer method IDXGISwapChain :: GetBuffer方法

Accesses one of the swap-chain's back buffers.
访问交换链的一个后台缓冲区。

Syntax


HRESULT GetBuffer(
  UINT   Buffer,
  REFIID riid,
  void   **ppSurface
);

Parameters
Buffer

Type: UINT

A zero-based buffer index.

从零开始的缓冲区索引。

If the swap chain's swap effect is DXGI_SWAP_EFFECT_DISCARD, this method can only access the first buffer; for this situation, set the index to zero.

如果交换链的交换效果是DXGI_SWAP_EFFECT_DISCARD,则此方法只能访问第一个缓冲区;对于这种情况,请将索引设置为零。

If the swap chain's swap effect is either DXGI_SWAP_EFFECT_SEQUENTIAL or DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL, only the swap chain's zero-index buffer can be read from and written to. The swap chain's buffers with indexes greater than zero can only be read from; so if you call the IDXGIResource::GetUsage method for such buffers, they have the DXGI_USAGE_READ_ONLY flag set.

如果交换链的交换效果是DXGI_SWAP_EFFECT_SEQUENTIAL或DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,则只能读取和写入交换链的零索引缓冲区。索引大于零的交换链缓冲区只能读取;因此,如果为此类缓冲区调用IDXGIResource :: GetUsage方法,则会设置DXGI_USAGE_READ_ONLY标志。

riid

Type: REFIID

The type of interface used to manipulate the buffer.

用于操作缓冲区的接口类型。

ppSurface

Type: void**

A pointer to a back-buffer interface.

指向后缓冲区接口的指针。


Create the render target view with the back buffer pointer 使用后缓冲区指针创建渲染目标视图

	// Create the render target view with the back buffer pointer.
	result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
	if(FAILED(result))
	{
		return false;
	}

ID3D11Device::CreateRenderTargetView method ID3D11Device :: CreateRenderTargetView方法

Creates a render-target view for accessing resource data.

创建用于访问资源数据的渲染目标视图。

Syntax


HRESULT CreateRenderTargetView(
  ID3D11Resource                      *pResource,
  const D3D11_RENDER_TARGET_VIEW_DESC *pDesc,
  ID3D11RenderTargetView              **ppRTView
);

Parameters
pResource

Type: ID3D11Resource*

Pointer to a ID3D11Resource that represents a render target. This resource must have been created with the D3D11_BIND_RENDER_TARGET flag.

指向表示渲染目标的ID3D11Resource的指针。必须使用D3D11_BIND_RENDER_TARGET标志创建此资源。

pDesc

Type: const D3D11_RENDER_TARGET_VIEW_DESC*

Pointer to a D3D11_RENDER_TARGET_VIEW_DESC that represents a render-target view description. Set this parameter to NULL to create a view that accesses all of the subresources in mipmap level 0.

指向D3D11_RENDER_TARGET_VIEW_DESC的指针,表示渲染目标视图描述。将此参数设置为NULL可创建一个视图,该视图可访问mipmap级别0中的所有子资源。

ppRTView

Type: ID3D11RenderTargetView**

Address of a pointer to an ID3D11RenderTargetView. Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

指向ID3D11RenderTargetView的指针的地址。将此参数设置为NULL以验证其他输入参数(如果其他输入参数通过验证,则该方法将返回S_FALSE)。


Create Texture2D For depth stencil buffer 创建Texture2D用于深度模板缓冲区

Now we create the depth/stencil buffer using that description. You will notice we use the CreateTexture2D function to make the buffers, hence the buffer is just a 2D texture. The reason for this is that once your polygons are sorted and then rasterized they just end up being colored pixels in this 2D buffer. Then this 2D buffer is drawn to the screen.

现在我们使用该描述创建深度/模板缓冲区。你会注意到我们使用CreateTexture2D函数来制作缓冲区,因此缓冲区只是一个2D纹理。这样做的原因是,一旦您的多边形被排序然后进行光栅化后,它们最终就会成为这个2D缓冲区中的彩色像素。然后将这个2D缓冲区绘制到屏幕上。

	// Create the texture for the depth buffer using the filled out description.
        //使用填写的description为深度缓冲区创建纹理。
	result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
	if(FAILED(result))
	{
		return false;
	}

ID3D11Device::CreateTexture2D method

Create an array of 2D textures.
创建2D纹理数组。

Syntax


HRESULT CreateTexture2D(
  const D3D11_TEXTURE2D_DESC   *pDesc,
  const D3D11_SUBRESOURCE_DATA *pInitialData,
  ID3D11Texture2D              **ppTexture2D
);

Parameters
pDesc

Type: const D3D11_TEXTURE2D_DESC*

A pointer to a D3D11_TEXTURE2D_DESC structure that describes a 2D texture resource. To create a typeless resource that can be interpreted at runtime into different, compatible formats, specify a typeless format in the texture description. To generate mipmap levels automatically, set the number of mipmap levels to 0.

指向描述2D纹理资源的D3D11_TEXTURE2D_DESC结构的指针。要创建可在运行时解释为不同的兼容格式的无类型资源,请在纹理描述中指定无类型格式。要自动生成mipmap级别,请将mipmap级别的数量设置为0。

pInitialData

Type: const D3D11_SUBRESOURCE_DATA*

A pointer to an array of D3D11_SUBRESOURCE_DATA structures that describe subresources for the 2D texture resource. Applications can't specify NULL for pInitialData when creating IMMUTABLE resources (see D3D11_USAGE). If the resource is multisampled, pInitialData must be NULL because multisampled resources cannot be initialized with data when they are created.

指向描述2D纹理资源的子资源的D3D11_SUBRESOURCE_DATA结构数组的指针。创建IMMUTABLE资源时,应用程序无法为pInitialData指定NULL(请参阅D3D11_USAGE)。如果资源是多重采样的,则pInitialData必须为NULL,因为多重采样资源在创建时无法使用数据进行初始化。

If you don't pass anything to pInitialData, the initial content of the memory for the resource is undefined. In this case, you need to write the resource content some other way before the resource is read.

如果未向pInitialData传递任何内容,则资源的内存的初始内容未定义。在这种情况下,您需要在读取资源之前以其他方式编写资源内容。

You can determine the size of this array from values in the MipLevels and ArraySize members of the D3D11_TEXTURE2D_DESC structure to which pDesc points by using the following calculation:

您可以使用以下计算从pDesc指向的D3D11_TEXTURE2D_DESC结构的MipLevels和ArraySize成员中的值确定此数组的大小:

MipLevels * ArraySize

For more information about this array size, see Remarks.

有关此数组大小的更多信息,请参阅“备注”。

ppTexture2D

Type: ID3D11Texture2D**

A pointer to a buffer that receives a pointer to a ID3D11Texture2D interface for the created texture. Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

指向缓冲区的指针,该缓冲区接收指向创建纹理的ID3D11Texture2D接口的指针。将此参数设置为NULL以验证其他输入参数(如果其他输入参数通过验证,则该方法将返回S_FALSE)。

Create a depth stencil state 创建深度模板状态

With the description filled out we can now create a depth stencil state.

填写完后,我们现在可以创建深度模板状态。


	// Create the depth stencil state.
	result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
	if(FAILED(result))
	{
		return false;
	}

ID3D11Device::CreateDepthStencilState method

Create a depth-stencil state object that encapsulates depth-stencil test information for the output-merger stage.

创建一个深度模板状态对象,该对象封装输出合并阶段的深度模板测试信息。

Syntax


HRESULT CreateDepthStencilState(
  const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc,
  ID3D11DepthStencilState        **ppDepthStencilState
);

Parameters
pDepthStencilDesc

Type: const D3D11_DEPTH_STENCIL_DESC*

Pointer to a depth-stencil state description (see D3D11_DEPTH_STENCIL_DESC).

指向深度模板状态描述的指针(请参阅D3D11_DEPTH_STENCIL_DESC)。

ppDepthStencilState

Type: ID3D11DepthStencilState**

Address of a pointer to the depth-stencil state object created (see ID3D11DepthStencilState).

指向创建的深度模板状态对象的指针的地址(请参阅ID3D11DepthStencilState)


Set depth stencil state 设置深度模板状态

With the created depth stencil state we can now set it so that it takes effect. Notice we use the device context to set it.

使用创建的深度模板状态,我们现在可以设置它以使其生效。请注意,我们使用设备上下文来设置它。

	// Set the depth stencil state.
        //设置深度模板状态。
	m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

ID3D11DeviceContext::OMSetDepthStencilState method ID3D11DeviceContext :: OMSetDepthStencilState方法

Sets the depth-stencil state of the output-merger stage.

设置输出合并阶段的深度模板状态。

Syntax


Copy
void OMSetDepthStencilState(
  ID3D11DepthStencilState *pDepthStencilState,
  UINT                    StencilRef
);

Parameters
pDepthStencilState

Type: ID3D11DepthStencilState*

Pointer to a depth-stencil state interface (see ID3D11DepthStencilState) to bind to the device. Set this to NULL to use the default state listed in D3D11_DEPTH_STENCIL_DESC.

指向深度模板状态接口(请参阅ID3D11DepthStencilState)以指向设备的指针。将其设置为NULL以使用D3D11_DEPTH_STENCIL_DESC中列出的默认状态。

StencilRef

Type: UINT

Reference value to perform against when doing a depth-stencil test. See remarks.

在进行的参行深度模板测试时执考值。


Create the description of the view of the depth stencil buffer 创建深度模板缓冲区视图的描述

The next thing we need to create is the description of the view of the depth stencil buffer. We do this so that Direct3D knows to use the depth buffer as a depth stencil texture. After filling out the description we then call the function CreateDepthStencilView to create it.

我们需要创建的下一件事是深度模板缓冲区视图的描述。我们这样做是为了让Direct3D知道使用深度缓冲区作为深度模板纹理。填写完描述后,我们再调用CreateDepthStencilView函数来创建它。

	// Initialize the depth stencil view.
        //初始化深度模板视图。
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
        //设置深度模板视图描述。
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	// Create the depth stencil view.
        //创建深度模板视图。
	result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
	if(FAILED(result))
	{
		return false;
	}

ID3D11Device::CreateDepthStencilView method ID3D11Device :: CreateDepthStencilView方法

Create a depth-stencil view for accessing resource data.

创建用于访问资源数据的深度模板视图。

Syntax


HRESULT CreateDepthStencilView(
  ID3D11Resource                      *pResource,
  const D3D11_DEPTH_STENCIL_VIEW_DESC *pDesc,
  ID3D11DepthStencilView              **ppDepthStencilView
);

Parameters
pResource

Type: ID3D11Resource*

Pointer to the resource that will serve as the depth-stencil surface. This resource must have been created with the D3D11_BIND_DEPTH_STENCIL flag.

指向将用作深度模板表面的资源的指针。必须使用D3D11_BIND_DEPTH_STENCIL标志创建此资源。

pDesc

Type: const D3D11_DEPTH_STENCIL_VIEW_DESC*

Pointer to a depth-stencil-view description (see D3D11_DEPTH_STENCIL_VIEW_DESC). Set this parameter to NULL to create a view that accesses mipmap level 0 of the entire resource (using the format the resource was created with).

指向深度模板视图描述的指针(请参阅D3D11_DEPTH_STENCIL_VIEW_DESC)。将此参数设置为NULL可创建一个视图,该视图访问整个资源的mipmap级别0(使用创建资源的格式)。

ppDepthStencilView

Type: ID3D11DepthStencilView**

Address of a pointer to an ID3D11DepthStencilView. Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

指向ID3D11DepthStencilView的指针的地址。将此参数设置为NULL以验证其他输入参数(如果其他输入参数通过验证,则该方法将返回S_FALSE)。

D3D11_DEPTH_STENCIL_VIEW_DESC structure D3D11_DEPTH_STENCIL_VIEW_DESC结构

Specifies the subresources of a texture that are accessible from a depth-stencil view.

指定可从深度模板视图访问的纹理的子资源。

Syntax


typedef struct D3D11_DEPTH_STENCIL_VIEW_DESC {
  DXGI_FORMAT         Format;
  D3D11_DSV_DIMENSION ViewDimension;
  UINT                Flags;
  union {
    D3D11_TEX1D_DSV         Texture1D;
    D3D11_TEX1D_ARRAY_DSV   Texture1DArray;
    D3D11_TEX2D_DSV         Texture2D;
    D3D11_TEX2D_ARRAY_DSV   Texture2DArray;
    D3D11_TEX2DMS_DSV       Texture2DMS;
    D3D11_TEX2DMS_ARRAY_DSV Texture2DMSArray;
  };
} D3D11_DEPTH_STENCIL_VIEW_DESC;

Members
Format

Type: DXGI_FORMAT

Resource data format (see DXGI_FORMAT). See remarks for allowable formats.

资源数据格式(参见DXGI_FORMAT)。请参阅允许格式的备注。

ViewDimension

Type: D3D11_DSV_DIMENSION

Type of resource (see D3D11_DSV_DIMENSION). Specifies how a depth-stencil resource will be accessed; the value is stored in the union in this structure.

资源类型(见D3D11_DSV_DIMENSION)。指定如何访问深度模板资源;该值存储在此结构的union中。

Flags

Type: UINT

A value that describes whether the texture is read only. Pass 0 to specify that it is not read only; otherwise, pass one of the members of the D3D11_DSV_FLAG enumerated type.

描述纹理是否为只读的值。传递0以指定它不是只读的;否则,传递D3D11_DSV_FLAG枚举类型的其中一个成员。

__unnamed_union_0717_7

__unnamed_union_0717_7.Texture1D

__unnamed_union_0717_7.Texture1DArray

__unnamed_union_0717_7.Texture2D

__unnamed_union_0717_7.Texture2DArray

__unnamed_union_0717_7.Texture2DMS

__unnamed_union_0717_7.Texture2DMSArray

Remarks
These are valid formats for a depth-stencil view:

这些是深度模板视图的有效格式:

  • DXGI_FORMAT_D16_UNORM
  • DXGI_FORMAT_D24_UNORM_S8_UINT
  • DXGI_FORMAT_D32_FLOAT
  • DXGI_FORMAT_D32_FLOAT_S8X24_UINT
  • DXGI_FORMAT_UNKNOWN

A depth-stencil view cannot use a typeless format. If the format chosen is DXGI_FORMAT_UNKNOWN, then the format of the parent resource is used.

深度模板视图不能使用无类型格式。如果选择的格式为DXGI_FORMAT_UNKNOWN,则使用父资源的格式。

A depth-stencil-view description is needed when calling ID3D11Device::CreateDepthStencilView.

调用ID3D11Device :: CreateDepthStencilView时需要深度模板视图描述。


Bind the render target view and depth stencil buffer to the output render pipeline 将渲染目标视图和深度模板缓冲区绑定到输出渲染管道

With that created we can now call OMSetRenderTargets. This will bind the render target view and the depth stencil buffer to the output render pipeline. This way the graphics that the pipeline renders will get drawn to our back buffer that we previously created. With the graphics written to the back buffer we can then swap it to the front and display our graphics on the user's screen.

通过创建,我们现在可以调用OMSetRenderTargets。这会将渲染目标视图和深度模板缓冲区绑定到输出渲染管道。这样,管道呈现的图形将被绘制到我们之前创建的后台缓冲区。将图形写入后缓冲区后,我们可以将其交换到前面并在用户屏幕上显示我们的图形。

	// Bind the render target view and depth stencil buffer to the output render pipeline.
        //将渲染目标视图和深度模板缓冲区绑定到输出渲染管道。
	m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

ID3D11DeviceContext::OMSetRenderTargets method ID3D11DeviceContext :: OMSetRenderTargets方法

Bind one or more render targets atomically and the depth-stencil buffer to the output-merger stage.

将一个或多个渲染目标原子绑定,深度模板缓冲区绑定到输出合并阶段。

Syntax


Copy
void OMSetRenderTargets(
  UINT                   NumViews,
  ID3D11RenderTargetView * const *ppRenderTargetViews,
  ID3D11DepthStencilView *pDepthStencilView
);

Parameters
NumViews

Type: UINT

Number of render targets to bind (ranges between 0 and D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT). If this parameter is nonzero, the number of entries in the array to which ppRenderTargetViews points must equal the number in this parameter.

要绑定的渲染目标数(范围介于0和D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT之间)。如果此参数非零,则ppRenderTargetViews指向的数组中的条目数必须等于此参数中的数字。

ppRenderTargetViews

Type: ID3D11RenderTargetView*

Pointer to an array of ID3D11RenderTargetView that represent the render targets to bind to the device. If this parameter is NULL and NumViews is 0, no render targets are bound.

指向ID3D11RenderTargetView数组的指针,表示要绑定到设备的渲染目标。如果此参数为NULL且NumViews为0,则不绑定任何渲染目标。

pDepthStencilView

Type: ID3D11DepthStencilView*

Pointer to a ID3D11DepthStencilView that represents the depth-stencil view to bind to the device. If this parameter is NULL, the depth-stencil state is not bound.

指向ID3D11DepthStencilView的指针,表示要绑定到设备的深度模板视图。如果此参数为NULL,则不绑定深度模板状态。

Return Value
Returns nothing.
什么都不返回.

Remarks
The maximum number of active render targets a device can have active at any given time is set by a #define in D3D11.h called D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT. It is invalid to try to set the same subresource to multiple render target slots. Any render targets not defined by this call are set to NULL.

设备在任何给定时间可以激活的最大活动渲染目标数由D3D11.h中的#define设置,称为D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT。尝试将相同的子资源设置为多个渲染目标插槽是无效的。此调用未定义的任何渲染目标都设置为NULL。

If any subresources are also currently bound for reading in a different stage or writing (perhaps in a different part of the pipeline), those bind points will be set to NULL, in order to prevent the same subresource from being read and written simultaneously in a single rendering operation.

如果任何子资源当前也被绑定在不同的阶段读取或写入(可能在管道的不同部分),那么这些绑定点将被设置为NULL,以防止同一个子资源被同时读取和写入单个渲染操作。

The method will hold a reference to the interfaces passed in. This differs from the device state behavior in Direct3D 10.

该方法将保存对传入的接口的引用。这与Direct3D 10中的设备状态行为不同。

If the render-target views were created from an array resource type, all of the render-target views must have the same array size.

如果渲染目标视图是从数组资源类型创建的,则所有渲染目标视图必须具有相同的数组大小。

This restriction also applies to the depth-stencil view, its array size must match that of the render-target views being bound.

此限制也适用于深度模板视图,其数组大小必须与绑定的渲染目标视图的大小相匹配。

The pixel shader must be able to simultaneously render to at least eight separate render targets. All of these render targets must access the same type of resource: Buffer, Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D, or TextureCube. All render targets must have the same size in all dimensions (width and height, and depth for 3D or array size for *Array types). If render targets use multisample anti-aliasing, all bound render targets and depth buffer must be the same form of multisample resource (that is, the sample counts must be the same). Each render target can have a different data format. These render target formats are not required to have identical bit-per-element counts.

像素着色器必须能够同时渲染到至少八个单独的渲染目标。所有这些渲染目标都必须访问相同类型的资源:Buffer,Texture1D,Texture1DArray,Texture2D,Texture2DArray,Texture3D或TextureCube。所有渲染目标在所有维度上必须具有相同的大小(宽度和高度,3D的深度或*阵列类型的数组大小)。如果渲染目标使用多重采样消除锯齿,则所有绑定渲染目标和深度缓冲区必须是多重采样资源的相同形式(即,样本计数必须相同)。每个渲染目标可以具有不同的数据格式。这些渲染目标格式不需要具有相同的每元素位数。

Any combination of the eight slots for render targets can have a render target set or not set.

渲染目标的八个插槽的任意组合都可以设置或不设置渲染目标。

The same resource view cannot be bound to multiple render target slots simultaneously. However, you can set multiple non-overlapping resource views of a single resource as simultaneous multiple render targets.

同一资源视图不能同时绑定到多个渲染目标插槽。但是,您可以将单个资源的多个非重叠资源视图设置为同时多个渲染目标。


Create the rasterizer state and the viewport. from the description 创建光栅化器状态和视口从description中

Now that the render targets are setup we can continue on to some extra functions that will give us more control over our scenes for future tutorials. First thing is we'll create is a rasterizer state. This will give us control over how polygons are rendered. We can do things like make our scenes render in wireframe mode or have DirectX draw both the front and back faces of polygons. By default DirectX already has a rasterizer state set up and working the exact same as the one below but you have no control to change it unless you set up one yourself.

现在我们已经设置了渲染目标,我们可以继续使用一些额外的功能,这些功能可以让我们更好地控制场景,以备将来的教程使用。首先,我们将创建一个光栅化器状态。这将使我们能够控制多边形的渲染方式。我们可以做一些事情,比如让我们的场景渲染为线框模式,或让DirectX绘制多边形的正面和背面。默认情况下,DirectX已经设置了光栅化器状态并且工作方式与下面的完全相同,但除非您自己设置,否则无法控制它。

	// Setup the raster description which will determine how and what polygons will be drawn.
        //设置光栅描述,该描述将决定如何绘制多边形以及绘制多边形。
        rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
        //从我们刚刚填写的描述中创建光栅化器状态。
	result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if(FAILED(result))
	{
		return false;
	}

	// Now set the rasterizer state.
        // 现在设置光栅化器状态。
	m_deviceContext->RSSetState(m_rasterState);
The viewport also needs to be setup so that Direct3D can map clip space coordinates to the render target space. Set this to be the entire size of the window.

	// Setup the viewport for rendering.
        //设置视口以进行渲染。
	viewport.Width = (float)screenWidth;
	viewport.Height = (float)screenHeight;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;

	// Create the viewport.
        //创建视口
	m_deviceContext->RSSetViewports(1, &viewport);

ID3D11DeviceContext::RSSetState method ID3D11DeviceContext :: RSSetState方法

Set the rasterizer state for the rasterizer stage of the pipeline.

为管道的光栅化器阶段设置光栅化器状态。

Syntax

void RSSetState(
  ID3D11RasterizerState *pRasterizerState
);

Parameters
pRasterizerState

Type: ID3D11RasterizerState*

Pointer to a rasterizer-state interface (see ID3D11RasterizerState) to bind to the pipeline.
指向光栅化器状态接口(请参阅ID3D11RasterizerState)以指向管道的指针。

Return Value
Returns nothing.

Remarks
To create a rasterizer state interface, call ID3D11Device::CreateRasterizerState.

要创建光栅化器状态接口,请调用ID3D11Device :: CreateRasterizerState。

The method will hold a reference to the interfaces passed in. This differs from the device state behavior in Direct3D 10.

该方法将保存对传入的接口的引用。这与Direct3D 10中的设备状态行为不同。

ID3D11DeviceContext::RSSetViewports method ID3D11DeviceContext :: RSSetViewports方法

Bind an array of viewports to the rasterizer stage of the pipeline.

Syntax


void RSSetViewports(
  UINT                 NumViewports,
  const D3D11_VIEWPORT *pViewports
);

Parameters
NumViewports

Type: UINT

Number of viewports to bind.

要绑定的视口数。

pViewports

Type: const D3D11_VIEWPORT*

An array of D3D11_VIEWPORT structures to bind to the device. See the structure page for details about how the viewport size is dependent on the device feature level which has changed between Direct3D 11 and Direct3D 10.

用于绑定到设备的D3D11_VIEWPORT结构数组。有关视口大小如何依赖于Direct3D 11和Direct3D 10之间已更改的设备功能级别的详细信息,请参阅结构页面。

Return Value
Returns nothing.
什么都不返回

Remarks
All viewports must be set atomically as one operation. Any viewports not defined by the call are disabled.

必须将所有视口原子设置为一个操作。任何未通过调用定义的视口都将被禁用。

Which viewport to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader; if a geometry shader does not specify the semantic, Direct3D will use the first viewport in the array.

要使用的视口由几何着色器的SV_ViewportArrayIndex语义输出确定;如果几何着色器未指定语义,则Direct3D将使用数组中的第一个视口。

Note Even though you specify float values to the members of the D3D11_VIEWPORT structure for the pViewports array in a call to ID3D11DeviceContext::RSSetViewports for feature levels 9_x, RSSetViewports uses DWORDs internally. Because of this behavior, when you use a negative top left corner for the viewport, the call to RSSetViewports for feature levels 9_x fails. This failure occurs because RSSetViewports for 9_x casts the floating point values into unsigned integers without validation, which results in integer overflow.

注意即使在为ID3D11DeviceContext :: RSSetViewports调用功能级别9_x时为pViewports数组的D3D11_VIEWPORT结构的成员指定浮点值,RSSetViewports也会在内部使用DWORD。由于此行为,当您对视口使用负左上角时,对功能级别9_x的RSSetViewports的调用将失败。发生此故障是因为用于9_x的RSSetViewports将浮点值转换为无符号整数而未进行验证,从而导致整数溢出。


Setup the projection matrix, world matrix and orthographic projection matrix 设置投影矩阵,世界矩阵和正交投影矩阵

Now we will create the projection matrix. The projection matrix is used to translate the 3D scene into the 2D viewport space that we previously created. We will need to keep a copy of this matrix so that we can pass it to our shaders that will be used to render our scenes.

现在我们将创建投影矩阵。投影矩阵用于将3D场景转换为我们先前创建的2D视口空间。我们需要保留此矩阵的副本,以便我们可以将其传递给将用于渲染场景的着色器。

	// Setup the projection matrix.
        //设置投影矩阵。
	fieldOfView = 3.141592654f / 4.0f;
	screenAspect = (float)screenWidth / (float)screenHeight;

	// Create the projection matrix for 3D rendering.
        //为3D渲染创建投影矩阵。
	m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);

We will also create another matrix called the world matrix. This matrix is used to convert the vertices of our objects into vertices in the 3D scene. This matrix will also be used to rotate, translate, and scale our objects in 3D space. From the start we will just initialize the matrix to the identity matrix and keep a copy of it in this object. The copy will be needed to be passed to the shaders for rendering also.

们还将创建另一个称为世界矩阵的矩阵。此矩阵用于将对象的顶点转换为3D场景中的顶点。此矩阵还将用于在3D空间中旋转,平移和缩放对象。从一开始,我们将矩阵初始化为单位矩阵,并在此对象中保留它的副本。副本将需要传递给着色器以进行渲染。

	// Initialize the world matrix to the identity matrix.
        //将世界矩阵初始化为单位矩阵。
	m_worldMatrix = XMMatrixIdentity();

This is where you would generally create a view matrix. The view matrix is used to calculate the position of where we are looking at the scene from. You can think of it as a camera and you only view the scene through this camera. Because of its purpose I am going to create it in a camera class in later tutorials since logically it fits better there and just skip it for now.

这是您通常创建视图矩阵的地方。视图矩阵用于计算我们从哪里看场景的位置。您可以将其视为相机,并且只能通过此相机查看场景。由于它的目的,我将在后面的教程中在相机类中创建它,因为逻辑上它更适合那里,现在就先跳过它(的创建)。

And the final thing we will setup in the Initialize function is an orthographic projection matrix. This matrix is used for rendering 2D elements like user interfaces on the screen allowing us to skip the 3D rendering. You will see this used in later tutorials when we look at rendering 2D graphics and fonts to the screen.

我们将在Initialize函数中设置的最后一项是正交投影矩阵。该矩阵用于渲染2D元素,如屏幕上的用户界面,允许我们跳过3D渲染。当我们看到将2D图形和字体渲染到屏幕时,您将在后面的教程中看到这个。

	// Create an orthographic projection matrix for 2D rendering.
	m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);

	return true;
}
posted @ 2019-01-24 23:35  威化饼干  阅读(750)  评论(0编辑  收藏  举报