OpenGL + GLU + C++ not drawing anything - c++

I'm really pulling my hair out with this problem. I'm trying to create a simple game where the player rolls a ball around a playing area.
I'm using WinAPI for window management and input handling.
I tried to render some simple quads too, instead of the GLU sphere, but that didn't work either.
I've separated the code across different classes. I present the relevant code below. This code is in my WinMain:
while (running) {
PeekMessage(&msg, hwnd, NULL, NULL, PM_REMOVE);
if (msg.message == WM_QUIT)
running = false;
else {
// handle key presses
// update
gameWorld->update(getDirections());
// render
gameWorld->render(deviceContext);
// I added this block of code for testing, still does not work
glColor4f(1, 1, 1, 1);
glBegin(GL_QUADS);
glVertex3f(10, 10, 0);
glVertex3f(10, -10, 0);
glVertex3f(-10, -10, 0);
glVertex3f(-10, 10, 0);
glEnd();
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Here's GameWorld.cpp:
GameWorld::GameWorld()
{
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
this->ball = new Ball(1, 10, 10);
this->camera = new Camera(ball);
}
GameWorld::~GameWorld()
{
delete this->ball;
}
void GameWorld::render(HDC deviceContext) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
this->ball->draw();
SwapBuffers(deviceContext);
}
void GameWorld::update(Directions dirs) {
glLoadIdentity();
this->ball->handleInput(dirs);
this->ball->update();
this->camera->update();
}
Here's Camera update method:
void Camera::update() {
GLdouble ballX = ball->getLocation()->getX();
GLdouble ballY = ball->getLocation()->getY();
GLdouble ballZ = ball->getLocation()->getZ();
GLdouble x = ballX + cos(90) * this->distanceFromBall;
GLdouble y = ballY + cos(90) * this->distanceFromBall;
GLdouble z = ballZ + cos(90) * this->distanceFromBall;
gluLookAt(
x, y, z,
ballX, ballY, ballZ,
0, 1, 0
);
}
Here's the Ball draw method:
void Ball::draw() {
glPushMatrix();
this->quadric = gluNewQuadric();
glTranslated(this->location->getX(), this->location->getY(), this->location->getZ());
gluQuadricDrawStyle(this->quadric, GLU_FILL);
glColor4f(1, 1, 1, 1);
gluSphere(this->quadric, this->radius, this->slices, this->stacks);
gluDeleteQuadric(this->quadric);
glPopMatrix();
}
What the #!#% is wrong with this code? I should get this thing done in a week, so I really could use some help...

I had to use the gluPerspective() function to make this work. My GameWorld constructor now looks like this:
GameWorld::GameWorld()
{
glViewport(0, 0, WIDTH, HEIGHT); // reset the viewport to new dimensions
glMatrixMode(GL_PROJECTION); // set projection matrix current matrix
glLoadIdentity(); // reset projection matrix
// calculate aspect ratio of window
gluPerspective(54.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW); // set modelview matrix
glLoadIdentity();
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
this->ball = new Ball(1, 20, 20);
this->camera = new Camera(ball);
}
The code is copied from the sample code of Dave Astle's book "OpenGL Game Programming".

Related

gluLookAt() has no effect in OpenGL

I'm trying to look at the square from the other side using the gluLookAt() function.
After using the function, nothing changes, although I expected that the corners of the square will change.
I set the camera point to the rightmost part of the world and look at its center, where the square is located.
He had to stretch out to the sides. Why hasn't anything changed?
Code:
#include "includes.h"
using namespace std;
constexpr auto FPS_RATE = 60;
int windowHeight = 600, windowWidth = 600, windowDepth = 600;
void init();
void idleFunction();
void displayFunction();
double getTime();
double getTime()
{
using Duration = std::chrono::duration<double>;
return std::chrono::duration_cast<Duration>(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count();
}
const double frame_delay = 1.0 / FPS_RATE;
double last_render = 0;
void init()
{
glutDisplayFunc(displayFunction);
glutIdleFunc(idleFunction);
glViewport(0, 0, windowWidth, windowHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-windowWidth / 2, windowWidth / 2, -windowHeight / 2, windowHeight / 2, -windowDepth / 2, windowDepth / 2);
glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
}
void idleFunction()
{
const double current_time = getTime();
if ((current_time - last_render) > frame_delay)
{
last_render = current_time;
glutPostRedisplay();
}
}
void displayFunction()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_POLYGON);
gluLookAt(-300, 0, 0,
0, 0, 0,
0, 1, 0);
glColor3f(1, 1, 1);
glVertex3i(-150, 150, 0);
glVertex3i(150, 150, 0);
glVertex3i(150, -150, 0);
glVertex3i(-150, -150, 0);
glEnd();
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition((GetSystemMetrics(SM_CXSCREEN) - windowWidth) / 2, (GetSystemMetrics(SM_CYSCREEN) - windowHeight) / 2);
glutCreateWindow("Window");
init();
glutMainLoop();
return 0;
}
The issue is caused because gluLookAt() is call with in a glBegin/glEnd sequence. This is not allowed. You've to call gluLookAt before glBegin.
Once drawing of primitives was started by glBegin it is only allowed to specify vertex coordinates (glVertex) and change attributes (e.g. glColor, glTexCoord ...), till the drawn is ended (glEnd).
All other instruction will be ignored and cause a GL_INVALID_OPERATION error (error code 1282).
Further note, that glLookAt doesn't set a the current matrix. It defines a matrix and multiplies the current matrix by the new matrix. Set the matrix mode (glMatrixMode) and set Identity matrix by glLoadIdentity before gluLookAt.
With the view matrix
gluLookAt(-300, 0, 0, 0, 0, 0, 0, 1, 0);
you want "see" anything, because with that matrix the line of sight is set along the x-axis and you look at the 2 dimensional polygon from the side.
Note, the polygon is a 2D object. The size of the object appears different if you look at it from the front, from the side (then it is a line and not visible) or from an direction in between. The first 3 parameters of gluLookAt define the point of view the next 3 parameters define the point you look at. The vector from the point of view to the point you look at is the line of sight.
Probably yo want look along the z-axis:
void displayFunction()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, -300, 0, 0, 0, 0, 1, 0);
glBegin(GL_POLYGON);
glColor3f(1, 1, 1);
glVertex3i(-150, 150, 0);
glVertex3i(150, 150, 0);
glVertex3i(150, -150, 0);
glVertex3i(-150, -150, 0);
glEnd();
glutSwapBuffers();
}
You use Orthographic (parallel) projection. If you would use Perspective projection, then the projected size of the object would decrease, when the distance to the point of view increases. Perspective projection can be set by gluPerspective. e.g.:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.0, (double)windowWidth / windowHeight, 0.1, 600.0);

