Thursday, February 27, 2025
spot_img

directx – Points rendering a dice in Direct3D11


I began finding out DirectX just lately and I am growing an “recreation engine”. For now I simply wish to draw a dice, however for some motive that I do not know why, it would not draw it in any respect. It is most likely some silly error however I do not know a lot about DirectX so I do not actually know what’s the downside :,)

Any concepts?

Primary.cpp

#pragma remark(lib, "d3d11.lib")
#pragma remark(lib, "d3dcompiler.lib")
#pragma remark(lib, "user32")             
#pragma remark( lib, "dxgi.lib")        
#embody 
#embody 
#embody 
#embody 
#embody 
#embody 
#embody "Variables.h"

bool InitializeDirect3dApp(HINSTANCE hInstance);
void CleanUp();
bool InitScene();
void UpdateScene();
void DrawScene();

bool InitializeDirect3dApp(HINSTANCE hInstance);

const int Width = 1920;
const int Peak = 1080;

bool InitializeWindow(HINSTANCE hInstance,
    int ShowWnd,
    int width, int top,
    bool windowed);

int messageloop();

LRESULT CALLBACK WndProc(HWND hWnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam);

int WINAPI WinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPSTR lpCmdLine,
    _In_ int nShowCmd)
{
    if (!InitializeWindow(hInstance, nShowCmd, Width, Peak, true))
    {
        MessageBox(0, L"An error has ocurred throughout window initialization!",
            L"Error", MB_OK);
        return 0;
    }

    if (!InitializeDirect3dApp(hInstance)) {
        MessageBox(0, L"An error has occurred throughout Direct3D initialization!", L"Error", MB_OK);
        return 0;
    }

    InitializeDirect3dApp(hInstance);
    messageloop();
    CleanUp();

    return 0;
}

bool InitializeWindow(HINSTANCE hInstance,
    int ShowWnd,
    int width, int top,
    bool windowed)
 CS_VREDRAW;    //class kinds
    wc.lpfnWndProc = WndProc;    //Default home windows process perform
    wc.cbClsExtra = NULL;    //Further bytes after our wc construction
    wc.cbWndExtra = NULL;    //Further bytes after our home windows occasion
    wc.hInstance = hInstance;    //Occasion to present software
    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);    //Title bar Icon
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);    //Default mouse Icon
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 2);    //Window bg coloration
    wc.lpszMenuName = NULL;    //Identify of the menu hooked up to our window
    wc.lpszClassName = WndClassName;    //Identify of our home windows class
    wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO); //Icon in your taskbar

    if (!RegisterClassEx(&wc))
     MB_ICONERROR);
        return false;
    

    hwnd = CreateWindowEx(
        NULL,
        WndClassName,
        windowName,
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        width,
        top,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (!hwnd)
     MB_ICONERROR);
        return false;
    

    ShowWindow(hwnd, ShowWnd);
    UpdateWindow(hwnd);

    return true;


//Initializes D3D11
bool InitializeDirect3dApp(HINSTANCE hInstance)
{
    DXGI_MODE_DESC bufferDesc;

    ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));

    bufferDesc.Width = Width;
    bufferDesc.Peak = Peak;
    bufferDesc.RefreshRate.Numerator = 60;
    bufferDesc.RefreshRate.Denominator = 1;
    bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

    DXGI_SWAP_CHAIN_DESC swapChainDesc = {};

    ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));

    swapChainDesc.BufferCount = 3;
    swapChainDesc.BufferDesc.Width = Width;
    swapChainDesc.BufferDesc.Peak = Peak;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
    swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.OutputWindow = hwnd;
    swapChainDesc.SampleDesc.Rely = 1;
    swapChainDesc.SampleDesc.High quality = 0;
    swapChainDesc.Windowed = TRUE;
    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

    hr = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0,
        D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon);
    if (FAILED(hr))
    {
        MessageBox(NULL, L"An error has ocurred throughout D3D11 Gadget Creation!",
            TEXT("Error"), MB_OK);
        return 0;
    }

    ID3D11Texture2D* BackBuffer;
    hr = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&BackBuffer);
    if (FAILED(hr))
    {
        MessageBox(NULL, L"An error has ocurred throughout getting buffer!",
            TEXT("Error"), MB_OK);
        return 0;
    }

    hr = d3d11Device->CreateRenderTargetView(BackBuffer, nullptr, &renderTargetView);
    BackBuffer->Launch();
    if (FAILED(hr))
    {
        MessageBox(NULL, L"An error has ocurred throughout creatting render goal!",
            TEXT("Error"), MB_OK);
        return 0;
    }

    D3D11_TEXTURE2D_DESC depthStencilDesc;

    depthStencilDesc.Width = Width;
    depthStencilDesc.Peak = Peak;
    depthStencilDesc.MipLevels = 1;
    depthStencilDesc.ArraySize = 1;
    depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilDesc.SampleDesc.Rely = 1;
    depthStencilDesc.SampleDesc.High quality = 0;
    depthStencilDesc.Utilization = D3D11_USAGE_DEFAULT;
    depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    depthStencilDesc.CPUAccessFlags = 0;
    depthStencilDesc.MiscFlags = 0;

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

    d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);

    return true;
}

