Question

I am trying to make a texture of 1 pixel, color is a variable passed to the function, and i have the following code:

unsigned char texArray[4];
texArray[0] = (unsigned char) color.x;
texArray[1] = (unsigned char) color.y;
texArray[2] = (unsigned char) color.z;
texArray[3] = (unsigned char) color.w;

ID3D11Texture2D *pTexture = nullptr;

ID3D11ShaderResourceView* pShaderResourceView;

D3D11_TEXTURE2D_DESC texDesc;

ZeroMemory(&texDesc, sizeof(D3D11_TEXTURE2D_DESC));
texDesc.ArraySize = 1;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.MipLevels = 1;
texDesc.MiscFlags = 0;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.Height = 1;
texDesc.Width = 1;

D3D11_SUBRESOURCE_DATA texInitData;
ZeroMemory(&texInitData, sizeof(D3D11_SUBRESOURCE_DATA));
texInitData.pSysMem = texArray;

HRESULT hr;

hr = m_pDevice->CreateTexture2D(&texDesc, &texInitData, &pTexture);
hr = m_pDevice->CreateShaderResourceView(pTexture, NULL, &pShaderResourceView);

But it fails to create the texture2D (return nullptr) & hr contains "parameter is incorrect".

What is wrong/missing?

Was it helpful?

Solution

Since you are creating a 2D-texture, you will need to specify the SysMemPitch value in texInitData, since you are creating a 2D texture (even though it is just 1x1 pixel in this case). You should specify it to sizeof(unsigned char) * 4 in this case, since the next line would begin after that many bytes if there was another line.

OTHER TIPS

It's a good practice to set the debug flag on when creating D3D device, in this case, you will get more information from Direct3D in Visual Studio's output window when running in debug mode.

UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;

#if defined( DEBUG ) || defined( _DEBUG )
    flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif 

HRESULT hr;
if (FAILED (hr = D3D11CreateDeviceAndSwapChain( NULL,
    D3D_DRIVER_TYPE_HARDWARE,
    NULL,
    flags,
    &FeatureLevelsRequested,
    numLevelsRequested,
    D3D11_SDK_VERSION,
    &sd, 
    &g_pSwapChain,
    &g_pd3dDevice,
    &FeatureLevelsSupported,
    &g_pImmediateContext )))
{
    return hr;
}

and here is what I got from your code, you can easily know what's wrong from the message.

D3D11 ERROR: ID3D11Device::CreateTexture2D: pInitialData[0].SysMemPitch cannot be 0 [ STATE_CREATION ERROR #100: CREATETEXTURE2D_INVALIDINITIALDATA]
First-chance exception at 0x74891EE9 in Teapot.exe: Microsoft C++ exception: _com_error at memory location 0x00E4F668.
First-chance exception at 0x74891EE9 in Teapot.exe: Microsoft C++ exception: _com_error at memory location 0x00E4F668.
D3D11 ERROR: ID3D11Device::CreateTexture2D: Returning E_INVALIDARG, meaning invalid parameters were passed. [ STATE_CREATION ERROR #104: CREATETEXTURE2D_INVALIDARG_RETURN]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top