Understanding GL coordinates - setting perspective and using gluLookAt - opengl

I'm using QGlWidget to draw a couple of points. The problems I'm having is that I seem to fail to set up the perspective properly and establish correct view on the points. I must be misunderstanding the coordinates somewhere or doing something else stupid, but after reading a bunch of guides and tutotrials I'm still stuck. The screen is black, no points. Here's the code:
void CGLWidget::initializeGL()
{
glEnable(GL_DEPTH_TEST);
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glEnable(GL_POINT_SPRITE);
glClearColor(0, 0, 0, 1);
assert (glGetError() == GL_NO_ERROR);
}
void CGLWidget::resizeGL(int w, int h)
{
glViewport(-w/2, -h/2, w/2, h <= 0 ? 1 : h/2);
glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective
//Set the camera perspective
glLoadIdentity(); //Reset the camera
gluPerspective(80.0, //The camera FoV
w/(double)h, //The width-to-height ratio
1, //The near z clipping coordinate
100); //The far z clipping coordinate
}
void CGLWidget::paintGL()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0);
glLoadIdentity();
glColor3i(255, 255, 255);
glBegin(GL_POINTS);
glVertex3d(0,0, -2);
glVertex3d(0,0, -3);
glVertex3d(0,0, +3);
glVertex3d(0,0, 0);
glVertex3f(-0.75f, -0.25f, -5.0f);
glEnd();
assert (glGetError() == GL_NO_ERROR);
}
I've tried manipulating z coordinate of the "eye" in gluLookAt to no avail, so I must be getting something else wrong.

