Sign in to follow this  
Linkandzelda

DX11 Depth Buffer rendering nothing

Recommended Posts

Linkandzelda    110

Hello, I'm completely new to Directx 11 and I'm trying to implement a depth buffer in my program. Currently this is the result I'm getting when trying to render:

 

https://dl.dropboxusercontent.com/u/2873587/ZBufferFail.mp4

 

I've followed 2 different tutorials for depth buffer and it results in the same thing, so I'm starting to think the issue is related to something elsewhere in the code. Problem is, I don't have enough experience to know where to look or where to begin, so attached is my complete main.cpp file and shaders.hlsl.

 

main.cpp

#include <windows.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <dxerr.h>

#define _XM_NO_INTRINSICS_
#define XM_NO_ALIGNMENT
#include <xnamath.h>

#include <windows.h>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;;

//////////////////////////////////////////////////////////////////////////////////////
//	Global Variables
//////////////////////////////////////////////////////////////////////////////////////
HINSTANCE	g_hInst = NULL;
HWND		g_hWnd = NULL;

ID3D11Buffer*			g_pVertexBuffer;                
ID3D11VertexShader*		g_pVertexShader;         
ID3D11PixelShader*		g_pPixelShader;          
ID3D11InputLayout*		g_pInputLayout; 

ID3D11DepthStencilView* depthStencilView;
ID3D11Texture2D* depthStencilBuffer;

// Define vertex structure
struct POS_COL_VERTEX
{
	XMFLOAT3 Pos;
	XMFLOAT4 Col;
};

// Define vertices of a triangle - screen coordinates -1.0 to +1.0
    POS_COL_VERTEX vertices[] =
    {
         {XMFLOAT3(0.0f, 0.5f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)},
		 {XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)},
         {XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)},

		 {XMFLOAT3(0.0f, 0.5f, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)},
         {XMFLOAT3(0.5f, -0.5f, 0.5f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)},
         {XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)},

		 {XMFLOAT3(0.0f, 0.5f, 0.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)},
         {XMFLOAT3(-0.5f, -0.5f, 0.5f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)},
		 {XMFLOAT3(0.5f, -0.5f, 0.5f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)},

		 {XMFLOAT3(0.0f, 0.5f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)},
		 {XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)},
		 {XMFLOAT3(-0.5f, -0.5f, 0.5f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)},

		 {XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)},
         {XMFLOAT3(0.5f, -0.5f, 0.5f), XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)},
		 {XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)},

		 {XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)},
         {XMFLOAT3(0.5f, -0.5f, 0.5f), XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)},
		 {XMFLOAT3(-0.5f, -0.5f, 0.5f), XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)}
         
    };

// Rename for each tutorial
char		g_TutorialName[100] = "SWD304 - Tutorial 06 Exercise 01\0";

D3D_DRIVER_TYPE         g_driverType = D3D_DRIVER_TYPE_NULL;
D3D_FEATURE_LEVEL       g_featureLevel = D3D_FEATURE_LEVEL_11_0;
ID3D11Device*           g_pD3DDevice = NULL;
ID3D11DeviceContext*    g_pImmediateContext = NULL;
IDXGISwapChain*         g_pSwapChain = NULL;

ID3D11RenderTargetView* g_pBackBufferRTView = NULL;

float g_clear_colour[4] = {0.8f, 0.8f, 0.8f, 1.0f};

int screen_res[] = {640, 480};

ID3D11Buffer*			g_pConstantBuffer0; 

float redUpdate = 0.0f;
float scaleUpdate = 1.0f;
float xMod = 0.0f;
float yMod = 0.0f;

// Const buffer structs. Pack to 16 bytes. Don't let any single element cross a 16 byte boundary
struct CONSTANT_BUFFER0 
{
	float RedAmount;  	// 4 bytes
	float ScaleAmount; // 4 bytes
	float xModAmount; // 4 bytes
	float yModAmount; // 4 bytes
	XMMATRIX WorldViewProjection; // 64 bytes
	// Total 80
};

int buffer0_size = 80;

// World vars
float world_z = 2.00f;
float world_x = 0.00f;
float world_y = 0.00f;

float world_fieldOfView = 45.00f;
float world_z_min = 0.00f;
float world_z_max = 100.00f;

