教程5:纹理贴图

原文链接

本教程将介绍如何在 DirectX 11 中使用纹理,纹理使我们能够通过将照片和其他图像应用到多边形面上,为场景添加真实感。

例如,在本教程中,我们将使用如下图像:

纹理贴图

然后将其应用于上一教程中的多边形,以生成如下内容:

纹理效果

我们将使用的纹理格式是 .tga 文件,这是支持红色、绿色、蓝色和 alpha 通道的常见图形格式。你可以使用任何通用图像编辑软件创建和编辑 targa 文件,这种文件格式一般是可以直接使用的。

在我们进入代码之前,我们应该讨论纹理贴图是如何工作的。

我们使用所谓的 Texel 坐标系(纹理坐标系)来将 .tga 格式图片的像素映射到多边形上,该系统将像素的整数值转换为介于 0.0f 和 1.0f 之间的浮点值;例如,如果纹理宽度为 256 像素宽,则 1 个像素将映射到 0.0f,第 256 个像素将映射到 1.0f,中间第 128 个像素将映射到 0.5f。

在纹理坐标系中,宽度值命名为 “U”,高度值命名为 “V”,宽度从左到右为 0.0 ~ 1.0,高度从顶部到底部为 0.0 ~ 1.0。例如,左上角表示为 U 0.0,V 0.0,右下角表示为 U 1.0,V 1.0

我在下面做了一个图表来说明这个系统:

纹理贴图坐标系

现在我们已经基本了解了如何将纹理映射到多边形上,我们可以看看本教程更新后的框架:

框架示意图

相较于一个教程,对框架的更改是:在 ModelClass 中的新增了 TextureClass,并使用 TextureShaderClass 替换了 ColorShaderClass

我们先来看 HLSL 纹理着色器部分的代码。

Texture.vs

纹理顶点着色器与之前的颜色着色器类似,只是有一些更改以适应纹理。

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: texture.vs
  3. ////////////////////////////////////////////////////////////////////////////////
  4. /////////////
  5. // GLOBALS //
  6. /////////////
  7. cbuffer MatrixBuffer
  8. {
  9. matrix worldMatrix;
  10. matrix viewMatrix;
  11. matrix projectionMatrix;
  12. };

我们不再在顶点类型中使用颜色,而是使用纹理坐标。

由于纹理坐标的 U和V 为浮点坐标,因此我们使用 float2 作为其类型。

对于顶点着色器和像素着色器,纹理坐标的语义为 TEXCOORD0,你可以将 0 更改为任意数字,以指示你正在使用的坐标集,允许使用多个纹理坐标。

  1. //////////////
  2. // TYPEDEFS //
  3. //////////////
  4. struct VertexInputType
  5. {
  6. float4 position : POSITION;
  7. float2 tex : TEXCOORD0;
  8. };
  9. struct PixelInputType
  10. {
  11. float4 position : SV_POSITION;
  12. float2 tex : TEXCOORD0;
  13. };
  14. ////////////////////////////////////////////////////////////////////////////////
  15. // Vertex Shader
  16. ////////////////////////////////////////////////////////////////////////////////
  17. PixelInputType TextureVertexShader(VertexInputType input)
  18. {
  19. PixelInputType output;
  20. // Change the position vector to be 4 units for proper matrix calculations.
  21. input.position.w = 1.0f;
  22. // Calculate the position of the vertex against the world, view, and projection matrices.
  23. output.position = mul(input.position, worldMatrix);
  24. output.position = mul(output.position, viewMatrix);
  25. output.position = mul(output.position, projectionMatrix);

与上一教程中的颜色顶点着色器相比,纹理顶点着色器的唯一区别在于,我们不从输入顶点获取颜色的副本,而是获取纹理坐标的副本并将其传递给像素着色器。

  1. // Store the texture coordinates for the pixel shader.
  2. output.tex = input.tex;
  3. return output;
  4. }

Texture.ps

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: texture.ps
  3. ////////////////////////////////////////////////////////////////////////////////

纹理像素着色器有两个全局变量:

第一个是 Texture2D shaderTexture,它是纹理资源,用于在模型上渲染纹理;

第二个新变量是 SampleState SampleType,采样器状态允许我们修改着色时像素写入多边形面的方式,例如,如果多边形非常遥远,并且在屏幕上只有 8 个像素,那么我们使用采样状态来确定将实际绘制原始纹理中的哪些像素或像素的组合。

原始纹理可能是 256 x 256 像素,因此决定绘制哪些像素对于确保纹理在非常小的多边形面上看起来仍然正常非常重要;我们还将在 TextureShaderClass 中设置采样器状态,然后将其附加到资源指针,以便该像素着色器可以使用它来确定要绘制的像素样本。

  1. /////////////
  2. // GLOBALS //
  3. /////////////
  4. Texture2D shaderTexture;
  5. SamplerState SampleType;

纹理像素着色器的 PixelInputType 也会使用纹理坐标而不是颜色值进行修改。

  1. //////////////
  2. // TYPEDEFS //
  3. //////////////
  4. struct PixelInputType
  5. {
  6. float4 position : SV_POSITION;
  7. float2 tex : TEXCOORD0;
  8. };

像素着色器已被修改,因此它现在使用 HLSL 的采样函数。

采样函数使用我们上面定义的采样器状态和该像素的纹理坐标,它使用这两个变量来确定并返回多边形面上该 UV 位置的像素值。

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Pixel Shader
  3. ////////////////////////////////////////////////////////////////////////////////
  4. float4 TexturePixelShader(PixelInputType input) : SV_TARGET
  5. {
  6. float4 textureColor;
  7. // Sample the pixel color from the texture using the sampler at this texture coordinate location.
  8. textureColor = shaderTexture.Sample(SampleType, input.tex);
  9. return textureColor;
  10. }

Textureshaderclass.h