To develop a more clear understanding of how gluPerspective() and gluLookAt() works, I recommend playing with the tutorials from Nate Robins, more specifically the projection demo.
Trust me, this is the droid you are looking for!
Anyway, a few days ago I wrote a spiced up version of Nehe lesson 5 (3D Shapes) in Qt:
GLWidget.cpp:
#include "GLWidget.h"
#include <iostream>
#include <QKeyEvent>
#include <QTimer>
GLWidget::GLWidget(QWidget *parent)
: QGLWidget(parent)
{
angle_tri = 0.f;
angle_quad = 0.f;
_eye_x = 0.f;
_eye_y = 0.f;
_mouse_is_moving = false;
_width = 0;
_height = 0;
}
GLWidget::~GLWidget()
{
}
void GLWidget::_tick()
{
update(); // triggers paintGL()
QTimer::singleShot(33, this, SLOT(_tick()));
}
void GLWidget::initializeGL()
{
// glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 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_COLOR_MATERIAL );
// glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
_tick();
}
void GLWidget::paintGL()
{
if (_mouse_is_moving)
{
glMatrixMode ( GL_PROJECTION ); // Select The Projection Matrix
glLoadIdentity ( ); // Reset The Projection Matrix
gluPerspective ( 60, ( float ) _width / ( float ) _height, 1.0, 50.0 );
gluLookAt(0.0, 0.0, 2.0, // eye
_eye_x, _eye_y, 0.0, // center
0.0, 1.0, 0.0); // up
std::cout << "paintGL: eye " << _eye_x << "," << _eye_y << std::endl;
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity(); // Reset The Current Modelview Matrix
glPushMatrix();
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glRotatef(angle_tri,0.0f,1.0f,0.0f); // Rotate The Triangle On The Y axis
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left)
glEnd(); // Finished Drawing The Triangle
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(1.5f,0.0f,-9.0f); // Move Right 1.5 Units And Into The Screen 6.0
glRotatef(angle_quad,1.0f,0.0f,0.0f); // Rotate The Quad On The X axis
glBegin(GL_QUADS); // Draw A Quad
glColor3f(0.0f,1.0f,0.0f); // Set The Color To Green
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Top)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Top)
glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top)
glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top)
glColor3f(1.0f,0.5f,0.0f); // Set The Color To Orange
glVertex3f( 1.0f,-1.0f, 1.0f); // Top Right Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f, 1.0f); // Top Left Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Bottom)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Bottom)
glColor3f(1.0f,0.0f,0.0f); // Set The Color To Red
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front)
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Front)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Front)
glColor3f(1.0f,1.0f,0.0f); // Set The Color To Yellow
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Back)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Back)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Back)
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Back)
glColor3f(0.0f,0.0f,1.0f); // Set The Color To Blue
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Left)
glColor3f(1.0f,0.0f,1.0f); // Set The Color To Violet
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Right)
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Right)
glEnd(); // Done Drawing The Quad
glPopMatrix();
angle_tri += 3.2f; // Increase The Rotation Variable For The Triangle ( NEW )
angle_quad -= 3.15f; // Decrease The Rotation Variable For The Quad ( NEW )
}
void GLWidget::resizeGL( int w, int h)
{
_width = w;
_height = h;
glViewport ( 0, 0, w, h );
glMatrixMode ( GL_PROJECTION ); // Select The Projection Matrix
glLoadIdentity ( ); // Reset The Projection Matrix
if ( h==0 ) // Calculate The Aspect Ratio Of The Window
gluPerspective ( 60, ( float ) w, 1.0, 50.0 );
else
gluPerspective ( 60, ( float ) w / ( float ) h, 1.0, 50.0 );
gluLookAt(0.0, 0.0, 2.0, // eye
0.0, 0.0, 0.0, // center
0.0, 1.0, 0.0); // up
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity ( ); // Reset The Model View Matrix
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
std::cout << "mousePressEvent:" << std::endl;
_mouse_is_moving = true;
}
void GLWidget::mouseReleaseEvent(QMouseEvent *event)
{
std::cout << "mouseReleaseEvent:" << std::endl;
_mouse_is_moving = false;
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
if (_mouse_x == 0)
_mouse_x = event->pos().x();
if (_mouse_y == 0)
_mouse_y = event->pos().y();
std::cout << "mouseMoveEvent: " << event->pos().x() << "," << event->pos().y() << std::endl;
if (event->pos().x() > _mouse_x)
{
_eye_x += 0.10;
}
else if (event->pos().x() < _mouse_x)
{
_eye_x -= 0.10;
}
if (event->pos().y() > _mouse_y)
{
_eye_y += 0.10;
}
else if (event->pos().y() < _mouse_y)
{
_eye_y -= 0.10;
}
_mouse_x = event->pos().x();
_mouse_y = event->pos().y();
}
GLWidget.h:
#include <QGLWidget>
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
explicit GLWidget(QWidget* parent = 0);
virtual ~GLWidget();
/* OpenGL initialization, viewport resizing, and painting */
void initializeGL();
void paintGL();
void resizeGL( int width, int height);
/* enable the user to interact directly with the scene using the mouse */
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
private:
float angle_tri; // Angle For The Triangle
float angle_quad; // Angle For The Quad
float _eye_x;
float _eye_y;
bool _mouse_is_moving;
int _mouse_x;
int _mouse_y;
int _width;
int _height;
protected slots:
void _tick();
};
main.cpp:
#include <QApplication>
#include "glwidget.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
GLWidget gl_widget;
gl_widget.show();
return app.exec();
}

I think what you've got there looks mostly correct, though your glViewport parameters look wrong. glViewport is supposed to be (left, bottom, width, height), but you're using something else.
Set glViewport to glViewport(0,0,width,height);.
For more explanation:
After transformation by modelViewProjection matrix (and perspective divide), all coordinates lie in what's known as Normalized Device Coordinates (abbreviated as NDC). NDC ranges from -1 to 1 on each axis, which puts (0,0,0) right in the center of the viewing region.
When your point lies directly in front of the camera, this gets transformed to xy (0,0) in normalized device coordinates.
If you look at the formulas on glViewport, these map NDC to the actual pixels on the screen.
So if you supply (0,0,1024,768) as the parameters, it gets mapped as the following:
screen X = ( Xnd + 1 ) ( width / 2) + x;
screen Y = ( Ynd + 1 ) ( height / 2) + y;
Substituting our glViewport values:
screen X = ( 0 + 1 ) ( 1024 / 2) + 0;
screen Y = ( 0 + 1 ) ( 768 / 2) + 0;
screen X = ( 1 ) ( 1024 / 2) ;
screen Y = ( 1 ) ( 768 / 2) ;
screen X = ( 1 ) ( 512 ) ;
screen Y = ( 1 ) ( 384 ) ;
screen X = 512 ; //center of screen X
screen Y = 384 ; //center of screen Y

