World, view & projection spaces

Started by
20 comments, last by thefatshizms 10 years, 4 months ago

Still having problems with this. Bump.

Advertisement

After loading symbols it now highlights this line:

g_Devicecontext->UpdateSubresource(g_PerObjectbuffer, 0, NULL, &PerObj, 0, 0);

Updated code:


#include "directx.h"
#include <D3Dcompiler.h>
#include <Windows.h>

using namespace std;

struct Vertex {
	DirectX::XMFLOAT3 position;
	DirectX::XMFLOAT4 color;
};

struct PerObject
{
	DirectX::XMMATRIX  WVP;
};

PerObject PerObj;

Vertex triangle[] = {

	DirectX::XMFLOAT3( -0.5f, -0.5f, 0.5f), DirectX::XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f ),
	DirectX::XMFLOAT3( -0.5f,  0.5f, 0.5f), DirectX::XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f ),
	DirectX::XMFLOAT3(  0.5f,  0.5f, 0.5f), DirectX::XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f ),
	DirectX::XMFLOAT3(  0.5f, -0.5f, 0.5f), DirectX::XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f ),
};

Directx::Directx() : g_Swapchain(NULL), g_Device(NULL), g_Devicecontext(NULL), g_Rendertarget(NULL){}

Directx::~Directx() {}

bool Directx::InitializeD3D(HWND hwnd, int width, int height, bool fullscreen) { 
	
	DXGI_SWAP_CHAIN_DESC sd;

	ZeroMemory(&sd, sizeof(sd));

	sd.BufferCount = 1;
    sd.BufferDesc.Width = width;
    sd.BufferDesc.Height = height;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = hwnd;
    sd.SampleDesc.Count = 4;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = (fullscreen) ? false : true;


	D3D_FEATURE_LEVEL featurelevels[] = 
	{
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
		D3D_FEATURE_LEVEL_9_3,
		D3D_FEATURE_LEVEL_9_2,
		D3D_FEATURE_LEVEL_9_1,
	};

	int numfeaturelevels = 5;

	if(FAILED(D3D11CreateDeviceAndSwapChain(NULL,  D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, featurelevels, numfeaturelevels, D3D11_SDK_VERSION, &sd, &g_Swapchain, &g_Device, NULL, &g_Devicecontext)))
		return false;


	ID3D11Texture2D *pBackBuffer;
	HRESULT hr;

	if(FAILED(g_Swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer)))
			return false;

	hr = g_Device->CreateRenderTargetView(pBackBuffer, NULL, &g_Rendertarget);
	pBackBuffer->Release();

	if(FAILED(hr))
			return false;

	g_Devicecontext->OMSetRenderTargets(1, &g_Rendertarget, g_DepthStencilview);

	D3D11_VIEWPORT vp;

	vp.Height = (FLOAT)height;
	vp.Width = (FLOAT)width;
	vp.MaxDepth = 1.0f;
	vp.MinDepth = 0.0f;
	vp.TopLeftX = 0;
	vp.TopLeftY = 0;

	D3D11_TEXTURE2D_DESC depthstencil;

	ZeroMemory(&depthstencil, sizeof(depthstencil));

	depthstencil.Width = width;
	depthstencil.Height = height;
	depthstencil.MipLevels = 1;
	depthstencil.ArraySize = 1;
	depthstencil.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthstencil.SampleDesc.Count = 1;
	depthstencil.SampleDesc.Quality = 0;
	depthstencil.Usage = D3D11_USAGE_DEFAULT;
	depthstencil.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthstencil.CPUAccessFlags = 0;
	depthstencil.MiscFlags = 0;

	g_Device->CreateTexture2D(&depthstencil, NULL, &g_Depthbuffer);
	g_Device->CreateDepthStencilView(g_Depthbuffer, NULL, &g_DepthStencilview);

	g_Devicecontext->RSSetViewports(1, &vp);

	D3D11_BUFFER_DESC cb;

	cb.Usage = D3D11_USAGE_DEFAULT;
	cb.ByteWidth = sizeof(g_PerObjectbuffer);
	cb.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	cb.CPUAccessFlags = 0;
	cb.MiscFlags = 0;

	g_Device->CreateBuffer(&cb, NULL, &g_PerObjectbuffer);

	camPosition = DirectX::XMVectorSet(0.0f, 0.0f, -0.5f, 0.0f);
	camTarget = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	camUp = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	camView = DirectX::XMMatrixLookAtLH(camPosition, camTarget, camUp);

	camProjection = DirectX::XMMatrixPerspectiveFovLH(0.4f * 3.14f, (float)width/height, 1.0f, 1000.0f);

	return true; 
}

