【Visual C++】游戏开发笔记三十 DirectX11 2D纹理映射知识全攻略

本系列文章由zhmxy555(毛星云)编写,转载请注明出处。

http://blog.csdn.net/zhmxy555/article/details/7801729

作者:毛星云 邮箱: happylifemxy@163.com

本节知识先是对DirectX11关于2D纹理映射方面基础知识的一个讲解,然后通过一个demo的创建过程来将学到的理论知识付诸实践。

一、引言

在之前我们提到过,纹理实际上就是映射到物体表面的数据。其实,纹理也可能是其他的一些信息片段,比如用于映射的常规映射值,用于控制透明度的alpha值,等等。

通常情况下,纹理是通过一个叫做纹理映射的过程来映射一幅图像到表面上的颜色值,这种功能能显著地增加所绘制场景的细腻感和真实感。

纹理和游戏开发中需要的其他数据一样,通常都是在运行时加载的。由于纹理是Direct3D重要的组成的部分,微软为我们提供了众多功能强大而丰富的Direct3D内建的函数,来处理纹理相关的操作。

二、基础知识讲解

1.纹理的加载

在Direct3D11中,我们通常使用D3DX11CreateTextureFromFile函数用于从硬盘文件中加载纹理。这个函数支持非常丰富的图像格式,比如BMP,PNG,以及DDS。D3DX11CreateTextureFromFile函数拥有六个变量,具有以下的函数原型:

  1. HRESULT D3DX11CreateTextureFromFile(
  2. ID3D11Device* pDevice,
  3. LPCTSTR pSrcFile,
  4. D3DX11_IMAGE_LOAD_INFO* pLoadInfo,
  5. ID3DX11ThreadPump* pPump,
  6. ID3D11Resource** ppTexture,
  7. HRESULT* pHResult
  8. );
HRESULT D3DX11CreateTextureFromFile(

ID3D11Device* pDevice,

LPCTSTR pSrcFile,

D3DX11_IMAGE_LOAD_INFO* pLoadInfo,

ID3DX11ThreadPump* pPump,

ID3D11Resource** ppTexture,

HRESULT* pHResult

);


D3DX11CreateTextureFromFile函数的第一个的参数为ID3D11Device类型的指针变量。

第二个参数pSrcFile为被加载文件的文件路径和文件名。

第三个参数pLoadInfo为一个图形信息结构体。它为一个可选的参数,并允许我们通过指定CPU访问的标识、内部格式、宽度和高度来控制图像纹理的加载方式。

第四个参数pPump用于多线程加载纹理时的异步处理。

第五个参数ppTexture用是纹理对象被调用时这个函数创建出的地址。如果D3DX11CreateTextureFromFile函数调用成功,这个变量就会拥有一个现成的纹理供使用。

最后一个参数pHResult是指向线程返回值的指针。

若此线程的参数不为空,pHResult必须为一个有效的内存地址。在Direct3D中我们能够使用很多函数载入各种琳琅满目的图

像文件格式,下面我们对他们进行一个详细的列举:

Windows Bitmap (BMP)

Joint Photographic Expert Group—i.e., JPEG (JPG)

Portable Network Graphics (PNG)

Tagged Image Format (TIFF)

Graphics Interchange Format (GIF)

DirectDraw Surface (DDS)

Windows Media Player (WMP)

2.纹理接口

纹理接口通常用于管理一个特定类型的图像数据。目前Direct3D纹理接口主要有三种类型,他们分别是:

ID3D11Texture1D——用于1D或者条形的纹理

ID3D11Texture2D——用于2D数据,这也是最常用的纹理资源类型、

ID3D11Texture3D——用于表示3D数据的纹理资源类型

上述3种纹理资源类型都包含一个或者多个子资源。

而游戏开发中使用的大多数纹理类型基本上都为二维的,他们都需要转化为ID3D11Texture2D型资源后再使用。而这些子资源代表了纹理中不同的 MIP等级。

譬如Adobe’s Photoshop这类的图像编辑器是创造2D纹理的最得力帮手。

3. 纹理细节

在游戏开发的过程中,常常我们需要从加载的纹理中得到一些特定的信息,比如说维度或者像素格式。这时候隶属于ID3D11Texture2D中的GetDesc函数就可以派上用场了。这个函数的功能是为我们填充D3D11_TEXTURE2D_DESC结构体中的各种细节,从而通过这个结构体作为载体,有关的各类数据就一目了然了。

D3D11_TEXTURE2D_DESC是专用于2D纹理的纹理描述结构体家族中的一员。

对于其他的两个维度,Direct3D11为我们准备了D3D11_TEXTURE1D_DESC用于1D纹理,D3D11_TEXTURE3D_DESC用于3D纹理。

作为最常见的纹理,二维的D3D11_TEXTURE2D_DESC声明形式如下:

  1. typedef struct D3D11_TEXTURE2D_DESC {
  2. UINT Width;
  3. UINT Height;
  4. UINT MipLevels;
  5. UINT ArraySize;
  6. DXGI_FORMAT Format;
  7. DXGI_SAMPLE_DESC SampleDesc;
  8. D3D11_USAGE Usage;
  9. UINT BindFlags;
  10. UINT CPUAccessFlags;
  11. UINT MiscFlags;
  12. } D3D11_TEXTURE2D_DESC;
typedef struct D3D11_TEXTURE2D_DESC {

UINT Width;

UINT Height;

UINT MipLevels;

UINT ArraySize;

DXGI_FORMAT Format;

DXGI_SAMPLE_DESC SampleDesc;

D3D11_USAGE Usage;

UINT BindFlags;

UINT CPUAccessFlags;

UINT MiscFlags;

} D3D11_TEXTURE2D_DESC;


三、DirectX11 2D纹理映射demo的创建

这里,我们先介绍一下这个demo的组成结构:

如图,头文件有Dx11DemoBase.h以及Texture2DDemo.h

源文件有 Dx11DemoBase.cpp,Texture2DDemo.h以及main.cpp

在之前的TriangleDemo的基础上,我们再添加一个叫做TextureDemo的类,以及添加一个叫做colorMap_的D3D11ShaderResourceView类型的着色器资源视图和一个D3D11SamplerState类型的唤做colorMapSampler_ 的采样状态。

着色资源视图简单的来说是一个用于访问资源的对象。当我们加载纹理到内存中的时候,必须创建一个着色器资源视图来通过着色器获取数据,而这些数据会被绑定到输出程序集当中。着色器资源视图也有其他的作用,比如为DirectCompute提供异步运算时需要的数据,本节我们主要是介绍其在纹理方面的运用。ID3D11Texture2D代表数据的缓存,而着色器资源视图允许我们在着色器中查看这个缓存的各项数据。