Your near value is quite large to be honest, usually this has to be a low value so that if you have a 2D environment as your example you can still render objects. I would say a 0.1(0.5) for the near value of the perspective should go nicely.
Note: If you set the near value to be a big number your geometry will be clipped by the camera (perspective frustum).

Related

OpenGL and Multithreading

I'm having some troubles with OpenGL and multithreading. The thing is I cannot understand why I have this issue.
I'm using MACOS (the includes are therefore going to be different if you try my code).
Here the simple program that I manage to run without any problem.
char title[] = "3D Shapes with animation";
GLfloat anglePyramid = 0.0f; // Rotational angle for pyramid [NEW]
GLfloat angleCube = 0.0f; // Rotational angle for cube [NEW]
int refreshMills = 15; // refresh interval in milliseconds [NEW]
bool serverHasInput = false ;
float matrix[16] = {0.7599139,0.0,-0.65002376,0.0,-0.45789394,0.709777,-0.5353035,0.0,0.4613719,0.70442647,0.5393694,0.0,0.0,0.0,0.0,1.0};
float moveX = 0;
float moveY = 0;
pthread_mutex_t mymutex ;
pthread_cond_t mycondition ;
/* Initialize OpenGL Graphics */
void initGL() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClearDepth(1.0f); // Set background depth to farthest
glEnable(GL_DEPTH_TEST); // Enable depth testing for z-culling
glDepthFunc(GL_LEQUAL); // Set the type of depth-test
glShadeModel(GL_SMOOTH); // Enable smooth shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Nice perspective corrections
}
/* Handler for window-repaint event. Called back when the window first appears and
whenever the window needs to be re-painted. */
void display() {
//while(matrixSet == true){
// sleep(0.01);
//}
pthread_mutex_lock(&mymutex);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers
glMatrixMode(GL_MODELVIEW); // To operate on model-view matrix
// Render a color-cube consisting of 6 quads with different colors
glLoadIdentity(); // Reset the model-view matrix
glTranslatef(1.5f, 0.0f, -7.0f); // Move right and into the screen
glRotatef(angleCube, 1.0f, 1.0f, 1.0f); // Rotate about (1,1,1)-axis [NEW]
glMultMatrixf(matrix);
pthread_mutex_unlock(&mymutex);
glBegin(GL_QUADS); // Begin drawing the color cube with 6 quads
// Top face (y = 1.0f)
// Define vertices in counter-clockwise (CCW) order with normal pointing out
glColor3f(0.0f, 1.0f, 0.0f); // Green
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
// Bottom face (y = -1.0f)
glColor3f(1.0f, 0.5f, 0.0f); // Orange
glVertex3f( 1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
// Front face (z = 1.0f)
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
// Back face (z = -1.0f)
glColor3f(1.0f, 1.0f, 0.0f); // Yellow
glVertex3f( 1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
// Left face (x = -1.0f)
glColor3f(0.0f, 0.0f, 1.0f); // Blue
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face (x = 1.0f)
glColor3f(1.0f, 0.0f, 1.0f); // Magenta
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glEnd(); // End of drawing color-cube
glutSwapBuffers(); // Swap the front and back frame buffers (double buffering)
// Update the rotational angle after each refresh [NEW]
//anglePyramid += 1.2f;
//angleCube -= 0.15f;
pthread_cond_signal(&mycondition);
pthread_mutex_unlock(&mymutex);
}
/* Called back when timer expired [NEW] */
void timer(int value) {
glutPostRedisplay(); // Post re-paint request to activate display()
glutTimerFunc(refreshMills, timer, 0); // next timer call milliseconds later
}
/* Handler for window re-size event. Called back when the window first appears and
whenever the window is re-sized with its new width and height */
void reshape(GLsizei width, GLsizei height) { // GLsizei for non-negative integer
// Compute aspect ratio of the new window
if (height == 0) height = 1; // To prevent divide by 0
GLfloat aspect = (GLfloat)width / (GLfloat)height;
// Set the viewport to cover the new window
glViewport(0, 0, width, height);
// Set the aspect ratio of the clipping volume to match the viewport
glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix
glLoadIdentity(); // Reset
// Enable perspective projection with fovy, aspect, zNear and zFar
gluPerspective(45.0f, aspect, 0.1f, 100.0f);
}
void keyPressed (unsigned char key, int x, int y) {
if (key == 'y'){
moveY += 0.5;
cout << "y" << endl ;
}
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char* argv[]) {
glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode
glutInitWindowSize(640, 480); // Set the window's initial width & height
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
glutCreateWindow(title); // Create window with the given title
glutDisplayFunc(display); // Register callback handler for window re-paint event
glutReshapeFunc(reshape); // Register callback handler for window re-size event
initGL(); // Our own OpenGL initialization
glutTimerFunc(0, timer, 0); // First timer call immediately [NEW]
glutKeyboardFunc(keyPressed); // Tell GLUT to use the method "keyPressed" for key presses
glutMainLoop(); // Enter the infinite event-processing loop
}
So this is my basic code that works like a charm.
However, when I'm trying to create a thread to make it run I cannot get theKeyboardInput anymmore as well as some other aspects that are wrong (cannot clic on the X to exit the window for instace).
Here is my code:
My OpenGL functions are all the same except for this part:
/* Main function: GLUT runs as a console application starting at main() */
void* launch(void* args) {
mainArg* arg = (mainArg*) args ;
glutInit(arg->argc, &arg->argv); // Initialize GLUT
And here is how I create the threads:
//the thread function
void *connection_handler(void *);
void * connection_thread(void *);
void * input_thread(void *);
void test();
int main(int argc , char *argv[])
{
//Draw* d = new Draw() ;
pthread_t server_thread ;
pthread_t drawing_thread ;
pthread_t input_thread ;
mainArg args ;
args.argc = &argc ;
args.argv = *argv ;
pthread_mutex_init (&mymutex, NULL);
pthread_cond_init (&mycondition, NULL);
cout << "Begin" << endl ;
if( pthread_create( &server_thread , NULL , &connection_thread , NULL) != 0)
{
cout << "could not create Connection thread" << endl ;
return 1;
}
/*if( pthread_create( &input_thread , NULL , &connection_thread , NULL) != 0)
{
cout << "could not create input thread" << endl ;
return 1;
}*/
if( pthread_create( &drawing_thread , NULL , &launch , &args) != 0)
{
perror("could not create Drawing thread");
return 1;
}
//while(1);
pthread_join(server_thread, NULL);
pthread_join(drawing_thread,NULL);
Would you happen to know what's wrong here? Cause I've been looking at it for days now and I can't seem to find an answer.
EDIT: I am not sharing the OpenGL context or anything that has to be a part of the OGL rendering on an other thread. My other thread is only a server communication with other devices.
EDIT2: I saw here a while ago that not having OGL rendering on the main thread should not be an issue OpenGL Rendering in a secondary thread
So #user1118321 was correct.
There are absolutely no problem to try and do the rendering on a background thread.
However, GLUT will not be able to access the information of the OS window (i.e keyboard press, exit window ... ) if it is done that way. Still, if the purpose of the rendering thread is just to render, no problem at all to put it on a background thread.
Hope it helps other people too.

GLUT + OpenGL multisampling anti aliasing (MSAA)

I make OpenGL application that draw cube.
I want to add anti aliasing but have no success.
Maybe someone can help (User Xcode 6.1.1, GLUT, OpenGL) ?
I need create antialiasing without ay external libraries.
Result of code below.
GLfloat xRotated, yRotated, zRotated; void init(void){
glClearColor(0,0,0,0);
glEnable (GL_DEPTH_TEST);
// Turn on antialiasing, and give hint to do the best
// job possible.
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_LINEAR);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_LINEAR);
glEnable(GL_POLYGON_SMOOTH);
glHint(GL_POLYGON_SMOOTH_HINT, GL_LINEAR);
glEnable(GL_MULTISAMPLE); } void DrawCube(void) {
glMatrixMode(GL_MODELVIEW);
// clear the drawing buffer.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0,0.0,-10.5);
glRotatef(xRotated,1.0,0.0,0.0);
// rotation about Y axis
glRotatef(yRotated,0.0,1.0,0.0);
// rotation about Z axis
glRotatef(zRotated,0.0,0.0,1.0);
glBegin(GL_QUADS); // Draw The Cube Using quads
glColor3f(0.0f,1.0f,0.0f); // Color Blue
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Top)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Top)
glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top)
glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top)
glColor3f(1.0f,0.5f,0.0f); // Color Orange
glVertex3f( 1.0f,-1.0f, 1.0f); // Top Right Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f, 1.0f); // Top Left Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Bottom)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Bottom)
glColor3f(1.0f,0.0f,0.0f); // Color Red
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front)
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Front)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Front)
glColor3f(1.0f,1.0f,0.0f); // Color Yellow
glVertex3f( 1.0f,-1.0f,-1.0f); // Top Right Of The Quad (Back)
glVertex3f(-1.0f,-1.0f,-1.0f); // Top Left Of The Quad (Back)
glVertex3f(-1.0f, 1.0f,-1.0f); // Bottom Left Of The Quad (Back)
glVertex3f( 1.0f, 1.0f,-1.0f); // Bottom Right Of The Quad (Back)
glColor3f(0.0f,0.0f,1.0f); // Color Blue
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Left)
glColor3f(1.0f,0.0f,1.0f); // Color Violet
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Right)
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Right)
glEnd(); // End Drawing The Cube
glFlush(); } void animation(void) {
yRotated += 0.1;
xRotated += 0.2;
DrawCube(); } void reshape(int x, int y) {
if (y == 0 || x == 0) return; //Nothing is visible then, so return
//Set a new projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(40.0,(GLdouble)x/(GLdouble)y,0.5,20.0);
glMatrixMode(GL_MODELVIEW);
glViewport(0,0,x,y); //Use the whole window for rendering } int main(int argc, char** argv){
glutInit(&argc, argv);
//we initizlilze the glut. functions
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(DrawCube);
glutReshapeFunc(reshape);
//Set the function for the animation.
glutIdleFunc(animation);
glutMainLoop();
return 0; }
GLUT lacks the setting of the number of samples. Freeglut does. To enable it, use
glutSetOption(GLUT_MULTISAMPLE, 8);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE);
And remember to glEnable it
void enableMultisample(int msaa)
{
if (msaa)
{
glEnable(GL_MULTISAMPLE);
glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
// detect current settings
GLint iMultiSample = 0;
GLint iNumSamples = 0;
glGetIntegerv(GL_SAMPLE_BUFFERS, &iMultiSample);
glGetIntegerv(GL_SAMPLES, &iNumSamples);
printf("MSAA on, GL_SAMPLE_BUFFERS = %d, GL_SAMPLES = %d\n", iMultiSample, iNumSamples);
}
else
{
glDisable(GL_MULTISAMPLE);
printf("MSAA off\n");
}
}