void Directx::Render() {

	float ClearColor[4] = { 0.0f, 0.125f, 0.6f, 1.0f };
	g_Devicecontext->ClearRenderTargetView(g_Rendertarget, ClearColor);
	g_Devicecontext->ClearDepthStencilView(g_DepthStencilview, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);

	World = DirectX::XMMatrixIdentity();

	WVP = World * camView * camProjection;

	PerObj.WVP = DirectX::XMMatrixTranspose(WVP);

	g_Devicecontext->UpdateSubresource(g_PerObjectbuffer, 0, NULL, &PerObj, 0, 0);
	g_Devicecontext->VSGetConstantBuffers(0, 1, &g_PerObjectbuffer);


	g_Devicecontext->DrawIndexed(6, 0, 0);
	g_Swapchain->Present(0, 0);
}

int Directx::DrawSquare() {

	DWORD indices[] = {
		0, 1, 2,
		0, 2, 3,
	};
	
	D3D11_BUFFER_DESC bd;
	ZeroMemory(&bd, sizeof(bd));

	bd.ByteWidth = sizeof(DWORD) * 2 * 3;
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;

	D3D11_SUBRESOURCE_DATA data;

	ZeroMemory(&data, sizeof(data));

	data.pSysMem = indices;
	g_Device->CreateBuffer(&bd, &data, &g_Indexbuffer);

	g_Devicecontext->IASetIndexBuffer(g_Indexbuffer, DXGI_FORMAT_R32_UINT, 0);

	D3D11_BUFFER_DESC vertexBufferDesc;
	ZeroMemory( &vertexBufferDesc, sizeof(vertexBufferDesc) );

	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.ByteWidth = sizeof( Vertex ) * 4;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;

	D3D11_SUBRESOURCE_DATA vertexBufferData; 

	ZeroMemory( &vertexBufferData, sizeof(vertexBufferData) );
	vertexBufferData.pSysMem = triangle;
	g_Device->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &g_Vertexbuffer);


	CHAR* pVertexShaderCode =   "struct VS_OUTPUT"
								"{"
									"float4 Pos : SV_POSITION;"
									"float4 Color : COLOR;"
								"};cbuffer PerObject { float4x4 WVP;};"
							"void vertex_shader( in float4 posIn : POSITION, in float4 colorIn : COLOR,"
                            "out float4 posOut : SV_POSITION, out float4 colorOut : COLOR)"
                            "{ VS_OUTPUT output; posOut = posIn; output.Pos = mul(inPos, WVP);"
                            "  colorOut = colorIn; return output; }";

	CHAR* pPixelShaderCode =    "float4 pixel_shader( VS_OUTPUT input) : SV_TARGET"    
                            "{ return input.color; }";

	ID3D10Blob* pVertexShaderBytecode = NULL;  
    ID3D10Blob* pCompileErrors = NULL;

	
	D3DCompile(pVertexShaderCode,  lstrlenA( pVertexShaderCode ) + 1, "vertex shader", NULL, NULL, "vertex_shader", "vs_4_0", NULL, 0, &pVertexShaderBytecode, &pCompileErrors );  
	if( pCompileErrors != NULL ) { 
		OutputDebugStringA( (CHAR*)pCompileErrors->GetBufferPointer() ); 
        pCompileErrors->Release();   
		return 0;
	}

     

    g_Device->CreateVertexShader( pVertexShaderBytecode->GetBufferPointer(), pVertexShaderBytecode->GetBufferSize(), NULL, &g_pVertexShader );      


    ID3D10Blob* pPixelShaderBytecode = NULL;  
    D3DCompile(pPixelShaderCode, 0, 0, NULL, NULL, "pixel_shader", "ps_4_0", NULL, 0, &pPixelShaderBytecode, &pCompileErrors );    
        

	if( pCompileErrors != NULL ) {    
		OutputDebugStringA( (CHAR*)pCompileErrors->GetBufferPointer() ); 
        pCompileErrors->Release();  
		return 0;
    }     


    g_Device->CreatePixelShader( pPixelShaderBytecode->GetBufferPointer(), pPixelShaderBytecode->GetBufferSize(), NULL, &g_pPixelShader );    
    pPixelShaderBytecode->Release();  



    D3D11_INPUT_ELEMENT_DESC inputLayoutDesc[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

    UINT numElements = ARRAYSIZE( inputLayoutDesc );

    g_Device->CreateInputLayout( inputLayoutDesc, numElements, pVertexShaderBytecode->GetBufferPointer(), pVertexShaderBytecode->GetBufferSize(), &g_pInputLayout );    
    pVertexShaderBytecode->Release();    

    g_Devicecontext->IASetInputLayout( g_pInputLayout ); 
    UINT stride = sizeof( Vertex );  
    UINT offset = 0; 
    g_Devicecontext->IASetVertexBuffers(0, 1, &g_Vertexbuffer, &stride, &offset );       

    g_Devicecontext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );  

    g_Devicecontext->VSSetShader( g_pVertexShader, NULL, 0 );   
    g_Devicecontext->PSSetShader( g_pPixelShader, NULL, 0 );

	return true;
}

void Directx::ShutdownDirectx() {

	g_Swapchain->Release();
	g_Device->Release();
	g_Devicecontext->Release();
	g_Rendertarget->Release();
	g_Vertexbuffer->Release();
	g_Indexbuffer->Release();
	g_pPixelShader->Release();
	g_pInputLayout->Release();
	g_pVertexShader->Release();
	g_Depthbuffer->Release();
	g_DepthStencilview->Release();
	g_PerObjectbuffer->Release();
}