void CleanUp()
{
    SwapChain->Launch();
    d3d11Device->Launch();
    d3d11DevCon->Launch();
    renderTargetView->Launch();
    squareVertBuffer->Launch();
    squareIndexBuffer->Launch();
    VS->Launch();
    PS->Launch();
    VS_Buffer->Launch();
    PS_Buffer->Launch();
    vertLayout->Launch();
    depthStencilView->Launch();
    depthStencilBuffer->Launch();
    cbPerObjectBuffer->Launch();
    WireFrame->Launch();
}

bool InitScene()
{
    hr = D3DCompileFromFile(L"VertexShader.hlsl", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "vs_main", "vs_5_0",
        flags, 0, &vs_blob_ptr, &error_blob);
    if (FAILED(hr)) {
        if (error_blob) {
            OutputDebugStringA((char*)error_blob->GetBufferPointer());
            error_blob->Launch();
        }
        if (vs_blob_ptr) { vs_blob_ptr->Launch(); }
    }

    hr = D3DCompileFromFile(L"VertexShader.hlsl", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "ps_main", "ps_5_0",
        flags, 0, &ps_blob_ptr, &error_blob);
    if (FAILED(hr)) {
        if (error_blob) {
            OutputDebugStringA((char*)error_blob->GetBufferPointer());
            error_blob->Launch();
        }
        if (ps_blob_ptr) { ps_blob_ptr->Launch(); }
    }

    hr = d3d11Device->CreateVertexShader(
        vs_blob_ptr->GetBufferPointer(),
        vs_blob_ptr->GetBufferSize(),
        NULL,
        &VS);

    hr = d3d11Device->CreatePixelShader(
        ps_blob_ptr->GetBufferPointer(),
        ps_blob_ptr->GetBufferSize(),
        NULL,
        &PS);

    d3d11DevCon->VSSetShader(VS, NULL, 0);
    d3d11DevCon->PSSetShader(PS, NULL, 0);

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

    indexBufferDesc.Utilization = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(DWORD) * 12 * 3;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA iinitData;

    iinitData.pSysMem = indices;
    d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &squareIndexBuffer);
    d3d11DevCon->IASetIndexBuffer(squareIndexBuffer, DXGI_FORMAT_R32_UINT, 0);

    D3D11_BUFFER_DESC vertexBufferDesc;
    ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
    vertexBufferDesc.Utilization = D3D11_USAGE_DEFAULT;
    vertexBufferDesc.ByteWidth = sizeof(Vertex) * 8;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = 0;
    vertexBufferDesc.MiscFlags = 0;
    D3D11_SUBRESOURCE_DATA vertexBufferData;
    ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
    vertexBufferData.pSysMem = v;
    hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &squareVertBuffer);
    d3d11DevCon->IASetVertexBuffers(0, 1, &squareVertBuffer, &vertex_stride, &vertex_offset);

    hr = d3d11Device->CreateInputLayout(inputElementDesc, numElements, vs_blob_ptr->GetBufferPointer(),
        vs_blob_ptr->GetBufferSize(), &input_layout_ptr);
    d3d11DevCon->IASetInputLayout(vertLayout);

    d3d11DevCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = Width;
    viewport.Peak = Peak;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;

    d3d11DevCon->RSSetViewports(1, &viewport);

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

    cbbd.Utilization = D3D11_USAGE_DEFAULT;
    cbbd.ByteWidth = sizeof(cbPerObject);
    cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbbd.CPUAccessFlags = 0;
    cbbd.MiscFlags = 0;

    hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);

    camPosition = XMVectorSet(0.0f, 3.0f, -8.0f, 0.0f);
    camTarget = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
    camUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
    camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);
    camProjection = XMMatrixPerspectiveFovLH(0.4f * 3.14f, (float)Width / Peak, 1.0f, 1000.0f);

    D3D11_RASTERIZER_DESC wfdesc;
    ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC));
    wfdesc.FillMode = D3D11_FILL_WIREFRAME;
    wfdesc.CullMode = D3D11_CULL_NONE;
    hr = d3d11Device->CreateRasterizerState(&wfdesc, &WireFrame);

    d3d11DevCon->RSSetState(WireFrame);

    return true;
}

void UpdateScene()
{
    rot += .0005f;
    if (rot > 6.28f)
        rot = 0.0f;

    dice = XMMatrixIdentity();

    XMVECTOR rotaxis = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
    Rotation = XMMatrixRotationAxis(rotaxis, rot);
    Translation = XMMatrixTranslation(0.0f, 0.0f, 4.0f);

    dice = Translation * Rotation;
}

void DrawScene()
{
    float background_colour[4] = { 0.0f, 0.0f, 1.0f, 1.0f };

    d3d11DevCon->ClearRenderTargetView(renderTargetView, background_colour);

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

    WVP = dice * camView * camProjection;
    cbPerObj.WVP = XMMatrixTranspose(WVP);
    d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
    d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);

    d3d11DevCon->DrawIndexed(index_count, 0, 0);

    SwapChain->Current(0, 0);
}