creating a cube in 3d

I am trying to add walls to my checkboard floor so that they form a cube, I have the bottom already but I am having difficulties to draw the back side or the walls.
Here is my code:
class Checkerboard {
int displayListId;
int width;
int depth;
public:
Checkerboard(int width, int depth): width(width), depth(depth) {}
double centerx() {return width / 2;}
double centerz() {return depth / 2;}
void create() {
displayListId = glGenLists(1);
glNewList(displayListId, GL_COMPILE);
GLfloat lightPosition[] = {4, 3, 7, 1};
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
glBegin(GL_QUADS);
glNormal3d(0, 1, 0);
for (int x = 0; x < width - 1; x++) {
for (int z = 0; z < depth - 1; z++) {
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE,
(x + z) % 2 == 0 ? RED : WHITE);
glVertex3d(x, 0, z);
glVertex3d(x+1, 0, z);
glVertex3d(x+1, 0, z+1);
glVertex3d(x, 0, z+1);
}
}
glEnd();
glEndList();
}
void draw() {
glCallList(displayListId);
}
}
;
I am trying to add the following code:
glColor3f(1.0f,1.0f,0.0f); // Color Yellow
glVertex3d( 1.0f,-1.0f,-1.0f); // Top Right Of The Quad (Back)
glVertex3d(-1.0f,-1.0f,-1.0f); // Top Left Of The Quad (Back)
glVertex3d(-1.0f, 1.0f,-1.0f); // Bottom Left Of The Quad (Back)
glVertex3d( 1.0f, 1.0f,-1.0f); // Bottom Right Of The Quad (Back)
Can somebody point out what I am doing wrong?
Maybe you are effectively drawing the face you're trying to add, but you can't see it because of backface culling. Try glDisable(GL_CULL_FACE); before drawing you quads, or try to change the order of the vertices.
Note: if you disable backface culling, consider it as a temporary workaround to debug your program. Backface culling is an important optimisation and it should be enabled in most situations.
Change the code to:
glColor3f(1.0f,1.0f,0.0f); // Color Yellow
glVertex3d( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Back)
glVertex3d( -1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Back)
glVertex3d( -1.0f, -1.0f,-1.0f); // Bottom Left Of The Quad (Back)
glVertex3d( 1.0f, -1.0f,-1.0f); // Bottom Right Of The Quad (Back)
Note your comments were in the right winding order (CCW) but your vertices were not (They were clock wise). OpenGL by default will cull them (not show them) because it thinks they are back faces if culling is enabled.

