2017-06-30 105 views
1

我是新来Direct3D11和我目前想我的代码中编程创建纹理使用此代码我在网上找到:混淆的Texture2D和ShaderResourceViews

// Some Constants 
int w = 256; 
int h = 256; 
int bpp = 4; 
int *buf = new int[w*h]; 

//declarations 
ID3D11Texture2D* tex; 
D3D11_TEXTURE2D_DESC sTexDesc; 
D3D11_SUBRESOURCE_DATA tbsd; 

// filling the image 
for (int i = 0; i<h; i++) 
    for (int j = 0; j<w; j++) 
    { 
     if ((i & 32) == (j & 32)) 
      buf[i*w + j] = 0x00000000; 
     else 
      buf[i*w + j] = 0xffffffff; 
    } 

// setting up D3D11_SUBRESOURCE_DATA 
tbsd.pSysMem = (void *)buf; 
tbsd.SysMemPitch = w*bpp; 
tbsd.SysMemSlicePitch = w*h*bpp; // Not needed since this is a 2d texture 

// initializing sTexDesc 
sTexDesc.Width = w; 
sTexDesc.Height = h; 
sTexDesc.MipLevels = 1; 
sTexDesc.ArraySize = 1; 
sTexDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; 
sTexDesc.SampleDesc.Count = 1; 
sTexDesc.SampleDesc.Quality = 0; 
sTexDesc.Usage = D3D11_USAGE_DEFAULT; 
sTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; 
sTexDesc.CPUAccessFlags = 0; 
sTexDesc.MiscFlags = 0; 

hr = m_pd3dDevice->CreateTexture2D(&sTexDesc, &tbsd, &tex); 

和”所有罚款和花花公子,但我对于如何将其实际加载到着色器中有点困惑。下面,我初始化这个ID3D11ShaderResourceView:

 ID3D11ShaderResourceView*   m_pTextureRV = nullptr; 

我在微软的教程我需要使用CreateShaderResourceView找到。但我究竟如何使用它?我尝试这样做:

 hr = m_pd3dDevice->CreateShaderResourceView(tex, NULL , m_pTextureRV); 

,但它给了我一个错误,告诉我,m_pTextureRV不是功能的有效论据。我在这里做错了什么?

回答

0

正确的方法调用该函数是:

hr = m_pd3dDevice->CreateShaderResourceView(tex, nullptr, &m_pTextureRV); 

记住ID3D11ShaderResourceView*是一个指向的接口。你需要一个指针指针来获得一个新的实例。

你应该真的考虑使用像Microsoft::WRL::ComPtr这样的COM智能指针,而不是这些接口的原始指针。

为纹理对象创建着色器资源视图后,您需要将其与HLSL希望找到的任何插槽相关联。因此,例如,如果您要编写HLSL源文件如:

Texture2D texture : register(t0); 
SamplerState sampler: register(s0); 

float4 PS(float2 tex : TEXCOORD0) : SV_Target 
{ 
    return texture.Sample(sampler, tex); 
} 

它然后编译为一个像素着色器,它通过PSSetShader绑定到渲染管线。然后,你需要拨打:

ID3D11ShaderResourceView* srv[1] = { m_pTextureRV }; 
m_pImmediateContext->PSSetShaderResources(0, 1, srv); 

当然,你还需要一个ID3D11SamplerState*采样约束以及:

ID3D11SamplerState* m_pSamplerLinear = nullptr; 

D3D11_SAMPLER_DESC sampDesc = {}; 
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; 
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; 
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; 
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; 
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; 
sampDesc.MinLOD = 0; 
sampDesc.MaxLOD = D3D11_FLOAT32_MAX; 
hr = m_pd3dDevice->CreateSamplerState(&sampDesc, &m_pSamplerLinear); 

然后,当你将要绘制:

m_pImmediateContext->PSSetSamplers(0, 1, &m_pSamplerLinear); 

我强烈建议您在那里查看DirectX Tool Kittutorials

+0

非常感谢你查克!我一定会研究COM智能指针。 – NAKASSEIN