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)
{
...
Related
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
I need help in understanding how to scale my coordinates. The instruction says, modify the code to move the triangle to the mouse click position. Can someone explain how this is done?
Here is the source code I'm working with:
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stddef.h>
#include <iostream>
// values controlled by fast keys
float g_angle = 0.0f;
float g_xoffset = 0.0f;
float g_yoffset = 0.0f;
int x;
int y;
// increments
const float g_angle_step = 32.0f; // degrees
const float g_offset_step = 32.0f; // world coord units
// last cursor click
int g_cursor_x = 0;
int g_cursor_y = 0;
void draw_triangle()
{
// in model cooridnates centred at (0,0)
static float vertex[3][2] =
{
{-1.0f, -1.0f},
{1.0f, -1.0f},
{0.0f, 1.0f}
};
glBegin(GL_LINE_LOOP);
for (size_t i=0;i<3;i++)
glVertex2fv(vertex[i]);
glEnd();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
glLineWidth(2.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(500.0f+g_xoffset, 500.0f+g_yoffset, 0.0f);
glScalef(100.0f, 100.0f, 1.0f);
glRotatef(g_angle, 0.0f, 0.0f, 1.0f);
draw_triangle();
glPopMatrix(); // done with stack
glutSwapBuffers();
}
// handles mouse click events
// button will say which button is presed, e.g. GLUT_LEFT_BUTTON, GLUT_RIGHT_BUTTON
// state will say if the button is GLUT_UP or GLUT_DOWN
// x and y are the poitner position
void mouse_click(int button, int state, int x, int y)
{
if (button==GLUT_LEFT_BUTTON)
{
std::cerr << "\t left mouse button pressed!" << std::endl;
if (state==GLUT_UP)
{
std::cerr << "\t button released...click finished" << std::endl;
g_cursor_x = x;
g_cursor_y = y;
std::cerr << "\t cursor at (" << g_cursor_x << ", " <<
g_cursor_y << ")" << std::endl;
}
}
else
if (button==GLUT_RIGHT_BUTTON)
{
std::cerr << "\t right mouse button pressed!" << std::endl;
}
// Here is my attempt:
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
float x_min = (-x+500)/512;
float x_max = (x-500)/512;
float y_min = (-y+500)/512;
float y_max = (y-500)/512;
gluOrtho2D(x_min, x_max, y_min, y_max);
//glTranslatef(x/512, 1-y/512, 0.0f);
std::cerr << x << ", " << y << std::endl;
}
glutPostRedisplay();
}
void mouse_motion(int x, int y)
{
std::cerr << "\t mouse is at (" << x << ", " << y << ")" << std::endl;
glutPostRedisplay();
}
// will get which key was pressed and x and y positions if required
void keyboard(unsigned char key, int, int)
{
std::cerr << "\t you pressed the " << key << " key" << std::endl;
switch (key)
{
case 'q': exit(1); // quit!
// clockwise rotate
case 'r': g_angle += g_angle_step; break;
}
glutPostRedisplay(); // force a redraw
}
// any special key pressed like arrow keys
void special(int key, int, int)
{
// handle special keys
switch (key)
{
case GLUT_KEY_LEFT: g_xoffset -= g_offset_step; break;
case GLUT_KEY_RIGHT: g_xoffset += g_offset_step; break;
case GLUT_KEY_UP: g_yoffset += g_offset_step; break;
case GLUT_KEY_DOWN: g_yoffset -= g_offset_step; break;
}
glutPostRedisplay(); // force a redraw
}
void init()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 1000, 0, 1000);
glClearColor(0.0f, 0.0f, 1.0f, 0.0f);
g_cursor_x = g_cursor_y = 500; // middle of window
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(512, 512);
glutInitWindowPosition(50, 50);
glutCreateWindow("Mouse Test");
glutDisplayFunc(display);
// handlers for keyboard input
glutKeyboardFunc(keyboard);
glutSpecialFunc(special);
// mouse event handlers
glutMouseFunc(mouse_click);
glutPassiveMotionFunc(mouse_motion);
init();
glutMainLoop();
return 0;
}
This should solve your issue.replace your code(your attempt) with the code below.
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
g_xoffset = x;
g_yoffset = 1000-y;
} glutPostRedisplay();
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.
This is basic question about lighting and texturing in OpenGL. I tried to apply a texture in pure OpenGL app, unfortunately, the color is different from the texture. Here is the texture:
and here is what i got after applying the texture:
I used Videotutorialrocks BMP Loader. This coloring problem does not exist if i use their BMP file (i.e. the color is the same as the texture file).
Here's the code:
#include <windows.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "imageloader.h"
using std::stringstream;
using std::cout;
using std::endl;
using std::ends;
using namespace std;
float lpos[4] = {1.0,0.0,0.0,0.0};
void *font = GLUT_BITMAP_8_BY_13;
float color[4] = {0.0, 1.0, 0.0, 1.0};
GLuint _textureId; //The id of the texture
float a = 0;
float eye_x = 5.0;
float eye_y = 5.0;
float eye_z = 5.0;
//Makes the image into a texture, and returns the id of the texture
GLuint loadTexture(Image* image) {
GLuint textureId;
glGenTextures(1, &textureId); //Make room for our texture
glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
//Map the image to the texture
glTexImage2D(GL_TEXTURE_2D, //Always GL_TEXTURE_2D
0, //0 for now
GL_RGB, //Format OpenGL uses for image
image->width, image->height, //Width and height
0, //The border of the image
GL_RGB, //GL_RGB, because pixels are stored in RGB format
GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
//as unsigned numbers
image->pixels); //The actual pixel data
return textureId; //Returns the id of the texture
}
// write 2d text using GLUT
// The projection matrix must be set to orthogonal before call this function.
void drawString(const char *str, int x, int y, float color[4], void *font)
{
glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask
glDisable(GL_LIGHTING); // need to disable lighting for proper text color
glColor4fv(color); // set text color
glRasterPos2i(x, y); // place text position
// loop all characters in the string
while(*str)
{
glutBitmapCharacter(font, *str);
++str;
}
glEnable(GL_LIGHTING);
glPopAttrib();
}
void changeSize(int w, int h) {
// Prevent a divide by zero, when window is too short. (you cant make a window of zero width).
if(h == 0)
h = 1;
float ratio = 1.0* w / h;
// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(45,ratio,1,100);
glMatrixMode(GL_MODELVIEW);
}
void initRendering(){
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
Image* image = loadBMP("vtr_6.bmp");
_textureId = loadTexture(image);
delete image;
}
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Add ambient light
//GLfloat ambientColor[] = {0.4f, 0.2f, 0.2f, 1.0f}; //Color(0.2, 0.2, 0.2)
GLfloat ambientColor[] = {1.0f, 1.0f, 1.0f, 1.0f}; //Color(0.2, 0.2, 0.2)
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
//Add positioned light
//GLfloat lightColor0[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Color (0.5, 0.5, 0.5)
GLfloat lightColor0[] = {1.0f, 1.0f, 1.0f, 1.0f}; //Color (0.5, 0.5, 0.5)
GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 1.0f}; //Positioned at (4, 0, 8)
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
//Add directed light
//GLfloat lightColor1[] = {0.7f, 0.2f, 0.1f, 1.0f}; //Color (0.5, 0.2, 0.2)
GLfloat lightColor1[] = {1.0f, 1.0f, 1.0f, 1.0f};
//Coming from the direction (-1, 0.5, 0.5)
GLfloat lightPos1[] = {1.0f, 0.5f, 0.5f, 0.0f};
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, _textureId);
//Bottom
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
gluLookAt(eye_x,eye_y,eye_z,
0.0,0.0,0.0,
0.0f,1.0f,0.0f);
stringstream ss;
ss << std::fixed << std::setprecision(2);
ss << "Eye Position : x,y,z = (" << eye_x << ", " << eye_y << ", " << eye_z << ")" << ends;
drawString(ss.str().c_str(), -6, 1, color, font);
ss.str("");
glRotatef(a,0,1,0);
glutSolidTeapot(2);
glDisable(GL_TEXTURE_2D);
a+=0.1;
glutSwapBuffers();
}
void processNormalKeys(unsigned char key, int x, int y) {
switch ( key )
{
case 27:
exit(0);
break;
case '1':
eye_x += 0.1;
break;
case '2':
eye_x -= 0.1;
break;
case '3' :
eye_y += 0.1;
break;
case '4' :
eye_y -= 0.1;
break;
case '5':
eye_z += 0.1;;
break;
case '6':
eye_z -= 0.1;
break;
case '0':
eye_x = 5.0;
eye_y = 5.0;
eye_z = 5.0;
break;
}
}
#define printOpenGLError() printOglError(__FILE__, __LINE__)
int printOglError(char *file, int line)
{
GLenum glErr;
int retCode = 0;
glErr = glGetError();
while (glErr != GL_NO_ERROR)
{
printf("glError in file %s # line %d: %s\n", file, line, gluErrorString(glErr));
retCode = 1;
glErr = glGetError();
}
return retCode;
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(800,600);
glutCreateWindow("OpenGL Teapot w/ lighting");
initRendering();
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutKeyboardFunc(processNormalKeys);
glutIdleFunc(renderScene);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
return 0;
}
Here is the code for Image Loader:
#include <assert.h>
#include <fstream>
#include "imageloader.h"
using namespace std;
Image::Image(char* ps, int w, int h) : pixels(ps), width(w), height(h) {
}
Image::~Image() {
delete[] pixels;
}
namespace {
//Converts a four-character array to an integer, using little-endian form
int toInt(const char* bytes) {
return (int)(((unsigned char)bytes[3] << 24) |
((unsigned char)bytes[2] << 16) |
((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
//Converts a two-character array to a short, using little-endian form
short toShort(const char* bytes) {
return (short)(((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
//Reads the next four bytes as an integer, using little-endian form
int readInt(ifstream &input) {
char buffer[4];
input.read(buffer, 4);
return toInt(buffer);
}
//Reads the next two bytes as a short, using little-endian form
short readShort(ifstream &input) {
char buffer[2];
input.read(buffer, 2);
return toShort(buffer);
}
//Just like auto_ptr, but for arrays
template<class T>
class auto_array {
private:
T* array;
mutable bool isReleased;
public:
explicit auto_array(T* array_ = NULL) :
array(array_), isReleased(false) {
}
auto_array(const auto_array<T> &aarray) {
array = aarray.array;
isReleased = aarray.isReleased;
aarray.isReleased = true;
}
~auto_array() {
if (!isReleased && array != NULL) {
delete[] array;
}
}
T* get() const {
return array;
}
T &operator*() const {
return *array;
}
void operator=(const auto_array<T> &aarray) {
if (!isReleased && array != NULL) {
delete[] array;
}
array = aarray.array;
isReleased = aarray.isReleased;
aarray.isReleased = true;
}
T* operator->() const {
return array;
}
T* release() {
isReleased = true;
return array;
}
void reset(T* array_ = NULL) {
if (!isReleased && array != NULL) {
delete[] array;
}
array = array_;
}
T* operator+(int i) {
return array + i;
}
T &operator[](int i) {
return array[i];
}
};
}
Image* loadBMP(const char* filename) {
ifstream input;
input.open(filename, ifstream::binary);
assert(!input.fail() || !"Could not find file");
char buffer[2];
input.read(buffer, 2);
assert(buffer[0] == 'B' && buffer[1] == 'M' || !"Not a bitmap file");
input.ignore(8);
int dataOffset = readInt(input);
//Read the header
int headerSize = readInt(input);
int width;
int height;
switch(headerSize) {
case 40:
//V3
width = readInt(input);
height = readInt(input);
input.ignore(2);
assert(readShort(input) == 24 || !"Image is not 24 bits per pixel");
assert(readShort(input) == 0 || !"Image is compressed");
break;
case 12:
//OS/2 V1
width = readShort(input);
height = readShort(input);
input.ignore(2);
assert(readShort(input) == 24 || !"Image is not 24 bits per pixel");
break;
case 64:
//OS/2 V2
assert(!"Can't load OS/2 V2 bitmaps");
break;
case 108:
//Windows V4
assert(!"Can't load Windows V4 bitmaps");
break;
case 124:
//Windows V5
assert(!"Can't load Windows V5 bitmaps");
break;
default:
assert(!"Unknown bitmap format");
}
//Read the data
int bytesPerRow = ((width * 3 + 3) / 4) * 4 - (width * 3 % 4);
int size = bytesPerRow * height;
auto_array<char> pixels(new char[size]);
input.seekg(dataOffset, ios_base::beg);
input.read(pixels.get(), size);
//Get the data into the right format
auto_array<char> pixels2(new char[width * height * 3]);
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
for(int c = 0; c < 3; c++) {
pixels2[3 * (width * y + x) + c] =
pixels[bytesPerRow * y + 3 * x + (2 - c)];
}
}
}
input.close();
return new Image(pixels2.release(), width, height);
}
And this is the header file:
#ifndef IMAGE_LOADER_H_INCLUDED
#define IMAGE_LOADER_H_INCLUDED
//Represents an image
class Image {
public:
Image(char* ps, int w, int h);
~Image();
/* An array of the form (R1, G1, B1, R2, G2, B2, ...) indicating the
* color of each pixel in image. Color components range from 0 to 255.
* The array starts the bottom-left pixel, then moves right to the end
* of the row, then moves up to the next column, and so on. This is the
* format in which OpenGL likes images.
*/
char* pixels;
int width;
int height;
};
//Reads a bitmap image from file.
Image* loadBMP(const char* filename);
#endif
I have tried to replace the file format for glTexImage2D with GL_BGR_EXT, but no result. Is there any way to correct the texture?
Perhaps your image has an alpha channel, which requires GL_RGBA, not GL_RGB.
Try opening your texture with some sort of image editing software (gimp, photoshop, etc), and save it as a BMP with 24 color bits (I think: 8 for each r/b/g), and just make sure all of the BMP settings are correct. It definitely looks like it's a problem with the format of your texture. There are multiple BMP formats.
See what happens when you disable lighting.
Also this page suggests you should use:
glFrontFace(GL_CW);
glutSolidTeapot(size);
glFrontFace(GL_CCW);
http://pyopengl.sourceforge.net/documentation/manual/glutSolidTeapot.3GLUT.html
In the loadTexture function, in glTexImage2D change the second(format) GL_RGB to GL_BGR.
If you try loading PNG image file, add the alpha, too.
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.