Orbiting sphere should cast spot light on central cube

I'm writing a program that draws a rotating cube (with texture) in the middle of the screen followed by a small yellow sphere that orbits around the cube. The idea is to make the sphere as a spot light source that illuminates the cube.
Here is the problem: as you can see in the images below, I'm failing to achieve the spot light effect. It seems that the entire cube gets lighted:
I'm setting GL_SPOT_DIRECTION to be the cube position. I didn't set surface normals because I'm struggling to understand how to compute them for the cube, and I'm not sure a simple graphic application like this really requires it.
I'm sharing the code below:
main.cpp:
#include <QApplication>
#include "glwidget.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
GLWidget gl_widget;
gl_widget.show();
return app.exec();
}
GLWidget.h:
#pragma once
#include <QGLWidget>
#include <QImage>
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
explicit GLWidget(QWidget* parent = 0);
virtual ~GLWidget();
void _draw_texture_cube(int w, int h);
void _draw_light();
/* OpenGL initialization, viewport resizing, and painting */
void initializeGL();
void paintGL();
void resizeGL( int width, int height);
/* enable the user to interact directly with the scene using the keyboard */
void keyPressEvent(QKeyEvent *e);
private:
int _width;
int _height;
QImage* _img;
GLuint _texture;
float xrot;
float yrot;
float zrot;
bool _light_on;
bool _must_rotate;
bool _pause_light;
GLfloat _light_pos[3];
GLfloat _cube_pos[3];
GLUquadricObj* _quadratic;
protected slots:
void _tick();
};
GLWidget.cpp:
#include "GLWidget.h"
#include <iostream>
#include <QKeyEvent>
#include <QTimer>
#include <cmath>
#define LIGHT_MOVEMENT_SPEED 20.0f // Degrees per second
#define pi 3.141592654f
GLWidget::GLWidget(QWidget *parent)
: QGLWidget(parent), _img(NULL), _light_on(true), _must_rotate(true),
_pause_light(false), _quadratic(NULL)
{
_width = 0;
_height = 0;
_texture = 0;
xrot = 0.f;
yrot = 0.f;
zrot = 0.f;
// Set central cube position
_cube_pos[0] = 0.0f;
_cube_pos[1] = 0.0f;
_cube_pos[2] = -7.0f;
// Set light position
_light_pos[0] = 0.5f;
_light_pos[1] = 0.5f;
_light_pos[2] = -7.0f;
}
GLWidget::~GLWidget()
{
if (_img)
delete _img;
glDeleteTextures(1, &_texture);
}
void GLWidget::_tick()
{
update(); // triggers paintGL()
QTimer::singleShot(33, this, SLOT(_tick()));
}
void GLWidget::initializeGL()
{
std::cout << "GLWidget::initializeGL" << std::endl;
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black Background
glEnable(GL_CULL_FACE);
/* Load bitmap */
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
if (!_img)
{
std::cout << "GLWidget::paintGL: loading image" << std::endl;
QImage tmp(":/crate.jpg");
if (tmp.isNull())
{
std::cout << "GLWidget::paintGL: !!! Failed QImage #1" << std::endl;
return;
}
_img = new QImage(QGLWidget::convertToGLFormat(tmp));
}
/* Convert bitmap into texture */
// Create The Texture
glGenTextures(1, &_texture);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, _texture);
// Generate The Texture
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0,
GL_RGBA, _img->width(), _img->height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, _img->bits());
if (glGetError() != GL_NO_ERROR)
{
std::cout << "GLWidget::paintGL: !!! Failed glTexImage2D" << std::endl;
return;
}
/* Setup lighting */
glShadeModel(GL_SMOOTH); //Smooth color shading
// Light properties
GLfloat AmbientLight[4] = {0.2, 0.2, 0.2, 1.0};
GLfloat DiffuseLight[4] = {0.8, 0.8, 0.8, 1.0}; // color
GLfloat SpecularLight[4] = {1.0, 1.0, 1.0, 1.0}; // bright
GLfloat SpecRef[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLubyte Shine = 60.0;
//glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, AmbientLight);
glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularLight);
glLightfv(GL_LIGHT0, GL_POSITION, _light_pos);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT, GL_SPECULAR, SpecRef); // refletância do material
glMaterialf(GL_FRONT, GL_SHININESS, Shine); // concentração do brilho
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
//glColorMaterial(GL_FRONT,GL_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
// Sphere
_quadratic = gluNewQuadric(); // Create A Pointer To The Quadric Object
gluQuadricNormals(_quadratic, GLU_SMOOTH); // Create Smooth Normals
gluQuadricTexture(_quadratic, GL_TRUE); // Create Texture Coords
/* Start the timer */
_tick();
}
/* Draw the central cube with texture
*/
void GLWidget::_draw_texture_cube(int w, int h)
{
glPushMatrix();
glTranslatef(_cube_pos[0], _cube_pos[1], _cube_pos[2]);
glRotatef ( xrot, 1.0, 0.0, 0.0 );
glRotatef ( yrot, 0.0, 1.0, 0.0 );
glRotatef ( zrot, 0.0, 0.0, 1.0 );
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS); // Draw A Cube
// Front Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(w, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(w, h); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, h); glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
glTexCoord2f(w, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(w, h); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, h); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
// Top Face
glTexCoord2f(0.0f, h); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(w, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(w, h); glVertex3f( 1.0f, 1.0f, -1.0f);
// Bottom Face
glTexCoord2f(w, h); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, h); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(w, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face
glTexCoord2f(w, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(w, h); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, _img->height()); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(w, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(w, h); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, h); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
glPopMatrix();
if (_must_rotate)
{
xrot += 0.6f;
yrot += 0.4f;
zrot += 0.8f;
}
}
/* Draw light source and light model (sphere)
*/
void GLWidget::_draw_light()
{
if (_light_on)
{
glEnable(GL_LIGHT0); // enable lights that we use
}
else
{
glDisable(GL_LIGHT0);
}
static float light_angle = 25.0f;
if (!_pause_light) // stop moving the light source
{
light_angle += LIGHT_MOVEMENT_SPEED * 0.1;
if (light_angle > 360.0f)
light_angle -= 360.0f;
}
/* Set light source position */
_light_pos[0] = 4.0f * (float) cos(light_angle * pi / 180.0f);
_light_pos[1] = 4.0f * (float) sin(light_angle * pi / 180.0f);
_light_pos[2] = -7;
glLightfv(GL_LIGHT0, GL_POSITION, _light_pos);
GLfloat SpotDir[] = {_cube_pos[0], _cube_pos[1], _cube_pos[2], 0.0 };
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, SpotDir);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 150.0);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 15.0);
/* Set the light model position to be the same as the light source */
glPushMatrix();
glTranslatef(_light_pos[0], _light_pos[1], _light_pos[2]);
glColor3ub(255, 255, 0); // yellow
gluSphere(_quadratic, 0.2f, 32, 32); // draw sphere
glPopMatrix();
}
void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity(); // Reset The Current Modelview Matrix
/* Draw central cube */
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, _texture); // Select Our Texture
_draw_texture_cube(_img->width(), _img->height());
glDisable(GL_TEXTURE_RECTANGLE_ARB);
/* Draw light source and light model*/
_draw_light();
}
void GLWidget::resizeGL( int w, int h)
{
_width = w;
_height = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
if (h == 0) // Calculate The Aspect Ratio Of The Window
gluPerspective ( 60, ( float ) w, 0.4, 500.0 );
else
gluPerspective ( 60, ( float ) w / ( float ) h, 0.4, 500.0 );
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity ( ); // Reset The Model View Matrix
gluLookAt(0.0, 0.0, 2.0, // eye
0.0, 0.0, 0.0, // center
0.0, 1.0, 0.0); // up
}
void GLWidget::keyPressEvent(QKeyEvent *e)
{
switch (e->key())
{
case Qt::Key_L:
if (_light_on)
_light_on = false;
else
_light_on = true;
break;
case Qt::Key_P:
if (_pause_light)
_pause_light = false;
else
_pause_light = true;
break;
case Qt::Key_R:
if (_must_rotate)
_must_rotate = false;
else
_must_rotate = true;
break;
default:
break;
}
}
Lighting.pro:
QT += core gui opengl
SOURCES += \
GLWidget.cpp \
main.cpp
HEADERS += \
GLWidget.h
RESOURCES += \
resource.qrc
What needs to be changed in this application in order to achieve the desired effect?
You do not specify any normals for your cube faces. As OpenGL is a state machine, it will use the default surface normal for all vertices, hence all of your faces. As the normal vector is crucial for the lighting, all of your faces will be lit almost identical (vertex postions still are different, but the effect is weak).
You should also be aware that the fixed function lighting of OpenGL is done per vertex. If you really want to see a good spotlight on the cuve, you would either need to tessalate it so more vertices are used where the lighting equation is actually evaluated, or use shaders for per-fragment lighting.

