Directx 9 Basic Terrain Creation w/Vertices - c++

I'm trying to create terrain using indexed primitives...I've written a class to handle the graphics, however, I can't get the textured terrain to appear on the screen...The following are the source and header files associated with this process...please ignore skybox functions...
graphics.h:
#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include <d3dx9tex.h>
#include <string>
#include "Camera.h"
class CGraphics
{
public:
CGraphics(IDirect3DDevice9 *device);
~CGraphics(void);
IDirect3DDevice9 *m_d3ddev;
LPDIRECT3DVERTEXBUFFER9 m_vertexBuffer;
LPDIRECT3DVERTEXBUFFER9 m_terrainVertexBuffer;
LPDIRECT3DINDEXBUFFER9 m_terrainIndexBuffer;
LPDIRECT3DTEXTURE9 m_textures[6];
LPDIRECT3DTEXTURE9 m_terrainTexture;
int m_numVertices;
int m_numFaces;
bool SkyBox(void);
void UpdateSkyBox(void);
bool Terrain(D3DXVECTOR3 minB, D3DXVECTOR3 maxB, int numCellsW, int numCellsL);
void RenderTerrain(void);
private:
void RenderSkyBox(void);
};
graphics.cpp:
#include "Graphics.h"
#include "3D Shapes.h"
#include "assert.h"
CGraphics::CGraphics(IDirect3DDevice9 *device) : m_d3ddev(device), m_vertexBuffer(0)
{
for(unsigned int i = 0; i < sizeof(LPDIRECT3DTEXTURE9)/sizeof(m_textures); i++)
{
m_textures[i] = 0;
m_terrainVertexBuffer = NULL;
m_terrainIndexBuffer = NULL;
}
}
CGraphics::~CGraphics(void)
{
if(m_vertexBuffer)
{
delete m_vertexBuffer;
m_vertexBuffer=0;
}
if(m_d3ddev)
{
m_d3ddev->Release();
m_d3ddev=0;
}
if(m_terrainVertexBuffer){
m_terrainVertexBuffer->Release();
m_terrainVertexBuffer=0;
}
if(m_terrainIndexBuffer){
m_terrainIndexBuffer->Release();
m_terrainIndexBuffer=0;
}
}
bool CGraphics::SkyBox(void)
{
HRESULT hr;
hr = m_d3ddev->CreateVertexBuffer(sizeof(TEXTUREVERTEX) * 24, 0, CUSTOMFVF, D3DPOOL_MANAGED,
&m_vertexBuffer, NULL);
if(FAILED(hr))
{
MessageBox(NULL, L"Failed to 'Create Vertex Buffer for SkyBox'", L"ERROR", MB_OK);
return false;
}
void* pVertices = NULL;
m_vertexBuffer->Lock(0, sizeof(TEXTUREVERTEX)*24, (void**)&pVertices, 0);
memcpy(pVertices, skyBox, sizeof(TEXTUREVERTEX)*24);
m_vertexBuffer->Unlock();
hr = D3DXCreateTextureFromFileA(m_d3ddev, fileF.c_str(), &m_textures[0]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileB.c_str(), &m_textures[1]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileL.c_str(), &m_textures[2]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileR.c_str(), &m_textures[3]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileTop.c_str(), &m_textures[4]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileBottom.c_str(), &m_textures[5]);
if ( FAILED(hr) )
{
MessageBox(NULL, L"Failed to open 1 or more images files!", L"Error Opening Texture Files", MB_OK);
return false;
}
return true;
}
void CGraphics::UpdateSkyBox(void)
{
D3DXMATRIX matView, matSave, matWorld;
m_d3ddev->GetTransform(D3DTS_VIEW, &matSave);
matView = matSave;
matView._41 = 0.0f; matView._42 = -0.4f; matView._43 = 0.0f;
m_d3ddev->SetTransform(D3DTS_VIEW, &matView);
D3DXMatrixIdentity(&matWorld);
m_d3ddev->SetTransform(D3DTS_WORLD, &matWorld);
RenderSkyBox();
m_d3ddev->SetTransform(D3DTS_VIEW, &matSave);
}
void CGraphics::RenderSkyBox(void)
{
m_d3ddev->SetRenderState(D3DRS_ZENABLE, false);
m_d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, false);
m_d3ddev->SetRenderState(D3DRS_LIGHTING, false);
m_d3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP );
m_d3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP );
m_d3ddev->SetFVF(CUSTOMFVF);
m_d3ddev->SetStreamSource(0, m_vertexBuffer, 0, sizeof(TEXTUREVERTEX));
for(unsigned int i = 0; i < 6; i ++)
{
m_d3ddev->SetTexture(0, m_textures[i]);
m_d3ddev->DrawPrimitive(D3DPT_TRIANGLESTRIP, i*4, 2);
}
m_d3ddev->SetRenderState(D3DRS_ZENABLE, true);
m_d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, true);
m_d3ddev->SetRenderState(D3DRS_LIGHTING, true);
}
bool CGraphics::Terrain(D3DXVECTOR3 minB, D3DXVECTOR3 maxB, int numCellsW, int numCellsL)
{
HRESULT hr = D3DXCreateTextureFromFileA(m_d3ddev, (LPCSTR)texFileTerrain.c_str(), &m_terrainTexture);
if(FAILED(hr))
{
MessageBox(NULL, L"Could not 'Load Texture(Terrain)'", L"ERROR", MB_OK);
return false;
}
TERRAIN terra = {minB,maxB,numCellsW,numCellsL,numCellsW+1,numCellsL+1,(maxB.x - minB.x)/numCellsW,
(maxB.z - minB.z)/numCellsL,
terra.vertices = new VERTEXARRAY[terra.numVertsX*terra.numVertsZ],
};
m_numVertices = terra.numVertsX*terra.numVertsZ;
m_numFaces = terra.numCellsX*terra.numCellsZ*2;
DWORD *indices = new DWORD[terra.numCellsX*terra.numCellsZ*6];
for(int i = 0; i < sizeof(indices); i++)
{
indices[i] = 0;
}
D3DXVECTOR3 pos(minB.x, 0, minB.z);
int vIter = 0;
for(int z = 0; z < terra.numVertsZ; z++)
{
for(int x = 0; x < terra.numVertsX; x++)
{
terra.vertices[vIter].x = 0;
terra.vertices[vIter].y = 0;
terra.vertices[vIter].z = 0;
terra.vertices[vIter].tu = 0;
terra.vertices[vIter].tv = 0;
vIter++;
}
}
double curTexPosZ = 1.0;
vIter=0;
for(double z = 0; z < (double)terra.numVertsZ; z++)
{
pos.x = minB.x;
curTexPosZ = (double)((double)terra.numCellsZ - z) / (double)(terra.numCellsZ);
for(double x = 0; x < terra.numVertsX; x++)
{
terra.vertices[vIter].x = pos.x;
terra.vertices[vIter].y = pos.y;
terra.vertices[vIter].z = pos.z;
//terra.vertices[vIter].color = D3DCOLOR_ARGB(0,255,255,255);
terra.vertices[vIter].tu = (float)(x / (double)terra.numCellsX);
terra.vertices[vIter].tv = (float)curTexPosZ;
pos.x += terra.stepX;
vIter++;
}
pos.z += terra.stepZ;
}
assert(vIter <= terra.numVertsX*terra.numVertsZ);
vIter = 0;
int iPos =0;
for(int z =0; z< terra.numCellsZ; z++)
{
for(int x = 0; x< terra.numCellsX; x++)
{
indices[iPos] = vIter; iPos++;
indices[iPos] = vIter+terra.numVertsX; iPos++;
indices[iPos] = vIter+terra.numVertsX+1; iPos++;
indices[iPos] = vIter; iPos++;
indices[iPos] = vIter+terra.numVertsX+1; iPos++;
indices[iPos] = vIter+1; iPos++;
vIter++;
}
vIter++;
}
assert(vIter <= terra.numCellsX*terra.numCellsZ*6);
void* pVoid;
hr = m_d3ddev->CreateVertexBuffer(sizeof(VERTEXARRAY)*terra.numVertsX*terra.numVertsZ,0,
CUSTOMFVF,D3DPOOL_MANAGED,&m_terrainVertexBuffer,NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
hr = m_terrainVertexBuffer->Lock(0, 0, (void**)&pVoid, NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Lock Vertex Buffer", L"ERROR", MB_OK);
return false;
}
memcpy(pVoid, terra.vertices, sizeof(terra.vertices));
m_terrainVertexBuffer->Unlock();
hr = m_d3ddev->CreateIndexBuffer(sizeof(DWORD)*sizeof(indices),0,
D3DFMT_INDEX16, D3DPOOL_MANAGED, &m_terrainIndexBuffer, NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Index Buffer", L"ERROR", MB_OK);
return false;
}
hr = m_terrainIndexBuffer->Lock(0, 0, (void**)&pVoid, 0);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
memcpy(pVoid, indices, sizeof(indices));
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
m_terrainIndexBuffer->Unlock();
return true;
}
void CGraphics::RenderTerrain(void)
{
m_d3ddev->SetFVF(CUSTOMFVF);
m_d3ddev->SetTexture(0, m_terrainTexture);
m_d3ddev->SetStreamSource(0, m_terrainVertexBuffer, 0, sizeof(VERTEXARRAY));
m_d3ddev->SetIndices(m_terrainIndexBuffer);
m_d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP, 0, 0, m_numVertices, 0, m_numFaces);
}
3D Shapes:
#pragma once
#define CUSTOMFVF (D3DFVF_XYZ | D3DFVF_TEX1)
struct TEXTUREVERTEX {
float x, y, z, tu, tv;
};
TEXTUREVERTEX skyBox[] = {
// Front quad, NOTE: All quads face inward
{-10.0f, -10.0f, 10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, 10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, 10.0f, 1.0f, 0.0f },
// Back quad
{ 10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, {-10.0f, -10.0f, -10.0f, 1.0f, 1.0f },{-10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Left quad
{-10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, {-10.0f, -10.0f, 10.0f, 1.0f, 1.0f }, {-10.0f, 10.0f, 10.0f, 1.0f, 0.0f },
// Right quad
{ 10.0f, -10.0f, 10.0f, 0.0f, 1.0f }, { 10.0f, 10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, -10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Top quad
{-10.0f, 10.0f, 10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, { 10.0f, 10.0f, 10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Bottom quad
{-10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, {-10.0f, -10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, -10.0f, 1.0f, 1.0f },{ 10.0f, -10.0f, 10.0f, 1.0f, 0.0f }
};
std::string fileF("skybox_front.jpg");
std::string fileB("skybox_back.jpg");
std::string fileL("skybox_left.jpg");
std::string fileR("skybox_right.jpg");
std::string fileTop("skybox_top.jpg");
std::string fileBottom("skybox_bottom.jpg");
struct VERTEXARRAY {
float x, y, z, tu, tv;
};
struct TERRAIN {
D3DXVECTOR3 minBounds; // minimum bounds (x, y, z)
D3DXVECTOR3 maxBounds; // maximum bounds (x, y, z)
int numCellsX; // # of cells in the x direction
int numCellsZ; // # of cells in the z direction
int numVertsX; // # of vertices in the x direction
int numVertsZ; // # of vertices in the z direction
float stepX; // space between vertices in the x direction
float stepZ; // space between vertices in the z direction
VERTEXARRAY *vertices; // vertex array pointer (stores the position for each vertex
};
std::string texFileTerrain("sunset.jpg");
I've looked through countless tutorials and samples online and found no solution. I imagine the problem I'm having is related to the settings, I must be overlooking something...any ideas would be appreciated...thanks in advance!

Related

Draw 2 quads with one function DirectX11

I'm Leanrning DirectX11 and I'm trying to draw 2 Quad with a single function but when i call this function , the function override the previous QUAD.
If you want to see the problem , here is a gif :
<video alt="Video from Gyazo" width="1280" autoplay muted loop playsinline controls><source src="https://i.gyazo.com/b819ffc64975c1531434047b9b4a92f7.mp4" type="video/mp4" /></video>
Here is the code :
(here is where i call the function to draw the QUAD)
void Application::ApplicationRun()
{
//wind.SetEventCallBack(std::bind(&Application::OnEvent, Instance, std::placeholders::_1));
Vertex v[] =
{
Vertex(-0.5f, -0.5f, 0.0f, 1.0f), /// botom Left Point - [0]
Vertex(-0.5f, 0.5f, 0.0f, 0.0f), //top Left Point - [1]
Vertex{ 0.0f, -0.5f, 1.0f, 1.0f}, // -[2]
Vertex(0.0f, 0.5f, 1.0f, 0.0f), //Right Point - [3]
};
Vertex vv[] =
{
Vertex(-0.1f, -0.1f, 0.0f, 0.0f), /// botom Left Point - [0]
Vertex(-0.1f, 0.1f, 0.0f, 0.0f), //top Left Point - [1]
Vertex{ 0.05f, -0.1f, 0.0f, 0.0f}, // -[2]
Vertex(0.05f, 0.1f, 0.0f, 0.0f), //Right Point - [3]
};
DWORD indices[] =
{
0,1,2,
1,2,3,
};
while (wind.PorcessMessage())
{
//
if (Armageddon::Application::GetInstance()->GetWindow()->GetNativeKeyBoard().KeyIsPressed(AG_KEY_A))
{
Log::GetLogger()->trace("A ");
wind.GetWindowGraphics()->DrawTriangle(v, ARRAYSIZE(v));
}
if (Armageddon::Application::GetInstance()->GetWindow()->GetNativeKeyBoard().KeyIsPressed(AG_KEY_B))
{
Log::GetLogger()->trace("B");
wind.GetWindowGraphics()->DrawTriangle(vv, ARRAYSIZE(vv));
}
}
}
(Here is the DrawTriangle Function) :
void Armageddon::D3D_graphics::DrawTriangle(Vertex v[], int Vertexcount)
{
HRESULT hr = vertexBuffer.Initialize(this->device.Get(),this->device_context.Get() , v, Vertexcount);
if (FAILED(hr))
{
Armageddon::Log::GetLogger()->error("FAILED INITIALIZE VERTEX BUFFER ");
}
DWORD indices[] =
{
0,1,2,
1,2,3,
};
hr = this->indicesBuffer.Init(this->device.Get(), indices, ARRAYSIZE(indices));
hr = DirectX::CreateWICTextureFromFile(this->device.Get(), L"..\\TestApplication\\assets\\Textures\\tex.png",nullptr,textures.GetAddressOf());
if (FAILED(hr))
{
Armageddon::Log::GetLogger()->error("FAILED INITIALIZE WIC TEXTURE ");
}
}
(Here is where i initialize the Vertex and the Indice buffer) :
HRESULT Initialize(ID3D11Device* device , ID3D11DeviceContext* device_context, T* data, UINT numElements)
{
this->bufferSize = numElements;
this->stride = sizeof(T);
D3D11_BUFFER_DESC vertex_buffer_desc;
ZeroMemory(&vertex_buffer_desc, sizeof(vertex_buffer_desc));
vertex_buffer_desc.Usage = D3D11_USAGE_DEFAULT;
vertex_buffer_desc.ByteWidth = sizeof(Vertex) * numElements;
vertex_buffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertex_buffer_desc.CPUAccessFlags = 0;
vertex_buffer_desc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA VertexBufferData;
ZeroMemory(&VertexBufferData, sizeof(VertexBufferData));
VertexBufferData.pSysMem = data;
HRESULT hr = device->CreateBuffer(&vertex_buffer_desc, &VertexBufferData, buffer.GetAddressOf());
UINT offset = 0;
device_context->IASetVertexBuffers(0, 1, buffer.GetAddressOf(), &stride, &offset);
return hr;
};```
HRESULT Init(ID3D11Device* device, DWORD* data, UINT n_indices)
{
D3D11_SUBRESOURCE_DATA Indice_buffer_data;
this->buffer_size = n_indices;
D3D11_BUFFER_DESC Indice_buffer_desc;
ZeroMemory(&Indice_buffer_desc, sizeof(Indice_buffer_desc));
Indice_buffer_desc.Usage = D3D11_USAGE_DEFAULT;
Indice_buffer_desc.ByteWidth = sizeof(DWORD) * n_indices;
Indice_buffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
Indice_buffer_desc.CPUAccessFlags = 0;
Indice_buffer_desc.MiscFlags = 0;
ZeroMemory(&Indice_buffer_data, sizeof(Indice_buffer_data));
Indice_buffer_data.pSysMem = data;
HRESULT hr = device->CreateBuffer(&Indice_buffer_desc, &Indice_buffer_data, buffer.GetAddressOf());
return hr;
};
And here is where I draw the quads :
void Armageddon::D3D_graphics::RenderFrame()
{
float color[] = { 0.1f,0.1f,0.1f,1.0f };
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
ImGui::Render();
this->device_context->OMSetRenderTargets(1, target_view.GetAddressOf(), this->depthStencilView.Get());
this->device_context->ClearRenderTargetView(this->target_view.Get(), color);
this->device_context->ClearDepthStencilView(this->depthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
//ICI QU'ON FAIT TOUT LES RENDU APRES AVOIR CLEAN LE PLAN
this->device_context->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
f += 0.1;
ConstantBuffer.data.mat = DirectX::XMMatrixRotationRollPitchYaw(0.0f,0.0f,f);
ConstantBuffer.data.mat = DirectX::XMMatrixTranspose(ConstantBuffer.data.mat);
ConstantBuffer.data.Yoffset = f;
ConstantBuffer.data.Xoffset = 0;
// Armageddon::Log::GetLogger()->trace(ConstantBuffer.data.Yoffset);
if (!ConstantBuffer.ApplyChanges())
{
Armageddon::Log::GetLogger()->error("ERRO WHEN APPLYING CHANGES");
}
this->device_context->VSSetConstantBuffers(0, 1, ConstantBuffer.GetAdressOf());
/***********SHADER*******************************/
this->device_context->VSSetShader(vertexShader.GetShader(), NULL, 0);
this->device_context->PSSetShader(pixelShader.GetShader(), NULL, 0);
this->device_context->IASetInputLayout(this->vertexShader.GetInputLayout());
/***********Texture Sampler*******************************/
this->device_context->PSSetSamplers(0, 1, this->ColorSampler.GetAddressOf());
/***********DEPHT BUFFER*******************************/
this->device_context->OMSetDepthStencilState(this->depthStencilState.Get(), 0);
/***********RASTERIZER STATE*******************************/
this->device_context->RSSetState(this->rasterizerState.Get());
/***********UPDATE LES CONSTANTS BUFFER*******************************/
UINT stride = sizeof(Vertex);
UINT offset = 0;
this->device_context->IASetIndexBuffer(indicesBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
//this->device_context->IASetVertexBuffers(0, 1, vertexBuffer.GetAddressOf(), &stride, &offset);
this->device_context->PSSetShaderResources(0, 1, this->textures.GetAddressOf());
this->device_context->DrawIndexed(indicesBuffer.GetSize(), 0,0);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
this->swapchain->Present(1,0);
}

Vulkan vkCmdDrawIndexed used only first Value from VertexBuffer

i`m trying to implement instanced mesh rendering in Vulkan.
My Problem is that Vulkan uses only the first Vertex from the binded VertexBuffer and duplicate the Value for all Indices.
Output RenderDoc:
RenderDoc output Duplicated Vertex Input
These should be the correct values {{<inPosition>},{<inColor>},{<inTexCoord>}}:
const vkf::Vertex vertices[] = {
{ { -0.2f, -0.5f, 0.0f },{ 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f } },
{ { 0.5f, -0.5f, 0.0f },{ 0.0f, 1.0f, 0.0f },{ 0.0f, 0.0f } },
{ { 0.5f, 0.5f, 0.0f },{ 0.0f, 0.0f, 1.0f },{ 0.0f, 1.0f } },
{ { -0.5f, 0.5f, 0.0f },{ 1.0f, 1.0f, 1.0f },{ 1.0f, 1.0f } }
};
I've checked the VertexBuffer multiple times and it contains the correct values.
Here is the snipped from my CommandBuffer creating:
vkCmdBindPipeline(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.agents);
VkBuffer vertexBuffers[] = { models.agent.verticesBuffer };
VkBuffer instanceBuffers[] = { m_instanceBuffer.buffer };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(m_commandBuffers[i], 0, 1, vertexBuffers, offsets);
vkCmdBindVertexBuffers(m_commandBuffers[i], 1, 1, instanceBuffers, offsets);
vkCmdBindIndexBuffer(m_commandBuffers[i], models.agent.indexBuffer, 0, VK_INDEX_TYPE_UINT16);
vkCmdBindDescriptorSets(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayouts.pipelineLayoutAgent, 0, 1, &descriptorSets.agent, 0, nullptr);
vkCmdDrawIndexed(m_commandBuffers[i], static_cast<uint32_t> (models.agent.indexCount), 5, 0, 0, 0);
My first assumption was that my binding description is wrong. But I can`t see the error:
bindingDescription = {};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
Why is only the first value from the buffer used?
EDIT:
InstanceData:
struct InstanceData
{
glm::vec3 pos;
glm::vec3 rot;
float scale;
static VkVertexInputBindingDescription getBindingDescription()
{
VkVertexInputBindingDescription bindingDescription = {};
bindingDescription.binding = INSTANCING_BIND_ID;
bindingDescription.stride = sizeof(InstanceData);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_INSTANCE;
return bindingDescription;
}
};
The whole VkPipelineVertexInputStateCreateInfo:
std::vector<VkVertexInputBindingDescription> bindingDesciption = {};
std::vector<VkVertexInputAttributeDescription> attributeDescriptions = {};
bindingDesciption = {
models.agent.bindingDescription,
InstanceData::getBindingDescription()
};
attributeDescriptions =
{
vertexInputAttributeDescription(VERTEX_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(vkf::Vertex, pos)),
vertexInputAttributeDescription(VERTEX_BIND_ID, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(vkf::Vertex, color)),
vertexInputAttributeDescription(INSTANCING_BIND_ID, 2, VK_FORMAT_R32G32B32_SFLOAT, offsetof(InstanceData, pos)),
vertexInputAttributeDescription(VERTEX_BIND_ID, 3, VK_FORMAT_R32G32_SFLOAT, offsetof(vkf::Vertex, texCoord))
};
VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDesciption.size());
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputInfo.pVertexBindingDescriptions = bindingDesciption.data();
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
EDIT 2
#define VERTEX_BIND_ID 0
#define INSTANCING_BIND_ID 1
EDIT 3:
I`m using VulkanMemoryAllocator.
Creating Staging Buffer
size_t vertexBufferSize = sizeof(vkf::Vertex) *_countof(vertices);
createStagingBuffer(vertexBufferSize );
VkBuffer createStagingBuffer(VkDeviceSize size)
{
VkBuffer buffer;
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = size;
bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_PERSISTENT_MAP_BIT;
VmaAllocationInfo allocInfo = {};
if (vmaCreateBuffer(m_allocator, &bufferInfo, &allocCreateInfo, &buffer, &m_allocation, &allocInfo) != VK_SUCCESS)
{
throw std::runtime_error("failed to create Buffer!");
}
return buffer;
}
Copy vertices:
memcpy(mappedStaging, vertices, vertexBufferSize);
Creating Buffer:
createBuffer(vertexBufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
VkBuffer createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VmaMemoryUsage vmaUsage)
{
VkBuffer buffer;
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = vmaUsage;
allocCreateInfo.flags = 0;
VmaAllocationInfo allocInfo;
if (vmaCreateBuffer(m_allocator, &bufferInfo, &allocCreateInfo, &buffer, &m_allocation, &allocInfo) != VK_SUCCESS)
{
throw std::runtime_error("failed to create Buffer!");
}
return buffer;
}
This is how I transfair my Buffer from staging:
copyBuffer(stagingVertexBuffer, verticesBuffer, vertexBufferSize);
void Base::copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBuffer commandBuffer = beginSingleTimeCommands();
VkBufferCopy copyRegion = {};
copyRegion.dstOffset = 0;
copyRegion.srcOffset = 0;
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion);
endSingleTimeCommands(commandBuffer);
}
I checked several times if the data is in the staging Buffer and after modifing the createBuffer Prozess also in the verticesBuffer. They are stored there correctly.
I found the mistake.
The mistake was here:
bindingDesciption = {
models.agent.bindingDescription,
InstanceData::getBindingDescription()
};
By the time the binding took place, models.agent.bindingDescription,was not initialized yet. As a result, the VkVertexInputBindingDescription was faulty.
models.agent.bindingDescription was filled with the standard values for VkVertexInputBindingDescription:
binding = 0
stroke = 0
inputRate = VK_VERTEX_INPUT_RATE_VERTEX

ID3DX11EffectPass GetDesc Access Violation

Hi I just got Introduction to 3D Game Programming with DirectX 11 and am trying to get the BoxDemo code working, however I am having troubles with the effect.
Basically the compiled shader part works, and even the creation of the effect works but when it comes to getting the description from the effect pass, I get a Access Violation error, I have tried, and researched online but can't find any help for this matter.
Please note I have the latest version of effects11.
Here is the fx:
//***************************************************************************** **********
// color.fx by Frank Luna (C) 2011 All Rights Reserved.
//
// Transforms and colors geometry.
//***************************************************************************************
cbuffer cbPerObject
{
float4x4 gWorldViewProj;
};
struct VertexIn
{
float3 PosL : POSITION;
float4 Color : COLOR;
};
struct VertexOut
{
float4 PosH : SV_POSITION;
float4 Color : COLOR;
};
VertexOut VS(VertexIn vin)
{
VertexOut vout;
// Transform to homogeneous clip space.
vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj);
// Just pass vertex color into the pixel shader.
vout.Color = vin.Color;
return vout;
}
float4 PS(VertexOut pin) : SV_Target
{
return pin.Color;
}
technique11 ColorTech
{
pass P0
{
SetVertexShader(CompileShader(vs_5_0, VS()));
SetGeometryShader(NULL);
SetPixelShader(CompileShader(ps_5_0, PS()));
}
}
here is the cpp file:
#include "BoxApp.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
PSTR cmdLine, int showCmd)
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
BoxApp theApp(hInstance);
if (!theApp.Init())
return 0;
return theApp.Run();
}
BoxApp::BoxApp(HINSTANCE hInstance)
: D3DApp(hInstance), mBoxVB(0), mBoxIB(0), mFX(0), mTech(0),
mfxWorldViewProj(0), mInputLayout(0),
mTheta(1.5f*MathHelper::Pi), mPhi(0.25f*MathHelper::Pi), mRadius(5.0f)
{
mMainWndCaption = L"Box Demo";
mLastMousePos.x = 0;
mLastMousePos.y = 0;
XMMATRIX I = XMMatrixIdentity();
XMStoreFloat4x4(&mWorld, I);
XMStoreFloat4x4(&mView, I);
XMStoreFloat4x4(&mProj, I);
}
BoxApp::~BoxApp()
{
ReleaseCOM(mBoxVB);
ReleaseCOM(mBoxIB);
ReleaseCOM(mFX);
ReleaseCOM(mInputLayout);
}
bool BoxApp::Init()
{
if (!D3DApp::Init())
return false;
BuildGeometryBuffers();
BuildFX();
BuildVertexLayout();
return true;
}
void BoxApp::OnResize()
{
D3DApp::OnResize();
// The window resized, so update the aspect ratio and recompute the projection matrix.
XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
XMStoreFloat4x4(&mProj, P);
}
void BoxApp::UpdateScene(float dt)
{
// Convert Spherical to Cartesian coordinates.
float x = mRadius*sinf(mPhi)*cosf(mTheta);
float z = mRadius*sinf(mPhi)*sinf(mTheta);
float y = mRadius*cosf(mPhi);
// Build the view matrix.
XMVECTOR pos = XMVectorSet(x, y, z, 1.0f);
XMVECTOR target = XMVectorZero();
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX V = XMMatrixLookAtLH(pos, target, up);
XMStoreFloat4x4(&mView, V);
}
void BoxApp::DrawScene()
{
md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::LightSteelBlue));
md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
md3dImmediateContext->IASetInputLayout(mInputLayout);
md3dImmediateContext- >IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
UINT stride = sizeof(Vertex);
UINT offset = 0;
md3dImmediateContext->IASetVertexBuffers(0, 1, &mBoxVB, &stride, &offset);
md3dImmediateContext->IASetIndexBuffer(mBoxIB, DXGI_FORMAT_R32_UINT, 0);
// Set constants
XMMATRIX world = XMLoadFloat4x4(&mWorld);
XMMATRIX view = XMLoadFloat4x4(&mView);
XMMATRIX proj = XMLoadFloat4x4(&mProj);
XMMATRIX worldViewProj = world*view*proj;
mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj));
D3DX11_TECHNIQUE_DESC techDesc;
mTech->GetDesc(&techDesc);
for (UINT p = 0; p < techDesc.Passes; ++p)
{
mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);
// 36 indices for the box.
md3dImmediateContext->DrawIndexed(36, 0, 0);
}
HRESULT hr = (mSwapChain->Present(0, 0));
}
void BoxApp::OnMouseDown(WPARAM btnState, int x, int y)
{
mLastMousePos.x = x;
mLastMousePos.y = y;
SetCapture(mhMainWnd);
}
void BoxApp::OnMouseUp(WPARAM btnState, int x, int y)
{
ReleaseCapture();
}
void BoxApp::OnMouseMove(WPARAM btnState, int x, int y)
{
if ((btnState & MK_LBUTTON) != 0)
{
// Make each pixel correspond to a quarter of a degree.
float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));
// Update angles based on input to orbit camera around box.
mTheta += dx;
mPhi += dy;
// Restrict the angle mPhi.
mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi - 0.1f);
}
else if ((btnState & MK_RBUTTON) != 0)
{
// Make each pixel correspond to 0.005 unit in the scene.
float dx = 0.005f*static_cast<float>(x - mLastMousePos.x);
float dy = 0.005f*static_cast<float>(y - mLastMousePos.y);
// Update the camera radius based on input.
mRadius += dx - dy;
// Restrict the radius.
mRadius = MathHelper::Clamp(mRadius, 3.0f, 15.0f);
}
mLastMousePos.x = x;
mLastMousePos.y = y;
}
void BoxApp::BuildGeometryBuffers()
{
// Create vertex buffer
Vertex vertices[] =
{
{ XMFLOAT3(-1.0f, -1.0f, -1.0f), (const float*)&Colors::White },
{ XMFLOAT3(-1.0f, +1.0f, -1.0f), (const float*)&Colors::Black },
{ XMFLOAT3(+1.0f, +1.0f, -1.0f), (const float*)&Colors::Red },
{ XMFLOAT3(+1.0f, -1.0f, -1.0f), (const float*)&Colors::Green },
{ XMFLOAT3(-1.0f, -1.0f, +1.0f), (const float*)&Colors::Blue },
{ XMFLOAT3(-1.0f, +1.0f, +1.0f), (const float*)&Colors::Yellow },
{ XMFLOAT3(+1.0f, +1.0f, +1.0f), (const float*)&Colors::Cyan },
{ XMFLOAT3(+1.0f, -1.0f, +1.0f), (const float*)&Colors::Magenta }
};
D3D11_BUFFER_DESC vbd;
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = sizeof(Vertex) * 8;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
vbd.MiscFlags = 0;
vbd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA vinitData;
vinitData.pSysMem = vertices;
HRESULT hr1 = (md3dDevice->CreateBuffer(&vbd, &vinitData, &mBoxVB));
// Create the index buffer
UINT indices[] = {
// front face
0, 1, 2,
0, 2, 3,
// back face
4, 6, 5,
4, 7, 6,
// left face
4, 5, 1,
4, 1, 0,
// right face
3, 2, 6,
3, 6, 7,
// top face
1, 5, 6,
1, 6, 2,
// bottom face
4, 0, 3,
4, 3, 7
};
D3D11_BUFFER_DESC ibd;
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(UINT) * 36;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
ibd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = indices;
HRESULT hr2 = (md3dDevice->CreateBuffer(&ibd, &iinitData, &mBoxIB));
}
void BoxApp::BuildFX()
{
DWORD shaderFlags = 0;
//#if defined( DEBUG ) || defined( _DEBUG )
// shaderFlags |= D3D10_SHADER_DEBUG;
// shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
//#endif
ID3D10Blob* compiledShader = 0;
ID3D10Blob* compilationMsgs = 0;
HRESULT hr;
hr = D3DX11CompileFromFile(L"color.fx", NULL, NULL, "ColorTech", "fx_5_0"
, shaderFlags, 0, 0, &compiledShader, &compilationMsgs, &hr);
// compilationMsgs can store errors or warnings.
if (compilationMsgs != 0)
{
MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);
ReleaseCOM(compilationMsgs);
}
// Even if there are no compilationMsgs, check to make sure there were no other errors.
if (FAILED(hr))
{
//DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
}
ID3D10Blob* pErrorBlob = 0;
//ID3DInclude* include = D3D_COMPILE_STANDARD_FILE_INCLUDE;
HRESULT hr3 = (D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(),
0, md3dDevice, &mFX));
//HRESULT hr3 = (D3DX11CreateEffectFromFile(L"color.fx", shaderFlags, md3dDevice, &mFX));
// Done with compiled shader.
ReleaseCOM(compiledShader);
mTech = mFX->GetTechniqueByName("ColorTech");
mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
}
void BoxApp::BuildVertexLayout()
{
// Create the vertex input layout.
D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
// Create the input layout
D3DX11_PASS_DESC passDesc;
ID3DX11EffectPass* pass = mTech->GetPassByIndex(0);
if (pass != nullptr)
{
HRESULT hr5 = pass->GetDesc(&passDesc);
HRESULT hr4 = (md3dDevice->CreateInputLayout(vertexDesc, 2, passDesc.pIAInputSignature,
passDesc.IAInputSignatureSize, &mInputLayout));
}
}
You've commented out all the error checks, so it's probably that D3DX11CreateEffectFromMemory returned a failure. If a function returns an HRESULT, you must check it at runtime or you will miss potential errors. That means using the FAILED macro, the SUCCEEDED macro, or the ThrowIfFailed helper on every function that returns an HRESULT. See MSDN.
Since you are making use of the Effects for Direct3D 11 library, you should pick up the latest version from GitHub. If you are using VS 2013 or VS 2015 for a Windows desktop app, you can also get it from NuGet.
You should also read this post which has some additional notes about the Introduction to 3D Game Programming with DirectX 11 book. It's a good book, but unfortunately it was published just before the DirectX development story was changed rather radically with the deprecation of the DirectX SDK. See MSDN.
You should also take a look at the DirectX Tool Kit tutorials, particularly the material on ComPtr.
Ok finally here is the final code
BoxDemoApp.h:
#pragma once
//#pragma comment(lib, "Effects11.lib")
#pragma comment(lib, "d3d11.lib")
//#pragma comment(lib, "d3dx11.lib")
//#pragma comment(lib, "DxErr.lib")
//#pragma comment(lib, "D3DCompiler.lib")
//#pragma comment(lib, "dxguid.lib")
#include <windows.h>
#include <d3d11_1.h>
#include "d3dApp.h"
#include "d3dx11effect.h"
#include "MathHelper.h"
#include "StaticCamera.h"
#include "Conversion.h"
#include "DefinedModel.h"
#include <iostream>
using namespace std;
class BoxDemoApp : public D3DApp
{
public:
BoxDemoApp(HINSTANCE hInstance);
~BoxDemoApp();
bool Init();
bool InitScene();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
private:
DefinedModel* m_Model;
bool m_bLoaded;
bool m_bInitModel;
};
BoxDemoApp.cpp:
#include "BoxDemoApp.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
PSTR cmdLine, int showCmd)
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
BoxDemoApp theApp(hInstance);
if (!theApp.Init())
return 0;
return theApp.Run();
}
BoxDemoApp::BoxDemoApp(HINSTANCE hInstance)
: D3DApp(hInstance)
{
mMainWndCaption = L"Box Demo";
m_bLoaded = false;
m_bInitModel = false;
m_Model = NULL;
}
BoxDemoApp::~BoxDemoApp()
{
m_Model->Destroy();
SafeDelete(m_Model);
}
bool BoxDemoApp::Init()
{
if (!D3DApp::Init())
return false;
InitScene();
return true;
}
bool BoxDemoApp::InitScene()
{
//Camera information
m_Camera->setCamera(XMFLOAT4(0.0f, 3.0f, -8.0f, 0.0f),
XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f),
XMFLOAT4(0.0f, 1.0f, 0.0f, 0.0f));
//Set the Projection matrix
m_Camera->setFOV(0.4f*3.14f, (float)mClientWidth / mClientHeight, 1.0f, 1000.0f);
///////////////**************new**************////////////////////
return true;
}
void BoxDemoApp::OnResize()
{
D3DApp::OnResize();
//Create the Viewport
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = this->mClientWidth;
viewport.Height = this->mClientHeight;
//Set the Viewport
md3dImmediateContext->RSSetViewports(1, &viewport);
//Set the Projection matrix
m_Camera->setFOV(0.4f*3.14f, (float)mClientWidth / mClientHeight, 1.0f, 1000.0f);
///////////////**************new**************////////////////////
}
void BoxDemoApp::UpdateScene(float dt)
{
if (m_bLoaded && !m_bInitModel)
{
m_Model = new DefinedModel(this);
m_Model->create3DCube(4, 4, 4);
m_bInitModel = true;
}
}
void BoxDemoApp::DrawScene()
{
assert(md3dImmediateContext);
assert(mSwapChain);
md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::LightSteelBlue));
md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
if (m_bInitModel)
{
m_Model->Draw();
}
if (!m_bLoaded)
{
m_bLoaded = true;
}
HRESULT hr = (mSwapChain->Present(0, 0));
}
MathHelper.h:
//***************************************************************************************
// MathHelper.h by Frank Luna (C) 2011 All Rights Reserved.
//
// Helper math class.
//***************************************************************************************
#pragma once
#ifndef MATHHELPER_H
#define MATHHELPER_H
#include <Windows.h>
#include <xnamath.h>
class MathHelper
{
public:
// Returns random float in [0, 1).
static float RandF()
{
return (float)(rand()) / (float)RAND_MAX;
}
// Returns random float in [a, b).
static float RandF(float a, float b)
{
return a + RandF()*(b - a);
}
template<typename T>
static T Min(const T& a, const T& b)
{
return a < b ? a : b;
}
template<typename T>
static T Max(const T& a, const T& b)
{
return a > b ? a : b;
}
template<typename T>
static T Lerp(const T& a, const T& b, float t)
{
return a + (b - a)*t;
}
template<typename T>
static T Clamp(const T& x, const T& low, const T& high)
{
return x < low ? low : (x > high ? high : x);
}
// Returns the polar angle of the point (x,y) in [0, 2*PI).
static float AngleFromXY(float x, float y);
static XMMATRIX InverseTranspose(CXMMATRIX M)
{
// Inverse-transpose is just applied to normals. So zero out
// translation row so that it doesn't get into our inverse-transpose
// calculation--we don't want the inverse-transpose of the translation.
XMMATRIX A = M;
A.r[3] = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
XMVECTOR det = XMMatrixDeterminant(A);
return XMMatrixTranspose(XMMatrixInverse(&det, A));
}
static XMVECTOR RandUnitVec3();
static XMVECTOR RandHemisphereUnitVec3(XMVECTOR n);
static const float Infinity;
static const float Pi;
};
#endif // MATHHELPER_H
MathHelper.cpp:
//***************************************************************************************
// MathHelper.cpp by Frank Luna (C) 2011 All Rights Reserved.
//***************************************************************************************
#include "MathHelper.h"
#include <float.h>
#include <cmath>
const float MathHelper::Infinity = FLT_MAX;
const float MathHelper::Pi = 3.1415926535f;
float MathHelper::AngleFromXY(float x, float y)
{
float theta = 0.0f;
// Quadrant I or IV
if (x >= 0.0f)
{
// If x = 0, then atanf(y/x) = +pi/2 if y > 0
// atanf(y/x) = -pi/2 if y < 0
theta = atanf(y / x); // in [-pi/2, +pi/2]
if (theta < 0.0f)
theta += 2.0f*Pi; // in [0, 2*pi).
}
// Quadrant II or III
else
theta = atanf(y / x) + Pi; // in [0, 2*pi).
return theta;
}
XMVECTOR MathHelper::RandUnitVec3()
{
XMVECTOR One = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f);
XMVECTOR Zero = XMVectorZero();
// Keep trying until we get a point on/in the hemisphere.
while (true)
{
// Generate random point in the cube [-1,1]^3.
XMVECTOR v = XMVectorSet(MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), 0.0f);
// Ignore points outside the unit sphere in order to get an even distribution
// over the unit sphere. Otherwise points will clump more on the sphere near
// the corners of the cube.
if (XMVector3Greater(XMVector3LengthSq(v), One))
continue;
return XMVector3Normalize(v);
}
}
XMVECTOR MathHelper::RandHemisphereUnitVec3(XMVECTOR n)
{
XMVECTOR One = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f);
XMVECTOR Zero = XMVectorZero();
// Keep trying until we get a point on/in the hemisphere.
while (true)
{
// Generate random point in the cube [-1,1]^3.
XMVECTOR v = XMVectorSet(MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), 0.0f);
// Ignore points outside the unit sphere in order to get an even distribution
// over the unit sphere. Otherwise points will clump more on the sphere near
// the corners of the cube.
if (XMVector3Greater(XMVector3LengthSq(v), One))
continue;
// Ignore points in the bottom hemisphere.
if (XMVector3Less(XMVector3Dot(n, v), Zero))
continue;
return XMVector3Normalize(v);
}
}
StaticCamera.h:
#pragma once
#include "MathHelper.h"
#include "Conversion.h"
class StaticCamera
{
public:
StaticCamera();
~StaticCamera();
XMMATRIX* WVP();
XMMATRIX* World();
XMMATRIX* camView();
XMMATRIX* camProjection();
XMVECTOR* camPosition();
XMVECTOR* camTarget();
XMVECTOR* camUp();
void WVP(XMMATRIX WVP);
void World(XMMATRIX World);
void setFOV(float FOV, float aspectRatio, float nearZ, float farZ);
void setCamera(XMFLOAT4 position, XMFLOAT4 Target, XMFLOAT4 Up);
void updateMatrix();
private:
///////////////**************new**************////////////////////
XMMATRIX m_WVP;
XMMATRIX m_World;
XMMATRIX m_camView;
XMMATRIX m_camProjection;
XMVECTOR m_camPosition;
XMVECTOR m_camTarget;
XMVECTOR m_camUp;
///////////////**************new**************////////////////////
};
StaticCamera.cpp:
#include "StaticCamera.h"
StaticCamera::StaticCamera()
{
}
StaticCamera::~StaticCamera()
{
}
XMMATRIX* StaticCamera::WVP()
{
return &m_WVP;
}
XMMATRIX* StaticCamera::World()
{
return &m_World;
}
XMMATRIX* StaticCamera::camView()
{
return &m_camView;
}
XMMATRIX* StaticCamera::camProjection()
{
return &m_camProjection;
}
XMVECTOR* StaticCamera::camPosition()
{
return &m_camPosition;
}
XMVECTOR* StaticCamera::camTarget()
{
return &m_camTarget;
}
XMVECTOR* StaticCamera::camUp()
{
return &m_camUp;
}
void StaticCamera::WVP(XMMATRIX WVP)
{
m_WVP = WVP;
}
void StaticCamera::World(XMMATRIX World)
{
m_World = World;
}
void StaticCamera::setFOV(float FOV, float aspectRatio, float nearZ, float farZ)
{
//Set the Projection matrix
m_camProjection = XMMatrixPerspectiveFovLH(FOV, aspectRatio, nearZ, farZ);
updateMatrix();
}
void StaticCamera::setCamera(XMFLOAT4 position, XMFLOAT4 Target, XMFLOAT4 Up)
{
//Camera information
m_camPosition = Conversion::XMFLOAT4TOXMVECTOR(position);
m_camTarget = Conversion::XMFLOAT4TOXMVECTOR(Target);
m_camUp = Conversion::XMFLOAT4TOXMVECTOR(Up);
//Set the View matrix
m_camView = XMMatrixLookAtLH(m_camPosition, m_camTarget, m_camUp);
///////////////**************new**************////////////////////
updateMatrix();
}
void StaticCamera::updateMatrix()
{
m_World = XMMatrixIdentity();
m_WVP = (m_World * m_camView * m_camProjection);
}
Conversion.h:
#pragma once
#include "MathHelper.h"
#include <vector>
using namespace std;
static class Conversion
{
public:
static XMFLOAT4 XMVECTORTOXMFLOAT4(XMVECTOR Xmvector);
static XMFLOAT3 XMVECTORTOXMFLOAT3(XMVECTOR Xmvector);
static XMVECTOR XMFLOAT4TOXMVECTOR(XMFLOAT4 Xmfloat);
static void INTVECTORTOARRAY(std::vector<int> vector, int *arr);
static LPCWSTR STRINGTOLPCWSTR(std::string stdstr);
};
Conversion.cpp:
#include "Conversion.h"
XMFLOAT4 Conversion::XMVECTORTOXMFLOAT4(XMVECTOR Xmvector)
{
XMFLOAT4 pos;
XMStoreFloat4(&pos, Xmvector);
return pos;
}
XMFLOAT3 Conversion::XMVECTORTOXMFLOAT3(XMVECTOR Xmvector)
{
XMFLOAT3 pos;
XMStoreFloat3(&pos, Xmvector);
return pos;
}
XMVECTOR Conversion::XMFLOAT4TOXMVECTOR(XMFLOAT4 Xmfloat)
{
return XMLoadFloat4(&Xmfloat);
}
void Conversion::INTVECTORTOARRAY(std::vector<int> vector, int *arr)
{
arr = &vector[0];
}
LPCWSTR Conversion::STRINGTOLPCWSTR(std::string stdstr)
{
std::wstring stemp = std::wstring(stdstr.begin(), stdstr.end());
LPCWSTR sw = stemp.c_str();
return sw;
}
DefinedModel.h:
#pragma once
#include <windows.h>
#include <d3d11_1.h>
#include "ShaderHelper.h"
#include "d3dx11effect.h"
#include "Conversion.h"
#include "Vector3.h"
#include "d3dApp.h"
class DefinedModel
{
public:
enum RastMode {
Solid,
Wireframe
};
public:
DefinedModel(D3DApp* parent);
~DefinedModel();
protected:
D3DApp* m_pParent;
//Vertex Structure and Vertex Layout (Input Layout)//
struct Vertex //Overloaded Vertex Structure
{
Vertex() {}
Vertex(float x, float y, float z,
float cr, float cg, float cb, float ca)
: pos(x, y, z), color(cr, cg, cb, ca) {}
XMFLOAT3 pos;
XMFLOAT4 color;
};
std::vector<Vertex> m_VertexArray;
std::vector<int> m_indices;
struct cbPerObject
{
XMMATRIX WVP;
};
cbPerObject cbPerObj;
ID3D11Buffer* cbPerObjectBuffer;
ID3D11Buffer* squareIndexBuffer;
ID3D11Buffer* squareVertBuffer;
ID3D11VertexShader* VS;
ID3D11PixelShader* PS;
ID3D10Blob* VS_Buffer;
ID3D10Blob* PS_Buffer;
ID3D11InputLayout* vertLayout;
///////////////**************new**************////////////////////
Vector3 m_Rotation;
Vector3 m_Scale;
Vector3 m_Offset;
XMMATRIX m_modelWorld;
///////////////**************new**************////////////////////
RastMode m_RastMode;
ID3D11RasterizerState* m_RastState;
public:
virtual void create3DCube(float Width, float Height, float Depth);
void Init();
void Draw();
void Rotation(float X, float Y, float Z);
void Scale(float X, float Y, float Z);
void Offset(float X, float Y, float Z);
void rastMode(RastMode rastmode);
Vector3 Rotation();
Vector3 Scale();
Vector3 Offset();
XMMATRIX worldMatrix();
void Destroy();
private:
virtual void InitBuffers();
virtual void InitFX();
virtual void InitInputLayout();
virtual void InitCBBuffer();
};
DefinedModel.cpp:
#include "DefinedModel.h"
DefinedModel::DefinedModel(D3DApp* parent): m_pParent(parent)
{
m_VertexArray = std::vector<Vertex>();
m_indices = std::vector<int>();
m_modelWorld = XMMatrixIdentity();
Offset(0, 0, 0);
Scale(1, 1, 1);
Rotation(0, 0, 0);
rastMode(RastMode::Solid);
}
DefinedModel::~DefinedModel()
{
}
void DefinedModel::create3DCube(float Width, float Height, float Depth)
{
///////////////**************new**************////////////////////
//Create the vertex buffer
m_VertexArray = {
Vertex(-Width / 2, -Height / 2, -Depth / 2, 1.0f, 0.0f, 0.0f, 1.0f),
Vertex(-Width / 2, +Height / 2, -Depth / 2, 0.0f, 1.0f, 0.0f, 1.0f),
Vertex(+Width / 2, +Height / 2, -Depth / 2, 0.0f, 0.0f, 1.0f, 1.0f),
Vertex(+Width / 2, -Height / 2, -Depth / 2, 1.0f, 1.0f, 0.0f, 1.0f),
Vertex(-Width / 2, -Height / 2, +Depth / 2, 0.0f, 1.0f, 1.0f, 1.0f),
Vertex(-Width / 2, +Height / 2, +Depth / 2, 1.0f, 1.0f, 1.0f, 1.0f),
Vertex(+Width / 2, +Height / 2, +Depth / 2, 1.0f, 0.0f, 1.0f, 1.0f),
Vertex(+Width / 2, -Height / 2, +Depth / 2, 1.0f, 0.0f, 0.0f, 1.0f),
};
///////////////**************new**************////////////////////
m_indices = {
// front face
0, 1, 2,
0, 2, 3,
// back face
4, 6, 5,
4, 7, 6,
// left face
4, 5, 1,
4, 1, 0,
// right face
3, 2, 6,
3, 6, 7,
// top face
1, 5, 6,
1, 6, 2,
// bottom face
4, 0, 3,
4, 3, 7
};
Init();
}
void DefinedModel::Init()
{
InitBuffers();
InitFX();
InitInputLayout();
InitCBBuffer();
}
void DefinedModel::InitBuffers()
{
HRESULT hr;
//index buffer creation
D3D11_BUFFER_DESC indexBufferDesc;
ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(DWORD) * 12 * 3;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = &m_indices[0];
hr = m_pParent->Device()->CreateBuffer(&indexBufferDesc, &iinitData, &squareIndexBuffer);
//vertex buffer creation
D3D11_BUFFER_DESC vertexBufferDesc;
ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * 8;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vertexBufferData;
ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
vertexBufferData.pSysMem = &m_VertexArray[0];
hr = m_pParent->Device()->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &squareVertBuffer);
}
void DefinedModel::InitFX()
{
HRESULT hr;
//Compile Shaders from shader file
hr = D3DX11CompileFromFile(L"Trans.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);
hr = D3DX11CompileFromFile(L"Trans.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);
//Create the Shader Objects
hr = m_pParent->Device()->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
hr = m_pParent->Device()->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);
//Set Vertex and Pixel Shaders
m_pParent->DeviceContext()->VSSetShader(VS, 0, 0);
m_pParent->DeviceContext()->PSSetShader(PS, 0, 0);
}
void DefinedModel::InitInputLayout()
{
HRESULT hr;
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE(layout);
//Create the Input Layout
hr = m_pParent->Device()->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),
VS_Buffer->GetBufferSize(), &vertLayout);
}
void DefinedModel::InitCBBuffer()
{
HRESULT hr;
//Create the buffer to send to the cbuffer in effect file
D3D11_BUFFER_DESC cbbd;
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
cbbd.Usage = D3D11_USAGE_DEFAULT;
cbbd.ByteWidth = sizeof(cbPerObject);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;
hr = m_pParent->Device()->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
}
void DefinedModel::Draw()
{
//set index buffer
m_pParent->DeviceContext()->IASetIndexBuffer(squareIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
//Set the vertex buffer
UINT stride = sizeof(Vertex);
UINT offset = 0;
m_pParent->DeviceContext()->IASetVertexBuffers(0, 1, &squareVertBuffer, &stride, &offset);
//Set the Input Layout
m_pParent->DeviceContext()->IASetInputLayout(vertLayout);
//Set Primitive Topology
m_pParent->DeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//set rasteriser state
m_pParent->DeviceContext()->RSSetState(m_RastState);
//Matrices
///////////////**************new**************////////////////////
//Set the WVP matrix and send it to the constant buffer in effect file
XMMATRIX WVP = (worldMatrix()) * (*m_pParent->Camera()->camView()) * (*m_pParent->Camera()->camProjection());
cbPerObj.WVP = XMMatrixTranspose(WVP);
m_pParent->DeviceContext()->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
m_pParent->DeviceContext()->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
//draw shape
m_pParent->DeviceContext()->DrawIndexed(m_indices.size(), 0, 0);
}
void DefinedModel::Rotation(float X, float Y, float Z)
{
m_Rotation = Vector3(X, Y, Z);
//m_Rotation.X = X;
//m_Rotation.Y = Y;
//m_Rotation.Z = Z;
}
void DefinedModel::Scale(float X, float Y, float Z)
{
m_Scale = Vector3(X, Y, Z);
//m_Scale.X = X;
//m_Scale.Y = Y;
//m_Scale.Z = Z;
}
void DefinedModel::Offset(float X, float Y, float Z)
{
m_Offset = Vector3(X, Y, Z);
//m_Offset.X = X;
//m_Offset.Y = Y;
//m_Offset.Z = Z;
}
Vector3 DefinedModel::Rotation()
{
return m_Rotation;
}
Vector3 DefinedModel::Scale()
{
return m_Scale;
}
Vector3 DefinedModel::Offset()
{
return m_Offset;
}
XMMATRIX DefinedModel::worldMatrix()
{
XMMATRIX Scale = XMMatrixScaling(m_Scale.X(), m_Scale.Y(), m_Scale.Z());
XMMATRIX Rot = (XMMatrixRotationX(m_Rotation.X())) * (XMMatrixRotationY(m_Rotation.Y())) * (XMMatrixRotationZ(m_Rotation.Z()));
XMMATRIX Trans = XMMatrixTranslation(m_Offset.X(), m_Offset.Y(), m_Offset.Z());
// orbital
//m_modelWorld = Trans * Rot * Scale;
//on spot
m_modelWorld = Scale * Rot * Trans;
return m_modelWorld;
}
void DefinedModel::Destroy()
{
squareVertBuffer->Release();
squareIndexBuffer->Release();
VS->Release();
PS->Release();
VS_Buffer->Release();
PS_Buffer->Release();
vertLayout->Release();
cbPerObjectBuffer->Release();
m_VertexArray.clear();
m_indices.clear();
}
void DefinedModel::rastMode(RastMode rastmode)
{
HRESULT hr;
m_RastMode = rastmode;
switch (rastmode)
{
case RastMode::Solid:
{
///////////////**************new**************////////////////////
D3D11_RASTERIZER_DESC wfdesc;
ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC));
wfdesc.FillMode = D3D11_FILL_SOLID;
wfdesc.CullMode = D3D11_CULL_BACK;
hr = m_pParent->Device()->CreateRasterizerState(&wfdesc, &m_RastState);
///////////////**************new**************////////////////////
break;
}
case RastMode::Wireframe:
{
///////////////**************new**************////////////////////
D3D11_RASTERIZER_DESC wfdesc;
ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC));
wfdesc.FillMode = D3D11_FILL_WIREFRAME;
wfdesc.CullMode = D3D11_CULL_BACK;
hr = m_pParent->Device()->CreateRasterizerState(&wfdesc, &m_RastState);
///////////////**************new**************////////////////////
break;
}
}
}
Effect file (trans.fx):
cbuffer cbPerObject
{
float4x4 WVP;
};
struct VS_OUTPUT
{
float4 Pos : SV_POSITION;
float4 Color : COLOR;
};
VS_OUTPUT VS(float4 inPos : POSITION, float4 inColor : COLOR)
{
VS_OUTPUT output;
output.Pos = mul(inPos, WVP);
output.Color = inColor;
return output;
}
float4 PS(VS_OUTPUT input) : SV_TARGET
{
return input.Color;
}

