2017-06-30 175 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