Not able to draw square DirectX 12 c++ - c++

In D3D12, How can I draw square? Following code only able to draw only first triangle.
Why don't we have D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLELIST in D3D12? Is there any option to for TRIANGLELIST? Or is there any way to draw square directly?
// Describe and create the graphics pipeline state object (PSO).
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
psoDesc.pRootSignature = g_rootSignature.Get();
psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader.Get());
psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader.Get());
psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState.DepthEnable = FALSE;
psoDesc.DepthStencilState.StencilEnable = FALSE;
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
psoDesc.SampleDesc.Count = 1;
if (SUCCEEDED(g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pipelineState))))
{
cout << "CreateGraphicsPipelineState passed";
}
else
{
cout << "CreateGraphicsPipelineState failed";
return E_FAIL;
}
}
// Create the command list.
if (SUCCEEDED(g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_commandAllocator.Get(), g_pipelineState.Get(), IID_PPV_ARGS(&g_commandList))))
{
cout << "CreateCommandList passed";
}
else
{
cout << "CreateCommandList failed";
return E_FAIL;
}
// Create the vertex buffer.
{
// Define the geometry for a triangle.
Vertex triangleVertices[] =
{
{ { -1.0f, 1.0f, 1.0f },{ 0.0f, 0.0f } },
{ { 1.0f, 1.0f , 1.0f },{ 1.0f, 0.0f } },
{ { 1.0f, -1.0f, 1.0f },{ 1.0f, 1.0f } },
{ { -1.0f, 1.0f, 1.0f },{ 0.0f, 0.0f } },
{ { 1.0f, -1.0f, 1.0f },{ 1.0f, 1.0f } },
{ { -1.0f, -1.0f , 1.0f },{ 0.0f, 1.0f } }
};
const UINT vertexBufferSize = sizeof(triangleVertices);
if (SUCCEEDED(g_pd3dDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES,
&CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&g_vertexBuffer))))
{
cout << "CreateCommittedResource passed";
}
else
{
cout << "CreateCommittedResource failed";
return E_FAIL;
}
// Copy the triangle data to the vertex buffer.
UINT8* pVertexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
if (SUCCEEDED(g_vertexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin))))
{
cout << "Copy the triangle data to the vertex buffer passed";
}
else
{
cout << "Copy the triangle data to the vertex buffer failed";
return E_FAIL;
}
memcpy(pVertexDataBegin, triangleVertices, sizeof(triangleVertices));
g_vertexBuffer->Unmap(0, nullptr);
// Initialize the vertex buffer view.
g_vertexBufferView.BufferLocation = g_vertexBuffer->GetGPUVirtualAddress();
g_vertexBufferView.StrideInBytes = sizeof(Vertex);
g_vertexBufferView.SizeInBytes = vertexBufferSize;
}

You still need to call IASetPrimitiveTopology to tell it whether you want a triangle strip or triangle list.
m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
See MSDN. ID3D12GraphicsCommandList::IASetPrimitiveTopology

Related

High CPU usage with VSYNC turned ON in Opengl and SDL2 application