float x_degrees = 00.00f;
float y_degrees = 00.00f;
float z_degrees = 00.00f;

//////////////////////////////////////////////////////////////////////////////////////
//	Forward declarations
//////////////////////////////////////////////////////////////////////////////////////
HRESULT InitialiseWindow(HINSTANCE hInstance, int nCmdShow);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

HRESULT InitialiseD3D();
void ShutdownD3D();
void RenderFrame(void);
static void Draw();

HRESULT InitialiseGraphics(void);

//////////////////////////////////////////////////////////////////////////////////////
// Entry point to the program. Initializes everything and goes into a message processing 
// loop. Idle time is used to render the scene.
//////////////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

	if(FAILED(InitialiseWindow(hInstance, nCmdShow)))
	{
		DXTRACE_MSG("Failed to create Window");
		return 0;
	}

	if(FAILED(InitialiseD3D()))
    {
 		DXTRACE_MSG("Failed to create Device");
		return 0;
    }

	if(FAILED(InitialiseGraphics())) 
	{
		DXTRACE_MSG( "Failed to initialise graphics" );
		return 0;
	}


	// Main message loop
	MSG msg = {0};

	while(msg.message != WM_QUIT)
	{
		if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			RenderFrame();
		}
	}

	ShutdownD3D();

	return (int) msg.wParam;
}


