Added the camera class

Added the DDS Texture Loading for future use
Added the gamepad class for future use
Added first child method to the scenegraph
Added RGB to intensity and lerp methods to the shared methods class
Added the terrain node class with normals
Fixed issue with submeshnode not passing the world transform to the actual meshes
This commit is contained in:
iDunnoDev
2022-04-18 22:33:15 +01:00
committed by iDunnoDev
parent 65255f1321
commit 7a57c73ac3
47 changed files with 4323 additions and 91 deletions

132
Graphics2/Camera.cpp Normal file
View File

@ -0,0 +1,132 @@
#include "Camera.h"
XMVECTOR defaultForward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
XMVECTOR defaultRight = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
XMVECTOR defaultUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
Camera::Camera()
{
_cameraPosition = XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f);
_moveLeftRight = 0.0f;
_moveForwardBack = 0.0f;
_cameraYaw = 0.0f;
_cameraPitch = 0.0f;
_cameraRoll = 0.0f;
}
Camera::~Camera()
{
}
void Camera::SetPitch(float pitch)
{
_cameraPitch += XMConvertToRadians(pitch);
}
void Camera::SetTotalPitch(float pitch)
{
_cameraPitch = XMConvertToRadians(pitch);
}
float Camera::GetPitch() const
{
return XMConvertToDegrees(_cameraPitch);
}
void Camera::SetYaw(float yaw)
{
_cameraYaw += XMConvertToRadians(yaw);
}
void Camera::SetTotalYaw(float yaw)
{
_cameraYaw = XMConvertToRadians(yaw);
}
float Camera::GetYaw() const
{
return XMConvertToDegrees(_cameraYaw);
}
void Camera::SetRoll(float roll)
{
_cameraRoll += XMConvertToRadians(roll);
}
void Camera::SetTotalRoll(float roll)
{
_cameraRoll = XMConvertToRadians(roll);
}
float Camera::GetRoll() const
{
return XMConvertToDegrees(_cameraRoll);
}
void Camera::SetLeftRight(float leftRight)
{
_moveLeftRight = leftRight;
}
void Camera::SetForwardBack(float forwardBack)
{
_moveForwardBack = forwardBack;
}
XMMATRIX Camera::GetViewMatrix(void)
{
return XMLoadFloat4x4(&_viewMatrix);
}
XMVECTOR Camera::GetCameraPosition(void)
{
return XMLoadFloat4(&_cameraPosition);
}
XMFLOAT4 Camera::GetRawCameraPosition(void)
{
return _cameraPosition;
}
void Camera::SetCameraPosition(float x, float y, float z)
{
_cameraPosition = XMFLOAT4(x, y, z, 0.0f);
}
void Camera::Update(void)
{
XMVECTOR cameraPosition;
XMVECTOR cameraTarget;
XMVECTOR cameraRight;
XMVECTOR cameraForward;
XMVECTOR cameraUp;
// Yaw (rotation around the Y axis) will have an impact on the forward and right vectors
XMMATRIX cameraRotationYaw = XMMatrixRotationAxis(defaultUp, _cameraYaw);
cameraRight = XMVector3TransformCoord(defaultRight, cameraRotationYaw);
cameraForward = XMVector3TransformCoord(defaultForward, cameraRotationYaw);
// Pitch (rotation around the X axis) impact the up and forward vectors
XMMATRIX cameraRotationPitch = XMMatrixRotationAxis(cameraRight, _cameraPitch);
cameraUp = XMVector3TransformCoord(defaultUp, cameraRotationPitch);
cameraForward = XMVector3TransformCoord(cameraForward, cameraRotationPitch);
// Roll (rotation around the Z axis) will impact the Up and Right vectors
XMMATRIX cameraRotationRoll = XMMatrixRotationAxis(cameraForward, _cameraRoll);
cameraUp = XMVector3TransformCoord(cameraUp, cameraRotationRoll);
cameraRight = XMVector3TransformCoord(cameraRight, cameraRotationRoll);
// Adjust the camera position by the appropriate amount forward/back and left/right
cameraPosition = XMLoadFloat4(&_cameraPosition) + _moveLeftRight * cameraRight + _moveForwardBack * cameraForward;
XMStoreFloat4(&_cameraPosition, cameraPosition);
// Reset the amount we are moving
_moveLeftRight = 0.0f;
_moveForwardBack = 0.0f;
// Calculate a vector that tells us the direction the camera is looking in
cameraTarget = cameraPosition + XMVector3Normalize(cameraForward);
// and calculate our view matrix
XMStoreFloat4x4(&_viewMatrix, XMMatrixLookAtLH(cameraPosition, cameraTarget, cameraUp));
}

41
Graphics2/Camera.h Normal file
View File

@ -0,0 +1,41 @@
#pragma once
#include "core.h"
#include "DirectXCore.h"
class Camera
{
public:
Camera();
~Camera();
void Update();
XMMATRIX GetViewMatrix();
XMVECTOR GetCameraPosition();
XMFLOAT4 GetRawCameraPosition();
void SetCameraPosition(float x, float y, float z);
void SetPitch(float pitch);
void SetTotalPitch(float pitch);
float GetPitch() const;
void SetYaw(float yaw);
void SetTotalYaw(float yaw);
float GetYaw() const;
void SetRoll(float roll);
void SetTotalRoll(float roll);
float GetRoll() const;
void SetLeftRight(float leftRight);
void SetForwardBack(float forwardBack);
private:
XMFLOAT4 _cameraPosition;
XMFLOAT4X4 _viewMatrix;
float _moveLeftRight;
float _moveForwardBack;
float _cameraYaw;
float _cameraPitch;
float _cameraRoll;
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,133 @@
//--------------------------------------------------------------------------------------
// File: DDSTextureLoader.h
//
// Functions for loading a DDS texture and creating a Direct3D runtime resource for it
//
// Note these functions are useful as a light-weight runtime loader for DDS files. For
// a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' library.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include <d3d11_1.h>
#include <stdint.h>
namespace DirectX
{
enum DDS_ALPHA_MODE
{
DDS_ALPHA_MODE_UNKNOWN = 0,
DDS_ALPHA_MODE_STRAIGHT = 1,
DDS_ALPHA_MODE_PREMULTIPLIED = 2,
DDS_ALPHA_MODE_OPAQUE = 3,
DDS_ALPHA_MODE_CUSTOM = 4,
};
// Standard version
HRESULT CreateDDSTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT CreateDDSTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
// Standard version with optional auto-gen mipmap support
HRESULT CreateDDSTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT CreateDDSTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
// Extended version
HRESULT CreateDDSTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT CreateDDSTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
// Extended version with optional auto-gen mipmap support
HRESULT CreateDDSTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
HRESULT CreateDDSTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr);
}

View File