In this simple triangle drawing application made with opengl3.3 and sdl2, the cpu's usage shoots up to 50+% with vsync enabled. The vsync is enabled using SDL_GL_SetSwapInterval( 1 ). When i remove the vsync by setting the previous function to 0 and capped the fps to 60 manually in the main loop the cpu usage sits at around 5% average.
What is the problem here? Am i misunderstanding something fundamental here? below is my code. (The vsync function is in the initialize() loop provided below).
Main file:
unsigned int triangle_Gen()
{
float vertices[] = {
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f,
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(float), (void*)(3*sizeof(float)));
glEnableVertexAttribArray(1);
return VAO;
}
int main(int argc, char* args[])
{
float StartTicks = 0;
float EndTicks = 0;
float timeStep = 0;
int fps = 0;
float frameStartTime = 0;
float frameEndTime = 0;
float onesectime = 0;
bool enableEditor = false;
int editor_keyCount = 0;
if(!initialize())
{
std::cout<<"Failed to initiate instance!!!"<<std::endl;
}
else
{
std::cout << glGetString(GL_VERSION) <<std::endl;
int color_shaderProgram = Shaders("ShaderFiles/color_shader.vs","ShaderFiles/color_shader.fs");
unsigned int triangle = triangle_Gen();
glUseProgram(color_shaderProgram);
glBindVertexArray(triangle);
while(isRunning)
{
SDL_GetWindowSize(window, &SCREEN_WIDTH, &SCREEN_HEIGHT);
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
if(!enableEditor)
{ SDL_SetRelativeMouseMode(SDL_TRUE); } //disable cursor
else
{ SDL_SetRelativeMouseMode(SDL_FALSE); } //enable cursor
Uint32 time = 0;
time = SDL_GetTicks() - StartTicks;
timeStep = time/1000.f;
StartTicks = SDL_GetTicks();
fps++; //fps counter
onesectime += timeStep; //1 sec counter
frameStartTime = SDL_GetTicks();
//=========================================input handle sector =========================================//
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
isRunning = false;
if( e.type == SDL_KEYDOWN && e.key.repeat == 0 )
{
switch(e.key.keysym.sym)
{
case SDLK_e: editor_keyCount++; break;
}
if(editor_keyCount == 1)
{ enableEditor = !enableEditor; }
}
if( e.type == SDL_KEYUP && e.key.repeat == 0 )
{
switch(e.key.keysym.sym)
{
case SDLK_e: editor_keyCount--; break;
}
}
}
//=========================================render sector=========================================//
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
//--------------------------------------fps stuff --------------------------------------------------------------//
frameEndTime = SDL_GetTicks();
/*if((frameEndTime - frameStartTime) < 16.67) //60fps manual cap
{
SDL_Delay(16.67-(frameEndTime-frameStartTime));
}*/
if(onesectime >= 1) //print fps
{
std::cout<<fps<<std::endl;
onesectime = 0;
fps = 0;
}
SDL_GL_SwapWindow( window );
}
}
close();
return 0;
}
initialize() function:
bool initialize()
{
Uint32 flags = SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_EVENTS;
//initializing
if(SDL_Init(flags) < 0)
{
std::cout<<"SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl;
isRunning = false;
}
else
{
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;//SDL_WINDOW_INPUT_GRABBED;
window = SDL_CreateWindow("Test Application", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, flags);
if( window == NULL )
{
std::cout<<"Window could not be created! SDL Error:" << SDL_GetError() << std::endl;
isRunning = false;
}
else
{
openGL_Context = SDL_GL_CreateContext( window );
if(openGL_Context == NULL)
{
std::cout<<"OpenGL context could not be created! SDL Error: %s\n" << SDL_GetError() <<std::endl;
isRunning = false;
}
else
{
//enable(1)or disable(0) vsync
if(SDL_GL_SetSwapInterval( 1 ) < 0)
{
std::cout<<"Warning, vsync disabled!"<<std::endl;
}
glewExperimental = GL_TRUE;
if( glewInit() != GLEW_OK)
{
std::cout<<"Unable to initialize glew!"<<std::endl;
isRunning = false;
}
else
{
SDL_WarpMouseInWindow(window, (SCREEN_WIDTH/2), (SCREEN_HEIGHT/2));
}
}
}
}
return isRunning;
}

How to stop incrementing variable after bool becomes true?