//////////////////////////////////////////////////////////////////////////////////////
// Register class and create window
//////////////////////////////////////////////////////////////////////////////////////
HRESULT InitialiseWindow(HINSTANCE hInstance, int nCmdShow)
{
	// Give your app window your own name
	char Name[100] = "Kristian Thomson\0";

	// Register class
	WNDCLASSEX wcex={0};
	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = WndProc;
	wcex.hInstance = hInstance;
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
//   wcex.hbrBackground = (HBRUSH )( COLOR_WINDOW + 1); // Needed for non-D3D apps
	wcex.lpszClassName = Name;

	if(!RegisterClassEx(&wcex)) return E_FAIL;

	// Create window
	g_hInst = hInstance;
	RECT rc = {0, 0, screen_res[0], screen_res[1]}; 
	AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
	g_hWnd = CreateWindow(	Name, g_TutorialName, WS_OVERLAPPEDWINDOW,
				CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, 
				rc.bottom - rc.top, NULL, NULL, hInstance, NULL);
	if(!g_hWnd)
		return E_FAIL;

	ShowWindow(g_hWnd, nCmdShow);

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////////////////
// Called every time the application receives a message
//////////////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;

	int mouse_x = LOWORD(lParam);
	int mouse_y = HIWORD(lParam);

	float pointX = ((2.0f * (float)mouse_x) / (float) screen_res[0]) - 1.0f;
	float pointY = (((2.0f * (float)mouse_y) / (float) screen_res[1]) - 1.0f) * -1.0f;

	switch(message)
	{
		case WM_PAINT:
			hdc = BeginPaint(hWnd, &ps);
			EndPaint(hWnd, &ps);
			break;

		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		case WM_LBUTTONDOWN:
			vertices[0].Pos.z -= 0.05f;
			vertices[1].Pos.z -= 0.05f;
			vertices[2].Pos.z -= 0.05f;

			//redUpdate += 0.05f;
			//scaleUpdate += 0.05f;
			
			break;

		case WM_RBUTTONDOWN:
			vertices[0].Pos.z += 0.05f;
			vertices[1].Pos.z += 0.05f;
			vertices[2].Pos.z += 0.05f;

			//redUpdate -= 0.05f;
			//scaleUpdate -= 0.05f;
			break;
		
		case WM_MOUSEMOVE:
			//g_clear_colour[0] = pointX;
			//g_clear_colour[1] = pointY;
			//g_clear_colour[2] = (mouse_x/mouse_y)/2;

			//vertices[0].Pos.x = pointX;
			//vertices[0].Pos.y = pointY;

			//vertices[3].Pos.x = pointX;
			//vertices[3].Pos.y = pointY;

			/*if (pointX > 0.0f && pointY > 0.0f) {
				vertices[1].Pos.x = pointX + -0.5f;
				vertices[1].Pos.y = pointY + -0.5f;
			}
			else {
				vertices[1].Pos.x = pointX + 0.5f;
				vertices[1].Pos.y = pointY + 0.5f;
			}*/

			//float xxx = vertices[3].Pos.x;
			break;

		case WM_KEYDOWN: 
			if(wParam == VK_ESCAPE) {
				DestroyWindow(g_hWnd);
				return 0;
			}
			if(wParam == VK_DOWN) {
				yMod -= 0.05f;
				world_z += 0.05f;
				break;
			}
			if(wParam == VK_UP) {
				yMod += 0.05f;
				world_z -= 0.05f;
				break;
			}
			if(wParam == VK_LEFT) {
				xMod -= 0.05f;
				world_x += 0.05f;
				break;
			}
			if(wParam == VK_RIGHT) {
				xMod += 0.05f;
				world_x -= 0.05f;
				break;
			}

			if(wParam == 0x54) {
				xMod += 0.05f;
				x_degrees -= 1.50f;
				break;
			}

			if(wParam == 0x59) {
				xMod += 0.05f;
				x_degrees += 1.50f;
				break;
			}
			if(wParam == 0x47) {
				xMod += 0.05f;
				y_degrees -= 1.50f;
				break;
			}

			if(wParam == 0x48) {
				xMod += 0.05f;
				y_degrees += 1.50f;
				break;
			}
			if(wParam == 0x42) {
				xMod += 0.05f;
				z_degrees -= 1.50f;
				break;
			}

			if(wParam == 0x4E) {
				xMod += 0.05f;
				z_degrees += 1.50f;
				break;
			}
            break;    		
             
		case WM_SIZE:
        if (g_pSwapChain)
        {
            g_pImmediateContext->OMSetRenderTargets(0, 0, 0);

            // Release all outstanding references to the swap chain's buffers.
            g_pBackBufferRTView->Release();

            HRESULT hr;
            // Preserve the existing buffer count and format.
            // Automatically choose the width and height to match the client rect for HWNDs.
            hr = g_pSwapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
                                            
            // Perform error handling here!

            // Get buffer and create a render-target-view.
            ID3D11Texture2D* pBuffer;
            hr = g_pSwapChain->GetBuffer(0, __uuidof( ID3D11Texture2D),
                                         (void**) &pBuffer );
            // Perform error handling here!

            hr = g_pD3DDevice->CreateRenderTargetView(pBuffer, NULL,
                                                     &g_pBackBufferRTView);
            // Perform error handling here!
            pBuffer->Release();

            g_pImmediateContext->OMSetRenderTargets(1, &g_pBackBufferRTView, NULL );

            // Set up the viewport.
			//RECT rc;
			//UINT width = rc.right - rc.left;
			//UINT height = rc.bottom - rc.top;

            D3D11_VIEWPORT vp;
            vp.Width = mouse_x;
            vp.Height = mouse_y;
            vp.MinDepth = 0.0f;
            vp.MaxDepth = 1.0f;
            vp.TopLeftX = 0;
            vp.TopLeftY = 0;
            g_pImmediateContext->RSSetViewports( 1, &vp );
        }
		break;

		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
	}

	return 0;
}