采样器声明(sampler state)允许我们访问的纹理采样的状态信息。后面将对其做更多更详细的讲解。

TextureDemo类的头文件代码书写风格如下:

代码段一 TextureDemo.h 对TextureDemo类的轮廓书写

  1. #ifndef _TEXTURE_2D_DEMO_H_
  2. #define _TEXTURE_2D_DEMO_H_
  3. #include"Dx11DemoBase.h"
  4. class TextureDemo : public Dx11DemoBase
  5. {
  6. public:
  7. TextureDemo( );
  8. virtual ~TextureDemo( );
  9. bool LoadContent( );
  10. void UnloadContent( );
  11. void Update( float dt );
  12. void Render( );
  13. private:
  14. ID3D11VertexShader* solidColorVS_;
  15. ID3D11PixelShader* solidColorPS_;
  16. ID3D11InputLayout* inputLayout_;
  17. ID3D11Buffer* vertexBuffer_;
  18. ID3D11ShaderResourceView* colorMap_;
  19. ID3D11SamplerState* colorMapSampler_;
  20. };
  21. #endif
#ifndef _TEXTURE_2D_DEMO_H_
#define _TEXTURE_2D_DEMO_H_

#include"Dx11DemoBase.h"


class TextureDemo : public Dx11DemoBase
{
    public:
        TextureDemo( );
        virtual ~TextureDemo( );

        bool LoadContent( );
        void UnloadContent( );

        void Update( float dt );
        void Render( );

    private:
        ID3D11VertexShader* solidColorVS_;
        ID3D11PixelShader* solidColorPS_;

        ID3D11InputLayout* inputLayout_;
        ID3D11Buffer* vertexBuffer_;

        ID3D11ShaderResourceView* colorMap_;
        ID3D11SamplerState* colorMapSampler_;
};

#endif


由于我们正在执行纹理映射这项操作,我们需要对顶点结构体的代码进行更新,使其包含两个浮点型的变量。这项工作可由XMFLOAT2结构体来完成。

代码段二中展示了这个demo中顶点结构体,LoadContent,函数和 UnloadContent函数的写法

代码段二 顶点结构体以及 LoadContent和UnloadContent的书写

  1. struct VertexPos
  2. {
  3. XMFLOAT3 pos;
  4. XMFLOAT2 tex0;
  5. };
  6. bool TextureDemo::LoadContent( )
  7. {
  8. ... Load vertex Shader ...
  9. D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
  10. {
  11. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
  12. 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  13. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,
  14. 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
  15. };
  16. unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout );
  17. d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout,
  18. totalLayoutElements, vsBuffer->GetBufferPointer( ),
  19. vsBuffer->GetBufferSize( ), &inputLayout_ );
  20. ... Load Pixel Shader ...
  21. VertexPos vertices[] =
  22. {
  23. { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
  24. { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
  25. { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
  26. { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
  27. { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
  28. { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
  29. };
  30. ... Create Vertex Buffer ...
  31. d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_,
  32. "decal.dds", 0, 0, &colorMap_, 0 );
  33. if( FAILED( d3dResult ) )
  34. {
  35. DXTRACE_MSG( "Failed to load the texture image!" );
  36. return false;
  37. }
  38. D3D11_SAMPLER_DESC colorMapDesc;
  39. ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) );
  40. colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  41. colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  42. colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  43. colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
  44. colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  45. colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX;
  46. d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc,
  47. &colorMapSampler_ );
  48. if( FAILED( d3dResult ) )
  49. {
  50. DXTRACE_MSG( "Failed to create color map sampler state!" );
  51. return false;
  52. }
  53. return true;
  54. }
  55. void TextureDemo::UnloadContent( )
  56. {
  57. if( colorMapSampler_ ) colorMapSampler_->Release( );
  58. if( colorMap_ ) colorMap_->Release( );
  59. if( solidColorVS_ ) solidColorVS_->Release( );
  60. if( solidColorPS_ ) solidColorPS_->Release( );
  61. if( inputLayout_ ) inputLayout_->Release( );
  62. if( vertexBuffer_ ) vertexBuffer_->Release( );
  63. colorMapSampler_ = 0;
  64. colorMap_ = 0;
  65. solidColorVS_ = 0;
  66. solidColorPS_ = 0;
  67. inputLayout_ = 0;
  68. vertexBuffer_ = 0;
  69. }
struct VertexPos

{

XMFLOAT3 pos;

XMFLOAT2 tex0;

};

bool TextureDemo::LoadContent( )

{

... Load vertex Shader ...

D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =

{

{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,

0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },

{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,

0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }

};

unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout );

d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout,

totalLayoutElements, vsBuffer->GetBufferPointer( ),

vsBuffer->GetBufferSize( ), &inputLayout_ );

... Load Pixel Shader ...

VertexPos vertices[] =

{

{ XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },

{ XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },

{ XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },

{ XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },

{ XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

{ XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },

};

... Create Vertex Buffer ...

d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_,

"decal.dds", 0, 0, &colorMap_, 0 );

if( FAILED( d3dResult ) )

{

DXTRACE_MSG( "Failed to load the texture image!" );

return false;

}

D3D11_SAMPLER_DESC colorMapDesc;

ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) );

colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;

colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;

colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;

colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;

colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;

colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX;

d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc,

&colorMapSampler_ );

if( FAILED( d3dResult ) )

{

DXTRACE_MSG( "Failed to create color map sampler state!" );

return false;

}

return true;

}

void TextureDemo::UnloadContent( )

{

if( colorMapSampler_ ) colorMapSampler_->Release( );

if( colorMap_ ) colorMap_->Release( );

if( solidColorVS_ ) solidColorVS_->Release( );

if( solidColorPS_ ) solidColorPS_->Release( );

if( inputLayout_ ) inputLayout_->Release( );

if( vertexBuffer_ ) vertexBuffer_->Release( );

colorMapSampler_ = 0;

colorMap_ = 0;

solidColorVS_ = 0;

solidColorPS_ = 0;

inputLayout_ = 0;

vertexBuffer_ = 0;

}


UnloadContent函数释放了新对象,而LoadContent函数进行了纹理图像的加载。我们可以使用Direct3D中的D3DX11CreateShaderResourceViewFromFile函数(这个函数名是不是略长啊,哈哈),来加载一个纹理然后在一个简单的调用之中创建着色器资源视图。这个函数在我们想毕其功于一役的时候,即希望加载一个纹理连着创建一个新的着色器资源视图一步到位的时候,非常的好用。