Directx9 Code working fine on AMD Graphics Card but fails on Nvidia Hardware

so I wrote a Post Processing class for some old open source game,
I have a begin scene function a end scene function, a render function and a function for creating the screen squad and resources.
bool CPostProcessingChain::BeginScene()
{
if (!m_lpSourceTexture || !m_lpLastPass || !m_lpTarget || !m_lpDepthStencilSurface)
{
if (!CreateResources())
{
return false;
}
}
STATEMANAGER.GetDevice()->GetRenderTarget(0, &m_lpBackupTargetSurface);
STATEMANAGER.GetDevice()->SetRenderTarget(0, m_lpSourceTextureSurface);
STATEMANAGER.GetDevice()->GetDepthStencilSurface(&m_lpDepthStencilBackup);
STATEMANAGER.GetDevice()->SetDepthStencilSurface(m_lpDepthStencilSurface);
return true;
}
bool CPostProcessingChain::EndScene()
{
STATEMANAGER.GetDevice()->SetRenderTarget(0, m_lpBackupTargetSurface);
STATEMANAGER.GetDevice()->SetDepthStencilSurface(m_lpDepthStencilBackup);
m_lpDepthStencilBackup->Release();
m_lpDepthStencilBackup = nullptr;
m_lpBackupTargetSurface->Release();
m_lpBackupTargetSurface = nullptr;
D3DXMATRIX mWorld, mView, mProj, mIdentity;
D3DXMatrixIdentity(&mIdentity);
STATEMANAGER.GetDevice()->GetTransform(D3DTS_WORLD, &mWorld);
STATEMANAGER.GetDevice()->GetTransform(D3DTS_VIEW, &mView);
STATEMANAGER.GetDevice()->GetTransform(D3DTS_PROJECTION, &mProj);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_WORLD, &mIdentity);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_VIEW, &mIdentity);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_PROJECTION, &mIdentity);
STATEMANAGER.SaveRenderState(D3DRS_ZENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE);
STATEMANAGER.GetDevice()->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0.0f);
STATEMANAGER.GetDevice()->SetTexture(0, m_lpTarget);
STATEMANAGER.GetDevice()->SetPixelShader(nullptr);
STATEMANAGER.GetDevice()->SetVertexShader(nullptr);
STATEMANAGER.GetDevice()->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
STATEMANAGER.GetDevice()->SetStreamSource(0, m_lpScreenQuad, 0, sizeof(TRTTVertex));
STATEMANAGER.GetDevice()->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2);
STATEMANAGER.RestoreRenderState(D3DRS_MULTISAMPLEANTIALIAS);
STATEMANAGER.RestoreRenderState(D3DRS_ZENABLE);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_WORLD, &mWorld);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_VIEW, &mView);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_PROJECTION, &mProj);
return true;
}
bool CPostProcessingChain::Render()
{
D3DXMATRIX mWorld, mView, mProj, mIdentity;
D3DXMatrixIdentity(&mIdentity);
STATEMANAGER.GetDevice()->GetTransform(D3DTS_WORLD, &mWorld);
STATEMANAGER.GetDevice()->GetTransform(D3DTS_VIEW, &mView);
STATEMANAGER.GetDevice()->GetTransform(D3DTS_PROJECTION, &mProj);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_WORLD, &mIdentity);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_VIEW, &mIdentity);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_PROJECTION, &mIdentity);
STATEMANAGER.GetDevice()->SetRenderTarget(0, m_lpLastPassSurface);
STATEMANAGER.SaveRenderState(D3DRS_ZENABLE, FALSE);
STATEMANAGER.SaveRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE);
STATEMANAGER.GetDevice()->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0.0f);
STATEMANAGER.GetDevice()->SetTexture(0, m_lpSourceTexture);
STATEMANAGER.GetDevice()->SetPixelShader(nullptr);
STATEMANAGER.GetDevice()->SetVertexShader(nullptr);
STATEMANAGER.GetDevice()->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
STATEMANAGER.GetDevice()->SetStreamSource(0, m_lpScreenQuad, 0, sizeof(TRTTVertex));
STATEMANAGER.GetDevice()->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2);
IDirect3DSurface9* pCurrentTarget = m_lpTargetSurface;
STATEMANAGER.GetDevice()->SetTexture(1, m_lpSourceTexture);
for (std::list<CPostProcessingEffect>::iterator it = m_kEffects.begin(); it != m_kEffects.end(); ++it)
{
D3DSURFACE_DESC kDesc;
pCurrentTarget->GetDesc(&kDesc);
D3DXVECTOR4 vScreenSize = D3DXVECTOR4(kDesc.Width, kDesc.Height, 0.0f, 0.0f);
(*it).GetConstants()->SetFloatArray(STATEMANAGER.GetDevice(), "ScreenSize", reinterpret_cast<float*>(&vScreenSize), 4);
if ((*it).Apply())
{
STATEMANAGER.GetDevice()->SetRenderTarget(0, pCurrentTarget);
STATEMANAGER.GetDevice()->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0.0f);
STATEMANAGER.GetDevice()->SetTexture(0, pCurrentTarget == m_lpLastPassSurface ? m_lpTarget : m_lpLastPass);
STATEMANAGER.GetDevice()->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
STATEMANAGER.GetDevice()->SetStreamSource(0, m_lpScreenQuad, 0, sizeof(TRTTVertex));
STATEMANAGER.GetDevice()->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2);
pCurrentTarget = pCurrentTarget == m_lpLastPassSurface ? m_lpTargetSurface : m_lpLastPassSurface;
}
}
STATEMANAGER.GetDevice()->SetTexture(1, nullptr);
if (pCurrentTarget == m_lpTargetSurface)
{
STATEMANAGER.GetDevice()->SetRenderTarget(0, m_lpTargetSurface);
STATEMANAGER.GetDevice()->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0.0f);
STATEMANAGER.GetDevice()->SetTexture(0, m_lpLastPass);
STATEMANAGER.GetDevice()->SetPixelShader(nullptr);
STATEMANAGER.GetDevice()->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);
STATEMANAGER.GetDevice()->SetStreamSource(0, m_lpScreenQuad, 0, sizeof(TRTTVertex));
STATEMANAGER.GetDevice()->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2);
}
STATEMANAGER.RestoreRenderState(D3DRS_MULTISAMPLEANTIALIAS);
STATEMANAGER.RestoreRenderState(D3DRS_ZENABLE);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_WORLD, &mWorld);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_VIEW, &mView);
STATEMANAGER.GetDevice()->SetTransform(D3DTS_PROJECTION, &mProj);
return true;
}
bool CPostProcessingChain::CreateResources()
{
ReleaseResources();
D3DSURFACE_DESC kDesc;
IDirect3DSurface9* pSurface;
STATEMANAGER.GetDevice()->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pSurface);
pSurface->GetDesc(&kDesc);
pSurface->Release();
if (FAILED(STATEMANAGER.GetDevice()->CreateTexture(kDesc.Width, kDesc.Width, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A32B32G32R32F, D3DPOOL_DEFAULT, &m_lpSourceTexture, nullptr)))
{
TraceError("CPostProcessingChain unable to create render target");
return false;
}
m_lpSourceTexture->GetSurfaceLevel(0, &m_lpSourceTextureSurface);
if (FAILED(STATEMANAGER.GetDevice()->CreateTexture(kDesc.Width, kDesc.Width, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A32B32G32R32F, D3DPOOL_DEFAULT, &m_lpLastPass, nullptr)))
{
TraceError("CPostProcessingChain unable to create pass render target");
return false;
}
m_lpLastPass->GetSurfaceLevel(0, &m_lpLastPassSurface);
if (FAILED(STATEMANAGER.GetDevice()->CreateTexture(kDesc.Width, kDesc.Width, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A32B32G32R32F, D3DPOOL_DEFAULT, &m_lpTarget, nullptr)))
{
TraceError("CPostProcessingChain unable to create final render target");
return false;
}
m_lpTarget->GetSurfaceLevel(0, &m_lpTargetSurface);
STATEMANAGER.GetDevice()->GetDepthStencilSurface(&pSurface);
pSurface->GetDesc(&kDesc);
pSurface->Release();
if (FAILED(STATEMANAGER.GetDevice()->CreateDepthStencilSurface(kDesc.Width, kDesc.Width, D3DFMT_D16, kDesc.MultiSampleType, kDesc.MultiSampleQuality, FALSE, &m_lpDepthStencilSurface, nullptr)))
{
TraceError("CPostProcessingChain unable to create depth surface");
return false;
}
if (FAILED(STATEMANAGER.GetDevice()->CreateVertexBuffer(sizeof(TRTTVertex)* 6, 0, D3DFVF_XYZRHW | D3DFVF_TEX1, D3DPOOL_MANAGED, &m_lpScreenQuad, nullptr)))
{
TraceError("CPostProcessingChain unable to create screen quad");
return false;
}
float fWidth = static_cast<float>(kDesc.Width) - 0.5f;
float fHeight = static_cast<float>(kDesc.Height) - 0.5f;
float fTexPos = fHeight / fWidth;
TRTTVertex* pVertices;
m_lpScreenQuad->Lock(0, 0, reinterpret_cast<void**>(&pVertices), 0);
pVertices[0].p = D3DXVECTOR4(-0.5f, -0.5f, 0.0f, 1.0f);
pVertices[0].t = D3DXVECTOR2(0.0f, 0.0f);
pVertices[1].p = D3DXVECTOR4(-0.5f, fHeight, 0.0f, 1.0f);
pVertices[1].t = D3DXVECTOR2(0.0f, 1.0f);
pVertices[2].p = D3DXVECTOR4(fWidth, fHeight, 0.0f, 1.0f);
pVertices[2].t = D3DXVECTOR2(1.0f, 1.0f);
pVertices[3].p = D3DXVECTOR4(-0.5f, -0.5f, 0.0f, 1.0f);
pVertices[3].t = D3DXVECTOR2(0.0f, 0.0f);
pVertices[4].p = D3DXVECTOR4(fWidth, fHeight, 0.0f, 1.0f);
pVertices[4].t = D3DXVECTOR2(1.0f, 1.0f);
pVertices[5].p = D3DXVECTOR4(fWidth, -0.5f, 0.0f, 1.0f);
pVertices[5].t = D3DXVECTOR2(1.0f, 0.0f);
m_lpScreenQuad->Unlock();
/*0, 0 | up left
0, height | down left
width, height | down right
0, 0 | up left
width, height | down right
width, 0 | up right*/
AddEffect("shaders/testshader.xml");
return true;
}
This code works on AMD Graphic cards but is not working on NVida Graphic cards,
I already tried to use cl2p clamp textures but that did not help so at the moment I have not the slightest idea why it is working on AMD but not on Nvidia Cards
It does not crash on Nvidia but the screen is black
If you have any ideas, please respond,
Thanks in advance