@ -7,7 +7,7 @@
DirectXFramework * _dxFramework = nullptr;
DirectXFramework::DirectXFramework() : DirectXFramework(800, 600)
{
{
}
DirectXFramework::DirectXFramework(unsigned int width, unsigned int height) : Framework(width, height)
@ -19,12 +19,6 @@ DirectXFramework::DirectXFramework(unsigned int width, unsigned int height) : Fr
_backgroundColour[1] = 0.0f;
_backgroundColour[2] = 0.0f;
_backgroundColour[3] = 0.0f;
// Initialise vectors used to create camera. We will move these
// to a separate Camera class later
_eyePosition = XMFLOAT4(0.0f, 20.0f, -90.0f, 0.0f);
_focalPointPosition = XMFLOAT4(0.0f, 20.0f, 0.0f, 0.0f);
_upVector = XMFLOAT4(0.0f, 1.0f, 0.0f, 0.0f);
}
DirectXFramework * DirectXFramework::GetDXFramework()
@ -32,11 +26,6 @@ DirectXFramework * DirectXFramework::GetDXFramework()
return _dxFramework;
}
XMMATRIX DirectXFramework::GetViewTransformation()
{
return XMLoadFloat4x4(&_viewTransformation);
}
XMMATRIX DirectXFramework::GetProjectionTransformation()
{
return XMLoadFloat4x4(&_projectionTransformation);
@ -73,12 +62,13 @@ bool DirectXFramework::Initialise()
}
OnResize(SIZE_RESTORED);
// Create camera and projection matrices (we will look at how the
// camera matrix is created from vectors later)
XMStoreFloat4x4(&_projectionTransformation, XMMatrixPerspectiveFovLH(XM_PIDIV4, (float)GetWindowWidth() / GetWindowHeight(), 1.0f, 10000.0f));
// Create camera and projection matrices
XMStoreFloat4x4(&_projectionTransformation, XMMatrixPerspectiveFovLH(XM_PIDIV4, (float)GetWindowWidth() / GetWindowHeight(), 1.0f, 1000.0f));
_resourceManager = make_shared<ResourceManager>();
_sceneGraph = make_shared<SceneGraph>();
_camera = make_shared<Camera>();
CreateSceneGraph();
return _sceneGraph->Initialise();
}
@ -93,6 +83,8 @@ void DirectXFramework::Update()
{
// Do any updates to the scene graph nodes
UpdateSceneGraph();
_camera->Update();
// Now apply any updates that have been made to world transformations
// to all the nodes
_sceneGraph->Update(XMMatrixIdentity());
@ -112,7 +104,7 @@ void DirectXFramework::Render()
void DirectXFramework::OnResize(WPARAM wParam)
{
// Update view and projection matrices to allow for the window size change
XMStoreFloat4x4(&_viewTransformation, XMMatrixLookAtLH(XMLoadFloat4(&_eyePosition), XMLoadFloat4(&_focalPointPosition), XMLoadFloat4(&_upVector)));
//XMStoreFloat4x4(&_viewTransformation, XMMatrixLookAtLH(XMLoadFloat4(&_eyePosition), XMLoadFloat4(&_focalPointPosition), XMLoadFloat4(&_upVector)));
XMStoreFloat4x4(&_projectionTransformation, XMMatrixPerspectiveFovLH(XM_PIDIV4, (float)GetWindowWidth() / GetWindowHeight(), 1.0f, 10000.0f));
// This will free any existing render and depth views (which

View File

@ -4,6 +4,7 @@
#include "DirectXCore.h"
#include "ResourceManager.h"
#include "SceneGraph.h"
#include "Camera.h"
class DirectXFramework : public Framework
{
@ -28,11 +29,12 @@ public:
inline shared_ptr<ResourceManager> GetResourceManager() { return _resourceManager; }
XMMATRIX GetViewTransformation();
XMMATRIX GetProjectionTransformation();
void SetBackgroundColour(XMFLOAT4 backgroundColour);
inline shared_ptr<Camera> GetCamera() { return _camera; }
private:
ComPtr<ID3D11Device> _device;
ComPtr<ID3D11DeviceContext> _deviceContext;
@ -48,13 +50,6 @@ private:
// to be aligned on 16-byte boundaries and the compiler cannot
// guarantee this for class variables
// For now, we are storing our camera vectors and matrix here.
// We will move it to a separate Camera class later
XMFLOAT4 _eyePosition;
XMFLOAT4 _focalPointPosition;
XMFLOAT4 _upVector;
XMFLOAT4X4 _viewTransformation;
XMFLOAT4X4 _projectionTransformation;
SceneGraphPointer _sceneGraph;
@ -64,5 +59,6 @@ private:
bool GetDeviceAndSwapChain();
shared_ptr<ResourceManager> _resourceManager;
shared_ptr<Camera> _camera;
};

View File

@ -0,0 +1,107 @@
#include "GamePadController.h"
GamePadController::GamePadController(void)
{
_firstTime = true;
_leftThumbDeadZoneSquared = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE * XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE;
_rightThumbDeadZoneSquared = XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE * XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE;
}
GamePadController::~GamePadController(void)
{
}
void GamePadController::ProcessGameController()
{
DWORD magnitudeSquared;
ZeroMemory(&_controllerState, sizeof(XINPUT_STATE));
// Get the state of the controller
if (XInputGetState(0, &_controllerState) != ERROR_SUCCESS)
{
// Controller is not connected or is lost
return;
}
// Uncomment out this if statement if you only want to test the controller if it has
// changed since the last time it was tested
//if (!_firstTime && _controllerState.dwPacketNumber != _lastPacketNumber)
//{
// No change in controller states
//}
_firstTime = false;
// Deal with the left thumb stick
SHORT thumbLX = _controllerState.Gamepad.sThumbLX;
SHORT thumbLY = _controllerState.Gamepad.sThumbLY;
// Determine how far the controller is pushed
magnitudeSquared = thumbLX * thumbLX + thumbLY * thumbLY;
// check if the controller is inside a circular dead zone. We do it this way to avoid having to
// take the square root of the magnitude above.
if (magnitudeSquared <= _leftThumbDeadZoneSquared)
{
thumbLX = 0;
thumbLY = 0;
}
// Deal with the right thumb stick
SHORT thumbRX = _controllerState.Gamepad.sThumbRX;
SHORT thumbRY = _controllerState.Gamepad.sThumbRY;
// Determine how far the controller is pushed
magnitudeSquared = thumbRX * thumbRX + thumbRY * thumbRY;
//check if the controller is inside a circular dead zone
if (magnitudeSquared <= _rightThumbDeadZoneSquared)
{
thumbRX = 0;
thumbRY = 0;
}
// Check left and right triggers
BYTE leftTrigger = _controllerState.Gamepad.bLeftTrigger;
if (leftTrigger <= XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
{
leftTrigger = 0;
}
BYTE rightTrigger = _controllerState.Gamepad.bRightTrigger;
if (rightTrigger <= XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
{
rightTrigger = 0;
}
// Test the different digital buttons
WORD buttons = _controllerState.Gamepad.wButtons;
if (buttons & XINPUT_GAMEPAD_DPAD_UP)
{
// Directional pad up pressed
}
if (buttons & XINPUT_GAMEPAD_DPAD_DOWN)
{
// Directional pad down pressed
}
if (buttons & XINPUT_GAMEPAD_DPAD_LEFT)
{
// Directional pad left pressed
}
if (buttons & XINPUT_GAMEPAD_DPAD_RIGHT)
{
// Directional pad right pressed
}
// Other button mask values that can be used are:
//
// XINPUT_GAMEPAD_START,
// XINPUT_GAMEPAD_BACK,
// XINPUT_GAMEPAD_LEFT_THUMB,
// XINPUT_GAMEPAD_RIGHT_THUMB,
// XINPUT_GAMEPAD_LEFT_SHOULDER,
// XINPUT_GAMEPAD_RIGHT_SHOULDER,
// XINPUT_GAMEPAD_A,
// XINPUT_GAMEPAD_B,
// XINPUT_GAMEPAD_X,
// XINPUT_GAMEPAD_Y
}

View File

@ -0,0 +1,24 @@
#pragma once
#include "Core.h"
#include "DirectXCore.h"
#include <XInput.h>
#pragma comment(lib, "XInput.lib")
class GamePadController
{
public:
GamePadController();
~GamePadController();
void ProcessGameController();
private:
XINPUT_STATE _controllerState;
DWORD _lastPacketNumber;
bool _firstTime;
// These two values are used to avoid having to calculate square roots (which are very time consuming)
// when we are checking if the movement of the left or right thumb stick is in the dead zone
DWORD _leftThumbDeadZoneSquared;
DWORD _rightThumbDeadZoneSquared;
};

View File

@ -3,19 +3,31 @@
Graphics2 app;
void Graphics2::CreateSceneGraph()
{
{
_boostMultiplier = 1;
_flySpeed = 1;
_turnSpeed = 1;
_invertPitch = -1;
GetCamera()->SetCameraPosition(0.0f, 320.0f, -80.0f);
SceneGraphPointer sceneGraph = GetSceneGraph();
// This is where you add nodes to the scene graph
//shared_ptr<TexturedCubeNode> cube = make_shared<TexturedCubeNode>(L"Body", L"Textures\\woodbox.bmp");
//cube->SetWorldTransform(XMMatrixScaling(5.0f, 8.0f, 2.5f) * XMMatrixTranslation(0, 23.0f, 0));
//sceneGraph->Add(cube);
shared_ptr<TerrainNode> terrainNode = make_shared<TerrainNode>(L"MainTerrain", L"Textures\\Example_HeightMap.raw", 1023, 1023, 10, 10);
sceneGraph->Add(terrainNode);
shared_ptr<SplitMeshNode> node = make_shared<SplitMeshNode>(L"Plane1", L"Models\\Plane\\Bonanza.3DS");
node->SetWorldTransform(XMMatrixScaling(0.5f, 0.5f, 0.5f) * XMMatrixRotationAxis(XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f), 90.0f * XM_PI / 180.0f) * XMMatrixTranslation(-30.0f, 20.0f, 0));
//shared_ptr<MeshNode> node = make_shared<MeshNode>(L"Plane1", L"Models\\Plane\\Bonanza.3DS");
node->SetWorldTransform(XMMatrixScaling(0.5f, 0.5f, 0.5f) * XMMatrixTranslation(-30.0f, 320.0f, 0));
sceneGraph->Add(node);
SetBackgroundColour(XMFLOAT4(0.29f, 0.38f, 0.72f, 1.0f));
//SetBackgroundColour(XMFLOAT4(0.29f, 0.38f, 0.72f, 1.0f));
//SetBackgroundColour(XMFLOAT4(SharedMethods::RGBValueToIntensity(0x89), 0, 1, 1));
_currentRotation = 0;
_currentSideRotation = 0;
@ -24,22 +36,132 @@ void Graphics2::CreateSceneGraph()
void Graphics2::UpdateSceneGraph()
{
GetCurrentControlInputs();
SceneGraphPointer sceneGraph = GetSceneGraph();
for (ControlInputs currentControl : _currentInputs)
{
switch (currentControl)
{
case ControlInputs::Forward:
GetCamera()->SetForwardBack(_flySpeed * _boostMultiplier);
break;
case ControlInputs::Back:
GetCamera()->SetForwardBack(-_flySpeed * _boostMultiplier);
break;
case ControlInputs::StrafeLeft:
GetCamera()->SetLeftRight(-_flySpeed * _boostMultiplier);
break;
case ControlInputs::StrafeRight:
GetCamera()->SetLeftRight(_flySpeed * _boostMultiplier);
break;
case ControlInputs::TurnLeft:
GetCamera()->SetYaw(-_turnSpeed);
break;
case ControlInputs::TurnRight:
GetCamera()->SetYaw(_turnSpeed);
break;
case ControlInputs::Up:
GetCamera()->SetPitch(_turnSpeed * _invertPitch);
break;
case ControlInputs::Down:
GetCamera()->SetPitch(-_turnSpeed * _invertPitch);
break;
}
}
sceneGraph->SetWorldTransform((SharedMethods::RotateFromPoint(30.0f, -20.0f, 0, XMMatrixRotationAxis(XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f), _currentSideRotation * XM_PI / 180.0f))) * XMMatrixRotationAxis(XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f), _currentRotation * XM_PI / 180.0f));
SceneNodePointer plane1 = sceneGraph->Find(L"Plane1");
sceneGraph->Find(L"airscrew")->SetWorldTransform(SharedMethods::RotateFromPoint(0.0f, 15.471f, 14.5f, XMMatrixRotationAxis(XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f), _currentPropRotation * XM_PI / 180.0f)));
plane1->GetFirstChild()->SetWorldTransform(SharedMethods::RotateFromPoint(-60.0f, 0, 0, XMMatrixRotationAxis(XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), _currentRotation * XM_PI / 180.0f)));
plane1 ->GetFirstChild()->AddToWorldTransform(XMMatrixRotationAxis(XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f), 90.0f * XM_PI / 180.0f));
//sceneGraph->Find(L"Plane1")->GetFirstChild()->GetFirstChild()->SetWorldTransform(XMMatrixRotationAxis(XMVectorSet(0.0f, -1.0f, -1.0f, 0.0f), _currentSideRotation * XM_PI / 180.0f));
//sceneGraph->Find(L"Plane1")->Update((SharedMethods::RotateFromPoint(30.0f, -20.0f, 0, XMMatrixRotationAxis(XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), _currentSideRotation * XM_PI / 180.0f))) * XMMatrixRotationAxis(XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f), _currentRotation * XM_PI / 180.0f));
plane1->Find(L"airscrew")->SetWorldTransform(SharedMethods::RotateFromPoint(0.0f, 15.471f, 14.5f, XMMatrixRotationAxis(XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f), _currentPropRotation * XM_PI / 180.0f)));
if (_currentRotation == 360)
{
_currentRotation = 0;
//_currentSideRotation = 0;
_currentSideRotation = 0;
_currentPropRotation = 0;
}
else
{
_currentRotation += 1;
_currentSideRotation += 0.3;
_currentSideRotation += 1;
_currentPropRotation += 100;
}
ResetCurrentControlInputs();
}
void Graphics2::GetCurrentControlInputs()
{
// Check if the window has focus before accepting any keypresses
if (GetForegroundWindow() == Framework::GetHWnd())
{
if (GetAsyncKeyState(VK_SHIFT))
{
_boostMultiplier = 2;
}
else
{
_boostMultiplier = 1;
}
// Forward
if (GetAsyncKeyState(0x57))
{
_currentInputs.push_back(ControlInputs::Forward);
}
// Back
if (GetAsyncKeyState(0x53))
{
_currentInputs.push_back(ControlInputs::Back);
}
// Turn Left
if (GetAsyncKeyState(0x41))
{
_currentInputs.push_back(ControlInputs::TurnLeft);
}
// Turn Right
if (GetAsyncKeyState(0x44))
{
_currentInputs.push_back(ControlInputs::TurnRight);
}
// Strafe Left
if (GetAsyncKeyState(0x51))
{
_currentInputs.push_back(ControlInputs::StrafeLeft);
}
// Strafe Right
if (GetAsyncKeyState(0x45))
{
_currentInputs.push_back(ControlInputs::StrafeRight);
}
// "Jump"
if (GetAsyncKeyState(VK_SPACE))
{
_currentInputs.push_back(ControlInputs::Up);
}
// "Crouch"
if (GetAsyncKeyState(VK_CONTROL))
{
_currentInputs.push_back(ControlInputs::Down);
}
}
}
void Graphics2::ResetCurrentControlInputs()
{
_currentInputs.clear();
}