OpenGL perspective projection and camera location

I am rendering a scene with some map image in OpenGL and using lat, lon of the map as coordinates directly. So my scene does not start at 0,0 and goes up to width, height. Although I can see my polygon (very small), I can't zoom by changing the z-value of the eye in the gluLookAt().
/*
* My boundary for map quad with texture
*/
#define TOP 41.9061
#define BOTTOM 41.8546
#define LEFT -87.7012
#define RIGHT -87.6054
/*
* window size
*/
const unsigned int window_width = 1024;
const unsigned int window_height = 739;
/*
* drawing a polygon with texture
*/
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mainMapTextureId);
glBegin( GL_POLYGON );
//bottom left
glTexCoord2f( 0.0f, 1.0f );
glVertex3f(LEFT, BOTTOM, 0.0);
//bottom right
glTexCoord2f( 1.0f, 1.0f );
glVertex3f(RIGHT, BOTTOM, 0.0);
//top right
glTexCoord2f( 1.0f, 0.0f );
glVertex3f(RIGHT, TOP, 0.0);
//top left
glTexCoord2f( 0.0f, 0.0f );
glVertex3f(LEFT, TOP, 0.0);
glEnd();
/*
* Setting up the camera
*/
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat)window_width/(GLfloat)window_height, 0.0, 10.0);
gluLookAt( (float)(LEFT+RIGHT)/2.0, (float)(TOP+BOTTOM)/2.0, 1.0,
(float)(LEFT+RIGHT)/2.0, (float)(TOP+BOTTOM)/2.0, 0.0,
0.0f, 1.0f, 0.0f);
It is not legal to have a value of 0.0 for the near plane of gluPerspective. Try replacing it with a nominal small value (0.1f).
Also always put a glGetError call in your code at the end, it will alert you to problems.