TextureShaderClass 只是上一教程中 ColorShaderClass 的更新版本,此类将用于使用顶点和像素着色器绘制 3D 模型。

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: textureshaderclass.h
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #ifndef _TEXTURESHADERCLASS_H_
  5. #define _TEXTURESHADERCLASS_H_
  6. //////////////
  7. // INCLUDES //
  8. //////////////
  9. #include <d3d11.h>
  10. #include <d3dcompiler.h>
  11. #include <directxmath.h>
  12. #include <fstream>
  13. using namespace DirectX;
  14. using namespace std;
  15. ////////////////////////////////////////////////////////////////////////////////
  16. // Class name: TextureShaderClass
  17. ////////////////////////////////////////////////////////////////////////////////
  18. class TextureShaderClass
  19. {
  20. private:
  21. struct MatrixBufferType
  22. {
  23. XMMATRIX world;
  24. XMMATRIX view;
  25. XMMATRIX projection;
  26. };
  27. public:
  28. TextureShaderClass();
  29. TextureShaderClass(const TextureShaderClass&);
  30. ~TextureShaderClass();
  31. bool Initialize(ID3D11Device*, HWND);
  32. void Shutdown();
  33. bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*);
  34. private:
  35. bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
  36. void ShutdownShader();
  37. void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
  38. bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*);
  39. void RenderShader(ID3D11DeviceContext*, int);
  40. private:
  41. ID3D11VertexShader* m_vertexShader;
  42. ID3D11PixelShader* m_pixelShader;
  43. ID3D11InputLayout* m_layout;
  44. ID3D11Buffer* m_matrixBuffer;

采样器状态指针有一个新的私有变量,该指针将用于与纹理着色器通信。

  1. ID3D11SamplerState* m_sampleState;
  2. };
  3. #endif

Textureshaderclass.cpp

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: textureshaderclass.cpp
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #include "textureshaderclass.h"
  5. TextureShaderClass::TextureShaderClass()
  6. {
  7. m_vertexShader = 0;
  8. m_pixelShader = 0;
  9. m_layout = 0;
  10. m_matrixBuffer = 0;

新的采样器变量在类构造函数中设置为空。

  1. m_sampleState = 0;
  2. }
  3. TextureShaderClass::TextureShaderClass(const TextureShaderClass& other)
  4. {
  5. }
  6. TextureShaderClass::~TextureShaderClass()
  7. {
  8. }
  9. bool TextureShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
  10. {
  11. bool result;

新的 texture.vs 和 texture.ps 这两个 HLSL 文件为这个着色器而加载。

  1. // Initialize the vertex and pixel shaders.
  2. result = InitializeShader(device, hwnd, L"../Engine/texture.vs", L"../Engine/texture.ps");
  3. if(!result)
  4. {
  5. return false;
  6. }
  7. return true;
  8. }

Shutdown 函数调用着色器变量的释放函数。

  1. void TextureShaderClass::Shutdown()
  2. {
  3. // Shutdown the vertex and pixel shaders as well as the related objects.
  4. ShutdownShader();
  5. return;
  6. }

渲染函数现在采用一个名为 texture 的新参数,该参数是指向纹理资源的指针,然后将其发送到 SetShaderParameters 函数中,以便可以在着色器中设置用于渲染的纹理。

  1. bool TextureShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
  2. XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
  3. {
  4. bool result;
  5. // Set the shader parameters that it will use for rendering.
  6. result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture);
  7. if(!result)
  8. {
  9. return false;
  10. }
  11. // Now render the prepared buffers with the shader.
  12. RenderShader(deviceContext, indexCount);
  13. return true;
  14. }

InitializeShader 设置纹理着色器。

  1. bool TextureShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
  2. {
  3. HRESULT result;
  4. ID3D10Blob* errorMessage;
  5. ID3D10Blob* vertexShaderBuffer;
  6. ID3D10Blob* pixelShaderBuffer;
  7. D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
  8. unsigned int numElements;
  9. D3D11_BUFFER_DESC matrixBufferDesc;

我们有一个新的变量来保存纹理采样器的描述,该采样器将在此函数中设置。

  1. D3D11_SAMPLER_DESC samplerDesc;
  2. // Initialize the pointers this function will use to null.
  3. errorMessage = 0;
  4. vertexShaderBuffer = 0;
  5. pixelShaderBuffer = 0;

加载新的纹理顶点和像素着色器。

  1. // Compile the vertex shader code.
  2. result = D3DCompileFromFile(vsFilename, NULL, NULL, "TextureVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
  3. &vertexShaderBuffer, &errorMessage);
  4. if(FAILED(result))
  5. {
  6. // If the shader failed to compile it should have writen something to the error message.
  7. if(errorMessage)
  8. {
  9. OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
  10. }
  11. // If there was nothing in the error message then it simply could not find the shader file itself.
  12. else
  13. {
  14. MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
  15. }
  16. return false;
  17. }
  18. // Compile the pixel shader code.
  19. result = D3DCompileFromFile(psFilename, NULL, NULL, "TexturePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
  20. &pixelShaderBuffer, &errorMessage);
  21. if(FAILED(result))
  22. {
  23. // If the shader failed to compile it should have writen something to the error message.
  24. if(errorMessage)
  25. {
  26. OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
  27. }
  28. // If there was nothing in the error message then it simply could not find the file itself.
  29. else
  30. {
  31. MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
  32. }
  33. return false;
  34. }
  35. // Create the vertex shader from the buffer.
  36. result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader);
  37. if(FAILED(result))
  38. {
  39. return false;
  40. }
  41. // Create the pixel shader from the buffer.
  42. result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
  43. if(FAILED(result))
  44. {
  45. return false;
  46. }

输入布局已经改变,因为我们现在有了纹理元素而不是颜色,第一个位置元素保持不变,但第二个元素的语义名称和格式已更改为 TEXCOORDDXGI_Format_R32G32_FLOAT