View File

@ -4,8 +4,11 @@
#include "TexturedCubeNode.h"
#include "MeshNode.h"
#include "SplitMeshNode.h"
#include "TerrainNode.h"
#include <ctime>
enum class ControlInputs {Forward, Back, TurnLeft, TurnRight, StrafeLeft, StrafeRight, Up, Down, Fire1, Fire2};
class Graphics2 : public DirectXFramework
{
public:
@ -13,8 +16,21 @@ public:
void UpdateSceneGraph();
private:
bool _boosting;
float _boostMultiplier;
float _flySpeed;
float _turnSpeed;
int _invertPitch;
float _currentRotation = 0.0f;
float _currentSideRotation = 0.0f;
float _currentPropRotation = 0.0f;
vector<ControlInputs> _currentInputs;
void GetCurrentControlInputs();
void ResetCurrentControlInputs();
};

View File

@ -29,13 +29,13 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
@ -48,7 +48,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
@ -144,10 +144,13 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="Camera.h" />
<ClInclude Include="Core.h" />
<ClInclude Include="DDSTextureLoader.h" />
<ClInclude Include="DirectXCore.h" />
<ClInclude Include="Framework.h" />
<ClInclude Include="DirectXFramework.h" />
<ClInclude Include="GamePadController.h" />
<ClInclude Include="Graphics2.h" />
<ClInclude Include="HelperFunctions.h" />
<ClInclude Include="Mesh.h" />
@ -163,7 +166,9 @@
<ClInclude Include="SubMeshNode.h" />
<ClInclude Include="SubMeshRenderer.h" />
<ClInclude Include="targetver.h" />
<ClInclude Include="TerrainNode.h" />
<ClInclude Include="TexturedCubeNode.h" />
<ClInclude Include="Vector3D.h" />
<ClInclude Include="WICTextureLoader.h" />
</ItemGroup>
<ItemGroup>
@ -179,8 +184,11 @@
<Image Include="Textures\woodbox.bmp" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Camera.cpp" />
<ClCompile Include="DDSTextureLoader.cpp" />
<ClCompile Include="Framework.cpp" />
<ClCompile Include="DirectXFramework.cpp" />
<ClCompile Include="GamePadController.cpp" />
<ClCompile Include="Graphics2.cpp" />
<ClCompile Include="Mesh.cpp" />
<ClCompile Include="MeshNode.cpp" />
@ -191,7 +199,9 @@
<ClCompile Include="SplitMeshNode.cpp" />
<ClCompile Include="SubMeshNode.cpp" />
<ClCompile Include="SubMeshRenderer.cpp" />
<ClCompile Include="TerrainNode.cpp" />
<ClCompile Include="TexturedCubeNode.cpp" />
<ClCompile Include="Vector3D.cpp" />
<ClCompile Include="WICTextureLoader.cpp" />
</ItemGroup>
<ItemGroup>
@ -208,6 +218,16 @@
<None Include="assimp-vc140-mt.dll" />
<None Include="zlib.dll" />
</ItemGroup>
<ItemGroup>
<Text Include="TerrainShaders.hlsl">
<FileType>Document</FileType>
</Text>
</ItemGroup>
<ItemGroup>
<Text Include="TerrainShadersNoBlend.hlsl">
<FileType>Document</FileType>
</Text>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>

View File

@ -81,6 +81,21 @@
<ClInclude Include="SplitMeshNode.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="TerrainNode.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Camera.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GamePadController.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="DDSTextureLoader.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Vector3D.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Graphics2.rc">
@ -153,6 +168,21 @@
<ClCompile Include="SplitMeshNode.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="TerrainNode.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Camera.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GamePadController.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="DDSTextureLoader.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Vector3D.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Text Include="shader.hlsl">
@ -161,6 +191,12 @@
<Text Include="TexturedShaders.hlsl">
<Filter>Shaders</Filter>
</Text>
<Text Include="TerrainShaders.hlsl">
<Filter>Shaders</Filter>
</Text>
<Text Include="TerrainShadersNoBlend.hlsl">
<Filter>Shaders</Filter>
</Text>
</ItemGroup>
<ItemGroup>
<None Include="assimp-vc140-mt.dll" />

