From 70c19f4619e92c9e0981907410acd443a3ed2ae0 Mon Sep 17 00:00:00 2001 From: axelpicou <115532798+axelpicou@users.noreply.github.com> Date: Wed, 20 Mar 2024 11:58:51 +0100 Subject: [PATCH 1/3] class d3d --- enginecustom/applicationclass.cpp | 32 ++ enginecustom/applicationclass.h | 4 +- enginecustom/d3dclass.cpp | 507 ++++++++++++++++++++++ enginecustom/d3dclass.h | 70 +++ enginecustom/enginecustom.vcxproj | 2 + enginecustom/enginecustom.vcxproj.filters | 6 + 6 files changed, 619 insertions(+), 2 deletions(-) create mode 100644 enginecustom/d3dclass.cpp create mode 100644 enginecustom/d3dclass.h diff --git a/enginecustom/applicationclass.cpp b/enginecustom/applicationclass.cpp index 2e18374..1b3d9ff 100644 --- a/enginecustom/applicationclass.cpp +++ b/enginecustom/applicationclass.cpp @@ -3,6 +3,7 @@ ApplicationClass::ApplicationClass() { + m_Direct3D = 0; } @@ -18,13 +19,31 @@ ApplicationClass::~ApplicationClass() bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd) { + bool result; + + // Create and initialize the Direct3D object. + m_Direct3D = new D3DClass; + + result = m_Direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR); + if (!result) + { + MessageBox(hwnd, L"Could not initialize Direct3D", L"Error", MB_OK); + return false; + } return true; } void ApplicationClass::Shutdown() { + // Release the Direct3D object. + if (m_Direct3D) + { + m_Direct3D->Shutdown(); + delete m_Direct3D; + m_Direct3D = 0; + } return; } @@ -32,13 +51,26 @@ void ApplicationClass::Shutdown() bool ApplicationClass::Frame() { + bool result; + + // Render the graphics scene. + result = Render(); + if (!result) + { + return false; + } return true; } bool ApplicationClass::Render() { + // Clear the buffers to begin the scene. + m_Direct3D->BeginScene(0.5f, 0.5f, 0.5f, 1.0f); + + // Present the rendered scene to the screen. + m_Direct3D->EndScene(); return true; } \ No newline at end of file diff --git a/enginecustom/applicationclass.h b/enginecustom/applicationclass.h index 833acfb..d62822f 100644 --- a/enginecustom/applicationclass.h +++ b/enginecustom/applicationclass.h @@ -6,7 +6,7 @@ // INCLUDES // ////////////// #include - +#include "d3dclass.h" ///////////// // GLOBALS // @@ -31,7 +31,7 @@ private: bool Render(); private: - + D3DClass* m_Direct3D; }; #endif \ No newline at end of file diff --git a/enginecustom/d3dclass.cpp b/enginecustom/d3dclass.cpp new file mode 100644 index 0000000..e87bc65 --- /dev/null +++ b/enginecustom/d3dclass.cpp @@ -0,0 +1,507 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: d3dclass.cpp +//////////////////////////////////////////////////////////////////////////////// +#include "d3dclass.h" + + +D3DClass::D3DClass() +{ + m_swapChain = 0; + m_device = 0; + m_deviceContext = 0; + m_renderTargetView = 0; + m_depthStencilBuffer = 0; + m_depthStencilState = 0; + m_depthStencilView = 0; + m_rasterState = 0; +} + + +D3DClass::D3DClass(const D3DClass& other) +{ +} + + +D3DClass::~D3DClass() +{ +} + + +bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear) +{ + HRESULT result; + IDXGIFactory* factory; + IDXGIAdapter* adapter; + IDXGIOutput* adapterOutput; + unsigned int numModes, i, numerator, denominator; + unsigned long long stringLength; + DXGI_MODE_DESC* displayModeList; + DXGI_ADAPTER_DESC adapterDesc; + int error; + DXGI_SWAP_CHAIN_DESC swapChainDesc; + D3D_FEATURE_LEVEL featureLevel; + ID3D11Texture2D* backBufferPtr; + D3D11_TEXTURE2D_DESC depthBufferDesc; + D3D11_DEPTH_STENCIL_DESC depthStencilDesc; + D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; + D3D11_RASTERIZER_DESC rasterDesc; + float fieldOfView, screenAspect; + + + // Store the vsync setting. + m_vsync_enabled = vsync; + + // Create a DirectX graphics interface factory. + result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); + if (FAILED(result)) + { + return false; + } + + // Use the factory to create an adapter for the primary graphics interface (video card). + result = factory->EnumAdapters(0, &adapter); + if (FAILED(result)) + { + return false; + } + + // Enumerate the primary adapter output (monitor). + result = adapter->EnumOutputs(0, &adapterOutput); + if (FAILED(result)) + { + return false; + } + + // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). + result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); + if (FAILED(result)) + { + return false; + } + + // Create a list to hold all the possible display modes for this monitor/video card combination. + displayModeList = new DXGI_MODE_DESC[numModes]; + if (!displayModeList) + { + return false; + } + + // Now fill the display mode list structures. + result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); + if (FAILED(result)) + { + return false; + } + + // Now go through all the display modes and find the one that matches the screen width and height. + // When a match is found store the numerator and denominator of the refresh rate for that monitor. + for (i = 0; i < numModes; i++) + { + if (displayModeList[i].Width == (unsigned int)screenWidth) + { + if (displayModeList[i].Height == (unsigned int)screenHeight) + { + numerator = displayModeList[i].RefreshRate.Numerator; + denominator = displayModeList[i].RefreshRate.Denominator; + } + } + } + + // Get the adapter (video card) description. + result = adapter->GetDesc(&adapterDesc); + if (FAILED(result)) + { + return false; + } + + // Store the dedicated video card memory in megabytes. + m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); + + // Convert the name of the video card to a character array and store it. + error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); + if (error != 0) + { + return false; + } + + // Release the display mode list. + delete[] displayModeList; + displayModeList = 0; + + // Release the adapter output. + adapterOutput->Release(); + adapterOutput = 0; + + // Release the adapter. + adapter->Release(); + adapter = 0; + + // Release the factory. + factory->Release(); + factory = 0; + + // Initialize the swap chain description. + ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); + + // Set to a single back buffer. + swapChainDesc.BufferCount = 1; + + // Set the width and height of the back buffer. + swapChainDesc.BufferDesc.Width = screenWidth; + swapChainDesc.BufferDesc.Height = screenHeight; + + // Set regular 32-bit surface for the back buffer. + swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + + // Set the refresh rate of the back buffer. + if (m_vsync_enabled) + { + swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; + swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; + } + else + { + swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; + swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; + } + + // Set the usage of the back buffer. + swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + + // Set the handle for the window to render to. + swapChainDesc.OutputWindow = hwnd; + + // Turn multisampling off. + swapChainDesc.SampleDesc.Count = 1; + swapChainDesc.SampleDesc.Quality = 0; + + // Set to full screen or windowed mode. + if (fullscreen) + { + swapChainDesc.Windowed = false; + } + else + { + swapChainDesc.Windowed = true; + } + + // Set the scan line ordering and scaling to unspecified. + swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; + swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; + + // Discard the back buffer contents after presenting. + swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + // Don't set the advanced flags. + swapChainDesc.Flags = 0; + + // Set the feature level to DirectX 11. + featureLevel = D3D_FEATURE_LEVEL_11_0; + + // Create the swap chain, Direct3D device, and Direct3D device context. + result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, + D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); + if (FAILED(result)) + { + return false; + } + + // Get the pointer to the back buffer. + result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); + if (FAILED(result)) + { + return false; + } + + // Create the render target view with the back buffer pointer. + result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); + if (FAILED(result)) + { + return false; + } + + // Release pointer to the back buffer as we no longer need it. + backBufferPtr->Release(); + backBufferPtr = 0; + + // Initialize the description of the depth buffer. + ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); + + // Set up the description of the depth buffer. + depthBufferDesc.Width = screenWidth; + depthBufferDesc.Height = screenHeight; + depthBufferDesc.MipLevels = 1; + depthBufferDesc.ArraySize = 1; + depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + depthBufferDesc.SampleDesc.Count = 1; + depthBufferDesc.SampleDesc.Quality = 0; + depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; + depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; + depthBufferDesc.CPUAccessFlags = 0; + depthBufferDesc.MiscFlags = 0; + + // Create the texture for the depth buffer using the filled out description. + result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); + if (FAILED(result)) + { + return false; + } + + // Initialize the description of the stencil state. + ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); + + // Set up the description of the stencil state. + depthStencilDesc.DepthEnable = true; + depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; + depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; + + depthStencilDesc.StencilEnable = true; + depthStencilDesc.StencilReadMask = 0xFF; + depthStencilDesc.StencilWriteMask = 0xFF; + + // Stencil operations if pixel is front-facing. + depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; + depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + + // Stencil operations if pixel is back-facing. + depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; + depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + + // Create the depth stencil state. + result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); + if (FAILED(result)) + { + return false; + } + + // Set the depth stencil state. + m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); + + // Initialize the depth stencil view. + ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); + + // Set up the depth stencil view description. + depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + depthStencilViewDesc.Texture2D.MipSlice = 0; + + // Create the depth stencil view. + result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); + if (FAILED(result)) + { + return false; + } + + // Bind the render target view and depth stencil buffer to the output render pipeline. + m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); + + // Setup the raster description which will determine how and what polygons will be drawn. + rasterDesc.AntialiasedLineEnable = false; + rasterDesc.CullMode = D3D11_CULL_BACK; + rasterDesc.DepthBias = 0; + rasterDesc.DepthBiasClamp = 0.0f; + rasterDesc.DepthClipEnable = true; + rasterDesc.FillMode = D3D11_FILL_SOLID; + rasterDesc.FrontCounterClockwise = false; + rasterDesc.MultisampleEnable = false; + rasterDesc.ScissorEnable = false; + rasterDesc.SlopeScaledDepthBias = 0.0f; + + // Create the rasterizer state from the description we just filled out. + result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); + if (FAILED(result)) + { + return false; + } + + // Now set the rasterizer state. + m_deviceContext->RSSetState(m_rasterState); + + // Setup the viewport for rendering. + m_viewport.Width = (float)screenWidth; + m_viewport.Height = (float)screenHeight; + m_viewport.MinDepth = 0.0f; + m_viewport.MaxDepth = 1.0f; + m_viewport.TopLeftX = 0.0f; + m_viewport.TopLeftY = 0.0f; + + // Create the viewport. + m_deviceContext->RSSetViewports(1, &m_viewport); + + // Setup the projection matrix. + fieldOfView = 3.141592654f / 4.0f; + screenAspect = (float)screenWidth / (float)screenHeight; + + // Create the projection matrix for 3D rendering. + m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth); + + // Initialize the world matrix to the identity matrix. + m_worldMatrix = XMMatrixIdentity(); + + // Create an orthographic projection matrix for 2D rendering. + m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth); + + return true; +} + + +void D3DClass::Shutdown() +{ + // Before shutting down set to windowed mode or when you release the swap chain it will throw an exception. + if (m_swapChain) + { + m_swapChain->SetFullscreenState(false, NULL); + } + + if (m_rasterState) + { + m_rasterState->Release(); + m_rasterState = 0; + } + + if (m_depthStencilView) + { + m_depthStencilView->Release(); + m_depthStencilView = 0; + } + + if (m_depthStencilState) + { + m_depthStencilState->Release(); + m_depthStencilState = 0; + } + + if (m_depthStencilBuffer) + { + m_depthStencilBuffer->Release(); + m_depthStencilBuffer = 0; + } + + if (m_renderTargetView) + { + m_renderTargetView->Release(); + m_renderTargetView = 0; + } + + if (m_deviceContext) + { + m_deviceContext->Release(); + m_deviceContext = 0; + } + + if (m_device) + { + m_device->Release(); + m_device = 0; + } + + if (m_swapChain) + { + m_swapChain->Release(); + m_swapChain = 0; + } + + return; +} + + +void D3DClass::BeginScene(float red, float green, float blue, float alpha) +{ + float color[4]; + + + // Setup the color to clear the buffer to. + color[0] = red; + color[1] = green; + color[2] = blue; + color[3] = alpha; + + // Clear the back buffer. + m_deviceContext->ClearRenderTargetView(m_renderTargetView, color); + + // Clear the depth buffer. + m_deviceContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0); + + return; +} + + +void D3DClass::EndScene() +{ + // Present the back buffer to the screen since rendering is complete. + if (m_vsync_enabled) + { + // Lock to screen refresh rate. + m_swapChain->Present(1, 0); + } + else + { + // Present as fast as possible. + m_swapChain->Present(0, 0); + } + + return; +} + + +ID3D11Device* D3DClass::GetDevice() +{ + return m_device; +} + + +ID3D11DeviceContext* D3DClass::GetDeviceContext() +{ + return m_deviceContext; +} + + +void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix) +{ + projectionMatrix = m_projectionMatrix; + return; +} + + +void D3DClass::GetWorldMatrix(XMMATRIX& worldMatrix) +{ + worldMatrix = m_worldMatrix; + return; +} + + +void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix) +{ + orthoMatrix = m_orthoMatrix; + return; +} + + +void D3DClass::GetVideoCardInfo(char* cardName, int& memory) +{ + strcpy_s(cardName, 128, m_videoCardDescription); + memory = m_videoCardMemory; + return; +} + + +void D3DClass::SetBackBufferRenderTarget() +{ + // Bind the render target view and depth stencil buffer to the output render pipeline. + m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); + + return; +} + + +void D3DClass::ResetViewport() +{ + // Set the viewport. + m_deviceContext->RSSetViewports(1, &m_viewport); + + return; +} \ No newline at end of file diff --git a/enginecustom/d3dclass.h b/enginecustom/d3dclass.h new file mode 100644 index 0000000..df75750 --- /dev/null +++ b/enginecustom/d3dclass.h @@ -0,0 +1,70 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: d3dclass.h +//////////////////////////////////////////////////////////////////////////////// +#ifndef _D3DCLASS_H_ +#define _D3DCLASS_H_ + + +///////////// +// LINKING // +///////////// +#pragma comment(lib, "d3d11.lib") +#pragma comment(lib, "dxgi.lib") +#pragma comment(lib, "d3dcompiler.lib") + + +////////////// +// INCLUDES // +////////////// +#include +#include +using namespace DirectX; + + +//////////////////////////////////////////////////////////////////////////////// +// Class name: D3DClass +//////////////////////////////////////////////////////////////////////////////// +class D3DClass +{ +public: + D3DClass(); + D3DClass(const D3DClass&); + ~D3DClass(); + + bool Initialize(int, int, bool, HWND, bool, float, float); + void Shutdown(); + + void BeginScene(float, float, float, float); + void EndScene(); + + ID3D11Device* GetDevice(); + ID3D11DeviceContext* GetDeviceContext(); + + void GetProjectionMatrix(XMMATRIX&); + void GetWorldMatrix(XMMATRIX&); + void GetOrthoMatrix(XMMATRIX&); + + void GetVideoCardInfo(char*, int&); + + void SetBackBufferRenderTarget(); + void ResetViewport(); + +private: + bool m_vsync_enabled; + int m_videoCardMemory; + char m_videoCardDescription[128]; + IDXGISwapChain* m_swapChain; + ID3D11Device* m_device; + ID3D11DeviceContext* m_deviceContext; + ID3D11RenderTargetView* m_renderTargetView; + ID3D11Texture2D* m_depthStencilBuffer; + ID3D11DepthStencilState* m_depthStencilState; + ID3D11DepthStencilView* m_depthStencilView; + ID3D11RasterizerState* m_rasterState; + XMMATRIX m_projectionMatrix; + XMMATRIX m_worldMatrix; + XMMATRIX m_orthoMatrix; + D3D11_VIEWPORT m_viewport; +}; + +#endif \ No newline at end of file diff --git a/enginecustom/enginecustom.vcxproj b/enginecustom/enginecustom.vcxproj index 2ab0ec6..71dcc8c 100644 --- a/enginecustom/enginecustom.vcxproj +++ b/enginecustom/enginecustom.vcxproj @@ -20,12 +20,14 @@ + + diff --git a/enginecustom/enginecustom.vcxproj.filters b/enginecustom/enginecustom.vcxproj.filters index 57a70d5..6bef417 100644 --- a/enginecustom/enginecustom.vcxproj.filters +++ b/enginecustom/enginecustom.vcxproj.filters @@ -27,6 +27,9 @@ Fichiers sources + + Fichiers sources + @@ -38,5 +41,8 @@ Fichiers d%27en-tête + + Fichiers d%27en-tête + \ No newline at end of file From 6bd66dc5d4f095d0aad1d2e78df73af2f3b12691 Mon Sep 17 00:00:00 2001 From: axelpicou <115532798+axelpicou@users.noreply.github.com> Date: Wed, 20 Mar 2024 13:03:56 +0100 Subject: [PATCH 2/3] debut triangle --- enginecustom/Color.cpp | 18 ++ enginecustom/Color.h | 21 +++ enginecustom/Color.idl | 10 ++ enginecustom/Color.ps.hlsl | 22 +++ enginecustom/Color.vs.hlsl | 50 ++++++ enginecustom/Colorshaderclass.cpp | 203 ++++++++++++++++++++++ enginecustom/Colorshaderclass.h | 56 ++++++ enginecustom/applicationclass.cpp | 2 +- enginecustom/enginecustom.vcxproj | 28 +++ enginecustom/enginecustom.vcxproj.filters | 20 +++ enginecustom/packages.config | 4 + 11 files changed, 433 insertions(+), 1 deletion(-) create mode 100644 enginecustom/Color.cpp create mode 100644 enginecustom/Color.h create mode 100644 enginecustom/Color.idl create mode 100644 enginecustom/Color.ps.hlsl create mode 100644 enginecustom/Color.vs.hlsl create mode 100644 enginecustom/Colorshaderclass.cpp create mode 100644 enginecustom/Colorshaderclass.h create mode 100644 enginecustom/packages.config diff --git a/enginecustom/Color.cpp b/enginecustom/Color.cpp new file mode 100644 index 0000000..0a1c2f3 --- /dev/null +++ b/enginecustom/Color.cpp @@ -0,0 +1,18 @@ +#include "pch.h" +#include "Color.h" +#if __has_include("Color.g.cpp") +#include "Color.g.cpp" +#endif + +namespace winrt::enginecustom::implementation +{ + int32_t Color::MyProperty() + { + throw hresult_not_implemented(); + } + + void Color::MyProperty(int32_t /*value*/) + { + throw hresult_not_implemented(); + } +} diff --git a/enginecustom/Color.h b/enginecustom/Color.h new file mode 100644 index 0000000..23ade1d --- /dev/null +++ b/enginecustom/Color.h @@ -0,0 +1,21 @@ +#pragma once + +#include "Color.g.h" + +namespace winrt::enginecustom::implementation +{ + struct Color : ColorT + { + Color() = default; + + int32_t MyProperty(); + void MyProperty(int32_t value); + }; +} + +namespace winrt::enginecustom::factory_implementation +{ + struct Color : ColorT + { + }; +} diff --git a/enginecustom/Color.idl b/enginecustom/Color.idl new file mode 100644 index 0000000..cbbecc5 --- /dev/null +++ b/enginecustom/Color.idl @@ -0,0 +1,10 @@ +namespace enginecustom +{ + [bindable] + [default_interface] + runtimeclass Color + { + Color(); + Int32 MyProperty; + } +} diff --git a/enginecustom/Color.ps.hlsl b/enginecustom/Color.ps.hlsl new file mode 100644 index 0000000..f682d07 --- /dev/null +++ b/enginecustom/Color.ps.hlsl @@ -0,0 +1,22 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: color.ps +//////////////////////////////////////////////////////////////////////////////// + + +////////////// +// TYPEDEFS // +////////////// +struct PixelInputType +{ + float4 position : SV_POSITION; + float4 color : COLOR; +}; + + +//////////////////////////////////////////////////////////////////////////////// +// Pixel Shader +//////////////////////////////////////////////////////////////////////////////// +float4 ColorPixelShader(PixelInputType input) : SV_TARGET +{ + return input.color; +} diff --git a/enginecustom/Color.vs.hlsl b/enginecustom/Color.vs.hlsl new file mode 100644 index 0000000..a29c1a2 --- /dev/null +++ b/enginecustom/Color.vs.hlsl @@ -0,0 +1,50 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: color.vs +//////////////////////////////////////////////////////////////////////////////// + +///////////// +// GLOBALS // +///////////// +cbuffer MatrixBuffer +{ + matrix worldMatrix; + matrix viewMatrix; + matrix projectionMatrix; +}; + +////////////// +// TYPEDEFS // +////////////// +struct VertexInputType +{ + float4 position : POSITION; + float4 color : COLOR; +}; + +struct PixelInputType +{ + float4 position : SV_POSITION; + float4 color : COLOR; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Vertex Shader +//////////////////////////////////////////////////////////////////////////////// +PixelInputType ColorVertexShader(VertexInputType input) +{ + PixelInputType output; + + + // Change the position vector to be 4 units for proper matrix calculations. + input.position.w = 1.0f; + + // Calculate the position of the vertex against the world, view, and projection matrices. + output.position = mul(input.position, worldMatrix); + output.position = mul(output.position, viewMatrix); + output.position = mul(output.position, projectionMatrix); + + // Store the input color for the pixel shader to use. + output.color = input.color; + + return output; +} \ No newline at end of file diff --git a/enginecustom/Colorshaderclass.cpp b/enginecustom/Colorshaderclass.cpp new file mode 100644 index 0000000..43bc0f3 --- /dev/null +++ b/enginecustom/Colorshaderclass.cpp @@ -0,0 +1,203 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: colorshaderclass.cpp +//////////////////////////////////////////////////////////////////////////////// +#include "colorshaderclass.h" + +ColorShaderClass::ColorShaderClass() +{ + m_vertexShader = 0; + m_pixelShader = 0; + m_layout = 0; + m_matrixBuffer = 0; +} + + +ColorShaderClass::ColorShaderClass(const ColorShaderClass& other) +{ +} + + +ColorShaderClass::~ColorShaderClass() +{ +} + +bool ColorShaderClass::Initialize(ID3D11Device* device, HWND hwnd) +{ + bool result; + wchar_t vsFilename[128]; + wchar_t psFilename[128]; + int error; + + + // Set the filename of the vertex shader. + error = wcscpy_s(vsFilename, 128, L"../Engine/color.vs"); + if (error != 0) + { + return false; + } + + // Set the filename of the pixel shader. + error = wcscpy_s(psFilename, 128, L"../Engine/color.ps"); + if (error != 0) + { + return false; + } + + // Initialize the vertex and pixel shaders. + result = InitializeShader(device, hwnd, vsFilename, psFilename); + if (!result) + { + return false; + } + + return true; +} + +void ColorShaderClass::Shutdown() +{ + // Shutdown the vertex and pixel shaders as well as the related objects. + ShutdownShader(); + + return; +} + +bool ColorShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, + XMMATRIX projectionMatrix) +{ + bool result; + + + // Set the shader parameters that it will use for rendering. + result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix); + if (!result) + { + return false; + } + + // Now render the prepared buffers with the shader. + RenderShader(deviceContext, indexCount); + + return true; +} + +bool ColorShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) +{ + HRESULT result; + ID3D10Blob* errorMessage; + ID3D10Blob* vertexShaderBuffer; + ID3D10Blob* pixelShaderBuffer; + D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; + unsigned int numElements; + D3D11_BUFFER_DESC matrixBufferDesc; + + + // Initialize the pointers this function will use to null. + errorMessage = 0; + vertexShaderBuffer = 0; + pixelShaderBuffer = 0; + + // Compile the vertex shader code. + result = D3DCompileFromFile(vsFilename, NULL, NULL, "ColorVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, + &vertexShaderBuffer, &errorMessage); + if (FAILED(result)) + { + // If the shader failed to compile it should have writen something to the error message. + if (errorMessage) + { + OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); + } + // If there was nothing in the error message then it simply could not find the shader file itself. + else + { + MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK); + } + + return false; + } + + // Compile the pixel shader code. + result = D3DCompileFromFile(psFilename, NULL, NULL, "ColorPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, + &pixelShaderBuffer, &errorMessage); + if (FAILED(result)) + { + // If the shader failed to compile it should have writen something to the error message. + if (errorMessage) + { + OutputShaderErrorMessage(errorMessage, hwnd, psFilename); + } + // If there was nothing in the error message then it simply could not find the file itself. + else + { + MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK); + } + + return false; + } + + // Create the vertex shader from the buffer. + result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); + if (FAILED(result)) + { + return false; + } + + // Create the pixel shader from the buffer. + result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); + if (FAILED(result)) + { + return false; + } + + // Create the vertex input layout description. + // This setup needs to match the VertexType stucture in the ModelClass and in the shader. + polygonLayout[0].SemanticName = "POSITION"; + polygonLayout[0].SemanticIndex = 0; + polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; + polygonLayout[0].InputSlot = 0; + polygonLayout[0].AlignedByteOffset = 0; + polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; + polygonLayout[0].InstanceDataStepRate = 0; + + polygonLayout[1].SemanticName = "COLOR"; + polygonLayout[1].SemanticIndex = 0; + polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + polygonLayout[1].InputSlot = 0; + polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; + polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; + polygonLayout[1].InstanceDataStepRate = 0; + + // Get a count of the elements in the layout. + numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); + + // Create the vertex input layout. + result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), + vertexShaderBuffer->GetBufferSize(), &m_layout); + if (FAILED(result)) + { + return false; + } + + // Release the vertex shader buffer and pixel shader buffer since they are no longer needed. + vertexShaderBuffer->Release(); + vertexShaderBuffer = 0; + + pixelShaderBuffer->Release(); + pixelShaderBuffer = 0; + + // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. + matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; + matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); + matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + matrixBufferDesc.MiscFlags = 0; + matrixBufferDesc.StructureByteStride = 0; + + // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. + result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); + if (FAILED(result)) + { + return false; + } + + return true; +} \ No newline at end of file diff --git a/enginecustom/Colorshaderclass.h b/enginecustom/Colorshaderclass.h new file mode 100644 index 0000000..694dc8c --- /dev/null +++ b/enginecustom/Colorshaderclass.h @@ -0,0 +1,56 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: colorshaderclass.h +//////////////////////////////////////////////////////////////////////////////// +#ifndef _COLORSHADERCLASS_H_ +#define _COLORSHADERCLASS_H_ + + +////////////// +// INCLUDES // +////////////// +#include +#include +#include +#include +using namespace DirectX; +using namespace std; + + +//////////////////////////////////////////////////////////////////////////////// +// Class name: ColorShaderClass +//////////////////////////////////////////////////////////////////////////////// +class ColorShaderClass +{ +private: + struct MatrixBufferType + { + XMMATRIX world; + XMMATRIX view; + XMMATRIX projection; + }; + +public: + ColorShaderClass(); + ColorShaderClass(const ColorShaderClass&); + ~ColorShaderClass(); + + bool Initialize(ID3D11Device*, HWND); + void Shutdown(); + bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX); + +private: + bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*); + void ShutdownShader(); + void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*); + + bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX); + void RenderShader(ID3D11DeviceContext*, int); + +private: + ID3D11VertexShader* m_vertexShader; + ID3D11PixelShader* m_pixelShader; + ID3D11InputLayout* m_layout; + ID3D11Buffer* m_matrixBuffer; +}; + +#endif \ No newline at end of file diff --git a/enginecustom/applicationclass.cpp b/enginecustom/applicationclass.cpp index 1b3d9ff..1751adc 100644 --- a/enginecustom/applicationclass.cpp +++ b/enginecustom/applicationclass.cpp @@ -67,7 +67,7 @@ bool ApplicationClass::Frame() bool ApplicationClass::Render() { // Clear the buffers to begin the scene. - m_Direct3D->BeginScene(0.5f, 0.5f, 0.5f, 1.0f); + m_Direct3D->BeginScene(255.0f, 255.0f, 0.0f, 1.0f); // Present the rendered scene to the screen. diff --git a/enginecustom/enginecustom.vcxproj b/enginecustom/enginecustom.vcxproj index 71dcc8c..22bd778 100644 --- a/enginecustom/enginecustom.vcxproj +++ b/enginecustom/enginecustom.vcxproj @@ -1,5 +1,6 @@ + Debug @@ -20,6 +21,7 @@ + @@ -27,10 +29,28 @@ + + + + + + + Pixel + Pixel + Pixel + Pixel + + + Vertex + Vertex + Vertex + Vertex + + 17.0 Win32Proj @@ -141,5 +161,13 @@ + + + + Ce projet fait référence à des packages NuGet qui sont manquants sur cet ordinateur. Utilisez l'option de restauration des packages NuGet pour les télécharger. Pour plus d'informations, consultez http://go.microsoft.com/fwlink/?LinkID=322105. Le fichier manquant est : {0}. + + + + \ No newline at end of file diff --git a/enginecustom/enginecustom.vcxproj.filters b/enginecustom/enginecustom.vcxproj.filters index 6bef417..64ca351 100644 --- a/enginecustom/enginecustom.vcxproj.filters +++ b/enginecustom/enginecustom.vcxproj.filters @@ -13,6 +13,9 @@ {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + {b016e481-576e-4d99-bdde-34cc10c55b1d} + @@ -30,6 +33,9 @@ Fichiers sources + + Fichiers sources + @@ -44,5 +50,19 @@ Fichiers d%27en-tête + + Fichiers d%27en-tête + + + + + + + + shader + + + shader + \ No newline at end of file diff --git a/enginecustom/packages.config b/enginecustom/packages.config new file mode 100644 index 0000000..cbf6205 --- /dev/null +++ b/enginecustom/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file From fac2881d857992dbe3ecbf74cbdf22954cd67617 Mon Sep 17 00:00:00 2001 From: axelpicou <115532798+axelpicou@users.noreply.github.com> Date: Thu, 21 Mar 2024 09:42:07 +0100 Subject: [PATCH 3/3] los triangle --- enginecustom/Cameraclass.cpp | 112 ++++++++++++ enginecustom/Cameraclass.h | 40 +++++ enginecustom/{Color.ps.hlsl => Color.ps} | 0 enginecustom/{Color.vs.hlsl => Color.vs} | 0 enginecustom/Colorshaderclass.cpp | 127 +++++++++++++- enginecustom/applicationclass.cpp | 83 ++++++++- enginecustom/applicationclass.h | 8 +- enginecustom/enginecustom.vcxproj | 16 +- enginecustom/enginecustom.vcxproj.filters | 22 ++- enginecustom/modelclass.cpp | 199 ++++++++++++++++++++++ enginecustom/modelclass.h | 49 ++++++ 11 files changed, 641 insertions(+), 15 deletions(-) create mode 100644 enginecustom/Cameraclass.cpp create mode 100644 enginecustom/Cameraclass.h rename enginecustom/{Color.ps.hlsl => Color.ps} (100%) rename enginecustom/{Color.vs.hlsl => Color.vs} (100%) create mode 100644 enginecustom/modelclass.cpp create mode 100644 enginecustom/modelclass.h diff --git a/enginecustom/Cameraclass.cpp b/enginecustom/Cameraclass.cpp new file mode 100644 index 0000000..0520dd2 --- /dev/null +++ b/enginecustom/Cameraclass.cpp @@ -0,0 +1,112 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: cameraclass.cpp +//////////////////////////////////////////////////////////////////////////////// +#include "cameraclass.h" + +CameraClass::CameraClass() +{ + m_positionX = 0.0f; + m_positionY = 0.0f; + m_positionZ = 0.0f; + + m_rotationX = 0.0f; + m_rotationY = 0.0f; + m_rotationZ = 0.0f; +} + + +CameraClass::CameraClass(const CameraClass& other) +{ +} + + +CameraClass::~CameraClass() +{ +} + +void CameraClass::SetPosition(float x, float y, float z) +{ + m_positionX = x; + m_positionY = y; + m_positionZ = z; + return; +} + + +void CameraClass::SetRotation(float x, float y, float z) +{ + m_rotationX = x; + m_rotationY = y; + m_rotationZ = z; + return; +} + +XMFLOAT3 CameraClass::GetPosition() +{ + return XMFLOAT3(m_positionX, m_positionY, m_positionZ); +} + + +XMFLOAT3 CameraClass::GetRotation() +{ + return XMFLOAT3(m_rotationX, m_rotationY, m_rotationZ); +} + +void CameraClass::Render() +{ + XMFLOAT3 up, position, lookAt; + XMVECTOR upVector, positionVector, lookAtVector; + float yaw, pitch, roll; + XMMATRIX rotationMatrix; + + + // Setup the vector that points upwards. + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + + // Load it into a XMVECTOR structure. + upVector = XMLoadFloat3(&up); + + // Setup the position of the camera in the world. + position.x = m_positionX; + position.y = m_positionY; + position.z = m_positionZ; + + // Load it into a XMVECTOR structure. + positionVector = XMLoadFloat3(&position); + + // Setup where the camera is looking by default. + lookAt.x = 0.0f; + lookAt.y = 0.0f; + lookAt.z = 1.0f; + + // Load it into a XMVECTOR structure. + lookAtVector = XMLoadFloat3(&lookAt); + + // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians. + pitch = m_rotationX * 0.0174532925f; + yaw = m_rotationY * 0.0174532925f; + roll = m_rotationZ * 0.0174532925f; + + // Create the rotation matrix from the yaw, pitch, and roll values. + rotationMatrix = XMMatrixRotationRollPitchYaw(pitch, yaw, roll); + + // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin. + lookAtVector = XMVector3TransformCoord(lookAtVector, rotationMatrix); + upVector = XMVector3TransformCoord(upVector, rotationMatrix); + + // Translate the rotated camera position to the location of the viewer. + lookAtVector = XMVectorAdd(positionVector, lookAtVector); + + // Finally create the view matrix from the three updated vectors. + m_viewMatrix = XMMatrixLookAtLH(positionVector, lookAtVector, upVector); + + return; +} + +void CameraClass::GetViewMatrix(XMMATRIX& viewMatrix) +{ + viewMatrix = m_viewMatrix; + return; +} \ No newline at end of file diff --git a/enginecustom/Cameraclass.h b/enginecustom/Cameraclass.h new file mode 100644 index 0000000..1c4cfed --- /dev/null +++ b/enginecustom/Cameraclass.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: cameraclass.h +//////////////////////////////////////////////////////////////////////////////// +#ifndef _CAMERACLASS_H_ +#define _CAMERACLASS_H_ + + +////////////// +// INCLUDES // +////////////// +#include +using namespace DirectX; + + +//////////////////////////////////////////////////////////////////////////////// +// Class name: CameraClass +//////////////////////////////////////////////////////////////////////////////// +class CameraClass +{ +public: + CameraClass(); + CameraClass(const CameraClass&); + ~CameraClass(); + + void SetPosition(float, float, float); + void SetRotation(float, float, float); + + XMFLOAT3 GetPosition(); + XMFLOAT3 GetRotation(); + + void Render(); + void GetViewMatrix(XMMATRIX&); + +private: + float m_positionX, m_positionY, m_positionZ; + float m_rotationX, m_rotationY, m_rotationZ; + XMMATRIX m_viewMatrix; +}; + +#endif \ No newline at end of file diff --git a/enginecustom/Color.ps.hlsl b/enginecustom/Color.ps similarity index 100% rename from enginecustom/Color.ps.hlsl rename to enginecustom/Color.ps diff --git a/enginecustom/Color.vs.hlsl b/enginecustom/Color.vs similarity index 100% rename from enginecustom/Color.vs.hlsl rename to enginecustom/Color.vs diff --git a/enginecustom/Colorshaderclass.cpp b/enginecustom/Colorshaderclass.cpp index 43bc0f3..84abd56 100644 --- a/enginecustom/Colorshaderclass.cpp +++ b/enginecustom/Colorshaderclass.cpp @@ -30,14 +30,14 @@ bool ColorShaderClass::Initialize(ID3D11Device* device, HWND hwnd) // Set the filename of the vertex shader. - error = wcscpy_s(vsFilename, 128, L"../Engine/color.vs"); + error = wcscpy_s(vsFilename, 128, L"../enginecustom/Color.vs"); if (error != 0) { return false; } // Set the filename of the pixel shader. - error = wcscpy_s(psFilename, 128, L"../Engine/color.ps"); + error = wcscpy_s(psFilename, 128, L"../enginecustom/Color.ps"); if (error != 0) { return false; @@ -200,4 +200,127 @@ bool ColorShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* } return true; +} + +void ColorShaderClass::ShutdownShader() +{ + // Release the matrix constant buffer. + if (m_matrixBuffer) + { + m_matrixBuffer->Release(); + m_matrixBuffer = 0; + } + + // Release the layout. + if (m_layout) + { + m_layout->Release(); + m_layout = 0; + } + + // Release the pixel shader. + if (m_pixelShader) + { + m_pixelShader->Release(); + m_pixelShader = 0; + } + + // Release the vertex shader. + if (m_vertexShader) + { + m_vertexShader->Release(); + m_vertexShader = 0; + } + + return; +} + +void ColorShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename) +{ + char* compileErrors; + unsigned long long bufferSize, i; + ofstream fout; + + + // Get a pointer to the error message text buffer. + compileErrors = (char*)(errorMessage->GetBufferPointer()); + + // Get the length of the message. + bufferSize = errorMessage->GetBufferSize(); + + // Open a file to write the error message to. + fout.open("shader-error.txt"); + + // Write out the error message. + for (i = 0; i < bufferSize; i++) + { + fout << compileErrors[i]; + } + + // Close the file. + fout.close(); + + // Release the error message. + errorMessage->Release(); + errorMessage = 0; + + // Pop a message up on the screen to notify the user to check the text file for compile errors. + MessageBox(hwnd, L"Error compiling shader. Check shader-error.txt for message.", shaderFilename, MB_OK); + + return; +} + +bool ColorShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, + XMMATRIX projectionMatrix) +{ + HRESULT result; + D3D11_MAPPED_SUBRESOURCE mappedResource; + MatrixBufferType* dataPtr; + unsigned int bufferNumber; + + // Transpose the matrices to prepare them for the shader. + worldMatrix = XMMatrixTranspose(worldMatrix); + viewMatrix = XMMatrixTranspose(viewMatrix); + projectionMatrix = XMMatrixTranspose(projectionMatrix); + + // Lock the constant buffer so it can be written to. + result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); + if (FAILED(result)) + { + return false; + } + + // Get a pointer to the data in the constant buffer. + dataPtr = (MatrixBufferType*)mappedResource.pData; + + // Copy the matrices into the constant buffer. + dataPtr->world = worldMatrix; + dataPtr->view = viewMatrix; + dataPtr->projection = projectionMatrix; + + // Unlock the constant buffer. + deviceContext->Unmap(m_matrixBuffer, 0); + + // Set the position of the constant buffer in the vertex shader. + bufferNumber = 0; + + // Finanly set the constant buffer in the vertex shader with the updated values. + deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); + + return true; +} + +void ColorShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount) +{ + // Set the vertex input layout. + deviceContext->IASetInputLayout(m_layout); + + // Set the vertex and pixel shaders that will be used to render this triangle. + deviceContext->VSSetShader(m_vertexShader, NULL, 0); + deviceContext->PSSetShader(m_pixelShader, NULL, 0); + + // Render the triangle. + deviceContext->DrawIndexed(indexCount, 0, 0); + + return; } \ No newline at end of file diff --git a/enginecustom/applicationclass.cpp b/enginecustom/applicationclass.cpp index 1751adc..a28c4a7 100644 --- a/enginecustom/applicationclass.cpp +++ b/enginecustom/applicationclass.cpp @@ -1,9 +1,15 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: applicationclass.cpp +//////////////////////////////////////////////////////////////////////////////// #include "applicationclass.h" ApplicationClass::ApplicationClass() { m_Direct3D = 0; + m_Camera = 0; + m_Model = 0; + m_ColorShader = 0; } @@ -31,12 +37,62 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd) MessageBox(hwnd, L"Could not initialize Direct3D", L"Error", MB_OK); return false; } + + // Create the camera object. + m_Camera = new CameraClass; + + // Set the initial position of the camera. + m_Camera->SetPosition(0.0f, 0.0f, -5.0f); + + // Create and initialize the model object. + m_Model = new ModelClass; + + result = m_Model->Initialize(m_Direct3D->GetDevice()); + if (!result) + { + MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK); + return false; + } + + // Create and initialize the color shader object. + m_ColorShader = new ColorShaderClass; + + result = m_ColorShader->Initialize(m_Direct3D->GetDevice(), hwnd); + if (!result) + { + MessageBox(hwnd, L"Could not initialize the color shader object.", L"Error", MB_OK); + return false; + } + return true; } void ApplicationClass::Shutdown() { + // Release the color shader object. + if (m_ColorShader) + { + m_ColorShader->Shutdown(); + delete m_ColorShader; + m_ColorShader = 0; + } + + // Release the model object. + if (m_Model) + { + m_Model->Shutdown(); + delete m_Model; + m_Model = 0; + } + + // Release the camera object. + if (m_Camera) + { + delete m_Camera; + m_Camera = 0; + } + // Release the Direct3D object. if (m_Direct3D) { @@ -60,17 +116,40 @@ bool ApplicationClass::Frame() { return false; } + return true; } bool ApplicationClass::Render() { - // Clear the buffers to begin the scene. - m_Direct3D->BeginScene(255.0f, 255.0f, 0.0f, 1.0f); + XMMATRIX worldMatrix, viewMatrix, projectionMatrix; + bool result; + // Clear the buffers to begin the scene. + m_Direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f); + + // Generate the view matrix based on the camera's position. + m_Camera->Render(); + + // Get the world, view, and projection matrices from the camera and d3d objects. + m_Direct3D->GetWorldMatrix(worldMatrix); + m_Camera->GetViewMatrix(viewMatrix); + m_Direct3D->GetProjectionMatrix(projectionMatrix); + + // Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing. + m_Model->Render(m_Direct3D->GetDeviceContext()); + + // Render the model using the color shader. + result = m_ColorShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix); + if (!result) + { + return false; + } + // Present the rendered scene to the screen. m_Direct3D->EndScene(); + return true; } \ No newline at end of file diff --git a/enginecustom/applicationclass.h b/enginecustom/applicationclass.h index d62822f..8a74383 100644 --- a/enginecustom/applicationclass.h +++ b/enginecustom/applicationclass.h @@ -5,9 +5,12 @@ ////////////// // INCLUDES // ////////////// -#include +#include "cameraclass.h" +#include "modelclass.h" +#include "colorshaderclass.h" #include "d3dclass.h" + ///////////// // GLOBALS // ///////////// @@ -32,6 +35,9 @@ private: private: D3DClass* m_Direct3D; + CameraClass* m_Camera; + ModelClass* m_Model; + ColorShaderClass* m_ColorShader; }; #endif \ No newline at end of file diff --git a/enginecustom/enginecustom.vcxproj b/enginecustom/enginecustom.vcxproj index 22bd778..3c74b8c 100644 --- a/enginecustom/enginecustom.vcxproj +++ b/enginecustom/enginecustom.vcxproj @@ -21,35 +21,43 @@ + + + + - + Pixel Pixel Pixel Pixel - - + false + Document + + Vertex Vertex Vertex Vertex - + false + Document + 17.0 diff --git a/enginecustom/enginecustom.vcxproj.filters b/enginecustom/enginecustom.vcxproj.filters index 64ca351..c3fe977 100644 --- a/enginecustom/enginecustom.vcxproj.filters +++ b/enginecustom/enginecustom.vcxproj.filters @@ -36,6 +36,12 @@ Fichiers sources + + Fichiers sources + + + Fichiers sources + @@ -53,16 +59,20 @@ Fichiers d%27en-tête + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + - - - + shader - - + + shader - + \ No newline at end of file diff --git a/enginecustom/modelclass.cpp b/enginecustom/modelclass.cpp new file mode 100644 index 0000000..0eedb98 --- /dev/null +++ b/enginecustom/modelclass.cpp @@ -0,0 +1,199 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: modelclass.cpp +//////////////////////////////////////////////////////////////////////////////// +#include "modelclass.h" + + +ModelClass::ModelClass() +{ + m_vertexBuffer = 0; + m_indexBuffer = 0; +} + + +ModelClass::ModelClass(const ModelClass& other) +{ +} + + +ModelClass::~ModelClass() +{ +} + + +bool ModelClass::Initialize(ID3D11Device* device) +{ + bool result; + + + // Initialize the vertex and index buffers. + result = InitializeBuffers(device); + if (!result) + { + return false; + } + + return true; +} + + +void ModelClass::Shutdown() +{ + // Shutdown the vertex and index buffers. + ShutdownBuffers(); + + return; +} + + +void ModelClass::Render(ID3D11DeviceContext* deviceContext) +{ + // Put the vertex and index buffers on the graphics pipeline to prepare them for drawing. + RenderBuffers(deviceContext); + + return; +} + + +int ModelClass::GetIndexCount() +{ + return m_indexCount; +} + + +bool ModelClass::InitializeBuffers(ID3D11Device* device) +{ + VertexType* vertices; + unsigned long* indices; + D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc; + D3D11_SUBRESOURCE_DATA vertexData, indexData; + HRESULT result; + + + // Set the number of vertices in the vertex array. + m_vertexCount = 3; + + // Set the number of indices in the index array. + m_indexCount = 3; + + // Create the vertex array. + vertices = new VertexType[m_vertexCount]; + if (!vertices) + { + return false; + } + + // Create the index array. + indices = new unsigned long[m_indexCount]; + if (!indices) + { + return false; + } + + // Load the vertex array with data. + vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f); // Bottom left. + vertices[0].color = XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f); + + vertices[1].position = XMFLOAT3(0.0f, 1.0f, 0.0f); // Top middle. + vertices[1].color = XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f); + + vertices[2].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // Bottom right. + vertices[2].color = XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f); + + // Load the index array with data. + indices[0] = 0; // Bottom left. + indices[1] = 1; // Top middle. + indices[2] = 2; // Bottom right. + + // Set up the description of the static vertex buffer. + vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; + vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount; + vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + vertexBufferDesc.CPUAccessFlags = 0; + vertexBufferDesc.MiscFlags = 0; + vertexBufferDesc.StructureByteStride = 0; + + // Give the subresource structure a pointer to the vertex data. + vertexData.pSysMem = vertices; + vertexData.SysMemPitch = 0; + vertexData.SysMemSlicePitch = 0; + + // Now create the vertex buffer. + result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer); + if (FAILED(result)) + { + return false; + } + + // Set up the description of the static index buffer. + indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; + indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount; + indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; + indexBufferDesc.CPUAccessFlags = 0; + indexBufferDesc.MiscFlags = 0; + indexBufferDesc.StructureByteStride = 0; + + // Give the subresource structure a pointer to the index data. + indexData.pSysMem = indices; + indexData.SysMemPitch = 0; + indexData.SysMemSlicePitch = 0; + + // Create the index buffer. + result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer); + if (FAILED(result)) + { + return false; + } + + // Release the arrays now that the vertex and index buffers have been created and loaded. + delete[] vertices; + vertices = 0; + + delete[] indices; + indices = 0; + + return true; +} + + +void ModelClass::ShutdownBuffers() +{ + // Release the index buffer. + if (m_indexBuffer) + { + m_indexBuffer->Release(); + m_indexBuffer = 0; + } + + // Release the vertex buffer. + if (m_vertexBuffer) + { + m_vertexBuffer->Release(); + m_vertexBuffer = 0; + } + + return; +} + + +void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext) +{ + unsigned int stride; + unsigned int offset; + + + // Set vertex buffer stride and offset. + stride = sizeof(VertexType); + offset = 0; + + // Set the vertex buffer to active in the input assembler so it can be rendered. + deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset); + + // Set the index buffer to active in the input assembler so it can be rendered. + deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0); + + // Set the type of primitive that should be rendered from this vertex buffer, in this case triangles. + deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + return; +} \ No newline at end of file diff --git a/enginecustom/modelclass.h b/enginecustom/modelclass.h new file mode 100644 index 0000000..f84628b --- /dev/null +++ b/enginecustom/modelclass.h @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: modelclass.h +//////////////////////////////////////////////////////////////////////////////// +#ifndef _MODELCLASS_H_ +#define _MODELCLASS_H_ + + +////////////// +// INCLUDES // +////////////// +#include +#include +using namespace DirectX; + + +//////////////////////////////////////////////////////////////////////////////// +// Class name: ModelClass +//////////////////////////////////////////////////////////////////////////////// +class ModelClass +{ +private: + struct VertexType + { + XMFLOAT3 position; + XMFLOAT4 color; + }; + +public: + ModelClass(); + ModelClass(const ModelClass&); + ~ModelClass(); + + bool Initialize(ID3D11Device*); + void Shutdown(); + void Render(ID3D11DeviceContext*); + + int GetIndexCount(); + +private: + bool InitializeBuffers(ID3D11Device*); + void ShutdownBuffers(); + void RenderBuffers(ID3D11DeviceContext*); + +private: + ID3D11Buffer* m_vertexBuffer, * m_indexBuffer; + int m_vertexCount, m_indexCount; +}; + +#endif \ No newline at end of file