这两个更改现在将使该布局与 ModelClass 定义中的新 VertexType 和着色器文件中的类型定义保持一致。

  1. // Create the vertex input layout description.
  2. // This setup needs to match the VertexType stucture in the ModelClass and in the shader.
  3. polygonLayout[0].SemanticName = "POSITION";
  4. polygonLayout[0].SemanticIndex = 0;
  5. polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
  6. polygonLayout[0].InputSlot = 0;
  7. polygonLayout[0].AlignedByteOffset = 0;
  8. polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  9. polygonLayout[0].InstanceDataStepRate = 0;
  10. polygonLayout[1].SemanticName = "TEXCOORD";
  11. polygonLayout[1].SemanticIndex = 0;
  12. polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
  13. polygonLayout[1].InputSlot = 0;
  14. polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
  15. polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  16. polygonLayout[1].InstanceDataStepRate = 0;
  17. // Get a count of the elements in the layout.
  18. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
  19. // Create the vertex input layout.
  20. result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(),
  21. vertexShaderBuffer->GetBufferSize(), &m_layout);
  22. if(FAILED(result))
  23. {
  24. return false;
  25. }
  26. // Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
  27. vertexShaderBuffer->Release();
  28. vertexShaderBuffer = 0;
  29. pixelShaderBuffer->Release();
  30. pixelShaderBuffer = 0;
  31. // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
  32. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
  33. matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
  34. matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  35. matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  36. matrixBufferDesc.MiscFlags = 0;
  37. matrixBufferDesc.StructureByteStride = 0;
  38. // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
  39. result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
  40. if(FAILED(result))
  41. {
  42. return false;
  43. }

采样器状态描述在此处设置,之后可以传递给像素着色器,纹理采样器描述中最重要的元素是过滤器,过滤器将决定如何决定使用或组合哪些像素来创建多边形面上纹理的最终外观。

在这里的示例中,我使用 D3D11_FILTER_MIN_MAG_MIP_LINEAR,这在处理性能方面耗费高昂,但这提供了最佳的视觉效果,它告诉采样器使用线性插值进行缩小、放大和 mip 级别采样。

AddressUAddressV 设置为 Wrap,以确保坐标保持在 0.0f 和 1.0f 之间,除此之外的任何物体都会环绕并放置在 0.0f 和 1.0f 之间。

采样器状态描述的所有其他设置都是默认设置。

  1. // Create a texture sampler state description.
  2. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  3. samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  4. samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  5. samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  6. samplerDesc.MipLODBias = 0.0f;
  7. samplerDesc.MaxAnisotropy = 1;
  8. samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  9. samplerDesc.BorderColor[0] = 0;
  10. samplerDesc.BorderColor[1] = 0;
  11. samplerDesc.BorderColor[2] = 0;
  12. samplerDesc.BorderColor[3] = 0;
  13. samplerDesc.MinLOD = 0;
  14. samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
  15. // Create the texture sampler state.
  16. result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
  17. if (FAILED(result))
  18. {
  19. return false;
  20. }
  21. return true;
  22. }

ShutdowShader 函数释放 TextureShader 类中使用的所有变量。

  1. void TextureShaderClass::ShutdownShader()
  2. {

ShutdowShader 函数现在释放初始化期间创建的新采样器状态。

  1. // Release the sampler state.
  2. if (m_sampleState)
  3. {
  4. m_sampleState->Release();
  5. m_sampleState = 0;
  6. }
  7. // Release the matrix constant buffer.
  8. if(m_matrixBuffer)
  9. {
  10. m_matrixBuffer->Release();
  11. m_matrixBuffer = 0;
  12. }
  13. // Release the layout.
  14. if(m_layout)
  15. {
  16. m_layout->Release();
  17. m_layout = 0;
  18. }
  19. // Release the pixel shader.
  20. if(m_pixelShader)
  21. {
  22. m_pixelShader->Release();
  23. m_pixelShader = 0;
  24. }
  25. // Release the vertex shader.
  26. if(m_vertexShader)
  27. {
  28. m_vertexShader->Release();
  29. m_vertexShader = 0;
  30. }
  31. return;
  32. }

如果无法加载 HLSL 着色器,OutputShaderErrorMessage 会将错误写入文本文件。

  1. void TextureShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
  2. {
  3. char* compileErrors;
  4. unsigned long long bufferSize, i;
  5. ofstream fout;
  6. // Get a pointer to the error message text buffer.
  7. compileErrors = (char*)(errorMessage->GetBufferPointer());
  8. // Get the length of the message.
  9. bufferSize = errorMessage->GetBufferSize();
  10. // Open a file to write the error message to.
  11. fout.open("shader-error.txt");
  12. // Write out the error message.
  13. for(i=0; i<bufferSize; i++)
  14. {
  15. fout << compileErrors[i];
  16. }
  17. // Close the file.
  18. fout.close();
  19. // Release the error message.
  20. errorMessage->Release();
  21. errorMessage = 0;
  22. // Pop a message up on the screen to notify the user to check the text file for compile errors.
  23. MessageBox(hwnd, L"Error compiling shader. Check shader-error.txt for message.", shaderFilename, MB_OK);
  24. return;
  25. }