OpenGL - wrong objects positioning - gluLookAt()

I've got a taks from university and have to make a small example of solar system, the objects have to rotate etc. The problem is that when I do not call GluLookAt() everything looks fine, but I would like to change the view and when I call the function, there occurs that one orbit renders completely strangely.
I do not know if problem is with wrong creation of the first orbit, or with the proper values in gluLookAt parameters. Can anyone help?
Here's how it looks without calling gluLookAt():
Here's how it looks after gluLookAt():
Here's the code:
#include "stdafx.h"
#include <GL\glut.h>
#include <math.h>
GLfloat yRotated=1;
GLfloat movement = 0;
void drawCircle(float r) { // radius
glBegin(GL_LINE_LOOP);
for (int i = 0; i <= 300; i++) {
double angle = 2 * 3.14 * i / 300;
double x = r*cos(angle);
double y = r*sin(angle);
glVertex3d(x, y, -5.5);
}
glEnd();
}
void display(void) {
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
//gluLookAt(5, 5, 5, 0, 0, -8, 0, 1, 0); // 3rd coordinate - depth
float radius1 = 6;
float radius2 = 1;
//first orbit
glColor3f(1, 1, 1);
glPushMatrix();
glTranslatef(0, 0, -5.5);
drawCircle(radius1);
glPopMatrix();
//second orbit with rotation
glPushMatrix();
glRotatef(yRotated, 0, 0, 1);
glPushMatrix();
glTranslatef(radius1 / 2, 0, 0);
drawCircle(radius2);
glPopMatrix();
glPopMatrix();
//first czajnik
glColor3f(0.8, 0.2, 0.1);
glPushMatrix();
glTranslatef(0.0, 0.0, -5.5);
// glScalef(1.0, 1.0, 1.0);
glRotatef(yRotated, 0, 0, 1);
glRotatef(90, 1, 0, 0);
glutSolidSphere(1,20,20);
//second czajnik
glPushMatrix();
glColor3f(0, 0, 1);
glTranslatef(radius1/2, 0, 0);
glRotatef(yRotated, 0, 1, 0);
glutSolidSphere(0.5, 20, 20);
//third czajnik
glPushMatrix();
glTranslatef(radius2, 0, 0);
glColor3f(1, 1, 0);
glRotatef(yRotated, 0, 1, 0);
glutSolidSphere(0.2, 20, 20);
glPopMatrix();
//second czajnik pop
glPopMatrix();
//first czajnik pop
glPopMatrix();
glFlush();
}
void idle() {
yRotated += 0.1;
Sleep(2);
display();
}
void myReshape(int w, int h) {
if (w == 0 || h == 0) return;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(70.0, (GLdouble)w / (GLdouble)h, 0.5, 20.0);
glViewport(0, 0, w, h);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(900, 600);
glutCreateWindow("Solar system");
//window with a title
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glClearColor(0, 0, 0, 1.0);
glutDisplayFunc(display);
glutReshapeFunc(myReshape);
glutIdleFunc(idle);
glutMainLoop();
return 0;
}
Some of your objects are at different z values, e.g. 1st orbit at -5.5, second at 0, because you "popped" the matrix.
In general, do not do so many push\pops nested into each other, matrix stack isn't made of rubber.
There is more efficient circle drawing procedure than to calculate sine and cosine for each step, e.g. to get advantage of circle being a figure of rotation:
inline void circle(F32 r, U32 quality)
{
if (r < F_ALMOST_ZERO) return;
F32 th = M_PI /(quality-1);
F32 s = sinf(th);
F32 c = cosf(th);
F32 t;
F32 x = r;
F32 y = 0;
::glBegin (GL_LINE_LOOP);
for(U32 i = 0; i < quality; i++)
{
glVertex2f(x, y);
t = x;
x = c*x + s*y;
y = -s*t + c*y;
}
::glEnd();
}
it can be optimized further by using symmetry, but this one is the basis.