Make sure that PerObj.WVP is 16-byte aligned (since it's not heap-allocated, you only need to set the proper setting in the project proprieties http://msdn.microsoft.com/en-us/library/xh3e3fd0.aspx ).

If you still have issues, you should (must! since the code is quite small...) debug your code and check the parameters value of the call that gives you problems, and check backwards if you cannot immediately find the root of the problem. Using assertions on critical sections could be useful too (ie: check that pointers are not set to nullptr before trying to read them!).

"Recursion is the first step towards madness." - "Skegg?ld, Skálm?ld, Skildir ro Klofnir!"
Direct3D 12 quick reference: https://github.com/alessiot89/D3D12QuickRef/

Okay I've just set it to 16-byte aligned but it still crashes.

Unhandled exception at 0x74A2C41F (KernelBase.dll) in Directx11.exe: 0x0000087D (parameters: 0x00000000, 0x0032DC08, 0x0032D044).

(same line)

I'll start debugging now.

Okay i've added an hresult to everything with that return type and used this:

if(FAILED(hr))
DXTraceW(__FILE__, __LINE__, hr, (const WCHAR *)hr, true);
now it says this:
Unhandled exception at 0x00966B1B in Directx11.exe: 0xC0000005: Access violation reading location 0x80070057.
and highlights this line in strsafe.h:
while (cchMax && (*psz != L'\0'))
also, here's this if it's of any use:

You casted hr into a const WCHAR * in your call to DXTraceW. Why did you do that? The variable hr is an HRESULT, not a WCHAR *. If you want to get a human readable string representation of the HRESULT value, you'll have to use FormatMessage or write your own function that converts specific HRESULT values into a string. You can't just cast the HRESULT into a WCHAR*, because that makes no sense. It's basically saying "hey, I have this error code 0x80070057, why don't you go to that location in memory and try to read a string?"

The error code 0x80070057 is E_INVALIDARG, by the way.

How would I go about formatting the hresult into a string? Also, is there a list of all the error codes and what they mean?

EDIT: Found the error code page.

Okay I think i've managed to get it working on the error reporting.

http://puu.sh/5VWZR.png

Line 154:


hr = g_Device->CreateBuffer(&cb, NULL, &g_PerObjectbuffer);
	if(FAILED(hr)) {
		_com_error err(hr);
		const TCHAR * error = err.ErrorMessage();
		DXTraceW(__FILE__, __LINE__, hr,(const WCHAR *)error, true);
	}
	camPosition = DirectX::XMVectorSet(0.0f, 0.0f, -0.5f, 0.0f);
	camTarget = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	camUp = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	camView = DirectX::XMMatrixLookAtLH(camPosition, camTarget, camUp);

	camProjection = DirectX::XMMatrixPerspectiveFovLH(0.4f * 3.14f, (float)width/height, 1.0f, 1000.0f);

You can't pass a char * to a function that expects a wide char * just by casting it. Either convert it using something like MultiByteToWideChar or just pass NULL (no message is still better than random chinese gibberish).

As for why you get the error, you're setting the size of your buffer to sizeof(g_PerObjectbuffer), which is the size of the pointer you will be assigning the buffer to (4 or 8 bytes). That makes no sense and it's not a valid value because:

If the bind flag is D3D11_BIND_CONSTANT_BUFFER, you must set the ByteWidth value in multiples of 16

Thanks. It now produces this error: http://puu.sh/5Wct2.png

Which is this:


	CHAR* pVertexShaderCode =   "struct VS_OUTPUT"
								"{"
									"float4 Pos : SV_POSITION;"
									"float4 Color : COLOR;"
								"};cbuffer PerObject { float4x4 WVP;};"
							"VS_OUTPUT vertex_shader( in float4 posIn : POSITION, in float4 colorIn : COLOR,"
                            "out float4 posOut : SV_POSITION, out float4 colorOut : COLOR)"
                            "{ VS_OUTPUT output; posOut = posIn; output.Pos = mul(inPos, WVP);"
                            "  output.Color = colorIn; return output; }";

	CHAR* pPixelShaderCode =    "float4 pixel_shader( VS_OUTPUT input) : SV_TARGET"    
                            "{ return input.Color; }";

	ID3D10Blob* pVertexShaderBytecode = NULL;  
    ID3D10Blob* pCompileErrors = NULL;

	
	hr = D3DCompile(pVertexShaderCode,  lstrlenA( pVertexShaderCode ) + 1, "vertex shader", NULL, NULL, "vertex_shader", "vs_4_0", NULL, 0, &pVertexShaderBytecode, &pCompileErrors );  
	if(FAILED(hr)) {
		_com_error err(hr);
		DXTraceW(__FILE__, __LINE__, hr,NULL, true);
	}

I've compared my code to the code from the tutorial and I don't see any differences.

This topic is closed to new replies.

Advertisement