显示功能是在视图类中完成的,所以DX10的初始化及绘制工作都是视图类中完成。
首先建立一个多文档工程,工程名为02_01,在视图类头文件中加载相关的库,并包含头文件:
在视图类的头文件中添加DX10相关的成员:
其中三个变换矩阵、m_device以及显卡有关信息通过五个公有函数访问:
下面是DX具体的初始化过程,封装为一个视图类的成员函数InitDX()。
DX初始化过程中需要创建设备和交换链,在创建交换链的时候用到和视图窗口有关的几个参数:窗口的宽、高和窗口的句柄:
接下来是交换链、纹理资源、2D纹理描述结构体等,其中screenNear和screenDepth是渲染的深度范围,m_vsync_enabled设置为真,表明后面会根据实际的硬件设备设置刷新率,否则是尽可能快地刷新:
以下代码填充DXGI_SWAP_CHAIN_DESC结构体中在初始化过程中用到的一些成员:
// Initialize the swap chain description.
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
// Set to a single back buffer.
swapChainDesc.BufferCount = 1;
// Set the width and height of the back buffer.
swapChainDesc.BufferDesc.Width = screenWidth;
swapChainDesc.BufferDesc.Height = screenHeight;
// Set regular 32-bit surface for the back buffer.
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// Set the refresh rate of the back buffer.
if(m_vsync_enabled)
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 1;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 60;
}
else
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
// Set the usage of the back buffer.
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
// Set the handle for the window to render to.
swapChainDesc.OutputWindow = hwnd;
// Turn multisampling off.
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
// Set to full screen or windowed mode.
swapChainDesc.Windowed = true;
// Set the scan line ordering and scaling to unspecified.
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// Discard the back buffer contents after presenting.
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
// Don't set the advanced flags.
swapChainDesc.Flags = 0;