View File

@ -21,7 +21,7 @@ void MeshNode::Render()
{
_renderer->SetMesh(_mesh);
_renderer->SetWorldTransformation(XMLoadFloat4x4(&_combinedWorldTransformation));
_renderer->SetCameraPosition(XMFLOAT4(0.0f, 0.0f, -100.0f, 1.0f));
_renderer->SetCameraPosition(DirectXFramework::GetDXFramework()->GetCamera()->GetRawCameraPosition());
_renderer->SetAmbientLight(XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f));
_renderer->SetDirectionalLight(XMVectorSet(0.0f, -1.0f, 1.0f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f));
_renderer->Render();

View File

@ -58,10 +58,10 @@ void MeshRenderer::RenderNode(shared_ptr<Node> node, bool renderTransparent)
_deviceContext->IASetVertexBuffers(0, 1, _vertexBuffer.GetAddressOf(), &stride, &offset);
_indexBuffer = subMesh->GetIndexBuffer();
_deviceContext->IASetIndexBuffer(_indexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
_cBuffer.DiffuseCoefficient = material->GetDiffuseColour();
_cBuffer.SpecularCoefficient = material->GetSpecularColour();
_cBuffer.Shininess = material->GetShininess();
_cBuffer.Opacity = opacity;
_cBuffer.diffuseCoefficient = material->GetDiffuseColour();
_cBuffer.specularCoefficient = material->GetSpecularColour();
_cBuffer.shininess = material->GetShininess();
_cBuffer.opacity = opacity;
// Update the constant buffer
_deviceContext->VSSetConstantBuffers(0, 1, _constantBuffer.GetAddressOf());
_deviceContext->UpdateSubresource(_constantBuffer.Get(), 0, 0, &_cBuffer, 0, 0);
@ -90,18 +90,18 @@ void MeshRenderer::Render()
_deviceContext->RSSetState(_noCullRasteriserState.Get());
XMMATRIX projectionTransformation = DirectXFramework::GetDXFramework()->GetProjectionTransformation();
XMMATRIX viewTransformation = DirectXFramework::GetDXFramework()->GetViewTransformation();
XMMATRIX viewTransformation = DirectXFramework::GetDXFramework()->GetCamera()->GetViewMatrix();
XMMATRIX completeTransformation = XMLoadFloat4x4(&_worldTransformation) * viewTransformation * projectionTransformation;
// Draw the first cube
_cBuffer.CompleteTransformation = completeTransformation;
_cBuffer.WorldTransformation = XMLoadFloat4x4(&_worldTransformation);
_cBuffer.AmbientColor = _ambientLight;
_cBuffer.LightVector = XMVector4Normalize(XMLoadFloat4(&_directionalLightVector));
_cBuffer.LightColor = _directionalLightColour;
_cBuffer.CameraPosition = _cameraPosition;
// Reset the CBUFFER since its now a class member.
_cBuffer = CBUFFER();
_cBuffer.completeTransformation = completeTransformation;
_cBuffer.worldTransformation = XMLoadFloat4x4(&_worldTransformation);
_cBuffer.ambientColor = _ambientLight;
_cBuffer.lightVector = XMVector4Normalize(XMLoadFloat4(&_directionalLightVector));
_cBuffer.lightColor = _directionalLightColour;
_cBuffer.cameraPosition = _cameraPosition;
_deviceContext->VSSetShader(_vertexShader.Get(), 0, 0);
_deviceContext->PSSetShader(_pixelShader.Get(), 0, 0);

View File

@ -46,7 +46,6 @@ private:
CBUFFER _cBuffer;
void BuildShaders();
void BuildVertexLayout();
void BuildConstantBuffer();

View File

@ -77,4 +77,14 @@ SceneNodePointer SceneGraph::Find(wstring name)
}
}
return foundValue;
}
SceneNodePointer SceneGraph::GetFirstChild()
{
SceneNodePointer firstChild = nullptr;
if (_children.size() > 0)
{
firstChild = _children.front();
}
return firstChild;
}

View File

@ -17,6 +17,9 @@ public:
void Add(SceneNodePointer node);
void Remove(SceneNodePointer node);
SceneNodePointer Find(wstring name);
SceneNodePointer GetRootNode();
SceneNodePointer GetParent();
SceneNodePointer GetFirstChild();
private:
// Here you need to add whatever collection you are going to

View File

@ -26,12 +26,14 @@ public:
virtual void DoTestUpdate(float inputTest) { _testInt = inputTest; }
void SetWorldTransform(FXMMATRIX& worldTransformation) { XMStoreFloat4x4(&_worldTransformation, worldTransformation); }
void AddToWorldTransform(FXMMATRIX& transformation) { XMStoreFloat4x4(&_worldTransformation, XMLoadFloat4x4(&_worldTransformation) * transformation); }
// Although only required in the composite class, these are provided
// in order to simplify the code base.
virtual void Add(SceneNodePointer node) {}
virtual void Remove(SceneNodePointer node) {};
virtual SceneNodePointer Find(wstring name) { return (_name == name) ? shared_from_this() : nullptr; }
virtual SceneNodePointer GetFirstChild() { return shared_from_this(); }
protected:
XMFLOAT4X4 _worldTransformation;

View File

@ -5,3 +5,19 @@ XMMATRIX SharedMethods::RotateFromPoint(float x, float y, float z, XMMATRIX rota
// Translates a matrix to a point, rotates and then returns back to where it was
return XMMatrixTranslation(x, y, z) * rotationMatrix * XMMatrixTranslation(-x, -y, -z);
}
// Method so i can use normal RGB values and hopefully hex values too since im use to those
float SharedMethods::RGBValueToIntensity(int value)
{
return (float)value / 255.0f;
}
float SharedMethods::lerp(int a, int b, int p)
{
return lerp((float)a, (float)b, (float)p);
}
float SharedMethods::lerp(float a, float b, float p)
{
return a + p * (b - a);
}

View File

@ -3,21 +3,26 @@
struct CBUFFER
{
XMMATRIX CompleteTransformation;
XMMATRIX WorldTransformation;
XMFLOAT4 CameraPosition;
XMVECTOR LightVector;
XMFLOAT4 LightColor;
XMFLOAT4 AmbientColor;
XMFLOAT4 DiffuseCoefficient;
XMFLOAT4 SpecularCoefficient;
float Shininess;
float Opacity;
float Padding[2];
XMMATRIX completeTransformation;
XMMATRIX worldTransformation;
XMFLOAT4 cameraPosition;
XMVECTOR lightVector;
XMFLOAT4 lightColor;
XMFLOAT4 ambientColor;
XMFLOAT4 diffuseCoefficient;
XMFLOAT4 specularCoefficient;
float shininess;
float opacity;
float padding[2];
};
namespace SharedMethods
{
XMMATRIX RotateFromPoint(float x, float y, float z, XMMATRIX rotationMatrix);
float RGBValueToIntensity(int value);
float lerp(int a, int b, int p);
float lerp(float a, float b, float p);
};

View File