SetShaderParameters 函数现在接收指向纹理资源的指针,然后使用新的纹理资源指针将其指定给着色器,请注意,必须在渲染缓冲区之前设置纹理。

  1. bool TextureShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
  2. XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
  3. {
  4. HRESULT result;
  5. D3D11_MAPPED_SUBRESOURCE mappedResource;
  6. MatrixBufferType* dataPtr;
  7. unsigned int bufferNumber;
  8. // Transpose the matrices to prepare them for the shader.
  9. worldMatrix = XMMatrixTranspose(worldMatrix);
  10. viewMatrix = XMMatrixTranspose(viewMatrix);
  11. projectionMatrix = XMMatrixTranspose(projectionMatrix);
  12. // Lock the constant buffer so it can be written to.
  13. result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
  14. if(FAILED(result))
  15. {
  16. return false;
  17. }
  18. // Get a pointer to the data in the constant buffer.
  19. dataPtr = (MatrixBufferType*)mappedResource.pData;
  20. // Copy the matrices into the constant buffer.
  21. dataPtr->world = worldMatrix;
  22. dataPtr->view = viewMatrix;
  23. dataPtr->projection = projectionMatrix;
  24. // Unlock the constant buffer.
  25. deviceContext->Unmap(m_matrixBuffer, 0);
  26. // Set the position of the constant buffer in the vertex shader.
  27. bufferNumber = 0;
  28. // Finanly set the constant buffer in the vertex shader with the updated values.
  29. deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);

SetShaderParameters 函数已从上一教程中修改,现在包括在像素着色器中设置纹理。

  1. // Set shader texture resource in the pixel shader.
  2. deviceContext->PSSetShaderResources(0, 1, &texture);
  3. return true;
  4. }

RenderShader 调用着色器技术来渲染多边形。

  1. void TextureShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
  2. {
  3. // Set the vertex input layout.
  4. deviceContext->IASetInputLayout(m_layout);
  5. // Set the vertex and pixel shaders that will be used to render this triangle.
  6. deviceContext->VSSetShader(m_vertexShader, NULL, 0);
  7. deviceContext->PSSetShader(m_pixelShader, NULL, 0);

RenderShader 函数已更改为在渲染前在像素着色器中设置采样状态。

  1. // Set the sampler state in the pixel shader.
  2. deviceContext->PSSetSamplers(0, 1, &m_sampleState);
  3. // Render the triangle.
  4. deviceContext->DrawIndexed(indexCount, 0, 0);
  5. return;
  6. }

Textureclass.h

TextureClass 封装了单个纹理资源的加载、卸载和访问,对于所需的每个纹理,必须实例化此类的对象。

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: textureclass.h
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #ifndef _TEXTURECLASS_H_
  5. #define _TEXTURECLASS_H_
  6. //////////////
  7. // INCLUDES //
  8. //////////////
  9. #include <d3d11.h>
  10. #include <stdio.h>
  11. ////////////////////////////////////////////////////////////////////////////////
  12. // Class name: TextureClass
  13. ////////////////////////////////////////////////////////////////////////////////
  14. class TextureClass
  15. {
  16. private:

我们在这里定义 targa 文件的头结构,以便更容易读取数据。

  1. struct TargaHeader
  2. {
  3. unsigned char data1[12];
  4. unsigned short width;
  5. unsigned short height;
  6. unsigned char bpp;
  7. unsigned char data2;
  8. };
  9. public:
  10. TextureClass();
  11. TextureClass(const TextureClass&);
  12. ~TextureClass();
  13. bool Initialize(ID3D11Device*, ID3D11DeviceContext*, char*);
  14. void Shutdown();
  15. ID3D11ShaderResourceView* GetTexture();
  16. private:

这里有我们的 targa 读取函数,如果你想支持更多的格式,你可以在这里添加其他读取函数。

  1. bool LoadTarga(char*, int&, int&);
  2. private:

这个类有三个成员变量,第一个保存直接从文件中读取的原始 targa 数据,第二个名为 m_texture 的变量将保存 DirectX 用于渲染的结构化纹理数据,第三个变量是着色器在绘制时用来访问纹理数据的资源视图。

  1. unsigned char* m_targaData;
  2. ID3D11Texture2D* m_texture;
  3. ID3D11ShaderResourceView* m_textureView;
  4. };
  5. #endif

Textureclass.cpp

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: textureclass.cpp
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #include "textureclass.h"

在类构造函数中将三个指针初始化为空。

  1. TextureClass::TextureClass()
  2. {
  3. m_targaData = 0;
  4. m_texture = 0;
  5. m_textureView = 0;
  6. }
  7. TextureClass::TextureClass(const TextureClass& other)
  8. {
  9. }
  10. TextureClass::~TextureClass()
  11. {
  12. }