D3DX11CreateShaderResourceViewFromFile函数的变量和D3DX11CreateTextureFromFile函数的相似度很高,这员大将有以下原型:

  1. HRESULT D3DX11CreateShaderResourceViewFromFile(
  2. ID3D11Device* pDevice,
  3. LPCTSTR pSrcFile,
  4. D3DX11_IMAGE_LOAD_INFO* pLoadInfo,
  5. ID3DX11ThreadPump* pPump,
  6. ID3D11ShaderResourceView** ppShaderResourceView,
  7. HRESULT* pHResult
  8. );
HRESULT D3DX11CreateShaderResourceViewFromFile(

ID3D11Device* pDevice,

LPCTSTR pSrcFile,

D3DX11_IMAGE_LOAD_INFO* pLoadInfo,

ID3DX11ThreadPump* pPump,

ID3D11ShaderResourceView** ppShaderResourceView,

HRESULT* pHResult

);


LoadContent函数代码的最后一段完成的功能是采样器声明(sampler state)的创建。为了创建一个采样器声明(sampler state)的对象,很容易就可以通过功能联想到函数名——CreateSamplerState。这个函数以采样器描述作为其一个参数。 而采样器描述拥有以下的声明:

  1. typedef struct D3D11_SAMPLER_DESC {
  2. D3D11_FILTER Filter;
  3. D3D11_TEXTURE_ADDRESS_MODE AddressU;
  4. D3D11_TEXTURE_ADDRESS_MODE AddressV;
  5. D3D11_TEXTURE_ADDRESS_MODE AddressW;
  6. FLOAT MipLODBias;
  7. UINT MaxAnisotropy;
  8. D3D11_COMPARISON_FUNC ComparisonFunc;
  9. FLOAT BorderColor[4];
  10. FLOAT MinLOD;
  11. FLOAT MaxLOD;
  12. } D3D11_SAMPLER_DESC;
typedef struct D3D11_SAMPLER_DESC {

D3D11_FILTER Filter;

D3D11_TEXTURE_ADDRESS_MODE AddressU;

D3D11_TEXTURE_ADDRESS_MODE AddressV;

D3D11_TEXTURE_ADDRESS_MODE AddressW;

FLOAT MipLODBias;

UINT MaxAnisotropy;

D3D11_COMPARISON_FUNC ComparisonFunc;

FLOAT BorderColor[4];

FLOAT MinLOD;

FLOAT MaxLOD;

} D3D11_SAMPLER_DESC;


为了渲染我们的几何纹理,我们必须添加纹理资源以及设置采样器描述。这两项特殊的任务分别分配给PSSetShaderResources函数 以及 PSSetSamplers函数来完成,设置这些数据到像素着色器之中。PSSetShaderResources函数具有以下原型:

  1. void PSSetShaderResources(
  2. UINT StartSlot,
  3. UINT NumViews,
  4. ID3D11ShaderResourceView* const* ppShaderResourceViews
  5. );
void PSSetShaderResources(

UINT StartSlot,

UINT NumViews,

ID3D11ShaderResourceView* const* ppShaderResourceViews

  

);


PSSetSamplers函数也以起始点StartSlot以及采样数量NumViews作为其参数。我们在之前demo里面关于Render的代码随着这节里面对这两个函数的加入,我们就可以看到更加出色的效果了。目前需要做的就是就修改着色器的渲染效果了。Texture Mappingdemo类的Render函数如下代码段X

代码段三 TextureDemo 类的render函数的书写

  1. void TextureDemo::Render( )
  2. {
  3. if( d3dContext_ == 0 )
  4. return;
  5. float clearColor[4] = { 0.0f, 0.0f, 0.25f, 1.0f };
  6. d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor );
  7. unsigned int stride = sizeof( VertexPos );
  8. unsigned int offset = 0;
  9. d3dContext_->IASetInputLayout( inputLayout_ );
  10. d3dContext_->IASetVertexBuffers( 0, 1, &vertexBuffer_, &stride, &offset );
  11. d3dContext_->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_
  12. TRIANGLELIST );
  13. d3dContext_->VSSetShader( colorMapVS_, 0, 0 );
  14. d3dContext_->PSSetShader( colorMapPS_, 0, 0 );
  15. d3dContext_->PSSetShaderResources( 0, 1, &colorMap_ );
  16. d3dContext_->PSSetSamplers( 0, 1, &colorMapSampler_ );
  17. d3dContext_->Draw( 6, 0 );
  18. swapChain_->Present( 0, 0 );
  19. }
void TextureDemo::Render( )

{

if( d3dContext_ == 0 )

return;

float clearColor[4] = { 0.0f, 0.0f, 0.25f, 1.0f };

d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor );

unsigned int stride = sizeof( VertexPos );

unsigned int offset = 0;

d3dContext_->IASetInputLayout( inputLayout_ );

d3dContext_->IASetVertexBuffers( 0, 1, &vertexBuffer_, &stride, &offset );

d3dContext_->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_

TRIANGLELIST );

d3dContext_->VSSetShader( colorMapVS_, 0, 0 );

d3dContext_->PSSetShader( colorMapPS_, 0, 0 );

d3dContext_->PSSetShaderResources( 0, 1, &colorMap_ );

d3dContext_->PSSetSamplers( 0, 1, &colorMapSampler_ );

d3dContext_->Draw( 6, 0 );

swapChain_->Present( 0, 0 );

}


在着色器之中,如代码段四,我们拥有两个新的全局着色器对象,分别唤作colorMap_和colorSampler_。其中colorSampler_对象的类型为Texture2D,它可以用于2D 纹理之中,而colorSampler_为HLSL(High Level Shader Language高级着色器语言)类型的采样器声明。

为了将这些对象绑定到我们在Render函数中提供的着色器当中,我们需要使用中HLSL(High Level Shader Language高级着色器语言)中的register关键字。绑定第一个纹理输出我们采用t0来表示,其中t代表texture这个单词,0代表数量的索引,即第几个。同理,对于采样器声明,s代表sampler state这个词组,0代表第几个,则s0就代表第一个采样器。因为我们只有一种纹理和一种采样器声明,所以只需t0和s0即可。

着色器当中的另一个需要注意的地方是,我们必须更新顶点着色器以及像素着色器的输入结构来方便地获取纹理坐标。顶点着色器将从顶点缓存中取得纹理坐标,然后将其传递给像素着色器,以便像素着色器方便地访问这些数据。