How to replace 'gluOrtho2d' in a Qt app

I am working on bring back to life a program I wrote seven years ago. It is all written in Qt and uses some OpenGL to draw some frame lines on an image that the application is displaying. The problem is that 'gluOrtho2D' is used but is no longer found. I am wondering how I can get around the problem. Here is the code:
void MSContext::ResizePaint(int width, int height)
{
// setup viewport, projection etc.:
glViewport(0, 0, (GLint)width, (GLint)height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble) width, 0.0, (GLdouble) height);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.5, 0.5, 0.5, 1.0);
glShadeModel(GL_FLAT);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
CreatePrintCropMarks();
}
void MSContext::CreatePrintCropMarks()
{
GLuint print45CropId = openGLListMgr()->print45CropId();
glNewList( print45CropId, GL_COMPILE);
{
qreal lineSize = 4.0;
// Shrink down the canvas by 4 pixels so that the crop will show up
const QRectF& viewPort = primaryCanvas()->imageView()->viewRectangle();
QRectF shrunkingCanvas = viewPort.adjusted(lineSize, lineSize, -lineSize, -lineSize);
QRectF print45Crop = GetCropRect(shrunkingCanvas, 5, 4);
QRectF print57Crop = GetCropRect(print45Crop, 7, 5);
glLineWidth(lineSize / 2);
glLineStipple(1,0xFF00);
DrawBox(print57Crop);
glLineWidth(lineSize);
glLineStipple(1,0xFFFF);
DrawBox(print45Crop);
}
glEndList();
}
At the back of my head, I was wondering why I'd never heard of this function... turns out there is a fine alternative in (old-school) OpenGL. From the SGI GLU implementation:
void GLAPIENTRY
gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top)
{
glOrtho(left, right, bottom, top, -1, 1);
}
So you can write:
glOrtho(0.0, (GLdouble) width, 0.0, (GLdouble) height, -1, 1);

Move 2D Object to a Point in OpenGL

