OpenGL and Multithreading - c++

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.

Related

Opengl/Glut keyboard input trouble

i have an assignment to draw a pyramid onto the screen and then rotate after i press the 'k' key in my keyboard.
Everything works ok, except the rotation part as the program doesn't seem to be noting me pressing the key. The code goes as follows:
void changeSize(int w, int h) {
if(h == 0)
h = 1;
float ratio = w * 1.0 / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
// Set perspective
gluPerspective(45.0f ,ratio, 1.0f ,1000.0f);
// return to the model view matrix mode
glMatrixMode(GL_MODELVIEW);
}
void renderScene(void) {
// clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// set the camera
glLoadIdentity();
gluLookAt(5.0,5.0,5.0,
0.0,0.0,0.0,
0.0f,2.0f,0.0f);
// put the geometric transformations here
// put drawing instructions here
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_LINES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(-100.0f, 0.0f, 0.0f);
glVertex3f( 100.0f, 0.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(0.0f, -100.0f, 0.0f);
glVertex3f(0.0f, 100.0f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, -100.0f);
glVertex3f(0.0f, 0.0f, 100.0f);
glEnd();
//triangulos da base
glBegin(GL_TRIANGLES);
glColor3f(255.0f,255.0f,255.0f);
glVertex3f(1.0f,0.0f,1.0f);
glVertex3f(-1.0f,0.0f,-1.0f);
glVertex3f(-1.0f,0.0f,1.0f);
glEnd();
glBegin(GL_TRIANGLES);
glVertex3f(1.0f,0.0f,1.0f);
glVertex3f(1.0f,0.0f,-1.0f);
glVertex3f(-1.0f,0.0f,-1.0f);
glEnd();
//triangulos das faces
glBegin(GL_TRIANGLES);
glVertex3f(1.0f,0.0f,1.0f);
glVertex3f(0.0f,2.0f,0.0f);
glVertex3f(-1.0f,0.0f,1.0f);
glEnd();
glBegin(GL_TRIANGLES);
glVertex3f(1.0f,0.0f,-1.0f);
glVertex3f(0.0f,2.0f,0.0f);
glVertex3f(1.0f,0.0f,1.0f);
glEnd();
glBegin(GL_TRIANGLES);
glVertex3f(1.0f,0.0f,-1.0f);
glVertex3f(0.0f,2.0f,0.0f);
glVertex3f(-1.0f,0.0f,-1.0f);
glEnd();
glBegin(GL_TRIANGLES);
glVertex3f(-1.0f,0.0f,-1.0f);
glVertex3f(0.0f,2.0f,0.0f);
glVertex3f(-1.0f,0.0f,1.0f);
glEnd();
// End of frame
glutSwapBuffers();
}
// write function to process keyboard events
void rotate (unsigned char key, int x, int y) {
if (key == 'k')
glRotatef(45,1.0,1.0,0.0);
glutPostRedisplay();
}
int main(int argc, char **argv) {
// init GLUT and the window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(1200,1200);
glutCreateWindow("CG#DI-UM");
// Required callback registry
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
// put here the registration of the keyboard callbacks
glutKeyboardFunc(rotate);
// OpenGL settings
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
// enter GLUT's main cycle
glutMainLoop();
return 0;
}
It seems that my program is not noting me pressing the key even tho i am. Im tried only printing the keys that are being pressed, and that works, so i'm really lost here.
glRotatef seem to have no effect in rotate, because glLoadIdentity() is called at the begin of renderScene. Actually glRotatef changes the current matrix, but when the scene is rendered (renderScene), then glLoadIdentity() loads the Identity matrix to the current matrix.
Anyway it is a bad style to do changes to the current matrix in input event callbacks. Change states and values of variables in the input events and use the variables to set the current model view matrix before the scene is rendered in renderScene.
Add a global variable angle:
float angle = 0.0f;
Change the value of the variable in renderScene. e.g:
void rotate (unsigned char key, int x, int y) {
if (key == 'k') {
angle += 45.0f;
glutPostRedisplay();
}
}
And apply the rotation to the current matrix in renderScene:
void renderScene(void) {
// clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// set the camera
glLoadIdentity();
gluLookAt(5.0,5.0,5.0,
0.0,0.0,0.0,
0.0f,2.0f,0.0f);
// apply rotation
glRotatef(angle, 1.0f, 1.0f, 0.0f);
// [...]
}

Why are my 3D shapes in opengl acting weird?

I tried to write an "Engine" to render shapes using OpenGL.
The idea is that you can write "renderers" which are just functions that render shapes and add them to a list for the Engine class to display.
So I added a cube and a pyramid (the code for which I just copied from the internet) - and I made them rotate.
As you can see in the images at the bottom of the question - the shapes acted weird - you could see the back of the shape from the front, etc.
Now, I understand that OpenGL just renders stuff in the order I tell it to render them - causing things that are written first to be rendered first - but I used the glDepthFunc which should make it such that stuff renders by "depth" and not order of writing.
#include <GL/glut.h>
#include <iostream>
#include <list>
namespace Graphics
{
class Engine
{
public:
static void Init();
static void Display();
static void Reshape(GLsizei width, GLsizei height);
static void Timer(int value);
static bool Run(int argc, char** argv);
// A renderer is just a method that does stuff and return a boolean
using renderer_t = bool(*)();
static void AddRenderer(renderer_t renderer);
private:
static std::list<renderer_t> renderers;
};
}
namespace Graphics
{
std::list<Engine::renderer_t> Engine::renderers;
void Engine::Init()
{
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
}
void Engine::Display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers
glMatrixMode(GL_MODELVIEW); // To operate on model-view matrix
for (auto renderer : Engine::renderers)
{
if (!renderer())
{
std::cout << "A renderer has failed rendering something... :(" << std::endl;
}
}
glutSwapBuffers(); // Swap the front and back frame buffers (double buffering)
}
void Engine::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 Engine::Timer(int value)
{
glutPostRedisplay(); // Post re-paint request to activate display()
glutTimerFunc(15, Engine::Timer, 0); // next timer call milliseconds later
}
bool Engine::Run(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("FML"); // Create window with the given title
glutDisplayFunc(Engine::Display); // Register callback handler for window re-paint event
glutReshapeFunc(Engine::Reshape); // Register callback handler for window re-size event
Engine::Init(); // Our own OpenGL initialization
glutTimerFunc(0, Engine::Timer, 0); // Call the next display immediately
glutMainLoop(); // Enter the infinite event-processing loop
return true;
}
void Engine::AddRenderer(renderer_t renderer)
{
Engine::renderers.push_back(renderer);
}
}
using namespace Graphics;
static bool RenderCube()
{
static auto angleCube = 0.0f;
// 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);
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();
angleCube += 0.2f;
return true;
}
static bool RenderPyramid()
{
static auto anglePyramid = 0.0f;
// Render a pyramid consists of 4 triangles
glLoadIdentity(); // Reset the model-view matrix
glTranslatef(-1.5f, 0.0f, -6.0f); // Move left and into the screen
glRotatef(anglePyramid, 1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES); // Begin drawing the pyramid with 4 triangles
// Front
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f); // Green
glVertex3f(-1.0f, -1.0f, 1.0f);
glColor3f(0.0f, 0.0f, 1.0f); // Blue
glVertex3f(1.0f, -1.0f, 1.0f);
// Right
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f); // Blue
glVertex3f(1.0f, -1.0f, 1.0f);
glColor3f(0.0f, 1.0f, 0.0f); // Green
glVertex3f(1.0f, -1.0f, -1.0f);
// Back
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f); // Green
glVertex3f(1.0f, -1.0f, -1.0f);
glColor3f(0.0f, 0.0f, 1.0f); // Blue
glVertex3f(-1.0f, -1.0f, -1.0f);
// Left
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f);
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f);
glEnd(); // Done drawing the pyramid
anglePyramid += 0.25f;
return true;
}
int main(int argc, char** argv)
{
Engine::AddRenderer(RenderCube);
Engine::AddRenderer(RenderPyramid);
return Engine::Run(argc, argv);
}
Images of the resulting shapes rotating
As you can see the shapes are acting weird - you can see the back of them even though I used the glDepthFunc.
The OS/driver is under no obligation to give you any depth buffer bits unless you specifically request them; zero bits, no depth buffering.
As #BDL pointed out, for GLUT that means ORing in GLUT_DEPTH to your glutInitDisplayMode() parameter.