之后,像素着色器会使用这些纹理坐标和纹理对象来读取颜色值。这一步可以调用HLSL Texture2D对象的Sample函数来完成。

最后提一点,由于我们是从一个2D纹理中读取数据的,则纹理坐标需为float2类型。

在这里列出着色器的构成代码:

代码段四 纹理映射demo中着色器的构成代码

  1. Texture2D colorMap_ : register( t0 );
  2. SamplerState colorSampler_ : register( s0 );
  3. struct VS_Input
  4. {
  5. float4 pos : POSITION;
  6. float2 tex0 : TEXCOORD0;
  7. };
  8. struct PS_Input
  9. {
  10. float4 pos : SV_POSITION;
  11. float2 tex0 : TEXCOORD0;
  12. };
  13. PS_Input VS_Main( VS_Input vertex )
  14. {
  15. PS_Input vsOut = ( PS_Input )0;
  16. vsOut.pos = vertex.pos;
  17. vsOut.tex0 = vertex.tex0;
  18. return vsOut;
  19. }
  20. float4 PS_Main( PS_Input frag ) : SV_TARGET
  21. {
  22. return colorMap_.Sample( colorSampler_, frag.tex0 );
  23. }
Texture2D colorMap_ : register( t0 );

SamplerState colorSampler_ : register( s0 );

struct VS_Input

{

float4 pos : POSITION;

float2 tex0 : TEXCOORD0;

};

struct PS_Input

{

float4 pos : SV_POSITION;

float2 tex0 : TEXCOORD0;

};

PS_Input VS_Main( VS_Input vertex )

{

PS_Input vsOut = ( PS_Input )0;

vsOut.pos = vertex.pos;

vsOut.tex0 = vertex.tex0;

return vsOut;

}

float4 PS_Main( PS_Input frag ) : SV_TARGET

{

return colorMap_.Sample( colorSampler_, frag.tex0 );

}

 


到这一步,核心的代码都书写完毕了,为了观看的方便,浅墨在这里将最重头的Texture2DDemo.cpp贴出来(Texture2DDemo.h见代码段一):

代码段五 Texture2DDemo.cpp实现代码


  1. #include"Texture2DDemo.h"
  2. #include<xnamath.h>
  3. struct VertexPos //结构体
  4. {
  5. XMFLOAT3 pos;
  6. XMFLOAT2 tex0;
  7. };
  8. TextureDemo::TextureDemo( ) : solidColorVS_( 0 ), solidColorPS_( 0 ), //构造函数
  9. inputLayout_( 0 ), vertexBuffer_( 0 ),
  10. colorMap_( 0 ), colorMapSampler_( 0 )
  11. {
  12. }
  13. TextureDemo::~TextureDemo( )
  14. {
  15. }
  16. bool TextureDemo::LoadContent( )
  17. {
  18. ID3DBlob* vsBuffer = 0;
  19. bool compileResult = CompileD3DShader( "TextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer );
  20. if( compileResult == false )
  21. {
  22. DXTRACE_MSG( "编译顶点着色器失败!" );
  23. return false;
  24. }
  25. HRESULT d3dResult;
  26. d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ),
  27. vsBuffer->GetBufferSize( ), 0, &solidColorVS_ );
  28. if( FAILED( d3dResult ) )
  29. {
  30. DXTRACE_MSG( "创建顶点着色器失败!" );
  31. if( vsBuffer )
  32. vsBuffer->Release( );
  33. return false;
  34. }
  35. D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
  36. {
  37. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  38. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
  39. };
  40. unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout );
  41. d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements,
  42. vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ );
  43. vsBuffer->Release( );
  44. if( FAILED( d3dResult ) )
  45. {
  46. DXTRACE_MSG( "创建输入布局失败!" );
  47. return false;
  48. }
  49. ID3DBlob* psBuffer = 0;
  50. compileResult = CompileD3DShader( "TextureMap.fx", "PS_Main", "ps_4_0", &psBuffer );
  51. if( compileResult == false )
  52. {
  53. DXTRACE_MSG( "像素着色器编译失败!" );
  54. return false;
  55. }
  56. d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ),
  57. psBuffer->GetBufferSize( ), 0, &solidColorPS_ );
  58. psBuffer->Release( );
  59. if( FAILED( d3dResult ) )
  60. {
  61. DXTRACE_MSG( "创建像素着色器失败!" );
  62. return false;
  63. }
  64. VertexPos vertices[] =
  65. {
  66. { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
  67. { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
  68. { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
  69. { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
  70. { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
  71. { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
  72. };
  73. D3D11_BUFFER_DESC vertexDesc;
  74. ZeroMemory( &vertexDesc, sizeof( vertexDesc ) );
  75. vertexDesc.Usage = D3D11_USAGE_DEFAULT;
  76. vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  77. vertexDesc.ByteWidth = sizeof( VertexPos ) * 6;
  78. D3D11_SUBRESOURCE_DATA resourceData;
  79. ZeroMemory( &resourceData, sizeof( resourceData ) );
  80. resourceData.pSysMem = vertices;
  81. d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, &resourceData, &vertexBuffer_ );
  82. if( FAILED( d3dResult ) )
  83. {
  84. DXTRACE_MSG( "创建顶点缓存失败!" );
  85. return false;
  86. }
  87. d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_,
  88. "decal.dds", 0, 0, &colorMap_, 0 );
  89. if( FAILED( d3dResult ) )
  90. {
  91. DXTRACE_MSG( "读取纹理图像失败!" );
  92. return false;
  93. }
  94. D3D11_SAMPLER_DESC colorMapDesc;
  95. ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) );
  96. colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  97. colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  98. colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  99. colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
  100. colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  101. colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX;
  102. d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorMapSampler_ );
  103. if( FAILED( d3dResult ) )
  104. {
  105. DXTRACE_MSG( "创建颜色映射采样器声明失败!" );
  106. return false;
  107. }
  108. return true;
  109. }
  110. void TextureDemo::UnloadContent( ) //UnloadContent函数的书写
  111. {
  112. if( colorMapSampler_ ) colorMapSampler_->Release( );
  113. if( colorMap_ ) colorMap_->Release( );
  114. if( solidColorVS_ ) solidColorVS_->Release( );
  115. if( solidColorPS_ ) solidColorPS_->Release( );
  116. if( inputLayout_ ) inputLayout_->Release( );
  117. if( vertexBuffer_ ) vertexBuffer_->Release( );
  118. colorMapSampler_ = 0;
  119. colorMap_ = 0;
  120. solidColorVS_ = 0;
  121. solidColorPS_ = 0;
  122. inputLayout_ = 0;
  123. vertexBuffer_ = 0;
  124. }
  125. void TextureDemo::Update( float dt )
  126. {
  127. // 无需进行更新
  128. }
  129. void TextureDemo::Render( ) //Render函数的书写
  130. {
  131. if( d3dContext_ == 0 )
  132. return;
  133. float clearColor[4] = { 0.0f, 0.0f, 0.25f, 1.0f };
  134. d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor );
  135. unsigned int stride = sizeof( VertexPos );
  136. unsigned int offset = 0;
  137. d3dContext_->IASetInputLayout( inputLayout_ );
  138. d3dContext_->IASetVertexBuffers( 0, 1, &vertexBuffer_, &stride, &offset );
  139. d3dContext_->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
  140. d3dContext_->VSSetShader( solidColorVS_, 0, 0 );
  141. d3dContext_->PSSetShader( solidColorPS_, 0, 0 );
  142. d3dContext_->PSSetShaderResources( 0, 1, &colorMap_ );
  143. d3dContext_->PSSetSamplers( 0, 1, &colorMapSampler_ );
  144. d3dContext_->Draw( 6, 0 );
  145. swapChain_->Present( 0, 0 );
  146. }