//////////////////////////////////////////////////////////////////////////////////////
// Create D3D device and swap chain
//////////////////////////////////////////////////////////////////////////////////////
HRESULT InitialiseD3D()
{
	HRESULT hr = S_OK;

	RECT rc;
	GetClientRect(g_hWnd, &rc);
	UINT width = rc.right - rc.left;
	UINT height = rc.bottom - rc.top;

	UINT createDeviceFlags = 0;

#ifdef _DEBUG
	createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_DRIVER_TYPE driverTypes[] =
	{
		D3D_DRIVER_TYPE_HARDWARE, // comment out this line if you need to test D3D 11.0 functionality on hardware that doesn't support it
		D3D_DRIVER_TYPE_WARP, // comment this out also to use reference device
		D3D_DRIVER_TYPE_REFERENCE,
	};
	UINT numDriverTypes = ARRAYSIZE(driverTypes);

	D3D_FEATURE_LEVEL featureLevels[] =
	{
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
	};
	UINT numFeatureLevels = ARRAYSIZE(featureLevels);

	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 = g_hWnd;
	sd.SampleDesc.Count = 1;
	sd.SampleDesc.Quality = 0;
	sd.Windowed = true;
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	for(UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
	{
		g_driverType = driverTypes[driverTypeIndex];
		hr = D3D11CreateDeviceAndSwapChain(NULL, g_driverType, NULL, 
			createDeviceFlags, featureLevels, numFeatureLevels, 
			D3D11_SDK_VERSION, &sd, &g_pSwapChain, 
			&g_pD3DDevice, &g_featureLevel, &g_pImmediateContext);
		if(SUCCEEDED(hr))
			break;
	}

	if(FAILED(hr))
		return hr;

	// Get pointer to back buffer texture
	ID3D11Texture2D *pBackBufferTexture;
	hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
                                      (LPVOID*)&pBackBufferTexture);

	if(FAILED(hr)) return hr;
	
	// Use the back buffer texture pointer to create the render target view
	hr = g_pD3DDevice->CreateRenderTargetView(pBackBufferTexture, NULL,
                                                    &g_pBackBufferRTView);
	pBackBufferTexture->Release();

	if(FAILED(hr)) return hr;

	//Describe our Depth/Stencil Buffer
	D3D11_TEXTURE2D_DESC depthStencilDesc;

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

	g_pD3DDevice->CreateTexture2D(&depthStencilDesc, NULL, &depthStencilBuffer);
	g_pD3DDevice->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);

	// Set the render target view
	g_pImmediateContext->OMSetRenderTargets(1, &g_pBackBufferRTView, depthStencilView);

	// Set the viewport
	D3D11_VIEWPORT viewport;

	viewport.TopLeftX = 0;
	viewport.TopLeftY = 0;
	viewport.Width = width;
	viewport.Height = height;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;

	g_pImmediateContext->RSSetViewports(1, &viewport);


	return S_OK;
}

//////////////////////////////////////////////////////////////////////////////////////
// Clean up D3D objects
//////////////////////////////////////////////////////////////////////////////////////
void ShutdownD3D()
{
	if(g_pVertexBuffer) g_pVertexBuffer->Release();
	if(g_pInputLayout) g_pInputLayout->Release();
	if(g_pVertexShader) g_pVertexShader->Release();
	if(g_pPixelShader) g_pPixelShader->Release();
	
	if(g_pSwapChain) g_pSwapChain->Release();
	if(g_pImmediateContext) g_pImmediateContext->Release();
	if(g_pD3DDevice) g_pD3DDevice->Release();

	if(g_pBackBufferRTView) g_pBackBufferRTView->Release();

	if(g_pConstantBuffer0) g_pConstantBuffer0->Release();

	if(depthStencilView) depthStencilView->Release();
	if(depthStencilBuffer) depthStencilBuffer->Release();
}

// Render frame
void RenderFrame(void)
{
	g_pImmediateContext->ClearRenderTargetView(g_pBackBufferRTView, g_clear_colour);

	g_pImmediateContext->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);

	CONSTANT_BUFFER0 cb0_values;

	// Update world view projection
	XMMATRIX projection, world, view;
	XMMATRIX world2;

	world = XMMatrixRotationX(XMConvertToRadians(45));
	world *= XMMatrixRotationY(XMConvertToRadians(45));
	world *= XMMatrixRotationZ(XMConvertToRadians(45));
	world *= XMMatrixTranslation(0, 0 , 5);

	projection = XMMatrixPerspectiveFovLH(XMConvertToRadians(world_fieldOfView), (float)screen_res[0]/(float)screen_res[1], world_z_min, world_z_max);
	view = XMMatrixIdentity();
	view *= XMMatrixTranslation(world_x, world_y , 0);
	cb0_values.WorldViewProjection = world * view * projection;

	// Set vertex buffer 
	UINT stride = sizeof(POS_COL_VERTEX);
	UINT offset = 0;
	g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset);

	// Select which primtive type to use
	g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Draw the vertex buffer to the back buffer
	g_pImmediateContext->Draw(sizeof(vertices), 0);

	// upload the new values for the constant buffer
	g_pImmediateContext->UpdateSubresource(g_pConstantBuffer0, 0, 0, &cb0_values, 0, 0);

	world2 = XMMatrixRotationX(XMConvertToRadians(x_degrees));
	world2 *= XMMatrixRotationY(XMConvertToRadians(y_degrees));
	world2 *= XMMatrixRotationZ(XMConvertToRadians(z_degrees));
	world2 *= XMMatrixTranslation(0, 0.3f, world_z);

	cb0_values.WorldViewProjection = world2 * view * projection;

	g_pImmediateContext->UpdateSubresource(g_pConstantBuffer0, 0, 0, &cb0_values, 0, 0);

	// Draw the vertex buffer to the back buffer
	g_pImmediateContext->Draw(sizeof(vertices), 0);

	// Display what has just been rendered
	g_pSwapChain->Present(0, 0);

	Draw();
}