So I'm working on a game that tasks the player with pressing either A, B, or C to make one of three boxes disappear. If a box disappears to reveal a smaller box, the user wins. I'm having difficulty trying to make it so that when the user wins, the counters for the amount of total guesses made and wrong guesses are no longer incremented, because at the moment, one can just keep pressing a button to continually increment those two variables (aptly named totalGuesses and wrongGuesses respectively). Does anyone have any idea how I could accomplish this task? I'm sure it's relatively simple, but it's driving me up the wall. Thank you so much.
Here's my main.cpp:
#include "Box.h"
#include "Font.h"
#include "Camera.h"
#include "Time.h"
#include <vector>
#include <sstream>
using namespace std;
#include "vgl.h"
using namespace glm;
#define SPACEBAR_KEY 32
#define ESCAPE_KEY 033
vector<Box * > boxes;
Camera* camera;
Font* font;
int numGenerator, guesses, totalGuesses, rounds, wrongGuesses, wrongGuessesRound, oldGuess, oldWrongGuess;
bool win;
void closeApp()
{
delete camera;
delete font;
for (auto it = boxes.begin(); it != boxes.end(); ++it)
delete (*it);
}
void startNewGame()
{
rounds++;
win = false;
guesses = 0;
wrongGuesses = 0;
wrongGuessesRound = 0;
numGenerator = rand() % 3;
boxes[1]->Visible = true;
boxes[2]->Visible = true;
boxes[3]->Visible = true;
if (numGenerator == 0)
{
boxes[0]->Position = vec3(0.0f, -3.0f, 0.0f);
}
else if (numGenerator == 1)
{
boxes[0]->Position = vec3(0.0f, 0.0f, 0.0f);
}
else
{
boxes[0]->Position = vec3(0.0f, 3.0f, 0.0f);
}
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case ESCAPE_KEY: // ASCII Escape Key Code
closeApp();
exit(EXIT_SUCCESS);
break;
case 'a':
boxes[1]->Visible = false;
if (boxes[0]->Position != vec3(0.0f, -3.0f, 0.0f))
{
guesses++;
wrongGuesses++;
wrongGuessesRound++;
totalGuesses++;
}
else
{
win = true;
//totalGuesses++;
//guesses++;
}
glutPostRedisplay();
break;
case 'b':
boxes[2]->Visible = false;
if (boxes[0]->Position != vec3(0.0f, 0.0f, 0.0f))
{
guesses++;
wrongGuesses++;
totalGuesses++;
wrongGuessesRound++;
}
else
{
win = true;
//totalGuesses++;
//guesses++;
}
glutPostRedisplay();
break;
case 'c':
boxes[3]->Visible = false;
if (boxes[0]->Position != vec3(0.0f, 3.0f, 0.0f))
{
guesses++;
wrongGuesses++;
wrongGuessesRound++;
totalGuesses++;
}
else
{
win = true;
//totalGuesses++;
//guesses++;
}
glutPostRedisplay();
break;
case 'r':
if (win)
{
startNewGame();
}
glutPostRedisplay();
break;
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
font->printText("Guessing Game!", 260, 560, 20);
font->printText("Press A, B, or C to make one of the boxes disappear!", 10, 540, 15);
font->printText("Try to find the small cube! Press 'r' to restart!", 30, 520, 15);
if (win)
{
font->printText("You win!", 275, 480, 30);
guesses = oldGuess;
wrongGuesses += 0;
}
if (guesses >= 3)
{
guesses = 3;
}
/*if (wrongGuessesRound >= 3)
{
wrongGuessesRound = 3;
}*/
std::stringstream ss1;
ss1 << "Guesses: " << guesses;
font->printText(ss1.str().c_str(), 20, 350, 15);
std::stringstream ss2;
ss2 << "Rounds played: " << rounds;
font->printText(ss2.str().c_str(), 20, 330, 15);
std::stringstream ss3;
ss3 << "Wrong guesses: " << wrongGuesses;
font->printText(ss3.str().c_str(), 20, 290, 15);
std::stringstream ss4;
ss4 << "Total guesses: " << totalGuesses;
font->printText(ss4.str().c_str(), 20, 310, 15);
//std::stringstream ss5;
//ss5 << "Round wrong guesses: " << wrongGuessesRound;
//font->printText(ss5.str().c_str(), 20, 270, 15);
boxes[0]->Draw(camera->ProjectionMatrix, camera->ViewMatrix);
boxes[1]->Draw(camera->ProjectionMatrix, camera->ViewMatrix);
boxes[2]->Draw(camera->ProjectionMatrix, camera->ViewMatrix);
boxes[3]->Draw(camera->ProjectionMatrix, camera->ViewMatrix);
glutSwapBuffers();
}
void init()
{
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
srand(time(NULL));
font = new Font();
camera = new Camera();
camera->ViewMatrix = glm::lookAt(glm::vec3(0, 0, 20), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
VertexBufferData vertexBufferData = VertexBufferData("Data\\Models\\Objects.xml");
boxes.push_back(new Box(vertexBufferData, glm::vec3(0.0f, 0.0f, 0.0f), "data/images/wood.bmp", "Data\\Shaders\\Vertex.shader", "Data\\Shaders\\Fragment.shader", vec3(0.4f, 0.4f, 0.4f), true));
boxes.push_back(new Box(vertexBufferData, glm::vec3(0.0f, -3.0f, 0.0f), "data/images/ground.tga", "Data\\Shaders\\Vertex.shader", "Data\\Shaders\\Fragment.shader", vec3(1.0f, 1.0f, 1.0f), true));
boxes.push_back(new Box(vertexBufferData,glm::vec3(0.0f, 0.0f, 0.0f), "data/images/metal.bmp", "Data\\Shaders\\Vertex.shader", "Data\\Shaders\\Fragment.shader", vec3(1.0f, 1.0f, 1.0f), true));
boxes.push_back(new Box(vertexBufferData, glm::vec3(0.0f, 3.0f, 0.0f), "data/images/brick.bmp", "Data\\Shaders\\Vertex.shader", "Data\\Shaders\\Fragment.shader", vec3(1.0f, 1.0f, 1.0f), true));
startNewGame();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(1024, 768);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutCreateWindow("Satterwhite_Project_5");
if (glewInit())
{
cerr << "Unable to init glew" << endl;
exit(EXIT_FAILURE);
}
init();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
Why wouldn't you do this to start:
void keyboard(unsigned char key, int x, int y)
{
if (win)
{
if ((key == 'a') || (key == 'b') || (key == 'c'))
{
// ignore a,b,c if there is already a winner
return;
}
}
switch (key)
{
...

OpenGL textures not show

My problem is textures wont work. I put source below.
main.cpp
#include <cstdio>
#include <cstring>
#include <cmath>
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glext.h>
PFNGLACTIVETEXTUREPROC glActiveTexture;
#include "config.h"
#include "camera.cpp"
#include "keyboardControl.cpp"
void *__gxx_personality_v0;
#define win_style WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void EnableOpenGL();
void DisableOpenGL();
void renderframe();
void renderframe2();
void SetDCPixelFormat(HDC hDC);
void Reset();
void InitGL();
void SetRenderMode(int mode);
void InitKeys();
void CameraMove(void*);
void CameraRot(void*);
void sMode(void* data);
void LoadTextures();
HWND hWnd;
HDC hDC;
HGLRC hRC;
config CFG;
bool getFPS = 0;
int lx, ly;
int sx, sy;
bool m = false;
static int keys1[] = { 6, 'W', 'S', 'D', 'A', VK_SPACE, VK_LSHIFT, (int)&CameraMove };
static int keys2[] = { 1, 'Q', (int)&CameraRot };
static int keys3[] = { 3, '1', '2', '3', (int)&sMode };
GLuint texture;
float pixels[] = {
1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f
};
camera cam;
keyboardControl keys;
void LoadTextures() {
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_FLOAT, pixels);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
void sMode(void* data) {
for(int i = 0; i < 3; i++)
{
if( ((int*)data)[i] & 1 )
{
SetRenderMode(i);
return;
}
}
}
void CameraMove(void* data) {
int *bPtr = (int*)data;
double add[3] = { 0, 0, 0 };
for(int x = 0; x < 3; x++)
{
if(bPtr[x*2]) add[x] += 0.1f;
if(bPtr[x*2 + 1]) add[x] -= 0.1f;
}
cam.move(add[0], add[1], add[2]);
}
void CameraRot(void* data) {
if( *((int*)data) & 1 )
{
SetCursorPos(lx, ly);
m = !m;
}
}
void renderframe2() {
static float rot = 0.0f;
glLoadIdentity();
gluLookAt(cam.position[0], cam.position[1], cam.position[2], cam.lookAtPos[0], cam.lookAtPos[1], cam.lookAtPos[2], 0.0f, 0.0f, 1.0f);
glClearColor( 0.4f, 0.4f, 0.6f, 1.0f );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glRotatef(rot/10.0f, 1, 1, 0);
glBegin(GL_LINES);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f( 0.0f, 2.0f, 0.0f);
glVertex3f( 0.0f, -2.0f, 0.0f);
glVertex3f( 2.0f, 0.0f, 0.0f);
glVertex3f( -2.0f, 0.0f, 0.0f);
glVertex3f( 0.0f, 0.0f, 2.0f);
glVertex3f( 0.0f, 0.0f, -2.0f);
glEnd();
glActiveTexture(GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, texture );
glBegin(GL_QUADS);
glColor3f(0.0f,0.0f,1.0f);
glTexCoord2d(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f,-1.0f);
glTexCoord2d(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f,-1.0f);
glTexCoord2d(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2d(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2d(1.0f, 0.0f); glVertex3f( 1.0f,-1.0f, 1.0f);
glTexCoord2d(0.0f, 0.0f); glVertex3f(-1.0f,-1.0f, 1.0f);
glTexCoord2d(0.0f, 1.0f); glVertex3f(-1.0f,-1.0f,-1.0f);
glTexCoord2d(1.0f, 1.0f); glVertex3f( 1.0f,-1.0f,-1.0f);
glColor3f(1.0f,1.0f,1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glColor3f(0.0f,0.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glColor3f(1.0f,1.0f,1.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glColor3f(0.0f,0.0f,0.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glColor3f(1.0f,1.0f,1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glColor3f(0.0f,0.0f,0.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glColor3f(1.0f,1.0f,1.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glColor3f(0.0f,0.0f,0.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glEnd();
glFlush();
SwapBuffers( hDC );
rot += 1.0f;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) {
CFG.resolution[0] = 800;
CFG.resolution[1] = 600;
WNDCLASS wc;
MSG msg;
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
wc.lpszMenuName = NULL;
wc.lpszClassName = "Window1";
RegisterClass( &wc );
int x = 50, y = 50;
RECT wr = { x, y, x + CFG.resolution[0], y + CFG.resolution[1] };
hWnd = CreateWindow(
"Window1", "...",
win_style,
wr.left, wr.top, wr.right-wr.left, wr.bottom-wr.top,
NULL, NULL, hInstance, NULL );
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
double PCFreq = double(li.QuadPart);
double fc = PCFreq/64;
cam.setup(0, -10, 0, 0, 0);
EnableOpenGL();
InitKeys();
glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress ("glActiveTexture");
if(glActiveTexture == NULL)
{
printf("Critical Error 1\n");
return 1;
}
bool bEND = false;
__int64 CounterStart = 0;
__int64 CounterCur = 0;
__int64 CounterMark = 0;
while(!bEND)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)
{
bEND = true;
}
else
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
else
{
QueryPerformanceCounter((LARGE_INTEGER*)&CounterStart);
renderframe2();
keys.a();
QueryPerformanceCounter((LARGE_INTEGER*)&CounterCur);
CounterMark = CounterStart + fc;
while(CounterCur < CounterMark)
{
QueryPerformanceCounter((LARGE_INTEGER*)&CounterCur);
Sleep(1);
}
if(getFPS)
{
getFPS = 0;
printf("%0.2lf fps\n", (double)(1/((double)(CounterCur-CounterStart)/PCFreq)));
}
}
}
DisableOpenGL();
DestroyWindow(hWnd);
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch(message)
{
case WM_MOVE:
{
int xPos = ((__int16*)&lParam)[0];
int yPos = ((__int16*)&lParam)[1];
RECT wr = { xPos, yPos, xPos + CFG.resolution[0], yPos + CFG.resolution[1] };
RECT wr2;
memcpy(&wr2, &wr, sizeof(RECT));
AdjustWindowRect(&wr2, win_style, false);
lx = (CFG.resolution[0] >> 1) + wr2.left;
ly = (CFG.resolution[1] >> 1) + wr2.top;
sx = (CFG.resolution[0] >> 1) - wr2.right + wr.right;
sy = (CFG.resolution[1] >> 1) - wr.top + wr2.top;
} break;
case WM_MOUSEMOVE:
{
if(!m) break;
int xPos = ((__int16*)&lParam)[0];
int yPos = ((__int16*)&lParam)[1];
if(xPos == sx && yPos == sy)
{
break;
}
if(xPos != sx || yPos != sy)
{
int ia = (xPos - sx);
int ib = (sy - yPos);
double a = (ia)?(double)ia / 100:0;
double b = (ib)?(double)ib / 100:0;
cam.moveC(a, b);
}
SetCursorPos(lx, ly);
} break;
case WM_CREATE:
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
switch(wParam)
{
case VK_ESCAPE:
{
PostQuitMessage(0);
return 0;
}
return 0;
}
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
}
void Reset() {
RECT rc;
GetClientRect(hWnd, &rc);
int h = rc.bottom-rc.top;
int w = rc.right-rc.left;
if(!h) h=1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (float)w/(float)h, 1.0f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
};
void EnableOpenGL() {
hDC = GetDC(hWnd);
SetDCPixelFormat( hDC );
hRC = wglCreateContext( hDC );
wglMakeCurrent( hDC, hRC );
Reset();
InitGL();
LoadTextures();
SetRenderMode(2);
}
void DisableOpenGL() {
glDeleteTextures(1, &texture);
wglMakeCurrent( NULL, NULL );
wglDeleteContext( hRC );
ReleaseDC(hWnd, hDC);
}
void SetDCPixelFormat( HDC hDC ) {
INT nPixelFormat;
static PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER | PFD_TYPE_RGBA,
8,
0, 0, 0, 0, 0, 0,
0, 0,
0, 0, 0, 0, 0,
16,
0,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
nPixelFormat = ChoosePixelFormat(hDC, &pfd);
SetPixelFormat(hDC, nPixelFormat, &pfd);
}
void InitGL() {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
void InitKeys() {
keys.Add(keys1);
keys.Add(keys2);
keys.Add(keys3);
}
void SetRenderMode(int mode) {
switch (mode)
{
case 0: glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); break;
case 1:
{
glDisable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}; break;
case 2:
{
glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}; break;
};
};
camera.cpp
#pragma once
#include <cstring>
#include <cmath>
#include <cstdio>
class camera
{
public:
double position[3];
double lookAtPos[3];
private:
int r;
double speed;
double vRad, hRad;
public:
camera();
//~camera();
void setup(double x, double y, double z, double v, double h);
void moveC(double v, double h);
void move(double a, double b, double c);
void debug();
void reset();
};
camera::camera() {
memset(position, 0, sizeof(double)*3);
memset(lookAtPos, 0, sizeof(double)*3);
r = 10;
speed = 0.5f;
vRad = 0;
hRad = 0;
}
void camera::setup(double x, double y, double z, double v, double h) {
position[0] = x;
position[1] = y;
position[2] = z;
vRad = v;
hRad = h;
moveC(0, 0);
}
void camera::move(double a, double b, double c) {
double sv = sin(vRad), cv = cos(vRad);
double sh = sin(hRad), ch = cos(hRad);
if(a)
{
position[0] += ch * sv * a;
position[1] += ch * cv * a;
position[2] += sh * a;
}
if(b)
{
double svb = sin(vRad + 1.57), cvb = cos(vRad + 1.57);
position[0] += svb * b;
position[1] += cvb * b;
}
if(c)
{
position[2] += c;
}
reset();
}
void camera::moveC(double v, double h) {
if(v)
{
vRad += v;
if(vRad > 6.28) vRad -= 6.28;
if(vRad < 0) vRad += 6.28;
}
if(h)
{
hRad += h;
if(hRad > 1.57) hRad = 1.57;
if(hRad < -1.57) hRad = -1.57;
}
reset();
}
void camera::reset() {
double sv = sin(vRad), cv = cos(vRad), sh = sin(hRad), ch = cos(hRad);
lookAtPos[0] = ch * sv * r + position[0];
lookAtPos[1] = ch * cv * r + position[1];
lookAtPos[2] = sh * r + position[2];
}
keyboardControl.cpp
#pragma once
#include <cstdlib>
#include <windows.h>
class keyboardControl {
private:
int count;
int **DATA;
public:
keyboardControl();
~keyboardControl();
void Add(int*);
void a();
};
keyboardControl::keyboardControl() {
DATA = (int**) malloc(256 * 4);
count = 0;
}
keyboardControl::~keyboardControl() {
free(DATA);
}
void keyboardControl::a() {
for(int i = 0; i < count; i++)
{
int t[DATA[i][0]];
bool work = false;
for(int x = 0; x < DATA[i][0]; x++)
{
t[x] = GetAsyncKeyState(DATA[i][x + 1]);
if(t[x]) work = true;
}
if(work)
{
((void (*)(void*))DATA[i][DATA[i][0]+1])(t);
}
}
}
void keyboardControl::Add(int* data) {
DATA[count++] = data;
}
I'm using MinGW and compile.bat
#echo off
erase run.exe
set dir1="%cd%"
cd ../../../MinGW/bin
gcc %dir1%/main.cpp -lwsock32 -lopengl32 -lGdi32 -lglu32 -o %dir1%/run.exe
cd %dir1%
set dir1=
echo =-=
run
#echo on
Enable texturing via glEnable(GL_TEXTURE_2D) before attempting to render textured geometry:
glEnable(GL_TEXTURE_2D); // important!
glActiveTexture(GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, texture );
glBegin(GL_QUADS);
glColor3f(0.0f,0.0f,1.0f);
glTexCoord2d(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f,-1.0f);
...
glBindTexture() alone is necessary but not sufficient.

sfml2 RenderWindow + OpenGL

I'm trying to set up an OpenGL context with sfml2. Everthing worked fine and I was able to draw a triangle. In the next step I want to draw some 2D elements with SFML on top of the GL stuff. So I first changed all "Window" entries to "RenderWindow" to be able to draw something. There arno errors but when I compile the program, but it always crashes before drawing, and I don't know why. With sfml1.6 it worked with a RenderWindow. What makes it crash?
this is my code:
#include <iostream>
#include <glew.h>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
void handleEvents(RenderWindow*);
void fillVBO();
void drawGL();
bool running = true;
GLuint vertexBuffer;
static const GLfloat vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
int main() {
VideoMode mode;
mode.BitsPerPixel = 32;
mode.Width = 1024;
mode.Height = 768;
ContextSettings cs;
cs.AntialiasingLevel = 4;
cs.DepthBits = 32;
cs.StencilBits = 16;
cs.MajorVersion = 3;
cs.MinorVersion = 3;
RenderWindow App(mode, "SFML window", Style::Close|Style::Resize, cs);
cout << "Window OK" << endl;
if(glewInit() != GLEW_OK) {
cout << "Unable it initialize Glew!" << endl;
return -1;
}
else {
cout << "GLEW initialization OK" << endl;
}
glClearColor(0.0f, 0.0f, 0.3f, 0.0f);
fillVBO();
cout << "Fill VBO OK" << endl;
while(running) {
App.SetActive();
handleEvents(&App);
cout << "Handle Events OK" << endl;
drawGL();
cout << "Draw GL OK" << endl;
App.Display();
}
return EXIT_SUCCESS;
}
void handleEvents(RenderWindow* wnd) {
Event ev;
while(wnd->PollEvent(ev)) {
switch(ev.Type) {
case Event::Closed:
running = false;
break;
case Event::KeyPressed:
switch(ev.Key.Code) {
case Keyboard::Escape:
running = false;
break;
default:
break;
}
break;
case Event::Resized:
glViewport(0, 0, ev.Size.Width, ev.Size.Height);
break;
default:
break;
}
}
}
void fillVBO() {
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW);
}
void drawGL() {
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glDisableVertexAttribArray(0);
}
I found help on the sfml forum and thought I should post the solution here.
http://www.sfml-dev.org/forum/viewtopic.php?p=46348#46348
To get rid of this error you have to disable all arrays you don't use with glDisableClientState(). Then everything should work fine.

Why won't my OpenGL draw anything?

I'm working on porting my open source particle engine test from SDL to SDL + OpenGL. I've managed to get it compiling, and running, but the screen stays black no matter what I do.
main.cpp:
#include "glengine.h"
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
//Create a glengine instance
ultragl::glengine *gle = new ultragl::glengine();
if(gle->init())
gle->run();
else
std::cout << "glengine initializiation failed!" << std::endl;
//If we can't initialize, or the lesson has quit we delete the instance
delete gle;
return 0;
};
glengine.h:
//we need to include window first because GLee needs to be included before GL.h
#include "window.h"
#include <math.h> // Math Library Header File
#include <vector>
#include <stdio.h>
using namespace std;
namespace ultragl
{
class glengine
{
protected:
window m_Window; ///< The window for this lesson
unsigned int m_Keys[SDLK_LAST]; ///< Stores keys that are pressed
float piover180;
virtual void draw();
virtual void resize(int x, int y);
virtual bool processEvents();
void controls();
private:
/*
* We need a structure to store our vertices in, otherwise we
* just had a huge bunch of floats in the end
*/
struct Vertex
{
float x, y, z;
Vertex(){}
Vertex(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
};
struct particle
{
public :
double angle;
double speed;
Vertex v;
int r;
int g;
int b;
int a;
particle(double angle, double speed, Vertex v, int r, int g, int b, int a)
{
this->angle = angle;
this->speed = speed;
this->v = v;
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
particle()
{
}
};
particle p[500];
float particlesize;
public:
glengine();
~glengine();
virtual void run();
virtual bool init();
void glengine::test2(int num);
void glengine::update();
};
};
window.h:
#include <string>
#include <iostream>
#include "GLee/GLee.h"
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
#include <GL/glu.h>
using namespace std;
namespace ultragl
{
class window
{
private:
int w_height;
int w_width;
int w_bpp;
bool w_fullscreen;
string w_title;
public:
window();
~window();
bool createWindow(int width, int height, int bpp, bool fullscreen, const string& title);
void setSize(int width, int height);
int getHeight();
int getWidth();
};
};
glengine.cpp (the main one to look at):
#include "glengine.h"
namespace ultragl{
glengine::glengine()
{
piover180 = 0.0174532925f;
}
glengine::~glengine()
{
}
void glengine::resize(int x, int y)
{
std::cout << "Resizing Window to " << x << "x" << y << std::endl;
if (y <= 0)
{
y = 1;
}
glViewport(0,0,x,y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)x/(GLfloat)y,1.0f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
bool glengine::processEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))//get all events
{
switch (event.type)
{
// Quit event
case SDL_QUIT:
{
// Return false because we are quitting.
return false;
}
case SDL_KEYDOWN:
{
SDLKey sym = event.key.keysym.sym;
if(sym == SDLK_ESCAPE) //Quit if escape was pressed
{
return false;
}
m_Keys[sym] = 1;
break;
}
case SDL_KEYUP:
{
SDLKey sym = event.key.keysym.sym;
m_Keys[sym] = 0;
break;
}
case SDL_VIDEORESIZE:
{
//the window has been resized so we need to set up our viewport and projection according to the new size
resize(event.resize.w, event.resize.h);
break;
}
// Default case
default:
{
break;
}
}
}
return true;
}
bool glengine::init()
{
srand( time( NULL ) );
for(int i = 0; i < 500; i++)
p[i] = particle(0, 0, Vertex(0.0f, 0.0f, 0.0f), 0, 0, 0, 0);
if (!m_Window.createWindow(640, 480, 32, false, "Paricle Test GL"))
{
return false;
}
particlesize = 0.01;
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glEnable(GL_BLEND);
glBlendFunc(GL_ONE , GL_ONE_MINUS_SRC_ALPHA);
return true;
}
void glengine::test2(int num)
{
glPushMatrix();
glTranslatef(p[num].v.x, p[num].v.y, p[num].v.z);
glBegin(GL_QUADS);
glColor4i(p[num].r, p[num].g, p[num].b, p[num].a); // Green for x axis
glVertex3f(-particlesize, -particlesize, particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glEnd();
glPopMatrix();
}
void glengine::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
gluLookAt(0, 5, 20, 0, 0, 0, 0, 0, 0);
for(int i = 0; i < 500; i++)
test2(i);
}
void glengine::update()
{
for(int i = 0; i < 500; i++)
{
if(p[i].a <= 0)
p[i] = particle(5 + rand() % 360, (rand() % 10) * 0.1, Vertex(0.0f, 0.0f, 0.0f), 0, 255, 255, 255);
else
p[i].a -= 1;
p[i].v.x += (sin(p[i].angle * (3.14159265/180)) * p[i].speed);
p[i].v.y -= (cos(p[i].angle * (3.14159265/180)) * p[i].speed);
}
}
void glengine::run()
{
while(processEvents())
{
update();
draw();
SDL_GL_SwapBuffers();
}
}
};
And finally window.cpp:
#include "window.h"
namespace ultragl
{
window::window(): w_width(0), w_height(0), w_bpp(0), w_fullscreen(false)
{
}
window::~window()
{
SDL_Quit();
}
bool window::createWindow(int width, int height, int bpp, bool fullscreen, const string& title)
{
if( SDL_Init( SDL_INIT_VIDEO ) != 0 )
return false;
w_height = height;
w_width = width;
w_title = title;
w_fullscreen = fullscreen;
w_bpp = bpp;
//Set lowest possiable values.
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
//Set title.
SDL_WM_SetCaption(title.c_str(), title.c_str());
// Flags tell SDL about the type of window we are creating.
int flags = SDL_OPENGL;
if(fullscreen == true)
flags |= SDL_FULLSCREEN;
// Create window
SDL_Surface * screen = SDL_SetVideoMode( width, height, bpp, flags );
if(screen == 0)
return false;
//SDL doesn't trigger off a ResizeEvent at startup, but as we need this for OpenGL, we do this ourself
SDL_Event resizeEvent;
resizeEvent.type = SDL_VIDEORESIZE;
resizeEvent.resize.w = width;
resizeEvent.resize.h = height;
SDL_PushEvent(&resizeEvent);
return true;
}
void window::setSize(int width, int height)
{
w_height = height;
w_width = width;
}
int window::getHeight()
{
return w_height;
}
int window::getWidth()
{
return w_width;
}
};
Anyway, I really need to finish this, but I've already tried everything I could think of. I tested the glengine file many different ways to where it looked like this at one point:
#include "glengine.h"
#include "SOIL/SOIL.h"
#include "SOIL/stb_image_aug.h"
#include "SOIL/image_helper.h"
#include "SOIL/image_DXT.h"
namespace ultragl{
glengine::glengine()
{
piover180 = 0.0174532925f;
}
glengine::~glengine()
{
}
void glengine::resize(int x, int y)
{
std::cout << "Resizing Window to " << x << "x" << y << std::endl;
if (y <= 0)
{
y = 1;
}
glViewport(0,0,x,y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)x/(GLfloat)y,1.0f,1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
bool glengine::processEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))//get all events
{
switch (event.type)
{
// Quit event
case SDL_QUIT:
{
// Return false because we are quitting.
return false;
}
case SDL_KEYDOWN:
{
SDLKey sym = event.key.keysym.sym;
if(sym == SDLK_ESCAPE) //Quit if escape was pressed
{
return false;
}
m_Keys[sym] = 1;
break;
}
case SDL_KEYUP:
{
SDLKey sym = event.key.keysym.sym;
m_Keys[sym] = 0;
break;
}
case SDL_VIDEORESIZE:
{
//the window has been resized so we need to set up our viewport and projection according to the new size
resize(event.resize.w, event.resize.h);
break;
}
// Default case
default:
{
break;
}
}
}
return true;
}
bool glengine::init()
{
srand( time( NULL ) );
for(int i = 0; i < 500; i++)
p[i] = particle(0, 0, Vertex(0.0f, 0.0f, 0.0f), 0, 0, 0, 0);
if (!m_Window.createWindow(640, 480, 32, false, "Paricle Test GL"))
{
return false;
}
particlesize = 10.01;
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glEnable(GL_BLEND);
glBlendFunc(GL_ONE , GL_ONE_MINUS_SRC_ALPHA);
return true;
}
void glengine::test2(int num)
{
//glPushMatrix();
//glTranslatef(p[num].v.x, p[num].v.y, p[num].v.z);
glColor4i(255, 255, 255, 255);
glBegin(GL_QUADS);
glNormal3f( 0.0f, 0.0f, 1.0f);
glVertex3f(-particlesize, -particlesize, particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glEnd();
// Back Face
glBegin(GL_QUADS);
glNormal3f( 0.0f, 0.0f,-1.0f);
glVertex3f(-particlesize, -particlesize, -particlesize);
glVertex3f(-particlesize, particlesize, -particlesize);
glVertex3f( particlesize, particlesize, -particlesize);
glVertex3f( particlesize, -particlesize, -particlesize);
glEnd();
// Top Face
glBegin(GL_QUADS);
glNormal3f( 0.0f, 1.0f, 0.0f);
glVertex3f(-particlesize, particlesize, -particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f( particlesize, particlesize, -particlesize);
glEnd();
// Bottom Face
glBegin(GL_QUADS);
glNormal3f( 0.0f,-1.0f, 0.0f);
glVertex3f(-particlesize, -particlesize, -particlesize);
glVertex3f( particlesize, -particlesize, -particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glVertex3f(-particlesize, -particlesize, particlesize);
glEnd();
// Right face
glBegin(GL_QUADS);
glNormal3f( 1.0f, 0.0f, 0.0f);
glVertex3f( particlesize, -particlesize, -particlesize);
glVertex3f( particlesize, particlesize, -particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glEnd();
// Left Face
glBegin(GL_QUADS);
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(-particlesize, -particlesize, -particlesize);
glVertex3f(-particlesize, -particlesize, particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glVertex3f(-particlesize, particlesize, -particlesize);
glEnd();
//glPopMatrix();
}
void glengine::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
gluLookAt(0, 5, 20, 0, 0, 0, 0, 1, 0);
for(int i = 0; i < 500; i++)
test2(i);
}
void glengine::update()
{
for(int i = 0; i < 500; i++)
{
if(p[i].a <= 0)
p[i] = particle(5 + rand() % 360, (rand() % 10) * 0.1, Vertex(0.0f, 0.0f, -5.0f), 0, 255, 255, 255);
else
p[i].a -= 1;
p[i].v.x += (sin(p[i].angle * (3.14159265/180)) * p[i].speed);
p[i].v.y -= (cos(p[i].angle * (3.14159265/180)) * p[i].speed);
}
}
void glengine::run()
{
while(processEvents())
{
update();
draw();
SDL_GL_SwapBuffers();
}
}
};
It still didn't work. I'm really at my wits end on this one.
I haven't checked your code, but one thing I always do when debugging this kind of problems is to set the clear color to something colorful like (1, 0, 1) or so.
This will help you see if the problem is that your drawn object is completely black or if it's not drawn at all.
EDIT:
As someone mentioned in the comment: It also shows if you have a correct GL context if the clear operation clears to the right color or if it stays black.
Okay, I managed to fix it using a lot of your suggestions, and some other source code I had laying around. Turns out the problem was from 3 different lines.
particlesize = 0.01; should have been bigger: particlesize = 1.01;
glColor4i(255, 255, 255, 255) was turning the cube the same color as the clear color because I was using it wrong. I couldn't figure out how to use it right, so I'm using glColor4f(0.0f,1.0f,1.0f,0.5f) instead, and that works.
Last of all gluLookAt(0, 5, 20, 0, 0, 0, 0, 0, 0) needed to be gluLookAt(0, 5, 20, 0, 0, 0, 0, 1, 0)
Thank you all for your help, and your time.
You're not checking the return values of the SDL-GL-SetAttribute() calls.
And is 5/5/5/5 20-bpp color supported by your video card?
Check OpenGL for error states. Use glslDevil, glIntercept or gDebugger. Check the glGetError function. Can you test whether SDL actually acquired a device context?
Does the Window reflect changes in the glClearColor call? Don't use 0.5 as an alpha value in glClearColor.
Try these suggestions and report back with a minimal example as Simucal suggested.