#include"Texture2DDemo.h"
#include<xnamath.h>


struct VertexPos               //结构体
{
    XMFLOAT3 pos;
    XMFLOAT2 tex0;
};


TextureDemo::TextureDemo( ) : solidColorVS_( 0 ), solidColorPS_( 0 ),      //构造函数
                              inputLayout_( 0 ), vertexBuffer_( 0 ),
                              colorMap_( 0 ), colorMapSampler_( 0 )
{

}


TextureDemo::~TextureDemo( )
{

}


bool TextureDemo::LoadContent( )
{
    ID3DBlob* vsBuffer = 0;

    bool compileResult = CompileD3DShader( "TextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer );

    if( compileResult == false )
    {
        DXTRACE_MSG( "编译顶点着色器失败!" );
        return false;
    }

    HRESULT d3dResult;

    d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ),
        vsBuffer->GetBufferSize( ), 0, &solidColorVS_ );

    if( FAILED( d3dResult ) )
    {
        DXTRACE_MSG( "创建顶点着色器失败!" );

        if( vsBuffer )
            vsBuffer->Release( );

        return false;
    }

    D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

    unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout );

    d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements,
        vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ );

    vsBuffer->Release( );

    if( FAILED( d3dResult ) )
    {
        DXTRACE_MSG( "创建输入布局失败!" );
        return false;
    }

    ID3DBlob* psBuffer = 0;

    compileResult = CompileD3DShader( "TextureMap.fx", "PS_Main", "ps_4_0", &psBuffer );

    if( compileResult == false )
    {
        DXTRACE_MSG( "像素着色器编译失败!" );
        return false;
    }

    d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ),
        psBuffer->GetBufferSize( ), 0, &solidColorPS_ );

    psBuffer->Release( );

    if( FAILED( d3dResult ) )
    {
        DXTRACE_MSG( "创建像素着色器失败!" );
        return false;
    }

    VertexPos vertices[] =
    {
        { XMFLOAT3(  1.0f,  1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3(  1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },

        { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( -1.0f,  1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
        { XMFLOAT3(  1.0f,  1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
    };

    D3D11_BUFFER_DESC vertexDesc;
    ZeroMemory( &vertexDesc, sizeof( vertexDesc ) );
    vertexDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexDesc.ByteWidth = sizeof( VertexPos ) * 6;

    D3D11_SUBRESOURCE_DATA resourceData;
    ZeroMemory( &resourceData, sizeof( resourceData ) );
    resourceData.pSysMem = vertices;

    d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, &resourceData, &vertexBuffer_ );

    if( FAILED( d3dResult ) )
    {
        DXTRACE_MSG( "创建顶点缓存失败!" );
        return false;
    }

    d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_,
        "decal.dds", 0, 0, &colorMap_, 0 );

    if( FAILED( d3dResult ) )
    {
        DXTRACE_MSG( "读取纹理图像失败!" );
        return false;
    }

    D3D11_SAMPLER_DESC colorMapDesc;
    ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) );
    colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX;

    d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorMapSampler_ );

    if( FAILED( d3dResult ) )
    {
        DXTRACE_MSG( "创建颜色映射采样器声明失败!" );
        return false;
    }

    return true;
}


void TextureDemo::UnloadContent( )       //UnloadContent函数的书写
{
    if( colorMapSampler_ ) colorMapSampler_->Release( );
    if( colorMap_ ) colorMap_->Release( );
    if( solidColorVS_ ) solidColorVS_->Release( );
    if( solidColorPS_ ) solidColorPS_->Release( );
    if( inputLayout_ ) inputLayout_->Release( );
    if( vertexBuffer_ ) vertexBuffer_->Release( );

    colorMapSampler_ = 0;
    colorMap_ = 0;
    solidColorVS_ = 0;
    solidColorPS_ = 0;
    inputLayout_ = 0;
    vertexBuffer_ = 0;
}


void TextureDemo::Update( float dt )
{
    // 无需进行更新
}


void TextureDemo::Render( )       //Render函数的书写
{
    if( d3dContext_ == 0 )
        return;

    float clearColor[4] = { 0.0f, 0.0f, 0.25f, 1.0f };  
    d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor );

    unsigned int stride = sizeof( VertexPos );      
    unsigned int offset = 0;

    d3dContext_->IASetInputLayout( inputLayout_ );
    d3dContext_->IASetVertexBuffers( 0, 1, &vertexBuffer_, &stride, &offset );
    d3dContext_->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

    d3dContext_->VSSetShader( solidColorVS_, 0, 0 );
    d3dContext_->PSSetShader( solidColorPS_, 0, 0 );
    d3dContext_->PSSetShaderResources( 0, 1, &colorMap_ );
    d3dContext_->PSSetSamplers( 0, 1, &colorMapSampler_ );
    d3dContext_->Draw( 6, 0 );

    swapChain_->Present( 0, 0 );
}






下面依旧是像前面的几节中的demo一样,对Dx11DemoBase类进行修改,其修改后的代码也在这里列出来:

代码段六 Dx11DemoBase.h实现代码

  1. #ifndef _DEMO_BASE_H_
  2. #define _DEMO_BASE_H_
  3. #include<d3d11.h>
  4. #include<d3dx11.h>
  5. #include<DxErr.h>
  6. class Dx11DemoBase
  7. {
  8. public:
  9. Dx11DemoBase();
  10. virtual ~Dx11DemoBase();
  11. bool Initialize( HINSTANCE hInstance, HWND hwnd );
  12. void Shutdown( );
  13. bool CompileD3DShader( char* filePath, char* entry,
  14. char* shaderModel, ID3DBlob** buffer );
  15. virtual bool LoadContent( );
  16. virtual void UnloadContent( );
  17. virtual void Update( float dt ) = 0;
  18. virtual void Render( ) = 0;
  19. protected:
  20. HINSTANCE hInstance_;
  21. HWND hwnd_;
  22. D3D_DRIVER_TYPE driverType_;
  23. D3D_FEATURE_LEVEL featureLevel_;
  24. ID3D11Device* d3dDevice_;
  25. ID3D11DeviceContext* d3dContext_;
  26. IDXGISwapChain* swapChain_;
  27. ID3D11RenderTargetView* backBufferTarget_;
  28. };
  29. #endif
#ifndef _DEMO_BASE_H_

#define _DEMO_BASE_H_

 

#include<d3d11.h>

#include<d3dx11.h>

#include<DxErr.h>

 

 

class Dx11DemoBase

{

    public:

        Dx11DemoBase();

        virtual ~Dx11DemoBase();

 

        bool Initialize( HINSTANCE hInstance, HWND hwnd );

        void Shutdown( );

 

        bool CompileD3DShader( char* filePath, char* entry,

                               char* shaderModel, ID3DBlob** buffer );

 

        virtual bool LoadContent( );

        virtual void UnloadContent( );

 

        virtual void Update( float dt ) = 0;

        virtual void Render( ) = 0;

 

    protected:

        HINSTANCE hInstance_;

        HWND hwnd_;

 

        D3D_DRIVER_TYPE driverType_;

        D3D_FEATURE_LEVEL featureLevel_;

 

        ID3D11Device* d3dDevice_;

        ID3D11DeviceContext* d3dContext_;

        IDXGISwapChain* swapChain_;

        ID3D11RenderTargetView* backBufferTarget_;

};

 

#endif


代码段七 Dx11DemoBase.cpp实现代码

  1. #include"Dx11DemoBase.h"
  2. #include<D3Dcompiler.h>
  3. Dx11DemoBase::Dx11DemoBase( ) : driverType_( D3D_DRIVER_TYPE_NULL ), featureLevel_( D3D_FEATURE_LEVEL_11_0 ),
  4. d3dDevice_( 0 ), d3dContext_( 0 ), swapChain_( 0 ), backBufferTarget_( 0 )
  5. {
  6. }
  7. Dx11DemoBase::~Dx11DemoBase( )
  8. {
  9. Shutdown( );
  10. }
  11. bool Dx11DemoBase::Initialize( HINSTANCE hInstance, HWND hwnd )
  12. {
  13. hInstance_ = hInstance;
  14. hwnd_ = hwnd;
  15. RECT dimensions;
  16. GetClientRect( hwnd, &dimensions );
  17. unsigned int width = dimensions.right - dimensions.left;
  18. unsigned int height = dimensions.bottom - dimensions.top;
  19. D3D_DRIVER_TYPE driverTypes[] =
  20. {
  21. D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE
  22. };
  23. unsigned int totalDriverTypes = ARRAYSIZE( driverTypes );
  24. D3D_FEATURE_LEVEL featureLevels[] =
  25. {
  26. D3D_FEATURE_LEVEL_11_0,
  27. D3D_FEATURE_LEVEL_10_1,
  28. D3D_FEATURE_LEVEL_10_0
  29. };
  30. unsigned int totalFeatureLevels = ARRAYSIZE( featureLevels );
  31. DXGI_SWAP_CHAIN_DESC swapChainDesc;
  32. ZeroMemory( &swapChainDesc, sizeof( swapChainDesc ) );
  33. swapChainDesc.BufferCount = 1;
  34. swapChainDesc.BufferDesc.Width = width;
  35. swapChainDesc.BufferDesc.Height = height;
  36. swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  37. swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
  38. swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
  39. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  40. swapChainDesc.OutputWindow = hwnd;
  41. swapChainDesc.Windowed = true;
  42. swapChainDesc.SampleDesc.Count = 1;
  43. swapChainDesc.SampleDesc.Quality = 0;
  44. unsigned int creationFlags = 0;
  45. #ifdef _DEBUG
  46. creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
  47. #endif
  48. HRESULT result;
  49. unsigned int driver = 0;
  50. for( driver = 0; driver < totalDriverTypes; ++driver )
  51. {
  52. result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags,
  53. featureLevels, totalFeatureLevels,
  54. D3D11_SDK_VERSION, &swapChainDesc, &swapChain_,
  55. &d3dDevice_, &featureLevel_, &d3dContext_ );
  56. if( SUCCEEDED( result ) )
  57. {
  58. driverType_ = driverTypes[driver];
  59. break;
  60. }
  61. }
  62. if( FAILED( result ) )
  63. {
  64. DXTRACE_MSG( "创建 Direct3D 设备失败!" );
  65. return false;
  66. }
  67. ID3D11Texture2D* backBufferTexture;
  68. result = swapChain_->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&backBufferTexture );
  69. if( FAILED( result ) )
  70. {
  71. DXTRACE_MSG( "获取交换链后台缓存失败!" );
  72. return false;
  73. }
  74. result = d3dDevice_->CreateRenderTargetView( backBufferTexture, 0, &backBufferTarget_ );
  75. if( backBufferTexture )
  76. backBufferTexture->Release( );
  77. if( FAILED( result ) )
  78. {
  79. DXTRACE_MSG( "创建渲染目标视图失败!" );
  80. return false;
  81. }
  82. d3dContext_->OMSetRenderTargets( 1, &backBufferTarget_, 0 );
  83. D3D11_VIEWPORT viewport;
  84. viewport.Width = static_cast<float>(width);
  85. viewport.Height = static_cast<float>(height);
  86. viewport.MinDepth = 0.0f;
  87. viewport.MaxDepth = 1.0f;
  88. viewport.TopLeftX = 0.0f;
  89. viewport.TopLeftY = 0.0f;
  90. d3dContext_->RSSetViewports( 1, &viewport );
  91. return LoadContent( );
  92. }
  93. bool Dx11DemoBase::CompileD3DShader( char* filePath, char* entry, char* shaderModel, ID3DBlob** buffer )
  94. {
  95. DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
  96. #if defined( DEBUG ) || defined( _DEBUG )
  97. shaderFlags |= D3DCOMPILE_DEBUG;
  98. #endif
  99. ID3DBlob* errorBuffer = 0;
  100. HRESULT result;
  101. result = D3DX11CompileFromFile( filePath, 0, 0, entry, shaderModel,
  102. shaderFlags, 0, 0, buffer, &errorBuffer, 0 );
  103. if( FAILED( result ) )
  104. {
  105. if( errorBuffer != 0 )
  106. {
  107. OutputDebugStringA( ( char* )errorBuffer->GetBufferPointer( ) );
  108. errorBuffer->Release( );
  109. }
  110. return false;
  111. }
  112. if( errorBuffer != 0 )
  113. errorBuffer->Release( );
  114. return true;
  115. }
  116. bool Dx11DemoBase::LoadContent( )
  117. {
  118. //重载,进行相关实现
  119. return true;
  120. }
  121. void Dx11DemoBase::UnloadContent( )
  122. {
  123. //重载,进行相关实现
  124. }
  125. void Dx11DemoBase::Shutdown( )
  126. {
  127. UnloadContent( );
  128. if( backBufferTarget_ ) backBufferTarget_->Release( );
  129. if( swapChain_ ) swapChain_->Release( );
  130. if( d3dContext_ ) d3dContext_->Release( );
  131. if( d3dDevice_ ) d3dDevice_->Release( );
  132. backBufferTarget_ = 0;
  133. swapChain_ = 0;
  134. d3dContext_ = 0;
  135. d3dDevice_ = 0;
  136. }