初始化函数将 Direct3D 设备和 targa 图像文件的名称作为输入,它将首先将 targa 数据加载到一个数组中,然后创建一个纹理,并以正确的格式将 targa 数据加载到其中(默认情况下 targa 图像是向上的,需要反转);加载纹理后,它将创建纹理的资源视图,供着色器用于绘制。

  1. bool TextureClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
  2. {
  3. bool result;
  4. int height, width;
  5. D3D11_TEXTURE2D_DESC textureDesc;
  6. HRESULT hResult;
  7. unsigned int rowPitch;
  8. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;

首先我们调用 TextureClass:LoadTarga 函数将 targa 文件加载到 m_targaData 数组中,这个函数还将把纹理的高度和宽度传递给我们。

  1. // Load the targa image data into memory.
  2. result = LoadTarga(filename, height, width);
  3. if(!result)
  4. {
  5. return false;
  6. }

接下来,我们需要设置 DirectX 纹理的描述,我们将加载 targa 数据,我们将使用 targa 图像数据的高度和宽度,并把格式设置为 32 位 RGBA 纹理。

我们将 SampleDesc 设置为默认值,然后,我们将 Usage 设置为 D3D11_USAGE_DEFAULT,这是性能更好的内存,下面我们还会详细解释一下。

最后,我们将 MipLevelsBindFlagsMiscFlags 设置为 Mipmapped 纹理所需的设置。

描述完成后,我们调用 CreateTexture2D 为我们创建一个空纹理,下一步是将 targa 数据复制到该空纹理中。

  1. // Setup the description of the texture.
  2. textureDesc.Height = height;
  3. textureDesc.Width = width;
  4. textureDesc.MipLevels = 0;
  5. textureDesc.ArraySize = 1;
  6. textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  7. textureDesc.SampleDesc.Count = 1;
  8. textureDesc.SampleDesc.Quality = 0;
  9. textureDesc.Usage = D3D11_USAGE_DEFAULT;
  10. textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
  11. textureDesc.CPUAccessFlags = 0;
  12. textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
  13. // Create the empty texture.
  14. hResult = device->CreateTexture2D(&textureDesc, NULL, &m_texture);
  15. if(FAILED(hResult))
  16. {
  17. return false;
  18. }
  19. // Set the row pitch of the targa image data.
  20. rowPitch = (width * 4) * sizeof(unsigned char);

这里我们使用 UpdateSubresource 将 targa 数据数组复制到 DirectX 纹理中。

如果你还记得上一个教程中,我们使用 MapUnmapModelClass 中的矩阵复制到矩阵常量缓冲区中,我们可以在这里对纹理数据执行同样的操作。

事实上,使用 MapUnmap 通常比使用 UpdateSubresource 快得多,但是这两种加载方法都有特定的用途,出于性能原因,你需要正确选择使用哪种方法,建议对每一帧或非常定期地重新加载的数据使用 MapUnmap。而对于加载一次或者在加载过程中很少再次加载的东西,则使用 UpdateSubresource,原因是 UpdateSubresource 将数据放入速度更快的内存中,从而获得缓存保留配置,因为它知道你不会很快删除或重新加载数据。

当我们要使用 UpdateSubresource 加载时,我们还将使用 D3D11_USAGE_DEFAULT 让 DirectX 知道这件事,MapUnmap 会将数据放入不会缓存的内存位置,因为 DirectX 预计这些数据很快会被覆盖。

这就是为什么我们使用 D3D11_USAGE_DYNAMIC 来告知 DirectX 这种类型的数据是暂时的。

  1. // Copy the targa image data into the texture.
  2. deviceContext->UpdateSubresource(m_texture, 0, NULL, m_targaData, rowPitch, 0);

加载纹理后,我们创建一个着色器资源视图,该视图允许我们使用指针在着色器中设置纹理。

在描述中,我们还设置了两个重要的 Mipmap 变量,这将为我们提供全范围的 Mipmap 级别,以便在任何距离进行高质量纹理渲染。

创建着色器资源视图后,我们将调用 GenerateMaps,它将为我们创建 Mipmap。但是,如果你想要更好的质量,可以手动加载自己的 Mipmap 级别。

  1. // Setup the shader resource view description.
  2. srvDesc.Format = textureDesc.Format;
  3. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  4. srvDesc.Texture2D.MostDetailedMip = 0;
  5. srvDesc.Texture2D.MipLevels = -1;
  6. // Create the shader resource view for the texture.
  7. hResult = device->CreateShaderResourceView(m_texture, &srvDesc, &m_textureView);
  8. if(FAILED(hResult))
  9. {
  10. return false;
  11. }
  12. // Generate mipmaps for this texture.
  13. deviceContext->GenerateMips(m_textureView);
  14. // Release the targa image data now that the image data has been loaded into the texture.
  15. delete [] m_targaData;
  16. m_targaData = 0;
  17. return true;
  18. }

Shutdown 函数释放纹理数据,并将三个指针设置为空。

  1. void TextureClass::Shutdown()
  2. {
  3. // Release the texture view resource.
  4. if(m_textureView)
  5. {
  6. m_textureView->Release();
  7. m_textureView = 0;
  8. }
  9. // Release the texture.
  10. if(m_texture)
  11. {
  12. m_texture->Release();
  13. m_texture = 0;
  14. }
  15. // Release the targa data.
  16. if(m_targaData)
  17. {
  18. delete [] m_targaData;
  19. m_targaData = 0;
  20. }
  21. return;
  22. }

GetTexture 是一个辅助函数,用于为任何需要纹理视图进行渲染的着色器提供对纹理视图的轻松访问。

  1. ID3D11ShaderResourceView* TextureClass::GetTexture()
  2. {
  3. return m_textureView;
  4. }

这是我们的 targa 图像的加载函数,再次注意,targa 图像是颠倒存储的,使用前需要翻转。

在这里,我们将打开文件,将其读入数组,然后获取数组数据,并以正确的顺序将其加载到 m_targaData 数组中。

注意:我们有意只处理具有 alpha 通道的 32 位 targa 文件,此函数将拒绝存储格式为为 24 位的 targa 文件。

  1. bool TextureClass::LoadTarga(char* filename, int& height, int& width)
  2. {
  3. int error, bpp, imageSize, index, i, j, k;
  4. FILE* filePtr;
  5. unsigned int count;
  6. TargaHeader targaFileHeader;
  7. unsigned char* targaImage;
  8. // Open the targa file for reading in binary.
  9. error = fopen_s(&filePtr, filename, "rb");
  10. if(error != 0)
  11. {
  12. return false;
  13. }
  14. // Read in the file header.
  15. count = (unsigned int)fread(&targaFileHeader, sizeof(TargaHeader), 1, filePtr);
  16. if(count != 1)
  17. {
  18. return false;
  19. }
  20. // Get the important information from the header.
  21. height = (int)targaFileHeader.height;
  22. width = (int)targaFileHeader.width;
  23. bpp = (int)targaFileHeader.bpp;
  24. // Check that it is 32 bit and not 24 bit.
  25. if(bpp != 32)
  26. {
  27. return false;
  28. }
  29. // Calculate the size of the 32 bit image data.
  30. imageSize = width * height * 4;
  31. // Allocate memory for the targa image data.
  32. targaImage = new unsigned char[imageSize];
  33. if(!targaImage)
  34. {
  35. return false;
  36. }
  37. // Read in the targa image data.
  38. count = (unsigned int)fread(targaImage, 1, imageSize, filePtr);
  39. if(count != imageSize)
  40. {
  41. return false;
  42. }
  43. // Close the file.
  44. error = fclose(filePtr);
  45. if(error != 0)
  46. {
  47. return false;
  48. }
  49. // Allocate memory for the targa destination data.
  50. m_targaData = new unsigned char[imageSize];
  51. if(!m_targaData)
  52. {
  53. return false;
  54. }
  55. // Initialize the index into the targa destination data array.
  56. index = 0;
  57. // Initialize the index into the targa image data.
  58. k = (width * height * 4) - (width * 4);
  59. // Now copy the targa image data into the targa destination array in the correct order since the targa format is stored upside down.
  60. for(j=0; j<height; j++)
  61. {
  62. for(i=0; i<width; i++)
  63. {
  64. m_targaData[index + 0] = targaImage[k + 2]; // Red.
  65. m_targaData[index + 1] = targaImage[k + 1]; // Green.
  66. m_targaData[index + 2] = targaImage[k + 0]; // Blue
  67. m_targaData[index + 3] = targaImage[k + 3]; // Alpha
  68. // Increment the indexes into the targa data.
  69. k += 4;
  70. index += 4;
  71. }
  72. // Set the targa image data index back to the preceding row at the beginning of the column since its reading it in upside down.
  73. k -= (width * 8);
  74. }
  75. // Release the targa image data now that it was copied into the destination array.
  76. delete [] targaImage;
  77. targaImage = 0;
  78. return true;
  79. }