@ -1,10 +1,5 @@
#include "SplitMeshNode.h"
SplitMeshNode::SplitMeshNode(wstring name, wstring modelName)
{
_modelName = modelName;
}
bool SplitMeshNode::Initialise()
{
bool currentStatus = true;
@ -16,8 +11,8 @@ bool SplitMeshNode::Initialise()
currentStatus = false;
}
else
{
Add(AddMeshNode(_mesh->GetRootNode()));
{
Add(AddMeshNode(_mesh->GetRootNode()));
}
if (currentStatus)
@ -28,10 +23,10 @@ bool SplitMeshNode::Initialise()
return currentStatus;
}
SceneGraphPointer SplitMeshNode::AddMeshNode(shared_ptr<Node> node)
SceneNodePointer SplitMeshNode::AddMeshNode(shared_ptr<Node> node)
{
unsigned int subMeshCount = (unsigned int)node->GetMeshCount();
SceneGraphPointer currentNodeGraph = make_shared<SceneGraph>(node->GetName());
SceneNodePointer currentNodeGraph = make_shared<SceneGraph>(node->GetName());
/*string nameString;
for (char x : node->GetName())
@ -46,8 +41,7 @@ SceneGraphPointer SplitMeshNode::AddMeshNode(shared_ptr<Node> node)
{
unsigned int meshIndex = node->GetMesh(i);
shared_ptr<SubMesh> subMesh = _mesh->GetSubMesh(meshIndex);
shared_ptr<SubMeshNode> subNode = make_shared<SubMeshNode>(node->GetName() + L"_" + to_wstring(i), subMesh);
subNode->SetWorldTransform(XMMatrixIdentity());
shared_ptr<SubMeshNode> subNode = make_shared<SubMeshNode>(node->GetName() + L"_" + to_wstring(i), subMesh);
currentNodeGraph->Add(subNode);
}

View File

@ -6,9 +6,9 @@
class SplitMeshNode : public SceneGraph
{
public:
SplitMeshNode(wstring name, wstring modelName);
SplitMeshNode(wstring name, wstring modelName) : SceneGraph(name) { _modelName = modelName; }
bool Initialise(void);
SceneGraphPointer AddMeshNode(shared_ptr<Node> node);
SceneNodePointer AddMeshNode(shared_ptr<Node> node);
private:
shared_ptr<SubMeshRenderer> _renderer;

View File

@ -19,7 +19,7 @@ void SubMeshNode::Render()
{
_renderer->SetSubMesh(_subMesh);
_renderer->SetWorldTransformation(XMLoadFloat4x4(&_combinedWorldTransformation));
_renderer->SetCameraPosition(XMFLOAT4(0.0f, 0.0f, -100.0f, 1.0f));
_renderer->SetCameraPosition(DirectXFramework::GetDXFramework()->GetCamera()->GetRawCameraPosition());
_renderer->SetAmbientLight(XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f));
_renderer->SetDirectionalLight(XMVectorSet(0.0f, -1.0f, 1.0f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f));
_renderer->Render();

View File

@ -47,18 +47,19 @@ void SubMeshRenderer::Render()
_deviceContext->RSSetState(_noCullRasteriserState.Get());
XMMATRIX projectionTransformation = DirectXFramework::GetDXFramework()->GetProjectionTransformation();
XMMATRIX viewTransformation = DirectXFramework::GetDXFramework()->GetViewTransformation();
XMMATRIX viewTransformation = DirectXFramework::GetDXFramework()->GetCamera()->GetViewMatrix();
XMMATRIX completeTransformation = XMLoadFloat4x4(&_worldTransformation) * viewTransformation * projectionTransformation;
// Draw the first cube
_cBuffer.CompleteTransformation = completeTransformation;
_cBuffer.WorldTransformation = XMLoadFloat4x4(&_worldTransformation);
_cBuffer.AmbientColor = _ambientLight;
_cBuffer.LightVector = XMVector4Normalize(XMLoadFloat4(&_directionalLightVector));
_cBuffer.LightColor = _directionalLightColour;
_cBuffer.CameraPosition = _cameraPosition;
CBUFFER cBuffer;
cBuffer.completeTransformation = completeTransformation;
cBuffer.worldTransformation = XMLoadFloat4x4(&_worldTransformation);
cBuffer.ambientColor = _ambientLight;
cBuffer.lightVector = XMVector4Normalize(XMLoadFloat4(&_directionalLightVector));
cBuffer.lightColor = _directionalLightColour;
cBuffer.cameraPosition = _cameraPosition;
_deviceContext->VSSetShader(_vertexShader.Get(), 0, 0);
_deviceContext->PSSetShader(_pixelShader.Get(), 0, 0);
@ -77,13 +78,13 @@ void SubMeshRenderer::Render()
_deviceContext->IASetVertexBuffers(0, 1, _vertexBuffer.GetAddressOf(), &stride, &offset);
_indexBuffer = _subMesh->GetIndexBuffer();
_deviceContext->IASetIndexBuffer(_indexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
_cBuffer.DiffuseCoefficient = material->GetDiffuseColour();
_cBuffer.SpecularCoefficient = material->GetSpecularColour();
_cBuffer.Shininess = material->GetShininess();
_cBuffer.Opacity = opacity;
cBuffer.diffuseCoefficient = material->GetDiffuseColour();
cBuffer.specularCoefficient = material->GetSpecularColour();
cBuffer.shininess = material->GetShininess();
cBuffer.opacity = opacity;
// Update the constant buffer
_deviceContext->VSSetConstantBuffers(0, 1, _constantBuffer.GetAddressOf());
_deviceContext->UpdateSubresource(_constantBuffer.Get(), 0, 0, &_cBuffer, 0, 0);
_deviceContext->UpdateSubresource(_constantBuffer.Get(), 0, 0, &cBuffer, 0, 0);
_texture = material->GetTexture();
_deviceContext->PSSetShaderResources(0, 1, _texture.GetAddressOf());
_deviceContext->PSSetConstantBuffers(0, 1, _constantBuffer.GetAddressOf());

View File

@ -37,16 +37,13 @@ private:
ComPtr<ID3D11InputLayout> _layout;
ComPtr<ID3D11Buffer> _constantBuffer;
ComPtr<ID3D11ShaderResourceView> _texture;;
ComPtr<ID3D11ShaderResourceView> _texture;
ComPtr<ID3D11BlendState> _transparentBlendState;
ComPtr<ID3D11RasterizerState> _defaultRasteriserState;
ComPtr<ID3D11RasterizerState> _noCullRasteriserState;
CBUFFER _cBuffer;
void BuildShaders();
void BuildVertexLayout();
void BuildConstantBuffer();

410
Graphics2/TerrainNode.cpp Normal file
View File

@ -0,0 +1,410 @@
#include "TerrainNode.h"
#define WORLD_HEIGHT 512
TerrainNode::TerrainNode(wstring name, wstring heightMap, int widthX, int widthZ, int cellSizeX, int cellSizeZ) : SceneNode(name)
{
_heightMap = heightMap;
_widthX = widthX;
_widthZ = widthZ;
_gridCols = _widthX + 1;
_gridRows = _widthZ + 1;
_cellSizeX = cellSizeX;
_cellSizeZ = cellSizeZ;
_polygonsCount = (_gridCols * _gridRows) * 2;
_vertexCount = _polygonsCount * 2;
_indiciesCount = _polygonsCount * 3;
}
bool TerrainNode::Initialise()
{
_device = DirectXFramework::GetDXFramework()->GetDevice();
_deviceContext = DirectXFramework::GetDXFramework()->GetDeviceContext();
if (_heightMap.length() > 0)
{
if (LoadHeightMap(_heightMap))
{
_usedHeightMap = true;
}
else
{
_usedHeightMap = false;
}
}
else
{
_usedHeightMap = false;
}
GenerateTerrainData();
GenerateBuffers();
BuildShaders();
BuildVertexLayout();
BuildConstantBuffer();
BuildBlendState();
BuildRendererStates();
return true;
}
void TerrainNode::GenerateTerrainData()
{
float totalWidth = (float)(_gridCols * _cellSizeX);
float totalDepth = (float)(_gridRows * _cellSizeZ);
float centerWidth = totalWidth * -0.5f;
float centerDepth = totalDepth * 0.5f;
int currentVertexCount = 0;
for (int z = 0; z < _gridRows; z++)
{
for (int x = 0; x < _gridCols; x++)
{
int currentIndex = (z * _gridCols) + x;
int offsetIndexX = 1;
if (x == _widthX)
{
offsetIndexX = 0;
}
int offsetIndexZ = _gridCols;
if (z == _widthZ)
{
offsetIndexZ = 0;
}
Vector3D polygonNormal = Vector3D(0.0f, 0.0f, 0.0f);
VERTEX vertex;
vertex.Position = XMFLOAT3(x * _cellSizeX + centerWidth, GetHeightMapValueAt(currentIndex), (-z + 1) * _cellSizeZ + centerDepth);
vertex.Normal = XMFLOAT3(0.0f, 0.0f, 0.0f);
vertex.TexCoord = XMFLOAT2(0.0f, 1.0f);
_terrainVerts.push_back(vertex);
_terrainNormals.push_back(polygonNormal);
vertex = VERTEX();
vertex.Position = XMFLOAT3((x + 1) * _cellSizeX + centerWidth, GetHeightMapValueAt(currentIndex + offsetIndexX), (-z + 1) * _cellSizeZ + centerDepth);
vertex.Normal = XMFLOAT3(0.0f, 0.0f, 0.0f);
vertex.TexCoord = XMFLOAT2(1.0f, 1.0f);
_terrainVerts.push_back(vertex);
_terrainNormals.push_back(polygonNormal);
vertex = VERTEX();
vertex.Position = XMFLOAT3(x * _cellSizeX + centerWidth, GetHeightMapValueAt(currentIndex + offsetIndexZ), -z * _cellSizeZ + centerDepth);
vertex.Normal = XMFLOAT3(0.0f, 0.0f, 0.0f);
vertex.TexCoord = XMFLOAT2(0.0f, 0.0f);
_terrainVerts.push_back(vertex);
_terrainNormals.push_back(polygonNormal);
vertex = VERTEX();
vertex.Position = XMFLOAT3((x + 1) * _cellSizeX + centerWidth, GetHeightMapValueAt(currentIndex + offsetIndexZ + offsetIndexX), -z * _cellSizeZ + centerDepth);
vertex.Normal = XMFLOAT3(0.0f, 0.0f, 0.0f);
vertex.TexCoord = XMFLOAT2(1.0f, 0.0f);
_terrainVerts.push_back(vertex);
_terrainNormals.push_back(polygonNormal);
_indices.push_back(currentVertexCount);
_indices.push_back(currentVertexCount + 1);
_indices.push_back(currentVertexCount + 2);
_indices.push_back(currentVertexCount + 2);
_indices.push_back(currentVertexCount + 1);
_indices.push_back(currentVertexCount + 3);
currentVertexCount += 4;
}
}
int currentNormalIndex = 0;
for (int z = 0; z < _gridRows; z++)
{
for (int x = 0; x < _gridCols; x++)
{
Vector3D vectorA = Vector3D(_terrainVerts[currentNormalIndex + 1].Position, _terrainVerts[currentNormalIndex].Position);
Vector3D vectorB = Vector3D(_terrainVerts[currentNormalIndex + 2].Position, _terrainVerts[currentNormalIndex].Position);
Vector3D polygonNormal = Vector3D::CrossProduct(vectorA, vectorB);
_terrainNormals[currentNormalIndex] += polygonNormal;
_terrainNormals[currentNormalIndex + 1] += polygonNormal;
_terrainNormals[currentNormalIndex + 2] += polygonNormal;
_terrainNormals[currentNormalIndex + 3] += polygonNormal;
AddNormalToVertex(z - 1, x - 1, 3, polygonNormal);
AddNormalToVertex(z - 1, x, 2, polygonNormal);
AddNormalToVertex(z - 1, x, 3, polygonNormal);
AddNormalToVertex(z - 1, x + 1, 2, polygonNormal);
AddNormalToVertex(z, x - 1, 1, polygonNormal);
AddNormalToVertex(z, x - 1, 3, polygonNormal);
AddNormalToVertex(z, x + 1, 0, polygonNormal);
AddNormalToVertex(z, x + 1, 2, polygonNormal);
AddNormalToVertex(z + 1, x - 1, 1, polygonNormal);
AddNormalToVertex(z + 1, x, 0, polygonNormal);
AddNormalToVertex(z + 1, x, 1, polygonNormal);
AddNormalToVertex(z + 1, x + 1, 0, polygonNormal);
currentNormalIndex += 4;
}
}
for (int i = 0; i < _terrainNormals.size(); i++)
{
_terrainNormals[i].Normalize();
_terrainVerts[i].Normal = _terrainNormals[i].Get();
}
_terrainNormals.clear();
}
void TerrainNode::AddNormalToVertex(int row, int col, int vertexIndex, Vector3D normal)
{
int rowIndexOffset = row * _gridCols;
int colIndexOffset = col;
int finalIndex = vertexIndex + ((rowIndexOffset + colIndexOffset) * 4);
if (row >= 0 && row < _gridRows && col >= 0 && col < _gridCols)
{
_terrainNormals[finalIndex] += normal;
}
if (row == _gridRows)
{
int test = 1;
}
}
void TerrainNode::GenerateBuffers()
{
// Setup the structure that specifies how big the vertex
// buffer should be
D3D11_BUFFER_DESC vertexBufferDescriptor;
vertexBufferDescriptor.Usage = D3D11_USAGE_IMMUTABLE;
vertexBufferDescriptor.ByteWidth = sizeof(VERTEX) * _vertexCount;
vertexBufferDescriptor.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDescriptor.CPUAccessFlags = 0;
vertexBufferDescriptor.MiscFlags = 0;
vertexBufferDescriptor.StructureByteStride = 0;
// Now set up a structure that tells DirectX where to get the
// data for the vertices from
D3D11_SUBRESOURCE_DATA vertexInitialisationData;
vertexInitialisationData.pSysMem = &_terrainVerts[0];
// and create the vertex buffer
ThrowIfFailed(_device->CreateBuffer(&vertexBufferDescriptor, &vertexInitialisationData, _vertexBuffer.GetAddressOf()));
// Setup the structure that specifies how big the index
// buffer should be
D3D11_BUFFER_DESC indexBufferDescriptor;
indexBufferDescriptor.Usage = D3D11_USAGE_IMMUTABLE;
indexBufferDescriptor.ByteWidth = sizeof(UINT) * _indiciesCount;
indexBufferDescriptor.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDescriptor.CPUAccessFlags = 0;
indexBufferDescriptor.MiscFlags = 0;
indexBufferDescriptor.StructureByteStride = 0;
// Now set up a structure that tells DirectX where to get the
// data for the indices from
D3D11_SUBRESOURCE_DATA indexInitialisationData;
indexInitialisationData.pSysMem = &_indices[0];
// and create the index buffer
ThrowIfFailed(_device->CreateBuffer(&indexBufferDescriptor, &indexInitialisationData, _indexBuffer.GetAddressOf()));
}
void TerrainNode::Render()
{
XMMATRIX projectionTransformation = DirectXFramework::GetDXFramework()->GetProjectionTransformation();
XMMATRIX viewTransformation = DirectXFramework::GetDXFramework()->GetCamera()->GetViewMatrix();
XMMATRIX completeTransformation = XMLoadFloat4x4(&_worldTransformation) * viewTransformation * projectionTransformation;
// Draw the first cube
CBUFFER cBuffer;
cBuffer.completeTransformation = completeTransformation;
cBuffer.worldTransformation = XMLoadFloat4x4(&_worldTransformation);
cBuffer.ambientColor = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
//cBuffer.AmbientColor = XMFLOAT4(SharedMethods::RGBValueToIntensity(0xfd), 0.0f, 1.0f, 1.0f); //XMFLOAT4(1, 1, 1, 1); //_ambientLight;
cBuffer.lightVector = XMVector4Normalize(XMLoadFloat4(&_directionalLightVector));
cBuffer.lightColor = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
//cBuffer.LightColor = XMFLOAT4(SharedMethods::RGBValueToIntensity(0x89), 0.0f, 5.0f, 5.0f);
//cBuffer.LightColor = _directionalLightColor;
cBuffer.cameraPosition = DirectXFramework::GetDXFramework()->GetCamera()->GetRawCameraPosition();
_deviceContext->VSSetShader(_vertexShader.Get(), 0, 0);
_deviceContext->PSSetShader(_pixelShader.Get(), 0, 0);
_deviceContext->IASetInputLayout(_layout.Get());
// Update the constant buffer
_deviceContext->VSSetConstantBuffers(0, 1, _constantBuffer.GetAddressOf());
_deviceContext->UpdateSubresource(_constantBuffer.Get(), 0, 0, &cBuffer, 0, 0);
// Set the texture to be used by the pixel shader
_deviceContext->PSSetShaderResources(0, 1, _texture.GetAddressOf());
UINT stride = sizeof(VERTEX);
UINT offset = 0;
_deviceContext->IASetVertexBuffers(0, 1, _vertexBuffer.GetAddressOf(), &stride, &offset);
_deviceContext->IASetIndexBuffer(_indexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
cBuffer.diffuseCoefficient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
cBuffer.specularCoefficient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
cBuffer.shininess = 1.0f;
cBuffer.opacity = 1.0f;
// Update the constant buffer
_deviceContext->VSSetConstantBuffers(0, 1, _constantBuffer.GetAddressOf());
_deviceContext->UpdateSubresource(_constantBuffer.Get(), 0, 0, &cBuffer, 0, 0);
_deviceContext->PSSetShaderResources(0, 1, _texture.GetAddressOf());
_deviceContext->PSSetConstantBuffers(0, 1, _constantBuffer.GetAddressOf());
_deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//_deviceContext->RSSetState(_wireframeRasteriserState.Get());
_deviceContext->DrawIndexed(_indiciesCount, 0, 0);
// Turn back face culling back on in case another renderer
// relies on it
_deviceContext->RSSetState(_defaultRasteriserState.Get());
}
void TerrainNode::Shutdown(void)
{
}
void TerrainNode::BuildShaders()
{
DWORD shaderCompileFlags = 0;
#if defined( _DEBUG )
shaderCompileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
ComPtr<ID3DBlob> compilationMessages = nullptr;
//Compile vertex shader
HRESULT hr = D3DCompileFromFile(L"TerrainShadersNoBlend.hlsl",
nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
"VShader", "vs_5_0",
shaderCompileFlags, 0,
_vertexShaderByteCode.GetAddressOf(),
compilationMessages.GetAddressOf());
if (compilationMessages.Get() != nullptr)
{
// If there were any compilation messages, display them
MessageBoxA(0, (char*)compilationMessages->GetBufferPointer(), 0, 0);
}
// Even if there are no compiler messages, check to make sure there were no other errors.
ThrowIfFailed(hr);
ThrowIfFailed(_device->CreateVertexShader(_vertexShaderByteCode->GetBufferPointer(), _vertexShaderByteCode->GetBufferSize(), NULL, _vertexShader.GetAddressOf()));
// Compile pixel shader
hr = D3DCompileFromFile(L"TerrainShadersNoBlend.hlsl",
nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
"PShader", "ps_5_0",
shaderCompileFlags, 0,
_pixelShaderByteCode.GetAddressOf(),
compilationMessages.GetAddressOf());
if (compilationMessages.Get() != nullptr)
{
// If there were any compilation messages, display them
MessageBoxA(0, (char*)compilationMessages->GetBufferPointer(), 0, 0);
}
ThrowIfFailed(hr);
ThrowIfFailed(_device->CreatePixelShader(_pixelShaderByteCode->GetBufferPointer(), _pixelShaderByteCode->GetBufferSize(), NULL, _pixelShader.GetAddressOf()));
}
void TerrainNode::BuildVertexLayout()
{
// Create the vertex input layout. This tells DirectX the format
// of each of the vertices we are sending to it.
D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT , D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT , D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT , D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
ThrowIfFailed(_device->CreateInputLayout(vertexDesc, ARRAYSIZE(vertexDesc), _vertexShaderByteCode->GetBufferPointer(), _vertexShaderByteCode->GetBufferSize(), _layout.GetAddressOf()));
}
void TerrainNode::BuildConstantBuffer()
{
D3D11_BUFFER_DESC bufferDesc;
ZeroMemory(&bufferDesc, sizeof(bufferDesc));
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.ByteWidth = sizeof(CBUFFER);
bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
ThrowIfFailed(_device->CreateBuffer(&bufferDesc, NULL, _constantBuffer.GetAddressOf()));
}
void TerrainNode::BuildBlendState()
{
D3D11_BLEND_DESC transparentDesc = { 0 };
transparentDesc.AlphaToCoverageEnable = false;
transparentDesc.IndependentBlendEnable = false;
transparentDesc.RenderTarget[0].BlendEnable = true;
transparentDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
transparentDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
transparentDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
transparentDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
transparentDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
transparentDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
transparentDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
ThrowIfFailed(_device->CreateBlendState(&transparentDesc, _transparentBlendState.GetAddressOf()));
}
void TerrainNode::BuildRendererStates()
{
// Set default and wireframe rasteriser states
D3D11_RASTERIZER_DESC rasteriserDesc;
rasteriserDesc.FillMode = D3D11_FILL_SOLID;
rasteriserDesc.CullMode = D3D11_CULL_BACK;
rasteriserDesc.FrontCounterClockwise = false;
rasteriserDesc.DepthBias = 0;
rasteriserDesc.SlopeScaledDepthBias = 0.0f;
rasteriserDesc.DepthBiasClamp = 0.0f;
rasteriserDesc.DepthClipEnable = true;
rasteriserDesc.ScissorEnable = false;
rasteriserDesc.MultisampleEnable = false;
rasteriserDesc.AntialiasedLineEnable = false;
ThrowIfFailed(_device->CreateRasterizerState(&rasteriserDesc, _defaultRasteriserState.GetAddressOf()));
rasteriserDesc.FillMode = D3D11_FILL_WIREFRAME;
ThrowIfFailed(_device->CreateRasterizerState(&rasteriserDesc, _wireframeRasteriserState.GetAddressOf()));
}
bool TerrainNode::LoadHeightMap(wstring heightMapFilename)
{
unsigned int mapSize = _gridCols * _gridRows;
USHORT* rawFileValues = new USHORT[mapSize];
std::ifstream inputHeightMap;
inputHeightMap.open(heightMapFilename.c_str(), std::ios_base::binary);
if (!inputHeightMap)
{
return false;
}
inputHeightMap.read((char*)rawFileValues, mapSize * 2);
inputHeightMap.close();
// Normalise BYTE values to the range 0.0f - 1.0f;
for (unsigned int i = 0; i < mapSize; i++)
{
_heightValues.push_back((float)rawFileValues[i] / 65536);
}
delete[] rawFileValues;
return true;
}
float TerrainNode::GetHeightMapValueAt(int index)
{
float result = 0;
if (_usedHeightMap)
{
result = _heightValues[index] * WORLD_HEIGHT; // +(rand() % 10);
}
return result;
}

85
Graphics2/TerrainNode.h Normal file
View File

@ -0,0 +1,85 @@
#pragma once
#include <fstream>
#include <vector>
#include "WICTextureLoader.h"
#include "SharedMethods.h"
#include "SceneNode.h"
#include "Vector3D.h"
class TerrainNode : public SceneNode
{
public:
TerrainNode(wstring name, wstring heightMap, int widthX = 1023, int widthZ = 1023, int rows = 10, int cols = 10);
bool Initialise(void);
void Render(void);
void Shutdown(void);
private:
int _widthX;
int _widthZ;
UINT _gridRows;
UINT _gridCols;
int _cellSizeX;
int _cellSizeZ;
bool _usedHeightMap;
UINT _polygonsCount;
UINT _indiciesCount;
UINT _vertexCount;
float _terrainStartX;
float _terrainStartZ;
float _terrainEndX;
float _terrainEndZ;
wstring _heightMap;
wstring _textureName;
vector<VERTEX> _terrainVerts;
vector<int> _indices;
vector<float> _heightValues;
vector<Vector3D> _terrainNormals;
XMFLOAT4 _ambientLight;
XMFLOAT4 _directionalLightVector;
XMFLOAT4 _directionalLightColor;
XMFLOAT4 _cameraPosition;
ComPtr<ID3D11Device> _device;
ComPtr<ID3D11DeviceContext> _deviceContext;
ComPtr<ID3D11Buffer> _vertexBuffer;
ComPtr<ID3D11Buffer> _indexBuffer;
ComPtr<ID3DBlob> _vertexShaderByteCode = nullptr;
ComPtr<ID3DBlob> _pixelShaderByteCode = nullptr;
ComPtr<ID3D11VertexShader> _vertexShader;
ComPtr<ID3D11PixelShader> _pixelShader;
ComPtr<ID3D11InputLayout> _layout;
ComPtr<ID3D11Buffer> _constantBuffer;
ComPtr<ID3D11ShaderResourceView> _texture;
ComPtr<ID3D11BlendState> _transparentBlendState;
ComPtr<ID3D11RasterizerState> _defaultRasteriserState;
ComPtr<ID3D11RasterizerState> _wireframeRasteriserState;
void GenerateTerrainData();
void GenerateBuffers();
void BuildShaders();
void BuildVertexLayout();
void BuildConstantBuffer();
void BuildBlendState();
void BuildRendererStates();
void BuildTexture();
bool LoadHeightMap(wstring heightMapFilename);
float GetHeightMapValueAt(int index);
void AddNormalToVertex(int row, int col, int vertexIndex, Vector3D normal);
};

View File

@ -0,0 +1,99 @@
cbuffer ConstantBuffer
{
float4x4 completeTransformation;
float4x4 worldTransformation;
float4 cameraPosition;
float4 lightVector; // the light's vector
float4 lightColor; // the light's color
float4 ambientColor; // the ambient light's color
float4 diffuseCoefficient; // The diffuse reflection cooefficient
float4 specularCoefficient; // The specular reflection cooefficient
float shininess; // The shininess factor
float opacity; // The opacity (transparency) of the material. 0 = fully transparent, 1 = fully opaque
float2 padding;
}
Texture2D BlendMap : register(t0);
Texture2DArray TexturesArray : register(t1);
SamplerState ss
{
Filter = MIN_MAG_MIP_LINEAR;
AddressU = WRAP;
AddressV = WRAP;
};
struct VertexShaderInput
{
float3 Position : POSITION;
float3 Normal : NORMAL;
float2 TexCoord : TEXCOORD0;
float2 BlendMapTexCoord : TEXCOORD1;
};
struct PixelShaderInput
{
float4 Position : SV_POSITION;
float4 PositionWS: TEXCOORD2;
float4 NormalWS : TEXCOORD3;
float2 TexCoord : TEXCOORD0;
float2 BlendMapTexCoord : TEXCOORD1;
};
PixelShaderInput VShader(VertexShaderInput vin)
{
PixelShaderInput output;
float3 position = vin.Position;
output.Position = mul(completeTransformation, float4(position, 1.0f));
output.PositionWS = mul(worldTransformation, float4(position, 1.0f));
output.NormalWS = float4(mul((float3x3)worldTransformation, vin.Normal), 1.0f);
output.TexCoord = vin.TexCoord;
output.BlendMapTexCoord = vin.BlendMapTexCoord;
return output;
}
float4 PShader(PixelShaderInput input) : SV_TARGET
{
float4 directionToCamera = normalize(input.PositionWS - cameraPosition);
float4 directionToLight = normalize(-lightVector);
float surfaceShininess = shininess;
float4 adjustedNormal = normalize(input.NormalWS);
// Calculate diffuse lighting
float NdotL = max(0, dot(adjustedNormal, directionToLight));
float4 diffuse = saturate(lightColor * NdotL * diffuseCoefficient);
diffuse.a = 1.0f;
// Calculate specular component
float4 R = 2 * NdotL * adjustedNormal - directionToLight;
float RdotV = max(0, dot(R, directionToCamera));
float4 specular = saturate(lightColor * pow(RdotV, surfaceShininess) * specularCoefficient);
specular.a = 1.0f;
// Calculate ambient lighting
float4 ambientLight = ambientColor * diffuseCoefficient;
float4 color;
// Sample layers in texture array.
float4 c0 = TexturesArray.Sample(ss, float3(input.TexCoord, 0.0f));
float4 c1 = TexturesArray.Sample(ss, float3(input.TexCoord, 1.0f));
float4 c2 = TexturesArray.Sample(ss, float3(input.TexCoord, 2.0f));
float4 c3 = TexturesArray.Sample(ss, float3(input.TexCoord, 3.0f));
float4 c4 = TexturesArray.Sample(ss, float3(input.TexCoord, 4.0f));
// Sample the blend map.
float4 t = BlendMap.Sample(ss, input.BlendMapTexCoord);
// Blend the layers on top of each other.
color = c0;
color = lerp(color, c1, t.r);
color = lerp(color, c2, t.g);
color = lerp(color, c3, t.b);
color = lerp(color, c4, t.a);
// Combine all components
color = (ambientLight + diffuse) * color;
color = saturate(color + specular);
return color;
}

View File

@ -0,0 +1,70 @@
cbuffer ConstantBuffer
{
float4x4 completeTransformation;
float4x4 worldTransformation;
float4 cameraPosition;
float4 lightVector; // the light's vector
float4 lightColor; // the light's color
float4 ambientColor; // the ambient light's color
float4 diffuseCoefficient; // The diffuse reflection cooefficient
float4 specularCoefficient; // The specular reflection cooefficient
float shininess; // The shininess factor
float opacity; // The opacity (transparency) of the material. 0 = fully transparent, 1 = fully opaque
float2 padding;
}
Texture2D Texture;
SamplerState ss;
struct VertexShaderInput
{
float3 Position : POSITION;
float3 Normal : NORMAL;
float2 TexCoord : TEXCOORD;
};
struct PixelShaderInput
{
float4 Position : SV_POSITION;
float4 PositionWS: TEXCOORD1;
float4 NormalWS : TEXCOORD2;
float2 TexCoord : TEXCOORD0;
};
PixelShaderInput VShader(VertexShaderInput vin)
{
PixelShaderInput output;
output.Position = mul(completeTransformation, float4(vin.Position, 1.0f));
output.PositionWS = mul(worldTransformation, float4(vin.Position, 1.0f));
output.NormalWS = float4(mul((float3x3)worldTransformation, vin.Normal), 1.0f);
output.TexCoord = vin.TexCoord;
return output;
}
float4 PShader(PixelShaderInput input) : SV_TARGET
{
float4 viewDirection = normalize(cameraPosition - input.PositionWS);
float4 directionToLight = normalize(-lightVector);
// Calculate diffuse lighting
float4 adjustedNormal = normalize(input.NormalWS);
float NdotL = max(0, dot(adjustedNormal, directionToLight));
float4 diffuse = saturate(lightColor * NdotL * diffuseCoefficient);
// Calculate specular component
float4 R = 2 * NdotL * adjustedNormal - directionToLight;
float RdotV = max(0, dot(R, viewDirection));
float4 specular = saturate(lightColor * pow(RdotV, shininess) * specularCoefficient);
// Calculate ambient lighting
float4 ambientLight = ambientColor * diffuseCoefficient;
// Combine all components
float4 color = saturate((ambientLight + diffuse + specular));// *Texture.Sample(ss, input.TexCoord)); // ambientColor;
if (opacity < 1.0f)
{
color.a = opacity;
}
return color;
}

View File

@ -38,7 +38,7 @@ bool TexturedCubeNode::Initialise()
void TexturedCubeNode::Render()
{
XMMATRIX projectionTransformation = DirectXFramework::GetDXFramework()->GetProjectionTransformation();
XMMATRIX viewTransformation = DirectXFramework::GetDXFramework()->GetViewTransformation();
XMMATRIX viewTransformation = DirectXFramework::GetDXFramework()->GetCamera()->GetViewMatrix();
// Calculate the world x view x projection transformation
XMMATRIX completeTransformation = XMLoadFloat4x4(&_combinedWorldTransformation) * viewTransformation * projectionTransformation;

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 450 KiB

Binary file not shown.

File diff suppressed because one or more lines are too long

BIN
Graphics2/Textures/snow.dds Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

104
Graphics2/Vector3D.cpp Normal file
View File

@ -0,0 +1,104 @@
#include "Vector3D.h"
Vector3D::Vector3D(float x, float y, float z)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
}
Vector3D::Vector3D(XMFLOAT3 vertexA, XMFLOAT3 vertexB)
{
_vector.x = vertexB.x - vertexA.x;
_vector.y = vertexB.y - vertexA.y;
_vector.z = vertexB.z - vertexA.z;
}
Vector3D::Vector3D(const Vector3D& other)
{
Copy(other);
}
Vector3D::~Vector3D()
{
}
XMFLOAT3 Vector3D::Get() const
{
return _vector;
}
const void Vector3D::Normalize()
{
float length = (float) sqrt((_vector.x * _vector.x) + (_vector.y + _vector.y) + (_vector.z * _vector.z));
if (length != 0)
{
_vector.x /= length;
_vector.y /= length;
_vector.z /= length;
}
}
float Vector3D::DotProduct(const Vector3D v1, const Vector3D v2)
{
return v1.Get().x * v2.Get().x + v1.Get().y * v2.Get().y + v1.Get().z * v2.Get().z;
}
float Vector3D::Length(const Vector3D v1, const Vector3D v2)
{
return (float)sqrt(pow((v1.Get().x - v2.Get().x), 2) + pow((v1.Get().y - v2.Get().y), 2) + pow((v1.Get().z - v2.Get().z), 2));
}
Vector3D Vector3D::CrossProduct(Vector3D v1, Vector3D v2)
{
// v1.GetY() * v2.GetZ() - v1.GetZ() * v2.GetY()
float crossedX = v1.Get().y * v2.Get().z - v1.Get().z * v2.Get().y;
// v1.GetZ() * v2.GetX() - v1.GetX() * v2.GetZ()
float crossedY = v1.Get().z * v2.Get().x - v1.Get().x * v2.Get().z;
// v1.GetX() * v2.GetY() - v1.GetY() * v2.GetX()
float crossedZ = v1.Get().x * v2.Get().y - v1.Get().y * v2.Get().x;
return Vector3D(crossedX, crossedY, crossedZ);
}
Vector3D& Vector3D::operator= (const Vector3D& rhs)
{
if (this != &rhs)
{
Copy(rhs);
}
return *this;
}
const Vector3D Vector3D::operator+ (const Vector3D& rhs) const
{
return Vector3D(_vector.x + rhs.Get().x, _vector.y + rhs.Get().y, _vector.z + rhs.Get().z);
}
Vector3D& Vector3D::operator+= (const Vector3D& rhs)
{
_vector.x += rhs.Get().x;
_vector.y += rhs.Get().y;
_vector.z += rhs.Get().z;
return *this;
}
const Vector3D Vector3D::operator/ (const float rhs) const
{
return Vector3D(_vector.x / rhs, _vector.y / rhs, _vector.z / rhs);
}
const Vector3D Vector3D::operator/ (const int rhs) const
{
return Vector3D(_vector.x / rhs, _vector.y / rhs, _vector.z / rhs);
}
void Vector3D::Copy(const Vector3D& other)
{
_vector.x = other.Get().x;
_vector.y = other.Get().y;
_vector.z = other.Get().z;
}

33
Graphics2/Vector3D.h Normal file
View File

@ -0,0 +1,33 @@
#pragma once
#include "DirectXFramework.h"
#include "SharedMethods.h"
class Vector3D
{
public:
Vector3D(float x, float y, float z);
Vector3D(XMFLOAT3 vertexA, XMFLOAT3 vertexB);
Vector3D(const Vector3D& other);
~Vector3D();
XMFLOAT3 Get() const;
const void Normalize();
static float DotProduct(const Vector3D v1, const Vector3D v2);
static float Length(const Vector3D v1, const Vector3D v2);
static Vector3D CrossProduct(const Vector3D v1, const Vector3D v2);
Vector3D& operator= (const Vector3D& rhs);
const Vector3D operator+ (const Vector3D& rhs) const;
Vector3D& operator+= (const Vector3D& rhs);
const Vector3D operator/ (const float rhs) const;
const Vector3D operator/ (const int rhs) const;
private:
XMFLOAT3 _vector;
void Copy(const Vector3D& other);
};