#include"Dx11DemoBase.h"

#include<D3Dcompiler.h>

 

 

Dx11DemoBase::Dx11DemoBase( ) : driverType_( D3D_DRIVER_TYPE_NULL ), featureLevel_( D3D_FEATURE_LEVEL_11_0 ),

                                d3dDevice_( 0 ), d3dContext_( 0 ), swapChain_( 0 ), backBufferTarget_( 0 )

{

 

}

 

 

Dx11DemoBase::~Dx11DemoBase( )

{

    Shutdown( );

}

 

 

bool Dx11DemoBase::Initialize( HINSTANCE hInstance, HWND hwnd )

{

    hInstance_ = hInstance;

    hwnd_ = hwnd;

 

    RECT dimensions;

    GetClientRect( hwnd, &dimensions );

 

    unsigned int width = dimensions.right - dimensions.left;

    unsigned int height = dimensions.bottom - dimensions.top;

 

    D3D_DRIVER_TYPE driverTypes[] =

    {

        D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE

    };

 

    unsigned int totalDriverTypes = ARRAYSIZE( driverTypes );

 

    D3D_FEATURE_LEVEL featureLevels[] =

    {

        D3D_FEATURE_LEVEL_11_0,

        D3D_FEATURE_LEVEL_10_1,

        D3D_FEATURE_LEVEL_10_0

    };

 

    unsigned int totalFeatureLevels = ARRAYSIZE( featureLevels );

 

    DXGI_SWAP_CHAIN_DESC swapChainDesc;

    ZeroMemory( &swapChainDesc, sizeof( swapChainDesc ) );

    swapChainDesc.BufferCount = 1;

    swapChainDesc.BufferDesc.Width = width;

    swapChainDesc.BufferDesc.Height = height;

    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;

    swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;

    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

    swapChainDesc.OutputWindow = hwnd;

    swapChainDesc.Windowed = true;

    swapChainDesc.SampleDesc.Count = 1;

    swapChainDesc.SampleDesc.Quality = 0;

 

    unsigned int creationFlags = 0;

 

#ifdef _DEBUG

    creationFlags |= D3D11_CREATE_DEVICE_DEBUG;

#endif

 

    HRESULT result;

    unsigned int driver = 0;

 

    for( driver = 0; driver < totalDriverTypes; ++driver )

    {

        result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags,

                                                featureLevels, totalFeatureLevels,

                                                D3D11_SDK_VERSION, &swapChainDesc, &swapChain_,

                                                &d3dDevice_, &featureLevel_, &d3dContext_ );

 

        if( SUCCEEDED( result ) )

        {

            driverType_ = driverTypes[driver];

            break;

        }

    }

 

    if( FAILED( result ) )

    {

        DXTRACE_MSG( "创建 Direct3D 设备失败!" );

        return false;

    }

 

    ID3D11Texture2D* backBufferTexture;

 

    result = swapChain_->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&backBufferTexture );

 

    if( FAILED( result ) )

    {

        DXTRACE_MSG( "获取交换链后台缓存失败!" );

        return false;

    }

 

    result = d3dDevice_->CreateRenderTargetView( backBufferTexture, 0, &backBufferTarget_ );

 

    if( backBufferTexture )

        backBufferTexture->Release( );

 

    if( FAILED( result ) )

    {

        DXTRACE_MSG( "创建渲染目标视图失败!" );

        return false;

    }

 

    d3dContext_->OMSetRenderTargets( 1, &backBufferTarget_, 0 );

 

    D3D11_VIEWPORT viewport;

    viewport.Width = static_cast<float>(width);

    viewport.Height = static_cast<float>(height);

    viewport.MinDepth = 0.0f;

    viewport.MaxDepth = 1.0f;

    viewport.TopLeftX = 0.0f;

    viewport.TopLeftY = 0.0f;

 

    d3dContext_->RSSetViewports( 1, &viewport );

 

    return LoadContent( );

}

 

 

bool Dx11DemoBase::CompileD3DShader( char* filePath, char* entry, char* shaderModel, ID3DBlob** buffer )

{

    DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;

 

#if defined( DEBUG ) || defined( _DEBUG )

    shaderFlags |= D3DCOMPILE_DEBUG;

#endif

 

    ID3DBlob* errorBuffer = 0;

    HRESULT result;

 

    result = D3DX11CompileFromFile( filePath, 0, 0, entry, shaderModel,

        shaderFlags, 0, 0, buffer, &errorBuffer, 0 );

 

    if( FAILED( result ) )

    {

        if( errorBuffer != 0 )

        {

            OutputDebugStringA( ( char* )errorBuffer->GetBufferPointer( ) );

            errorBuffer->Release( );

        }

 

        return false;

    }

    

    if( errorBuffer != 0 )

        errorBuffer->Release( );

 

    return true;

}

 

 

bool Dx11DemoBase::LoadContent( )

{

    //重载,进行相关实现

    return true;

}

 

 

void Dx11DemoBase::UnloadContent( )

{

    //重载,进行相关实现

}

 

 

void Dx11DemoBase::Shutdown( )