Modelclass.h

自上一个教程以来,ModelClass已经更改,因此现在可以适应纹理。

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: modelclass.h
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #ifndef _MODELCLASS_H_
  5. #define _MODELCLASS_H_
  6. //////////////
  7. // INCLUDES //
  8. //////////////
  9. #include <d3d11.h>
  10. #include <directxmath.h>
  11. using namespace DirectX;

TextureClass 头文件现在包含在 ModelClass 头文件中。

  1. ///////////////////////
  2. // MY CLASS INCLUDES //
  3. ///////////////////////
  4. #include "textureclass.h"
  5. ////////////////////////////////////////////////////////////////////////////////
  6. // Class name: ModelClass
  7. ////////////////////////////////////////////////////////////////////////////////
  8. class ModelClass
  9. {
  10. private:

VertexType 已将颜色成员替换为纹理坐标组件,纹理坐标现在将替换上一教程中使用的绿色。

  1. struct VertexType
  2. {
  3. XMFLOAT3 position;
  4. XMFLOAT2 texture;
  5. };
  6. public:
  7. ModelClass();
  8. ModelClass(const ModelClass&);
  9. ~ModelClass();
  10. bool Initialize(ID3D11Device*, ID3D11DeviceContext*, char*);
  11. void Shutdown();
  12. void Render(ID3D11DeviceContext*);
  13. int GetIndexCount();

ModelClass 现在有一个 GetTexture 函数,因此它可以将自己的纹理资源传递给绘制此模型的着色器。

  1. ID3D11ShaderResourceView* GetTexture();
  2. private:
  3. bool InitializeBuffers(ID3D11Device*);
  4. void ShutdownBuffers();
  5. void RenderBuffers(ID3D11DeviceContext*);

ModelClass 现在还有一个私有的 LoadTextureReleaseTexture,用于加载和释放用于渲染此模型的纹理。

  1. bool LoadTexture(ID3D11Device*, ID3D11DeviceContext*, char*);
  2. void ReleaseTexture();
  3. private:
  4. ID3D11Buffer *m_vertexBuffer, *m_indexBuffer;
  5. int m_vertexCount, m_indexCount;

m_Texture 变量用于加载、释放和访问此模型的纹理资源。

  1. TextureClass* m_Texture;
  2. };
  3. #endif

Modelclass.cpp

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: modelclass.cpp
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #include "modelclass.h"
  5. ModelClass::ModelClass()
  6. {
  7. m_vertexBuffer = 0;
  8. m_indexBuffer = 0;

类构造函数现在将新的纹理对象初始化为空。

  1. m_Texture = 0;
  2. }
  3. ModelClass::ModelClass(const ModelClass& other)
  4. {
  5. }
  6. ModelClass::~ModelClass()
  7. {
  8. }

Initialize 现在将模型使用的纹理的文件名以及设备上下文作为输入。

  1. bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* textureFilename)
  2. {
  3. bool result;
  4. // Initialize the vertex and index buffers.
  5. result = InitializeBuffers(device);
  6. if(!result)
  7. {
  8. return false;
  9. }

Initialize 函数调用一个新的私有函数来加载纹理。

  1. // Load the texture for this model.
  2. result = LoadTexture(device, deviceContext, textureFilename);
  3. if (!result)
  4. {
  5. return false;
  6. }
  7. return true;
  8. }
  9. void ModelClass::Shutdown()
  10. {

Shutdown 函数现在调用新的私有函数来释放初始化期间加载的纹理对象。

  1. // Release the model texture.
  2. ReleaseTexture();
  3. // Shutdown the vertex and index buffers.
  4. ShutdownBuffers();
  5. return;
  6. }
  7. void ModelClass::Render(ID3D11DeviceContext* deviceContext)
  8. {
  9. // Put the vertex and index buffers on the graphics pipeline to prepare them for drawing.
  10. RenderBuffers(deviceContext);
  11. return;
  12. }
  13. int ModelClass::GetIndexCount()
  14. {
  15. return m_indexCount;
  16. }