How to move a 2D object in the direction of a point (not a GL_POINTS, but coordinates) using OpenGL?
For a better understanding of my code:
I've splited most of my code into different source codes, but this is the one that is actually creating the shapes and setting the scene:
void setupScene(int clearColor[]) {
glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
//glClearColor(250, 250, 250, 1.0); // Set the cleared screen colour to black.
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // This sets up the viewport so that the coordinates (0, 0) are at the top left of the window.
// Set up the orthographic projection so that coordinates (0, 0) are in the top left.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, -10, 10);
// Back to the modelview so we can draw stuff.
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen and depth buffer.
}
void drawScene() {
setupScene((int[]){250, 250, 250, 1});
triangle(210, WINDOW_WIDTH, WINDOW_HEIGHT);
glBegin(GL_QUADS);
glColor3f(RGB(80), RGB(80), RGB(80));
glPushMatrix();
glTranslatef(400, 400, 0);
glVertex2d(200, 100);
glVertex2d(100, 100);
glVertex2d(100, 200);
glVertex2d(200, 200);
glPopMatrix();
glEnd();
glutSwapBuffers(); // Send the scene to the screen.
}
void update(int value) {
glutPostRedisplay(); // Tell GLUT that the display has changed.
glutTimerFunc(25, update, 0); // Tell GLUT to call update again in 25 milliseconds.
}
You need to translate the modelview matrix. Assuming you're in modelview mode already:
glPushMatrix();
glTranslatef(x, y, z);
// Draw your shape
glPopMatrix();
[Edit]
#paddy: Something like this? I tried this but the square isn't moving.
pastebin.com/2PCsy5kC
Try explicitly selecting the modelview matrix. Your example does not tell us which mode it's currently in:
glSetMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x, y, z);
// Draw your shape
glPopMatrix();
Normally at the beginning of your render you reset everything... So you enter the GL_PROJECTION mode, call glLoadIdentity() to reset it and set up your camera, then do this for the GL_MODELVIEW matrix as well.
Answer on the behalf of the OP:
Thanks #paddy, I was trying to understand the use of glTranslatef and came with the solution. Here is the working code, it will create a square at 100x100 and will move it until 400x200:
void setupScene(int clearColor[]) {
glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
//glClearColor(250, 250, 250, 1.0); // Set the cleared screen colour to black.
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // This sets up the viewport so that the coordinates (0, 0) are at the top left of the window.
// Set up the orthographic projection so that coordinates (0, 0) are in the top left.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, -10, 10);
// Back to the modelview so we can draw stuff.
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen and depth buffer.
}
int a = 100;
int b = 200;
int x = 100;
int y = 100;
void drawScene() {
setupScene((int[]){250, 250, 250, 1});
triangle(210, WINDOW_WIDTH, WINDOW_HEIGHT);
glPushMatrix();
glTranslatef(x, y, 0);
glBegin(GL_QUADS);
glColor3f(RGB(80), RGB(80), RGB(80));
glVertex2d(b, a);
glVertex2d(a, a);
glVertex2d(a, b);
glVertex2d(b, b);
glEnd();
glPopMatrix();
glutSwapBuffers(); // Send the scene to the screen.
}
void update(int value) {
if (x != 400 && y != 200) {
x += 4;
y += 2;
}
glutPostRedisplay(); // Tell GLUT that the display has changed.
glutTimerFunc(25, update, 0); // Tell GLUT to call update again in 25 milliseconds.
}

gluLookAt trouble

I have some code which draws a line along the x, y and z axes. My problem is that these lines are being clipped so that they are invisible near the origin:
This sounds like a far clipping plane issue, but I gave zFar=50 to gluPerspective, which should be plenty. Making it even larger doesn't seem to help. What else could be causing the clipping?
Here is my code:
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.opengl.*;
import org.lwjgl.util.glu.GLU;
public class Test {
static int width = 300, height = 200;
public static void main(String[] _) throws Exception {
Display.setDisplayMode(new DisplayMode(width, height));
Display.create();
glClear(GL_COLOR_BUFFER_BIT);
// projection matrix
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
GLU.gluPerspective(50, width / (float) height, .1f, 50);
// modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
GLU.gluLookAt(
.8f, .8f, .8f,
0, 0, 0,
0, 1, 0);
// draw a line for each axis
glBegin(GL_LINES);
// x axis in red
glColor3f(1, 0, 0);
glVertex3i(0, 0, 0);
glVertex3i(10, 0, 0);
// y axis in green
glColor3f(0, 1, 0);
glVertex3i(0, 0, 0);
glVertex3i(0, 10, 0);
// z axis in blue
glColor3f(0, 0, 1);
glVertex3i(0, 0, 0);
glVertex3i(0, 0, 10);
glEnd();
Display.update();
// wait for a close event
while (!Display.isCloseRequested()) {
Thread.sleep(20);
Display.processMessages();
}
Display.destroy();
}
}
Update - Removing glLoadIdentity(); after glMatrixMode(GL_MODELVIEW); gives the desired result, but I don't understand why. Isn't the default modelview matrix the identity matrix?
Update - I wrote a C version of the same code and it works as desired. Why the difference?
Indeed, after testing it, it turns out that glMatrixMode(GL_PROJECTION_MATRIX); should be glMatrixMode(GL_PROJECTION); instead.
So it seems that the modelview was active by default and glLoadIdentity() cleared the results of GLU.gluPerspective(50, width / (float) height, .1f, 50);
edit: Btw. in case you wonder what GL_PROJECTION_MATRIX is for, it's to retrieve the current matrix from the top of the matrix stack with glGetFloatv(GL_PROJECTION_MATRIX,output); or glGetDoublev(GL_PROJECTION_MATRIX,output);