{

    UnloadContent( );

 

    if( backBufferTarget_ ) backBufferTarget_->Release( );

    if( swapChain_ ) swapChain_->Release( );

    if( d3dContext_ ) d3dContext_->Release( );

    if( d3dDevice_ ) d3dDevice_->Release( );    

 

    backBufferTarget_ = 0;

    swapChain_ = 0;

    d3dContext_ = 0;

    d3dDevice_ = 0;

}


最后的压轴依旧是永远最重要的main函数,其实现代码如下代码段八:

代码段八 main.cpp实现代码

  1. #include<Windows.h>
  2. #include<memory>
  3. #include"Texture2DDemo.h"
  4. LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam );
  5. //****wWinMain函数,程序入口点函数**************************************
  6. int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE prevInstance, LPWSTR cmdLine, int cmdShow )
  7. {
  8. UNREFERENCED_PARAMETER( prevInstance );
  9. UNREFERENCED_PARAMETER( cmdLine );
  10. WNDCLASSEX wndClass = { 0 };
  11. wndClass.cbSize = sizeof( WNDCLASSEX ) ;
  12. wndClass.style = CS_HREDRAW | CS_VREDRAW;
  13. wndClass.lpfnWndProc = WndProc;
  14. wndClass.hInstance = hInstance;
  15. wndClass.hCursor = LoadCursor( NULL, IDC_ARROW );
  16. wndClass.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
  17. wndClass.lpszMenuName = NULL;
  18. wndClass.lpszClassName = "DX11BookWindowClass";
  19. if( !RegisterClassEx( &wndClass ) )
  20. return -1;
  21. RECT rc = { 0, 0, 640, 480 };
  22. AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
  23. HWND hwnd = CreateWindowA( "DX11BookWindowClass", "2D纹理映射演示demo", WS_OVERLAPPEDWINDOW,
  24. CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top,
  25. NULL, NULL, hInstance, NULL );
  26. if( !hwnd )
  27. return -1;
  28. ShowWindow( hwnd, cmdShow );
  29. TextureDemo demo;
  30. // Demo的初始化
  31. bool result = demo.Initialize( hInstance, hwnd );
  32. if( result == false )
  33. return -1;
  34. MSG msg = { 0 };
  35. while( msg.message != WM_QUIT )
  36. {
  37. if( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ) )
  38. {
  39. TranslateMessage( &msg );
  40. DispatchMessage( &msg );
  41. }
  42. // 更新以及绘制
  43. demo.Update( 0.0f );
  44. demo.Render( );
  45. }
  46. // Demo善后工作
  47. demo.Shutdown( );
  48. return static_cast<int>( msg.wParam );
  49. }
  50. //****消息处理函数***********************************
  51. LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam )
  52. {
  53. PAINTSTRUCT paintStruct;
  54. HDC hDC;
  55. switch( message )
  56. {
  57. case WM_PAINT:
  58. hDC = BeginPaint( hwnd, &paintStruct );
  59. EndPaint( hwnd, &paintStruct );
  60. break;
  61. case WM_DESTROY:
  62. PostQuitMessage( 0 );
  63. break;
  64. default:
  65. return DefWindowProc( hwnd, message, wParam, lParam );
  66. }
  67. return 0;
  68. }
#include<Windows.h>

#include<memory>

#include"Texture2DDemo.h"

 

 

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam );

 

//****wWinMain函数,程序入口点函数************************************** 

 

int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE prevInstance, LPWSTR cmdLine, int cmdShow )

{

    UNREFERENCED_PARAMETER( prevInstance );

    UNREFERENCED_PARAMETER( cmdLine );

 

    WNDCLASSEX wndClass = { 0 };

    wndClass.cbSize = sizeof( WNDCLASSEX ) ;

    wndClass.style = CS_HREDRAW | CS_VREDRAW;

    wndClass.lpfnWndProc = WndProc;

    wndClass.hInstance = hInstance;

    wndClass.hCursor = LoadCursor( NULL, IDC_ARROW );

    wndClass.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );

    wndClass.lpszMenuName = NULL;

    wndClass.lpszClassName = "DX11BookWindowClass";

 

    if( !RegisterClassEx( &wndClass ) )

        return -1;

 

    RECT rc = { 0, 0, 640, 480 };

    AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );

 

    HWND hwnd = CreateWindowA( "DX11BookWindowClass", "2D纹理映射演示demo", WS_OVERLAPPEDWINDOW,

                                CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top,

                                NULL, NULL, hInstance, NULL );

 

    if( !hwnd )

        return -1;

 

    ShowWindow( hwnd, cmdShow );

 

    TextureDemo demo;

 

    // Demo的初始化

    bool result = demo.Initialize( hInstance, hwnd );

 

    if( result == false )

        return -1;

 

    MSG msg = { 0 };

 

    while( msg.message != WM_QUIT )

    {

        if( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ) )

        {

            TranslateMessage( &msg );

            DispatchMessage( &msg );

        }

 

        // 更新以及绘制

        demo.Update( 0.0f );

        demo.Render( );

    }

 

    // Demo善后工作

    demo.Shutdown( );

 

    return static_cast<int>( msg.wParam );

}

 

 

//****消息处理函数*********************************** 

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam )

{

    PAINTSTRUCT paintStruct;

    HDC hDC;

 

    switch( message )

    {

        case WM_PAINT:

            hDC = BeginPaint( hwnd, &paintStruct );

            EndPaint( hwnd, &paintStruct );

            break;

 

        case WM_DESTROY:

            PostQuitMessage( 0 );

            break;

 

        default:

            return DefWindowProc( hwnd, message, wParam, lParam );

    }

 

    return 0;

}


最后编译及运行,我们可以得到如下演示2D纹理映射的窗口:

本节到这里就结束了。

本篇文章配套源代码请点击这里下载:【Visual C++】Note_Code_30

感谢一直支持【Visual C++】游戏开发笔记系列专栏的朋友们。

【Visual C++】游戏开发 系列文章才刚刚展开一点而已,因为游戏世界实在是太博大精深了~

但我们不能着急,得慢慢打好基础。做学问最忌好高骛远,不是吗?

浅墨希望看到大家的留言,希望与大家共同交流,希望得到睿智的评论(即使是批评)。

你们的支持是我写下去的动力~

精通游戏开发的路还很长很长,非常希望能和大家一起交流,共同学习,共同进步。

大家看过后觉得值得一看的话,可以顶一下这篇文章,你们的支持是我继续写下去的动力~

如果文章中有什么疏漏的地方,也请大家指正。也希望大家可以多留言来和我探讨相关的问题。

最后,谢谢你们一直的支持~~~

——————————浅墨于2012年7月30日

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值