GetTexture 是一个新函数,用于返回模型纹理资源,纹理着色器需要访问该纹理才能渲染模型。

  1. ID3D11ShaderResourceView* ModelClass::GetTexture()
  2. {
  3. return m_Texture->GetTexture();
  4. }
  5. bool ModelClass::InitializeBuffers(ID3D11Device* device)
  6. {
  7. VertexType* vertices;
  8. unsigned long* indices;
  9. D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
  10. D3D11_SUBRESOURCE_DATA vertexData, indexData;
  11. HRESULT result;
  12. // Set the number of vertices in the vertex array.
  13. m_vertexCount = 3;
  14. // Set the number of indices in the index array.
  15. m_indexCount = 3;
  16. // Create the vertex array.
  17. vertices = new VertexType[m_vertexCount];
  18. if(!vertices)
  19. {
  20. return false;
  21. }
  22. // Create the index array.
  23. indices = new unsigned long[m_indexCount];
  24. if(!indices)
  25. {
  26. return false;
  27. }

顶点数组现在有一个纹理坐标组件,而不是颜色组件。

纹理向量总是 U 优先,V 第二。例如,第一个纹理坐标是对应于 U 0.0, V 1.0 的三角形的左下角,使用本章开始处的图表来计算坐标。

请注意,可以更改坐标从而将纹理的任何部分映射到多边形面的任何部分,在本教程中,为了简单起见,我们只做了一个直接映射。

  1. // Load the vertex array with data.
  2. vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f); // Bottom left.
  3. vertices[0].texture = XMFLOAT2(0.0f, 1.0f);
  4. vertices[1].position = XMFLOAT3(0.0f, 1.0f, 0.0f); // Top middle.
  5. vertices[1].texture = XMFLOAT2(0.5f, 0.0f);
  6. vertices[2].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // Bottom right.
  7. vertices[2].texture = XMFLOAT2(1.0f, 1.0f);
  8. // Load the index array with data.
  9. indices[0] = 0; // Bottom left.
  10. indices[1] = 1; // Top middle.
  11. indices[2] = 2; // Bottom right.
  12. // Set up the description of the static vertex buffer.
  13. vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
  14. vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
  15. vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  16. vertexBufferDesc.CPUAccessFlags = 0;
  17. vertexBufferDesc.MiscFlags = 0;
  18. vertexBufferDesc.StructureByteStride = 0;
  19. // Give the subresource structure a pointer to the vertex data.
  20. vertexData.pSysMem = vertices;
  21. vertexData.SysMemPitch = 0;
  22. vertexData.SysMemSlicePitch = 0;
  23. // Now create the vertex buffer.
  24. result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer);
  25. if(FAILED(result))
  26. {
  27. return false;
  28. }
  29. // Set up the description of the static index buffer.
  30. indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
  31. indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount;
  32. indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  33. indexBufferDesc.CPUAccessFlags = 0;
  34. indexBufferDesc.MiscFlags = 0;
  35. indexBufferDesc.StructureByteStride = 0;
  36. // Give the subresource structure a pointer to the index data.
  37. indexData.pSysMem = indices;
  38. indexData.SysMemPitch = 0;
  39. indexData.SysMemSlicePitch = 0;
  40. // Create the index buffer.
  41. result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer);
  42. if(FAILED(result))
  43. {
  44. return false;
  45. }
  46. // Release the arrays now that the vertex and index buffers have been created and loaded.
  47. delete [] vertices;
  48. vertices = 0;
  49. delete [] indices;
  50. indices = 0;
  51. return true;
  52. }
  53. void ModelClass::ShutdownBuffers()
  54. {
  55. // Release the index buffer.
  56. if(m_indexBuffer)
  57. {
  58. m_indexBuffer->Release();
  59. m_indexBuffer = 0;
  60. }
  61. // Release the vertex buffer.
  62. if(m_vertexBuffer)
  63. {
  64. m_vertexBuffer->Release();
  65. m_vertexBuffer = 0;
  66. }
  67. return;
  68. }
  69. void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
  70. {
  71. unsigned int stride;
  72. unsigned int offset;
  73. // Set vertex buffer stride and offset.
  74. stride = sizeof(VertexType);
  75. offset = 0;
  76. // Set the vertex buffer to active in the input assembler so it can be rendered.
  77. deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
  78. // Set the index buffer to active in the input assembler so it can be rendered.
  79. deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
  80. // Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
  81. deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  82. return;
  83. }

LoadTexture 是一个新的私有函数,它将创建纹理对象,然后使用提供的输入文件名对其进行初始化,此函数在初始化期间被调用。

  1. bool ModelClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
  2. {
  3. bool result;
  4. // Create the texture object.
  5. m_Texture = new TextureClass;
  6. if (!m_Texture)
  7. {
  8. return false;
  9. }
  10. // Initialize the texture object.
  11. result = m_Texture->Initialize(device, deviceContext, filename);
  12. if (!result)
  13. {
  14. return false;
  15. }
  16. return true;
  17. }

ReleaseTexture 函数将释放在 LoadTexture 函数期间创建和加载的纹理对象。

  1. void ModelClass::ReleaseTexture()
  2. {
  3. // Release the texture object.
  4. if (m_Texture)
  5. {
  6. m_Texture->Shutdown();
  7. delete m_Texture;
  8. m_Texture = 0;
  9. }
  10. return;
  11. }

Graphicsclass.h

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: graphicsclass.h
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #ifndef _GRAPHICSCLASS_H_
  5. #define _GRAPHICSCLASS_H_
  6. ///////////////////////
  7. // MY CLASS INCLUDES //
  8. ///////////////////////
  9. #include "d3dclass.h"
  10. #include "cameraclass.h"
  11. #include "modelclass.h"