OpenGL picking shows nothing after the pick

So I have 2 cubes in a display list and I want one of them be pickable so I can maybe change his color or something like that.
When I click on a cube then the screen turns black and nothing happens, the console gives me output of the closest hit but the screen turns black and doesn't show anything.
Here is my cpp file:
#include "glwidget.h"
#include <QDomDocument>
#include <QDebug>
#include <QFile>
#include <math.h>
#include <QString>
#include <stdlib.h>
GLWidget::GLWidget(QWidget *parent):QGLWidget(parent)
{
camPosx = 0.0, camPosy = 0.0, camPosz = 1.0;
camViewx = 0.0, camViewy = 0.0, camViewz = 0.0;
camUpx = 0.0, camUpy = 1.0, camUpz = 0.0;
camAngle = 0.0;
camViewz = -cos(camAngle);
camViewx = sin(camAngle);
mode = 1;
timer = new QTimer();
connect( timer, SIGNAL(timeout()), this, SLOT(updateGL()) );
}
void GLWidget::initializeGL() {
loadGLTextures();
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
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_LIGHT0); // Quick And Dirty Lighting (Assumes Light0 Is Set Up)
glEnable(GL_LIGHTING); // Enable Lighting
glEnable(GL_COLOR_MATERIAL); // Enable Material Coloring
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Perspective Calculations
buildLists(2); // Creating displaylist #
glLoadIdentity();
timer->start(50);
}
void GLWidget::resizeGL(int width, int height) {
//set viewport
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//set persepective
//change the next line order to have a different perspective
aspect_ratio=(GLdouble)width/(GLdouble)height;
gluPerspective(45.0f, aspect_ratio, 0.1 , 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void GLWidget::paintGL() {
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// store current matrix
glMatrixMode( GL_MODELVIEW );
glPushMatrix( );
gluLookAt(camPosx ,camPosy ,camPosz,
camPosx + camViewx,camViewy,camPosz + camViewz,
camUpx, camUpy, camUpz );
if (mode == 2) {
startPicking();
}
glColor3f(1.0f,0.0f,0.0f);
glCallList(displayList[0]);
glTranslatef(5.0,0.0,0.0);
glColor3f(0.0f,1.0f,1.0f);
glCallList(displayList[0]);
if (mode == 2)
stopPicking();
// glEnable( GL_LIGHTING );
// glEnable( GL_LIGHT0 );
// glScalef(10.0,10.0,10.0);
// glBindTexture(GL_TEXTURE_2D, texture[0]);
// glBegin(GL_QUADS);
// // Front Face
// glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
// glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
// glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
// glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad
// // Back Face
// glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
// glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
// glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
// glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad
// // Top Face
// glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
// glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Texture and Quad
// glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Texture and Quad
// glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
// // Bottom Face
// glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Top Right Of The Texture and Quad
// glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Top Left Of The Texture and Quad
// glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
// glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
// // Right face
// glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
// glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
// glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad
// glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
// // Left Face
// glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad
// glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
// glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
// glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
// glEnd();
// // XML
// QDomDocument doc( "AdBookML" );
// QDomNode n;
// QDomElement e;
// QFile file( "test2.xml" );
// QString s;
// QStringList sl;
//// if( !file.open(QIODevice::ReadOnly))
//// qDebug("probleem bij het openen");
// if( !doc.setContent( &file ) )
// {
// file.close();
// }
// file.close();
// QDomElement root = doc.documentElement();
// if( root.tagName() != "playlist" )
// // qDebug("root is different");
// //qDebug( root.tagName() );
// // doorheen u boom lopen
// n = root;
// float f1, f2, f3;
// glDisable( GL_LIGHTING );
// glBegin(GL_TRIANGLES);
// for(int i = 0; i< n.childNodes().length(); i++) // voor alle triangles
// {
// if(n.childNodes().at(i).toElement().tagName() == "triangle")
// {
// for(int j =0; j < 4; j++) // voor alle punten
// {
// e = n.childNodes().at(i).childNodes().at(j).toElement(); // e is een punt
// //qDebug(e.tagName());
// s = e.text();
// sl = s.split(" "); // opsplitsen naar het x, y , z coordinaat;
// f1 = sl.at(0).toFloat();
// f2 = sl.at(1).toFloat();
// f3 = sl.at(2).toFloat();
// if( j > 0)
// glVertex3f(f1, f2, f3); // de vertex tekenen
// if(j == 0)
// glColor3f(f1,f2,f3);
// }
// }
// }
// glEnd();
// glEnable(GL_LIGHTING);
// restore current matrix
glMatrixMode( GL_MODELVIEW );
glPopMatrix( );
}
void GLWidget::loadGLTextures()
{
QImage t;
QImage b;
if ( !b.load( "images/redbrick.png" ) )
{
qDebug("Didn't found the image.");
b = QImage( 16, 16, QImage::Format_RGB32 );
b.fill( 1 );
}
t = QGLWidget::convertToGLFormat( b );
glGenTextures( 1, &texture[0] );
glBindTexture( GL_TEXTURE_2D, texture[0] );
glTexImage2D( GL_TEXTURE_2D, 0, 3, t.width(), t.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, t.bits() );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}
//Functie die display lists kan aanmaken, het aantal ( is het aantal displaylists )
GLvoid GLWidget::buildLists(int aantal)
{
displayList = new GLuint[aantal];
for(int i = 0; i < aantal; i++)
{
displayList[i]=glGenLists(aantal); // Maak x Aantal displaylists
glNewList(displayList[i],GL_COMPILE); //start met de eerste display list te compile
//Hieronder moet er xml worden ingeladen
glBegin(GL_QUADS);
// Bottom Face
glNormal3f( 0.0f,-1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
// Front Face
glNormal3f( 0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
glNormal3f( 0.0f, 0.0f,-1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
// Right face
glNormal3f( 1.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
glEndList();
}
}
//functie die zorgt dat we renderen in selectiemode
void GLWidget::renderInSelectionMode() {
glInitNames(); //Creates empty stack
glPushName(1); //Push a name on the stack
//draw something
glColor3f(1.0f,0.0f,0.0f);
glCallList(displayList[0]);
glPopName(); //pop a name from the stack
glPushName(2); //Push a name on the stack
//draw something
glTranslatef(5.0,0.0,0.0);
glColor3f(0.0f,1.0f,1.0f);
glCallList(displayList[0]);
glPopName(); //Pops a name from the stack
}
void GLWidget::startPicking() {
GLint viewport[4];
glSelectBuffer(BUFSIZE,selectBuf);
glRenderMode(GL_SELECT);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glGetIntegerv(GL_VIEWPORT,viewport);
gluPickMatrix(cursorX,viewport[3]-cursorY,5,5,viewport);
gluPerspective(45,aspect_ratio,0.1,1000);
glMatrixMode(GL_MODELVIEW);
glInitNames();
}
void GLWidget::stopPicking() {
int hits;
// restoring the original projection matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glFlush();
// returning to normal rendering mode
hits = glRenderMode(GL_RENDER);
// if there are hits process them
if (hits != 0)
processHits(hits,selectBuf);
}
void GLWidget::processHits (GLint hits, GLuint buffer[])
{
unsigned int i, j;
GLuint names, *ptr, minZ,*ptrNames, numberOfNames;
printf ("hits = %d\n", hits);
ptr = (GLuint *) buffer;
minZ = 0xffffffff;
for (i = 0; i < hits; i++) {
names = *ptr;
ptr++;
if (*ptr < minZ) {
numberOfNames = names;
minZ = *ptr;
ptrNames = ptr+2;
}
ptr += names+2;
}
printf ("The closest hit names are ");
ptr = ptrNames;
for (j = 0; j < numberOfNames; j++,ptr++) {
printf ("%d ", *ptr);
}
printf ("\n");
}
void GLWidget::mousePressEvent(QMouseEvent * e)
{
if(e->button() == Qt::LeftButton)
{
qDebug("mouse");
qDebug("%d",QCursor::pos().x());
this->cursorX = QCursor::pos().x();
this->cursorY = QCursor::pos().y();
this->mode = 2;
}
}
void GLWidget::keyPressEvent( QKeyEvent * e ) {
double fraction = 0.1f;
if(e->key() == Qt::Key_Up)
{
camPosz += camViewz * fraction;
camPosx += camViewx * fraction ;
}
if(e->key() == Qt::Key_Down)
{
camPosz -= camViewz * fraction;
camPosx -= camViewx * fraction ;
}
if(e->key() == Qt::Key_Left)
{
camAngle -= 0.05f;
camViewz = -cos(camAngle);
camViewx = sin(camAngle);
}
if(e->key() == Qt::Key_Right)
{
qDebug("cam angle is %f", camAngle);
camAngle +=0.05f;
camViewz = -cos(camAngle);
camViewx = sin(camAngle);
}
}
#ifndef GLWIDGET_H
#define GLWIDGET_H
#include <QtOpenGL/QGLWidget>
#include <gl/GLU.h>
#include <QImage>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QTimer>
#define BUFSIZE 512
class GLWidget: public QGLWidget
{
Q_OBJECT
public:
GLWidget(QWidget *parent = NULL);
private:
double camPosx,camPosy,camPosz;
double camUpx,camUpy,camUpz;
double camViewx,camViewy,camViewz;
double camAngle;
protected:
void initializeGL();
void resizeGL(int width, int height);
void paintGL();
void keyPressEvent(QKeyEvent * e);
void mousePressEvent(QMouseEvent * e);
QTimer* timer;
void loadGLTextures();
GLuint texture[1];
GLuint * displayList;
void renderInSelectionMode();
GLvoid buildLists(int aantal);
void startPicking();
void stopPicking();
void processHits (GLint hits, GLuint buffer[]);
GLuint selectBuf[BUFSIZE];
GLdouble aspect_ratio;
int cursorY;
int cursorX;
int mode;
};
#endif // GLWIDGET_H
this is the normal view without clicking once
http://imageshack.us/photo/my-images/233/31536776.png/
then when clicked it keeps getting in startpicking and stop picking and gives a black screen
http://imageshack.us/photo/my-images/13/14180995.png/
and then after closing the window so it stops running it gives me this output http://imageshack.us/photo/my-images/861/13486229.png/
Could be wrong, but it looks like you aren't resetting your mode-variable back to 1 after the first mouseclick anywhere, so the start- & stopPicking-methods are called on each frame from the first click onwards. If that's not the case, then you probably have some problem with gl-states/matrices not all being reset correctly after the picking.

Can't get depth testing to work in OpenGL

I use SFML to create the window.
In this screenshot the cube should be behind the pyramid but it just doesn't work.
Here is the minimal code I used:
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <SFML/Graphics.hpp>
#include "ResourcePath.hpp"
void resize();
void drawScene();
void initGL();
float rtri = 0;
float rquad = 0;
float z = -10.0f;
int main (int argc, const char * argv[])
{
// Create the main window
sf::RenderWindow *window = new sf::RenderWindow();
window->Create( sf::VideoMode( 800, 600, 32 ), "Collision Detection", sf::Style::Close );
sf::Event event;
bool run = true;
initGL();
resize();
while( run ) {
window->PollEvent( event );
if( event.Type == sf::Event::Closed ) {
run = false;
}
drawScene();
window->Display();
// z+= 0.001f;
}
return EXIT_SUCCESS;
}
void resize() {
glViewport(0,0, 800,600);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,800/600,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(0.0f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glRotatef(rtri,0.0f,1.0f,0.0f); // Rotate The Triangle On The Y axis ( NEW )
glBegin(GL_TRIANGLES);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f( 1.0f,-1.0f, -1.0f);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f( 1.0f,-1.0f, -1.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f(-1.0f,-1.0f, -1.0f);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glEnd();
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(0.0f,0.0f,z); // Move Right 1.5 Units And Into The Screen 7.0
glRotatef(rquad,1.0f,1.0f,z); // Rotate The Quad On The X axis ( NEW )
glBegin(GL_QUADS);
glColor3f(0.0f,1.0f,0.0f);
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);
glColor3f(1.0f,0.5f,0.0f);
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);
glColor3f(1.0f,0.0f,0.0f);
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);
glColor3f(1.0f,1.0f,0.0f);
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);
glColor3f(0.0f,0.0f,1.0f);
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);
glColor3f(1.0f,0.0f,1.0f);
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(); // Done Drawing The Quad
rtri+=0.2f; // Increase The Rotation Variable For The Triangle ( NEW )
rquad-=0.15f;
z-=0.01;
}
void initGL() {
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
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable( GL_CULL_FACE );
/* Position the camera */
glTranslatef(0, 0, -5);
}
I've tried different depth functions, GL_LESS, GL_EQUAL, I've tried them all. Also enabling and disabling depth testing on different places, nothing seems to work.
I'm running Mac OS X 10.7 ( Lion ), not sure if that is important, though I didn't seem to have any trouble with these kind of things before upgrading.
Your code looks okay. I suspect that your window simply does not have a depth buffer. You're using sf::RenderWindow, whose documentation says (emphasis mine):
Simple wrapper for sf::Window that allows easy 2D rendering.
I don't know SFML, but this tutorial suggests to create your window like this:
sf::WindowSettings Settings;
Settings.DepthBits = 24; // Request a 24 bits depth buffer
Settings.StencilBits = 8; // Request a 8 bits stencil buffer
Settings.AntialiasingLevel = 2; // Request 2 levels of antialiasing
sf::Window App(sf::VideoMode(800, 600, 32), "SFML OpenGL", sf::Style::Close, Settings);
You could set StencilBits and AntialiasingLevel to 0 since this example doesn't need them.
In latest version of SFML WindowSettings replaced by ContextSettings. Depth settings can be configured as.
//Configuring SFML window
sf::ContextSettings window_settings;
window_settings.depthBits = 24; // Request a 24-bit depth buffer
window_settings.stencilBits = 8; // Request a 8 bits stencil buffer
window_settings.antialiasingLevel = 2; // Request 2 levels of antialiasing
// Opening SFML window
sf::Window window(sf::VideoMode(800, 600), "Title", sf::Style::Resize | sf::Style::Close, window_settings);
glewExperimental = GL_TRUE;
// Initializing glew and openGL
glewInit();
glViewport(0, 0, 800, 600);
// Enabling Depth
glEnable(GL_DEPTH_TEST);

OpenGL true coordinates and glutTimerFunc() problem C++

HI I am starting to learn openGl for C++.but at stating point I stucked.
I have 2 question that is the coordinates for drawing some objects? I mean where is X, Y and Z?
Second one I am making tutorial from some sites. and I am trying to animate my triangle.In tutorial it works but on my computer not.I Also downloaded source codes but It doesnt move. And there is no compiler error.
Edit:I solved problem. With restarting computer.I think it is poblem about my computer.
Here sample codes. I thougt that problem is glutTimerFunc().
#include <iostream>
#include <stdlib.h>
#ifdef __APPLE__
#include<OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <gl/glut.h>
#endif
using namespace std;
//Called when a key is pressed
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //Escape key
exit(0);
}
}
//Initializes 3D rendering
void initRendering() {
glEnable(GL_DEPTH_TEST);
}
//Called when the window is resized
void handleResize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (double)w / (double)h, 1.0, 200.0);
}
float _angle = 30.0f;
float _cameraAngle = 0.0f;
//Draws the 3D scene
void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective
glLoadIdentity(); //Reset the drawing perspective
glRotatef(-_cameraAngle, 0.0f, 1.0f, 0.0f); //Rotate the camera
glTranslatef(0.0f, 0.0f, -5.0f); //Move forward 5 units
glPushMatrix(); //Save the transformations performed thus far
glTranslatef(0.0f, -1.0f, 0.0f); //Move to the center of the trapezoid
glRotatef(_angle, 0.0f, 0.0f, 1.0f); //Rotate about the z-axis
glBegin(GL_QUADS);
//Trapezoid
glVertex3f(-0.7f, -0.5f, 0.0f);
glVertex3f(0.7f, -0.5f, 0.0f);
glVertex3f(0.4f, 0.5f, 0.0f);
glVertex3f(-0.4f, 0.5f, 0.0f);
glEnd();
glPopMatrix(); //Undo the move to the center of the trapezoid
glPushMatrix(); //Save the current state of transformations
glTranslatef(1.0f, 1.0f, 0.0f); //Move to the center of the pentagon
glRotatef(_angle, 0.0f, 1.0f, 0.0f); //Rotate about the y-axis
glScalef(0.7f, 0.7f, 0.7f); //Scale by 0.7 in the x, y, and z directions
glBegin(GL_TRIANGLES);
//Pentagon
glVertex3f(-0.5f, -0.5f, 0.0f);
glVertex3f(0.5f, -0.5f, 0.0f);
glVertex3f(-0.5f, 0.0f, 0.0f);
glVertex3f(-0.5f, 0.0f, 0.0f);
glVertex3f(0.5f, -0.5f, 0.0f);
glVertex3f(0.5f, 0.0f, 0.0f);
glVertex3f(-0.5f, 0.0f, 0.0f);
glVertex3f(0.5f, 0.0f, 0.0f);
glVertex3f(0.0f, 0.5f, 0.0f);
glEnd();
glPopMatrix(); //Undo the move to the center of the pentagon
glPushMatrix(); //Save the current state of transformations
glTranslatef(-1.0f, 1.0f, 0.0f); //Move to the center of the triangle
glRotatef(_angle, 1.0f, 2.0f, 3.0f); //Rotate about the the vector (1, 2, 3)
glBegin(GL_TRIANGLES);
//Triangle
glVertex3f(0.5f, -0.5f, 0.0f);
glVertex3f(0.0f, 0.5f, 0.0f);
glVertex3f(-0.5f, -0.5f, 0.0f);
glEnd();
glPopMatrix(); //Undo the move to the center of the triangle
glutSwapBuffers();
}
void update(int value) {
_angle += 2.0f;
if (_angle > 360) {
_angle -= 260;
}
glutPostRedisplay(); //Tell GLUT that the display has changed
//Tell GLUT to call update again in 25 milliseconds
glutTimerFunc(25, update, 0);
}
int main(int argc, char** argv) {
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400);
//Create the window
glutCreateWindow("Transformations and Timers - videotutorialsrock.com");
initRendering();
//Set handler functions
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutTimerFunc(24, update, 0); //Add a timer
glutMainLoop();
return 0;
}
Regarding your first question, you can use gluProject() to apply your transform matrices (via GL_MODELVIEW_MATRIX and GL_PROJECTION_MATRIX) to arbitrary vertexes.