int messageloop() {
    MSG msg = { 0 };
    bool should_close = false;
    whereas (!should_close) {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        if (msg.message == WM_QUIT) { break; }
        {
            InitScene();
            UpdateScene();
            DrawScene();
        }
    }
    return msg.wParam;
}


LRESULT CALLBACK WndProc(HWND hwnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam)
{
    swap (msg)
    {

    case WM_KEYDOWN:

        if (wParam == VK_ESCAPE)  MB_ICONQUESTION) == IDYES)

                DestroyWindow(hwnd);
        
        return 0;

    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }

    return DefWindowProc(hwnd,
        msg,
        wParam,
        lParam);
}

Variables.h

#pragma as soon as
#outline WIN32_LEAN_AND_MEAN
#pragma remark(lib, "d3d11.lib")
#pragma remark(lib, "d3dcompiler.lib")
#pragma remark(lib, "user32")             
#pragma remark( lib, "dxgi.lib")        
#embody 
#embody 
#embody 
#embody 
#embody 
#embody 

utilizing namespace DirectX;

ID3DBlob* vs_blob_ptr = NULL;
ID3DBlob* ps_blob_ptr = NULL;
ID3DBlob* error_blob = NULL;
ID3D11InputLayout* input_layout_ptr = NULL;

struct Vertex    //Overloaded Vertex Construction
{
    Vertex() {}
    Vertex(float x, float y, float z,
        float cr, float cg, float cb, float ca)
        : pos(x, y, z), coloration(cr, cg, cb, ca) {}

    XMFLOAT3 pos;
    XMFLOAT4 coloration;
};

Vertex v[] =
{
    Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
    Vertex(-1.0f, +1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
    Vertex(+1.0f, +1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
    Vertex(+1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
    Vertex(-1.0f, -1.0f, +1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
    Vertex(-1.0f, +1.0f, +1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
    Vertex(+1.0f, +1.0f, +1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
    Vertex(+1.0f, -1.0f, +1.0f, 1.0f, 0.0f, 0.0f, 1.0f),
};

DWORD indices[] = {
    // entrance face
    0, 1, 2,
    0, 2, 3,

    // again face
    4, 6, 5,
    4, 7, 6,

    // left face
    4, 5, 1,
    4, 1, 0,

    // proper face
    3, 2, 6,
    3, 6, 7,

    // high face
    1, 5, 6,
    1, 6, 2,

    // backside face
    4, 0, 3,
    4, 3, 7
};

UINT vertex_stride = sizeof(Vertex);
UINT vertex_offset = 0;
UINT index_count = ARRAYSIZE(indices);

UINT flags = D3DCOMPILE_ENABLE_STRICTNESS;

LPCTSTR WndClassName = L"D3D11 Engine";
HWND hwnd = NULL;
LPCWSTR windowName = L"D3D11 Engine";
LPCWSTR Exit = L"Are you positive you wish to exit? Any unsaved progress will probably be misplaced!";
LPCWSTR Exit2 = L"Exit";

IDXGISwapChain* SwapChain = NULL;
ID3D11Device* d3d11Device = NULL;
ID3D11DeviceContext* d3d11DevCon = NULL;
ID3D11RenderTargetView* renderTargetView = NULL;

ID3D11Buffer* triangleVertBuffer;
ID3D11VertexShader* VS = NULL;
ID3D11PixelShader* PS = NULL;
ID3DBlob* VS_Buffer;
ID3DBlob* PS_Buffer;
ID3D11InputLayout* vertLayout;
ID3DBlob* errorBuffer = NULL;
ID3D11Buffer* squareIndexBuffer;
ID3D11Buffer* squareVertBuffer;
ID3D11Buffer* vertex_buffer_ptr = NULL;

ID3D11DepthStencilView* depthStencilView;
ID3D11Texture2D* depthStencilBuffer;

ID3D11Buffer* cbPerObjectBuffer;

XMMATRIX WVP;
XMMATRIX World;
XMMATRIX camView;
XMMATRIX camProjection;

XMVECTOR camPosition;
XMVECTOR camTarget;
XMVECTOR camUp;

struct cbPerObject
{
    XMMATRIX  WVP;
};

cbPerObject cbPerObj;

XMMATRIX dice;
XMMATRIX Rotation;
XMMATRIX Scale;
XMMATRIX Translation;
float rot = 0.01f;

HRESULT hr;

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

UINT numElements = ARRAYSIZE(inputElementDesc);

ID3D11RasterizerState* WireFrame;

VertexShader.hlsl

struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float4 Coloration : COLOR;
};

cbuffer cbPerObject
{
    float4x4 WVP;
};

VS_OUTPUT vs_main(float4 inPos : POSITION, float4 inColor : COLOR)
{
    VS_OUTPUT output;
    output.Pos = mul(inPos, WVP);
    output.Coloration = inColor;
    
    return output;
}

// Pixel Shader
float4 ps_main(VS_OUTPUT enter) : SV_TARGET
{
    return enter.Coloration; 
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -spot_img

Latest Articles