GraphicsClass 现在包括新的 TextureShaderClass 头文件,ColorShaderClass 头文件已被删除。

  1. #include "textureshaderclass.h"
  2. /////////////
  3. // GLOBALS //
  4. /////////////
  5. const bool FULL_SCREEN = false;
  6. const bool VSYNC_ENABLED = true;
  7. const float SCREEN_DEPTH = 1000.0f;
  8. const float SCREEN_NEAR = 0.1f;
  9. ////////////////////////////////////////////////////////////////////////////////
  10. // Class name: GraphicsClass
  11. ////////////////////////////////////////////////////////////////////////////////
  12. class GraphicsClass
  13. {
  14. public:
  15. GraphicsClass();
  16. GraphicsClass(const GraphicsClass&);
  17. ~GraphicsClass();
  18. bool Initialize(int, int, HWND);
  19. void Shutdown();
  20. bool Frame();
  21. private:
  22. bool Render();
  23. private:
  24. D3DClass* m_Direct3D;
  25. CameraClass* m_Camera;
  26. ModelClass* m_Model;

添加了一个新的 TextureShaderClass 私有对象。

  1. TextureShaderClass* m_TextureShader;
  2. };
  3. #endif

Graphicsclass.cpp

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Filename: graphicsclass.cpp
  3. ////////////////////////////////////////////////////////////////////////////////
  4. #include "graphicsclass.h"

m_TextureShader 变量在构造函数中设置为空。

  1. GraphicsClass::GraphicsClass()
  2. {
  3. m_Direct3D = 0;
  4. m_Camera = 0;
  5. m_Model = 0;
  6. m_TextureShader = 0;
  7. }
  8. GraphicsClass::GraphicsClass(const GraphicsClass& other)
  9. {
  10. }
  11. GraphicsClass::~GraphicsClass()
  12. {
  13. }
  14. bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
  15. {
  16. bool result;
  17. // Create the Direct3D object.
  18. m_Direct3D = new D3DClass;
  19. if(!m_Direct3D)
  20. {
  21. return false;
  22. }
  23. // Initialize the Direct3D object.
  24. result = m_Direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
  25. if(!result)
  26. {
  27. MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
  28. return false;
  29. }
  30. // Create the camera object.
  31. m_Camera = new CameraClass;
  32. if (!m_Camera)
  33. {
  34. return false;
  35. }
  36. // Set the initial position of the camera.
  37. m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
  38. // Create the model object.
  39. m_Model = new ModelClass;
  40. if (!m_Model)
  41. {
  42. return false;
  43. }

ModelClass:Initialize 函数现在接受将用于渲染模型的纹理的名称。

  1. // Initialize the model object.
  2. result = m_Model->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "../Engine/data/stone01.tga");
  3. if (!result)
  4. {
  5. MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
  6. return false;
  7. }

新建 TextureShaderClass 对象将会被创建并初始化。

  1. // Create the texture shader object.
  2. m_TextureShader = new TextureShaderClass;
  3. if (!m_TextureShader)
  4. {
  5. return false;
  6. }
  7. // Initialize the color shader object.
  8. result = m_TextureShader->Initialize(m_Direct3D->GetDevice(), hwnd);
  9. if (!result)
  10. {
  11. MessageBox(hwnd, L"Could not initialize the color shader object.", L"Error", MB_OK);
  12. return false;
  13. }
  14. return true;
  15. }
  16. void GraphicsClass::Shutdown()
  17. {

TextureShaderClass 对象也会在 Shutdown 函数中释放。

  1. // Release the texture shader object.
  2. if (m_TextureShader)
  3. {
  4. m_TextureShader->Shutdown();
  5. delete m_TextureShader;
  6. m_TextureShader = 0;
  7. }
  8. // Release the model object.
  9. if (m_Model)
  10. {
  11. m_Model->Shutdown();
  12. delete m_Model;
  13. m_Model = 0;
  14. }
  15. // Release the camera object.
  16. if (m_Camera)
  17. {
  18. delete m_Camera;
  19. m_Camera = 0;
  20. }
  21. // Release the D3D object.
  22. if(m_Direct3D)
  23. {
  24. m_Direct3D->Shutdown();
  25. delete m_Direct3D;
  26. m_Direct3D = 0;
  27. }
  28. return;
  29. }
  30. bool GraphicsClass::Frame()
  31. {
  32. bool result;
  33. // Render the graphics scene.
  34. result = Render();
  35. if(!result)
  36. {
  37. return false;
  38. }
  39. return true;
  40. }
  41. bool GraphicsClass::Render()
  42. {
  43. XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
  44. bool result;
  45. // Clear the buffers to begin the scene.
  46. m_Direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
  47. // Generate the view matrix based on the camera's position.
  48. m_Camera->Render();
  49. // Get the world, view, and projection matrices from the camera and d3d objects.
  50. m_Direct3D->GetWorldMatrix(worldMatrix);
  51. m_Camera->GetViewMatrix(viewMatrix);
  52. m_Direct3D->GetProjectionMatrix(projectionMatrix);
  53. // Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
  54. m_Model->Render(m_Direct3D->GetDeviceContext());

现在调用纹理着色器而不是颜色着色器来渲染模型,请注意,它还从模型中获取纹理资源指针,以便纹理着色器可以从模型对象访问纹理。

  1. // Render the model using the texture shader.
  2. result = m_TextureShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture());
  3. if (!result)
  4. {
  5. return false;
  6. }
  7. // Present the rendered scene to the screen.
  8. m_Direct3D->EndScene();
  9. return true;
  10. }

总结

现在,您应该了解加载纹理、将其映射到多边形面,然后使用着色器渲染纹理的基础知识。

程序运行效果

练习

  1. 重新编译代码,确保屏幕上出现纹理贴图三角形,完成后按 escape 退出。

  2. 创建自己的 tga 纹理,并将其与 stone01.tga 放在同一目录中,在 GraphicsClass:Initialize 函数中,更改模型初始化以获得纹理名称,然后重新编译并运行程序。

  3. 更改代码,创建两个三角形,形成一个正方形,将整个纹理映射到此正方形,以便整个纹理正确显示在屏幕上。

  4. 将相机移动到不同的距离,以查看 MIN_MAG_MIP_LINEAR 的效果。

  5. 尝试一些其他的过滤器,并将相机移动到不同的距离,以查看不同的结果。