DirectX9 Lighting C++ Lighting not working

This is a simple program that draws a 3d cube with a texture. The problem is I can not see the texture because the lights are not working.I have turned off the lights just to make sure the texture is there and it is.So if any one can help me figure out why the lights are not working I would greatly appreciate it.
#include "DirectXGame.h"
DirectXGame::DirectXGame(void)
{
//init to zero good pratice
m_pD3DObject=0;
m_pD3DDevice=0;
m_currTime=0;
m_prevTime=0;
ZeroMemory(&m_D3Dpp,sizeof(m_D3Dpp));
FOV=D3DXToRadian(65.0f);
aspectRatio=800/600;
nearPlane=1.0f;
farPlane=1000.0f;
}
DirectXGame::~DirectXGame(void)
{
}
//create class for input
DirectXInput DXClass;
void DirectXGame::Initialize(HWND hWnd ,HINSTANCE hInst,bool bWindowed) // create the material struct)//
{
// grab the window width and height fronm the HWND
RECT r;
GetWindowRect(hWnd, &r);
m_nWidth = r.right - r.left;
m_nHeight = r.bottom - r.top;
m_bVSync = false;
// Create the D3D Object
m_pD3DObject = Direct3DCreate9(D3D_SDK_VERSION);
// Create our presentation parameters for our D3D Device
m_D3Dpp.hDeviceWindow = hWnd; // Handle to the window
m_D3Dpp.Windowed = bWindowed; // Windowed or Full-screen?
m_D3Dpp.BackBufferCount = 1; // Number of back-buffers
m_D3Dpp.BackBufferFormat = D3DFMT_X8R8G8B8; // Back-buffer pixel format
m_D3Dpp.BackBufferWidth = m_nWidth; // Back-buffer width
m_D3Dpp.BackBufferHeight = m_nHeight; // Back-buffer height
m_D3Dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // Swap effectm_bVSync ? D3DPRESENT_INTERVAL_DEFAULT :
m_D3Dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
m_D3Dpp.FullScreen_RefreshRateInHz = bWindowed ? 0 : D3DPRESENT_RATE_DEFAULT;
m_D3Dpp.EnableAutoDepthStencil = TRUE; // Enable depth and stencil buffer
m_D3Dpp.AutoDepthStencilFormat = D3DFMT_D24S8; // Depth/Stencil buffer bit format
m_D3Dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; // Discard the depth/stencil buffer upon Present()
m_D3Dpp.MultiSampleQuality = 0; // MSAA quality
m_D3Dpp.MultiSampleType = D3DMULTISAMPLE_NONE; // MSAA type
// Check the device's capabilities
DWORD deviceBehaviorFlags = 0;
m_pD3DObject->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &m_D3DCaps);
// Determine vertex processing mode
if(m_D3DCaps.DevCaps & D3DCREATE_HARDWARE_VERTEXPROCESSING)
{
deviceBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
}
else
{
deviceBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
// if hardware vertex processing is on, check for pure
if(m_D3DCaps.DevCaps & D3DCREATE_PUREDEVICE && deviceBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING)
{
deviceBehaviorFlags |= D3DCREATE_PUREDEVICE;
}
// Create D3D Device
m_pD3DObject->CreateDevice(
D3DADAPTER_DEFAULT, // Default display adapter
D3DDEVTYPE_HAL, // Device type to use
hWnd, // Handle to our window
deviceBehaviorFlags, // D3DCREATE_HARDWARE_VERTEXPROCESSINGVertex Processing Behavior Flags (PUREDEVICE, HARDWARE_VERTEXPROCESSING, SOFTWARE_VERTEXPROCESSING)
&m_D3Dpp, // Presentation parameters
&m_pD3DDevice); // Return a created D3D Device
//=================================================================//
// Create/Load Sprite & Font D3D and COM objects
//Create font
D3DXCreateFont(m_pD3DDevice, 23, 0, FW_BOLD, 0, true,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, TEXT("Times New Roman"),
&m_pD3DFont);
//for font 1 "Name"
RECT rct;
rct.left=2;
rct.right=780;
rct.top=10;
rct.bottom=rct.top+20;
//MATRIX
eyePos.x = 0;
eyePos.y = 2;
eyePos.z = -10;
lookAt.x = 0;
lookAt.y = 0;
lookAt.z = 0;
upVec.x = 0;
upVec.y = 1;
upVec.z = 0;
D3DXMatrixLookAtLH( &view_Matrix, &eyePos, &lookAt, &upVec);
m_pD3DDevice->SetTransform( D3DTS_VIEW, &view_Matrix);
// projection matrix
D3DXMatrixPerspectiveFovLH( &pro_Matrix, FOV, aspectRatio, nearPlane, farPlane);
m_pD3DDevice->SetTransform( D3DTS_PROJECTION, &pro_Matrix);
// MATRIX: VertexElement Declaration
D3DVERTEXELEMENT9 declaration[] =
{
{0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
{0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
D3DDECL_END()
};
//LPDIRECT3DVERTEXDECLARATION9 m_pVtxDeclObject;
// Create vertex declaration
m_pD3DDevice->CreateVertexDeclaration(declaration,&vertDec);
///---CUBE: Vertex and Indicies :START---///
// Load vertex info, listed per cube face quads
// Front
m_cubeVerts[0].position = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
m_cubeVerts[1].position = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
m_cubeVerts[2].position = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
m_cubeVerts[3].position = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
D3DXVec3Normalize(&m_cubeVerts[0].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
D3DXVec3Normalize(&m_cubeVerts[1].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
D3DXVec3Normalize(&m_cubeVerts[2].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
D3DXVec3Normalize(&m_cubeVerts[3].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
m_cubeVerts[0].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[1].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[2].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[3].uv = D3DXVECTOR2(1.0f, 1.0f);
// Back
m_cubeVerts[4].position = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
m_cubeVerts[5].position = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
m_cubeVerts[6].position = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
m_cubeVerts[7].position = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
D3DXVec3Normalize(&m_cubeVerts[4].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
D3DXVec3Normalize(&m_cubeVerts[5].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
D3DXVec3Normalize(&m_cubeVerts[6].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
D3DXVec3Normalize(&m_cubeVerts[7].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
m_cubeVerts[4].uv = D3DXVECTOR2(1.0f, 1.0f);
m_cubeVerts[5].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[6].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[7].uv = D3DXVECTOR2(1.0f, 0.0f);
// Top
m_cubeVerts[8].position = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
m_cubeVerts[9].position = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
m_cubeVerts[10].position = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
m_cubeVerts[11].position = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
D3DXVec3Normalize(&m_cubeVerts[8].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[9].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[10].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[11].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
m_cubeVerts[8].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[9].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[10].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[11].uv = D3DXVECTOR2(1.0f, 1.0f);
// Bottom
m_cubeVerts[12].position = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
m_cubeVerts[13].position = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
m_cubeVerts[14].position = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
m_cubeVerts[15].position = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
D3DXVec3Normalize(&m_cubeVerts[12].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[13].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[14].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[15].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
m_cubeVerts[12].uv = D3DXVECTOR2(1.0f, 1.0f);
m_cubeVerts[13].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[14].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[15].uv = D3DXVECTOR2(1.0f, 0.0f);
// Left
m_cubeVerts[16].position = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
m_cubeVerts[17].position = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
m_cubeVerts[18].position = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
m_cubeVerts[19].position = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
D3DXVec3Normalize(&m_cubeVerts[16].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[17].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[18].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[19].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
m_cubeVerts[16].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[17].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[18].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[19].uv = D3DXVECTOR2(1.0f, 1.0f);
// Right
m_cubeVerts[20].position = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
m_cubeVerts[21].position = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
m_cubeVerts[22].position = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
m_cubeVerts[23].position = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
D3DXVec3Normalize(&m_cubeVerts[20].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[21].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[22].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[23].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
m_cubeVerts[20].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[21].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[22].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[23].uv = D3DXVECTOR2(1.0f, 1.0f);
// Load index info, refers into index into verts array to compose triangles
// Note: A clockwise winding order of verts will show the front face.
// Front
m_cubeIndices[0] = 0; m_cubeIndices[1] = 1; m_cubeIndices[2] = 2; // Triangle 0
m_cubeIndices[3] = 0; m_cubeIndices[4] = 2; m_cubeIndices[5] = 3; // Triangle 1
// Back
m_cubeIndices[6] = 4; m_cubeIndices[7] = 5; m_cubeIndices[8] = 6; // Triangle 2
m_cubeIndices[9] = 4; m_cubeIndices[10] = 6; m_cubeIndices[11] = 7; // Triangle 3
// Top
m_cubeIndices[12] = 8; m_cubeIndices[13] = 9; m_cubeIndices[14] = 10; // Triangle 4
m_cubeIndices[15] = 8; m_cubeIndices[16] = 10; m_cubeIndices[17] = 11; // Triangle 5
// Bottom
m_cubeIndices[18] = 12; m_cubeIndices[19] = 13; m_cubeIndices[20] = 14; // Triangle 6
m_cubeIndices[21] = 12; m_cubeIndices[22] = 14; m_cubeIndices[23] = 15; // Triangle 7
// Left
m_cubeIndices[24] = 16; m_cubeIndices[25] = 17; m_cubeIndices[26] = 18; // Triangle 8
m_cubeIndices[27] = 16; m_cubeIndices[28] = 18; m_cubeIndices[29] = 19; // Triangle 9
// Right
m_cubeIndices[30] = 20; m_cubeIndices[31] = 21; m_cubeIndices[32] = 22; // Triangle 10
m_cubeIndices[33] = 20; m_cubeIndices[34] = 22; m_cubeIndices[35] = 23; // Triangle 11
///---CUBE: Vertex and Indicies :END---///
//create buffers
// create a vertex buffer interface called i_buffer
m_pD3DDevice->CreateVertexBuffer(4*6*sizeof(Vertex),
D3DUSAGE_WRITEONLY,
0,
D3DPOOL_MANAGED,
&VB,
NULL);
void* pVertices;
// lock VB and load the vertices into it
VB->Lock(0, 0,&pVertices, 0);
// send array
memcpy(pVertices, m_cubeVerts, 4*6*sizeof(Vertex));
//unlock
VB->Unlock();
///////////////////////////////////////////////////
m_pD3DDevice->CreateIndexBuffer(3*12*sizeof(WORD), // 3 and 12
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&IB,
NULL);
void* pIndices;
// lock index
IB->Lock(0,0,&pIndices,0);
//send array of indices to vram
memcpy(pIndices, m_cubeIndices, 3*12*sizeof(WORD));
//unlock index
IB->Unlock();
D3DLIGHT9 light;
D3DMATERIAL9 m_Mat;
ZeroMemory(&light, sizeof(light));
// clear out the light struct for use
light.Type = D3DLIGHT_POINT;
// make the light type 'directional light'
light.Diffuse.r = 0.5f;
light.Diffuse.g = 0.5f;
light.Diffuse.b = 0.5f;
light.Diffuse.a = 1.0f;
light.Ambient.r = 0.2f;
light.Ambient.g = 0.2f;
light.Ambient.b = 1.0f;
light.Specular.r = 1.0f;
light.Specular.g = 1.0f;
light.Specular.b = 1.0f;
// set the lighting position
light.Position.x = 30;
light.Position.y = 10;
light.Position.z = -10;
light.Range = 900.0f;
light.Attenuation0 = 0.0f;
light.Attenuation1 = 0.125f;
light.Attenuation2 = 0.0f;
m_pD3DDevice->SetLight(0, &light);
// send the light struct properties to light #0
m_pD3DDevice->LightEnable(0, TRUE);
// turn on light #0
ZeroMemory(&m_Mat, sizeof(m_Mat));
// clear out the struct for use
m_Mat.Diffuse.r = 1.0f;
m_Mat.Diffuse.g = 0.0f;
m_Mat.Diffuse.b = 0.0f;
m_Mat.Diffuse.a = 0.0f;
// set diffuse color to white
m_Mat.Ambient.r = 0.2f;
m_Mat.Ambient.g = 0.2f;
m_Mat.Ambient.b = 0.2f;
m_Mat.Ambient.a = 1.0f;
// set ambient color to white
m_Mat.Specular.r = 1.0f;
m_Mat.Specular.g =1.0f;
m_Mat.Specular.b =1.0f;
m_Mat.Specular.a =1.0f;
m_Mat.Power = 100.0f;
m_pD3DDevice->SetMaterial(&m_Mat);
// Create a texture using the with "test.tga" from the sprite labs.
//Apply tri-linear filtering to the texture, by modifying the sampler states by calling the device's SetSamplerState().
D3DXCreateTextureFromFile(m_pD3DDevice, L"test.png",&m_Texture);
//Apply tri-linear filtering to the texture, by modifying the sampler states by calling the device's SetSamplerState().
m_pD3DDevice->SetSamplerState( 0,D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState( 0,D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState( 0,D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
}
void DirectXGame::Update(HWND hWnd, bool& bWindowed, double dt)
{
}
void DirectXGame::Render()
{
// if our d3d device was not craeted return
if(!m_pD3DDevice)
return;
m_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(100,149,237), 1, 0); // 100,149,237 00255
// Begin the scene
if( SUCCEEDED( m_pD3DDevice->BeginScene() ) )
{
m_pD3DDevice->SetVertexDeclaration( vertDec);
//set cube postion
D3DXMATRIX translation, rotation, scale, world, position;
float index = 0.0f; index+=0.05f;
D3DXMatrixTranslation(&translation,0,0,0);
D3DXMatrixRotationY(&rotation, timeGetTime()/1000);
D3DXMatrixScaling(&scale,1,1, 1.0f);
world = scale*rotation*translation;
m_pD3DDevice->SetTransform(D3DTS_WORLD, &world);
// select the vertex and index buffers to use
m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
m_pD3DDevice->SetRenderState( D3DRS_SPECULARENABLE, TRUE );
m_pD3DDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_XRGB(60,60,60));
m_pD3DDevice->SetStreamSource(0, VB, 0, sizeof(Vertex));
m_pD3DDevice->SetIndices(IB);
m_pD3DDevice->SetMaterial(&m_Mat);
m_pD3DDevice->SetTexture( 0,m_Texture);
m_pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,//D3DPRIMITIVETYPE Type
0,/*BaseVertexIndex*/
0, //* MinIndex*/
24, /*NumVertices*/
0, /*StartIndex*/
12);//PrimitiveCount
///////////////////////////////////////////////////////////////////////////
//Font 1 "Name"
RECT rct;
rct.bottom = m_nHeight;
rct.top=2;
rct.left=658;
rct.right=m_nWidth;
//for the font2 FPS
RECT rect;
rect.bottom = m_nHeight;
rect.top =2;
rect.left = 10;
rect.right = m_nWidth;
wchar_t buffer[64];
swprintf_s(buffer, 64,L"Frames Per Second: %d", m_FPS);
m_pD3DFont->DrawText(0, buffer, -1, &rect, DT_TOP | DT_NOCLIP, D3DCOLOR_ARGB(255,255,255,255));
// Create a colour for the text ( blue)
D3DCOLOR fontColor = D3DCOLOR_ARGB(255,0,0,255);
//draw the text
m_pD3DFont->DrawText(NULL, L"Mariana Serrato", -1, &rct, 0, fontColor ); // move test to far right
// End the scene
m_pD3DDevice->EndScene();
// present the back buffer to the screen
m_pD3DDevice->Present(NULL, NULL, NULL, NULL);
//calculate Frames Per Second
m_currTime = timeGetTime();
static int fspCounter = 0;
if(m_currTime - m_prevTime >= 1000.0f)
{
m_prevTime = m_currTime;
m_FPS = fspCounter;
fspCounter =0;
} else {
++fspCounter;
}
}
}
void DirectXGame::Shutdown()
{
SAFE_RELEASE(VB);
SAFE_RELEASE(IB);
SAFE_RELEASE(vertDec);
SAFE_RELEASE(m_pD3DFont);
SAFE_RELEASE(m_Texture);
SAFE_RELEASE(m_Sprite);
SAFE_RELEASE(m_pD3DDevice);
SAFE_RELEASE(m_pD3DObject);
}
//////////////////////////////////////////////////////////////////////////////////////////
.h header file
pragma once
include // for random nums
include
include
include
include
include
include "DirectXInput.h"
include
include
pragma comment (lib, "d3d9.lib")
pragma comment (lib, "d3dx9.lib")
pragma comment(lib, "winmm.lib")//for timeGetTime()
pragma comment(lib, "dinput8.lib")
pragma comment(lib, "dxguid.lib")
// Macro to Safely release com obejcts
define SAFE_RELEASE(x) if(x) {x->Release(); x = 0;}
// Direct Input version
define DIRECTINPUT_VERSION 0x0800
// Define window size
define SCREEN_WIDTH 800
define SCREEN_HEIGHT 600
//#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)
class DirectXGame
{
struct Vertex
{
D3DXVECTOR3 position;
D3DXVECTOR3 normal;
D3DXVECTOR2 uv;
};
IDirect3D9* m_pD3DObject;
IDirect3DDevice9* m_pD3DDevice;
D3DPRESENT_PARAMETERS m_D3Dpp;
ID3DXFont* m_pD3DFont; //Font
LPDIRECT3DTEXTURE9 m_Texture;
ID3DXSprite* m_Sprite;//Sprite
D3DXVECTOR3 texCenter,eyePos,lookAt,upVec;
D3DCAPS9 m_D3DCaps; //D3D Device Caps
D3DLIGHT9 m_Light;
D3DMATERIAL9 m_Mat;
D3DVERTEXELEMENT9 m_Element;
D3DXMATRIX view_Matrix, pro_Matrix;
// cube
Vertex m_cubeVerts[24];
WORD m_cubeIndices[36];
IDirect3DVertexBuffer9* VB;
IDirect3DIndexBuffer9* IB;
IDirect3DVertexDeclaration9* vertDec;
bool m_bVSync;
char buffer [256];
int m_nWidth, m_nHeight;
int m_FPS,alfa[5],mFPS,mMilliSecPerFrame;
float m_currTime,m_prevTime,FOV, aspectRatio, nearPlane, farPlane;
DWORD D3DUSASE_DYNAMIC,D3DUSASE_WRITEONLY;
public:
DirectXGame(void);
~DirectXGame(void);
void Initialize(HWND hWnd,HINSTANCE hInst, bool bWindowed);
bool isDeviceLost();
void Update(HWND hWnd, bool& bWindowed, double dt);
void Render();
void CheckPosition();
void Shutdown();
};
You haven't enabled D3DRS_LIGHTING.
m_pD3DDevice->setRenderState(D3DRS_LIGHTING, TRUE);