static void Draw() {
	D3D11_MAPPED_SUBRESOURCE ms;
	g_pImmediateContext->Map(g_pVertexBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms);	// Lock the buffer to allow writing
	memcpy(ms.pData, vertices, sizeof(vertices)); // Copy the data
	g_pImmediateContext->Unmap(g_pVertexBuffer, NULL);	// Unlock the buffer
}

HRESULT InitialiseGraphics()
{
    HRESULT hr = S_OK;

    // Set up and create vertex buffer
    D3D11_BUFFER_DESC bufferDesc;
    ZeroMemory(&bufferDesc, sizeof(bufferDesc));
    bufferDesc.Usage = D3D11_USAGE_DYNAMIC;		// Used by CPU and GPU
    bufferDesc.ByteWidth = sizeof(POS_COL_VERTEX) * sizeof(vertices);	// Total size of buffer, 3 vertices
    bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;	// Use as a vertex buffer
    bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;// Allow CPU access
    hr = g_pD3DDevice->CreateBuffer(&bufferDesc, NULL, &g_pVertexBuffer);//Create the buffer

    if(FAILED(hr)) // return error code on failure
    {
         return hr;
    }
	

	// Create constant buffer
	D3D11_BUFFER_DESC constant_buffer_desc;
	ZeroMemory(&constant_buffer_desc, sizeof(constant_buffer_desc));

	constant_buffer_desc.Usage = D3D11_USAGE_DEFAULT;	// Can use UpdateSubresource() to update
	constant_buffer_desc.ByteWidth = buffer0_size;	// MUST be a multiple of 16, calculate from CB struct
	constant_buffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;// Use as a constant buffer

	hr = g_pD3DDevice->CreateBuffer(&constant_buffer_desc, NULL, &g_pConstantBuffer0);

	if(FAILED(hr)) return hr;

    // Copy the vertices into the buffer
    Draw();

    // Load and compile pixel and vertex shaders - use vs_5_0 to target DX11 hardware only
    ID3DBlob *VS, *PS, *error;
    hr = D3DX11CompileFromFile("shaders.hlsl", 0, 0, "VShader", "vs_4_0", 0, 0, 0, &VS, &error, 0);

    if(error != 0) // check for shader compilation error
    {
        OutputDebugStringA((char*)error->GetBufferPointer());
        error->Release();
        if(FAILED(hr)) // don't fail if error is just a warning
        {
            return hr;
        };
    }


    hr = D3DX11CompileFromFile("shaders.hlsl", 0, 0, "PShader", "ps_4_0", 0, 0, 0, &PS, &error, 0);

    if(error != 0)// check for shader compilation error
    {
        OutputDebugStringA((char*)error->GetBufferPointer());
        error->Release();
        if(FAILED(hr))// don't fail if error is just a warning
        {
            return hr;
        };
    }


    // Create shader objects
    hr = g_pD3DDevice->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &g_pVertexShader);

    if(FAILED(hr))
    {
        return hr;
    }
    
    hr = g_pD3DDevice->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &g_pPixelShader);

    if(FAILED(hr))
    {
        return hr;
    }

    // Set the shader objects as active
    g_pImmediateContext->VSSetShader(g_pVertexShader, 0, 0);
    g_pImmediateContext->PSSetShader(g_pPixelShader, 0, 0);
	g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer0);

    // Create and set the input layout object
    D3D11_INPUT_ELEMENT_DESC iedesc[] =
    {
      {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
      {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
    };

    hr = g_pD3DDevice->CreateInputLayout(iedesc, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &g_pInputLayout);

    if(FAILED(hr))
    {
        return hr;
    }

    g_pImmediateContext->IASetInputLayout(g_pInputLayout);

    return S_OK;
 }

Shaders

cbuffer CBuffer0
{
	float red_fraction; // 4 bytes
	float scale_fraction; // 4 bytes
	float xmod_fraction; // 4 bytes
	float ymod_fraction; // 4 bytes
	matrix WVPMatrix;	// 64 bytes
}


struct VOut
 {
     float4 position : SV_POSITION;
     float4 color : COLOR;
 };

 VOut VShader(float4 position : POSITION, float4 color : COLOR)
 {
     VOut output;

	 //color.r *= red_fraction;
	 //position.x *= scale_fraction;
	 //position.y *= scale_fraction;

	 //position.x += xmod_fraction;
	 //position.y += ymod_fraction;

     //output.position = position;
     output.color = color;

	 //output.color.g = output.position.y;
	 //output.color.b = output.position.x;

	 output.position = mul(WVPMatrix, position);

     return output;
 }


 float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
 {
	 //color.g = position.x;
	 //color.r = position.y;
	 
	 return color;
 }

Thank you very much in advance, I've been stuck on this all day and I have no idea what else to do to fix it.

Edited by Linkandzelda

Share this post


Link to post
Share on other sites
Zaoshi Kaba    8434

1. world_z_min cannot be 0. Use 0.1f or something similar.

 

2. 

g_pImmediateContext->Draw(sizeof(vertices), 0); 

sizeof() returns size in bytes, but Draw() call requires number of vertices, use ARRAYSIZE() macro.

Edited by Zaoshi Kaba

Share this post


Link to post
Share on other sites
Linkandzelda    110

1. world_z_min cannot be 0. Use 0.1f or something similar.

 

2. 

g_pImmediateContext->Draw(sizeof(vertices), 0); 

sizeof() returns size in bytes, but Draw() call requires number of vertices, use ARRAYSIZE() macro.

 

Hey, thanks so much! The min distance was the cause haha, can't believe I missed that one. As for the sizeof, good call, even though it's been working with that method so far.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By KaiserJohan
      Just a really quick question - is there any overhead to using DrawIndexedInstanced even for geometry you just render once vs using DrawIndexed? Or is the details obfuscated by the graphics driver?
      I would assume no but you never know  
    • By isu diss
       I'm trying to code Rayleigh part of Nishita's model (Display Method of the Sky Color Taking into Account Multiple Scattering). I get black screen no colors. Can anyone find the issue for me?
       
      #define InnerRadius 6320000 #define OutterRadius 6420000 #define PI 3.141592653 #define Isteps 20 #define Ksteps 10 static float3 RayleighCoeffs = float3(6.55e-6, 1.73e-5, 2.30e-5); RWTexture2D<float4> SkyColors : register (u0); cbuffer CSCONSTANTBUF : register( b0 ) { float fHeight; float3 vSunDir; } float Density(float Height) { return exp(-Height/8340); } float RaySphereIntersection(float3 RayOrigin, float3 RayDirection, float3 SphereOrigin, float Radius) { float t1, t0; float3 L = SphereOrigin - RayOrigin; float tCA = dot(L, RayDirection); if (tCA < 0) return -1; float lenL = length(L); float D2 = (lenL*lenL) - (tCA*tCA); float Radius2 = (Radius*Radius); if (D2<=Radius2) { float tHC = sqrt(Radius2 - D2); t0 = tCA-tHC; t1 = tCA+tHC; } else return -1; return t1; } float RayleighPhaseFunction(float cosTheta) { return ((3/(16*PI))*(1+cosTheta*cosTheta)); } float OpticalDepth(float3 StartPosition, float3 EndPosition) { float3 Direction = normalize(EndPosition - StartPosition); float RayLength = RaySphereIntersection(StartPosition, Direction, float3(0, 0, 0), OutterRadius); float SampleLength = RayLength / Isteps; float3 tmpPos = StartPosition + 0.5 * SampleLength * Direction; float tmp; for (int i=0; i<Isteps; i++) { tmp += Density(length(tmpPos)-InnerRadius); tmpPos += SampleLength * Direction; } return tmp*SampleLength; } static float fExposure = -2; float3 HDR( float3 LDR) { return 1.0f - exp( fExposure * LDR ); } [numthreads(32, 32, 1)] //disptach 8, 8, 1 it's 256 by 256 image void ComputeSky(uint3 DTID : SV_DispatchThreadID) { float X = ((2 * DTID.x) / 255) - 1; float Y = 1 - ((2 * DTID.y) / 255); float r = sqrt(((X*X)+(Y*Y))); float Theta = r * (PI); float Phi = atan2(Y, X); static float3 Eye = float3(0, 10, 0); float ViewOD = 0, SunOD = 0, tmpDensity = 0; float3 Attenuation = 0, tmp = 0, Irgb = 0; //if (r<=1) { float3 ViewDir = normalize(float3(sin(Theta)*cos(Phi), cos(Theta),sin(Theta)*sin(Phi) )); float ViewRayLength = RaySphereIntersection(Eye, ViewDir, float3(0, 0, 0), OutterRadius); float SampleLength = ViewRayLength / Ksteps; //vSunDir = normalize(vSunDir); float cosTheta = dot(normalize(vSunDir), ViewDir); float3 tmpPos = Eye + 0.5 * SampleLength * ViewDir; for(int k=0; k<Ksteps; k++) { float SunRayLength = RaySphereIntersection(tmpPos, vSunDir, float3(0, 0, 0), OutterRadius); float3 TopAtmosphere = tmpPos + SunRayLength*vSunDir; ViewOD = OpticalDepth(Eye, tmpPos); SunOD = OpticalDepth(tmpPos, TopAtmosphere); tmpDensity = Density(length(tmpPos)-InnerRadius); Attenuation = exp(-RayleighCoeffs*(ViewOD+SunOD)); tmp += tmpDensity*Attenuation; tmpPos += SampleLength * ViewDir; } Irgb = RayleighCoeffs*RayleighPhaseFunction(cosTheta)*tmp*SampleLength; SkyColors[DTID.xy] = float4(Irgb, 1); } }  
    • By Endurion
      I have a gaming framework with an renderer interface. Those support DX8, DX9 and latest, DX11. Both DX8 and DX9 use fixed function pipeline, while DX11 obviously uses shaders. I've got most of the parts working fine, as in I can switch renderers and notice almost no difference. The most advanced features are 2 directional lights with a single texture  
      My last problem is lighting; albeit there's documentation on the D3D lighting model I still can't get the behaviour right. My mistake shows most prominently in the dark side opposite the lights. I'm pretty sure the ambient calculation is off, but that one's supposed to be the most simple one and should be hard to get wrong.
      Interestingly I've been searching high and low, and have yet to find a resource that shows how to build a HLSL shader where diffuse, ambient and specular are used together with material properties. I've got various shaders for all the variations I'm supporting. I stepped through the shader with the graphics debugger, but the calculation seems to do what I want. I'm just not sure the formula is correct.
      This one should suffice though, it's doing two directional lights, texture modulated with vertex color and a normal. Maybe someone can spot one (or more mistakes). And yes, this is in the vertex shader and I'm aware lighting will be as "bad" as in fixed function; that's my goal currently.
      // A constant buffer that stores the three basic column-major matrices for composing geometry. cbuffer ModelViewProjectionConstantBuffer : register(b0) { matrix model; matrix view; matrix projection; matrix ortho2d; }; struct DirectionLight { float3 Direction; float PaddingL1; float4 Ambient; float4 Diffuse; float4 Specular; }; cbuffer LightsConstantBuffer : register( b1 ) { float4 Ambient; float3 EyePos; float PaddingLC1; DirectionLight Light[8]; }; struct Material { float4 MaterialEmissive; float4 MaterialAmbient; float4 MaterialDiffuse; float4 MaterialSpecular; float MaterialSpecularPower; float3 MaterialPadding; }; cbuffer MaterialConstantBuffer : register( b2 ) { Material _Material; }; // Per-vertex data used as input to the vertex shader. struct VertexShaderInput { float3 pos : POSITION; float3 normal : NORMAL; float4 color : COLOR0; float2 tex : TEXCOORD0; }; // Per-pixel color data passed through the pixel shader. struct PixelShaderInput { float4 pos : SV_POSITION; float2 tex : TEXCOORD0; float4 color : COLOR0; }; // Simple shader to do vertex processing on the GPU. PixelShaderInput main(VertexShaderInput input) { PixelShaderInput output; float4 pos = float4( input.pos, 1.0f ); // Transform the vertex position into projected space. pos = mul(pos, model); pos = mul(pos, view); pos = mul(pos, projection); output.pos = pos; // pass texture coords output.tex = input.tex; // Calculate the normal vector against the world matrix only. //set required lighting vectors for interpolation float3 normal = mul( input.normal, ( float3x3 )model ); normal = normalize( normal ); float4 ambientEffect = Ambient; float4 diffuseEffect = float4( 0, 0, 0, 0 ); float4 specularEffect = float4( 0, 0, 0, 0 ); for ( int i = 0; i < 2; ++i ) { // Invert the light direction for calculations. float3 lightDir = -Light[i].Direction; float lightFactor = max( dot( lightDir, input.normal ), 0 ); ambientEffect += Light[i].Ambient * _Material.MaterialAmbient; diffuseEffect += saturate( Light[i].Diffuse * dot( normal, lightDir ) );// * _Material.MaterialDiffuse; //specularEffect += Light[i].Specular * dot( normal, halfangletolight ) * _Material.MaterialSpecularPower; } specularEffect *= _Material.MaterialSpecular; //ambientEffect.w = 1.0; ambientEffect = normalize( ambientEffect ); /* Ambient effect: (L1.ambient + L2.ambient) * object ambient color Diffuse effect: (L1.diffuse * Dot(VertexNormal, Light1.Direction) + L2.diffuse * Dot(VertexNormal, Light2.Direction)) * object diffuse color Specular effect: (L1.specular * Dot(VertexNormal, HalfAngleToLight1) * Object specular reflection power + L2.specular * Dot(VertexNormal, HalfAngleToLight2) * Object specular reflection power ) * object specular color Resulting color = Ambient effect + diffuse effect + specular effect*/ float4 totalFactor = ambientEffect + diffuseEffect + specularEffect; totalFactor.w = 1.0; output.color = input.color * totalFactor; return output; }   Edit: This message editor is driving me nuts (Arrrr!) - I don't write code in Word.
    • By Mercesa
      Hey folks. So I'm having this problem in which if my camera is close to a surface, the SSAO pass suddenly spikes up to around taking 16 milliseconds.
      When still looking towards the same surface, but less close. The framerate resolves itself and becomes regular again.
      This happens with ANY surface of my model, I am a bit clueless in regards to what could cause this. Any ideas?
      In attached image: y axis is time in ms, x axis is current frame. The dips in SSAO milliseconds are when I moved away from the surface, the peaks happen when I am very close to the surface.

       
      Edit: So I've done some more in-depth profiling with Nvidia nsight. So these are the facts from my results
      Count of command buffers goes from 4 (far away from surface) to ~20(close to surface).
      The command buffer duration in % goes from around ~30% to ~99%
      Sometimes the CPU duration takes up to 0.03 to 0.016 milliseconds per frame while comparatively usually it takes around 0.002 milliseconds.
      I am using a vertex shader which generates my full-screen quad and afterwards I do my SSAO calculations in my pixel shader, could this be a GPU driver bug? I'm a bit lost myself. It seems there could be a CPU/GPU resource stall. But why would the amount of command buffers be variable depending on distance from a surface?
       
       
      Edit n2: Any resolution above 720p starts to have this issue, and I am fairly certain my SSAO is not that performance heavy it would crap itself at a bit higher resolutions.
       
    • By turanszkij
      In DirectX 11 we have a 24 bit integer depth + 8bit stencil format for depth-stencil resources ( DXGI_FORMAT_D24_UNORM_S8_UINT ). However, in an AMD GPU documentation for consoles I have seen they mentioned, that internally this format is implemented as a 64 bit resource with 32 bits for depth (but just truncated for 24 bits) and 32 bits for stencil (truncated to 8 bits). AMD recommends using a 32 bit floating point depth buffer instead with 8 bit stencil which is this format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT.
      Does anyone know why this is? What is the usual way of doing this, just follow the recommendation and use a 64 bit depthstencil? Are there performance considerations or is it just recommended to not waste memory? What about Nvidia and Intel, is using a 24 bit depthbuffer relevant on their hardware?
      Cheers!
       
  • Popular Now