glewInit() fails on macOS - c++

So I have a piece of code that runs fine on ubuntu machine, but fails to do so on xcode or via terminal. I'm trying to run it on xcode, but it fails on main with:
"Use of undeclared identifier glewInit; did you mean glutInit?"
"Too few argument to function call, expected 2, have 0"
The code is lengthy is been written by my professor and it runs on ubuntus. But with the errors, I'm thinking that the reasons is...well, underclared identifier, include is missing. So, after googling I figured out that glewInit is part of the glew library -> so I downloaded the code and installed it on my machine with following:
make
sudo -s
make install
which were successfully installed into my /usr/include/GL. Now, when i type into xcode #include or just #include , the compiler throws that glew.h is not found (though i can i see the file myself in the usr/include/GL).
Here is the code:
#include "include/Angel.h"
// The rotation around z axis
GLfloat Theta = 0.0; // Angle (in degrees)
GLfloat step = 0.01; // Incremental
GLuint locTheta;
enum { CW = 0, CCW = 1};
int direction = CW; // Direction
//Scale along x and y axes
GLfloat ScaleFactor[2] = {1.0, 1.0};
GLuint locScale;
const int NumPoints = 4;
void init();
void display( void );
void reshape( GLsizei w, GLsizei h );
void keyboard( unsigned char key, int x, int y );
void mouse( int button, int state, int x, int y );
void idle( void );
//----------------------------------------------------------------------------
// OpenGL initialization
void init()
{
// Vertices of a unit square centered at origin, sides aligned with axes
vec4 points[] = {
vec4( -0.5, -0.5, 0, 1.0 ), //v1
vec4( 0.5, -0.5, 0, 1.0 ), //v2
vec4( -0.5, 0.5, 0, 1.0 ), //v3
vec4( 0.5, 0.5, 0, 1.0 ) //v4
};
// RGBA colors
vec4 colors[] = {
vec4( 1.0, 0.0, 0.0, 1.0 ), // red
vec4( 0.0, 1.0, 0.0, 1.0 ), // green
vec4( 0.0, 1.0, 0.0, 1.0 ), // green
vec4( 0.0, 0.0, 1.0, 1.0 ), // blue
};
// Create and initialize a buffer object
GLuint buffer;
glGenBuffers( 1, &buffer );
glBindBuffer( GL_ARRAY_BUFFER, buffer );
glBufferData( GL_ARRAY_BUFFER, sizeof(points) + sizeof(colors), NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(points), points );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(points), sizeof(colors), colors );
// Load shaders and use the resulting shader program
GLuint program = InitShader( "vshader_rot.glsl", "fshader_rot.glsl" );
glUseProgram( program );
// set up vertex arrays
GLuint vPosition = glGetAttribLocation( program, "vPosition" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,
BUFFER_OFFSET(0) );
GLuint vColor = glGetAttribLocation( program, "vColor" );
glEnableVertexAttribArray( vColor );
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,
BUFFER_OFFSET(sizeof(points)) );
// The location of shader uniform variables
locTheta = glGetUniformLocation( program, "theta" );
locScale = glGetUniformLocation( program, "scale" );
glClearColor( 1.0, 1.0, 1.0, 1.0 );
}
//----------------------------------------------------------------------------
void display( void )
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glUniform1f( locTheta, Theta );
glUniform2fv( locScale, 1, ScaleFactor );
glDrawArrays( GL_TRIANGLE_STRIP, 0, NumPoints);
glutSwapBuffers();
}
//----------------------------------------------------------------------------
void reshape( GLsizei w, GLsizei h )
{
glViewport(0, 0, w, h);
// Scale the square to avoid stretching
if (w > h) ScaleFactor[0] = (float)h/w;
if (w < h) ScaleFactor[1] = (float)w/h;
}
//----------------------------------------------------------------------------
void keyboard( unsigned char key, int x, int y )
{
switch( key ) {
case 033: // Escape Key
case 'q': case 'Q':
exit( EXIT_SUCCESS );
break;
}
}
//----------------------------------------------------------------------------
void mouse( int button, int state, int x, int y )
{
if ( state == GLUT_DOWN ) {
switch( button )
{
case GLUT_LEFT_BUTTON:
direction = CCW;
break;
case GLUT_RIGHT_BUTTON:
direction = CW;
break;
}
}
}
//----------------------------------------------------------------------------
void idle( void )
{
// Animate the rotation
if (direction == CW)
Theta += step;
else
Theta -= step;
if ( Theta > 360.0 ) {
Theta -= 360.0;
}
glutPostRedisplay();
}
//----------------------------------------------------------------------------
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowSize( 512, 512 );
glutCreateWindow( "Rotating Color Square" );
glewInit();
init();
glutDisplayFunc( display );
glutReshapeFunc( reshape );
glutKeyboardFunc( keyboard );
glutMouseFunc( mouse );
glutIdleFunc( idle );
glutMainLoop();
return 0;
}
I have Lion 10.7.4 and xCode 4.2.1

glewInit() call (and the includes, of course) is not necessary on MacOS, so you might just exclude it this way:
#ifndef __APPLE__
glewInit();
#endif
The same with includes.
Now with the unresolved symbols. You have to include MacOSX's native GL headers:
#ifdef __APPLE__
# include <OpenGL/gl.h>
# include <OpenGL/glext.h>
#else /// your stuff for linux
# include "GL/GL.h"
.... whatever
#endif
OpenGL is a core technology for OSX, not an "extension", as in Linux/X Window. So just include the OpenGL and GLUT framework to your XCode project and hopefully it should build and work.

Related

How to draw points efficiently

My program receives PCL pointcloud and plot each point one by one using:
glBegin(GL_POINTS);
glVertex3f(point.x, point.y, point].z);
glEnd();
It works but due to the large number of points the program is pretty slow. Is there a more efficient way to do this?
Jam all the points into a big VBO when the point-cloud changes & draw 'em all in one go using a single glDrawArrays() call. That way OpenGL can shift all the vertex data to GPU once instead of you spoon-feeding the driver geometry one glVertex() at a time every frame.
Heck, even vertex arrays will buy you a huge speed-up by avoiding hundreds of thousands of function-calls into the GL driver.
EDIT: Comparison:
10 million random points, using vertex buffer objects:
Vertex arrays:
Display lists:
And using immediate-mode:
Code (hit 'n' to cycle between drawing methods):
// http://glew.sourceforge.net/
#include <GL/glew.h>
// http://freeglut.sourceforge.net/
#include <GL/freeglut.h>
// http://glm.g-truc.net/
#include <glm/glm.hpp>
#include <glm/gtc/random.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <vector>
#include <sstream>
#include <chrono>
#include <cstddef>
struct Vertex
{
glm::vec4 pos;
glm::vec4 color;
};
std::vector< Vertex > verts;
GLuint vbo = 0;
GLuint dlist = 0;
void init()
{
// init geometry
for( size_t i = 0; i < 10000000; i++ )
{
Vertex vert;
vert.pos = glm::vec4( glm::linearRand( glm::vec3( -1.0f, -1.0f, -1.0f ), glm::vec3( 1.0f, 1.0f, 1.0f ) ), 1.0f );
vert.color = glm::vec4( glm::linearRand( glm::vec3( 0.00f, 0.0f, 0.0f ), glm::vec3( 1.0f, 1.0f, 1.0f ) ), 1.0f );
verts.push_back( vert );
}
// create display list
dlist = glGenLists( 1 );
glNewList( dlist, GL_COMPILE );
glBegin( GL_POINTS );
for( size_t i = 0; i < verts.size(); ++i )
{
glColor4fv( glm::value_ptr( verts[i].color) );
glVertex4fv( glm::value_ptr( verts[i].pos) );
}
glEnd();
glEndList();
// create VBO
glGenBuffers( 1, &vbo );
glBindBuffer( GL_ARRAY_BUFFER, vbo );
glBufferData( GL_ARRAY_BUFFER, sizeof( Vertex ) * verts.size(), verts.data(), GL_STATIC_DRAW );
}
unsigned int method = 0;
void keyboard( unsigned char key, int x, int y )
{
if( 'n' == key )
{
method++;
if( method > 3 ) method = 0;
}
}
void display()
{
// timekeeping
static std::chrono::steady_clock::time_point prv = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point cur = std::chrono::steady_clock::now();
const float dt = std::chrono::duration< float >( cur - prv ).count();
prv = cur;
glClearColor( 0, 0, 0, 1 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
gluPerspective( 60.0, w / h, 0.1, 10.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt( 2, 2, 2, 0, 0, 0, 0, 0, 1 );
static float angle = 0.0f;
angle += dt * 6.0f;
glRotatef( angle, 0, 0, 1 );
// render
switch( method )
{
case 0:
// VBO
glBindBuffer( GL_ARRAY_BUFFER, vbo );
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );
glVertexPointer( 4, GL_FLOAT, sizeof( Vertex ), (void*)offsetof( Vertex, pos ) );
glColorPointer( 4, GL_FLOAT, sizeof( Vertex ), (void*)offsetof( Vertex, color ) );
glDrawArrays( GL_POINTS, 0, verts.size() );
glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
break;
case 1:
// vertex array
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );
glVertexPointer( 4, GL_FLOAT, sizeof( Vertex ), &verts[0].pos );
glColorPointer( 4, GL_FLOAT, sizeof( Vertex ), &verts[0].color );
glDrawArrays( GL_POINTS, 0, verts.size() );
glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );
break;
case 2:
// display list
glCallList( dlist );
break;
case 3:
// immediate mode
glBegin( GL_POINTS );
for( size_t i = 0; i < verts.size(); ++i )
{
glColor4fv( glm::value_ptr( verts[i].color) );
glVertex4fv( glm::value_ptr( verts[i].pos) );
}
glEnd();
break;
}
// info/frame time output
std::stringstream msg;
msg << "Using ";
switch( method )
{
case 0: msg << "vertex buffer object"; break;
case 1: msg << "vertex array"; break;
case 2: msg << "display list"; break;
case 3: msg << "immediate mode"; break;
}
msg << std::endl;
msg << "Frame time: " << (dt * 1000.0f) << " ms";
glColor3ub( 255, 255, 0 );
glWindowPos2i( 10, 25 );
glutBitmapString( GLUT_BITMAP_9_BY_15, (unsigned const char*)( msg.str().c_str() ) );
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glewInit();
init();
glutDisplayFunc( display );
glutKeyboardFunc( keyboard );
glutIdleFunc( display );
glutMainLoop();
return 0;
}
Yes definitely, the code you are showing is from a quite old version of OpenGL.
In more recent versions you can pack your data together and send it to the GPU in one call. The code becomes a little bit more complex but it is worth it.
I suggest you to look at this website : https://learnopengl.com/
It gathers everything you need to start using modern opengl.
Hope it helped.

Unable to display a vertex in the world

I am not able to plot the vertex glVertex2f( 10.0, 0.0 ) in the window, but when I use points like 0.8 it shows up.
Height = 640
Width = 480
So, I might be able to plot points in this range I guess. Can anyone point out the mistake and correct it?
Code:
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <cstdlib>
//defining constants
#define MAX_WIDTH 640
#define MAX_HEIGHT 480
//display callback function
void display(){
glClear( GL_COLOR_BUFFER_BIT );
glPointSize( 5 );
glLoadIdentity();
gluLookAt( 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 1.0, 0.0 );
glBegin( GL_POINTS );
//setting the pointer color
glColor3f( 1.0, 1.0, 1.0 );
glVertex2f( 0.0, 0.0 );
glVertex2f( 10.0, 0.0 );
glEnd();
glFlush();
}
//catching keyboard events
void keyboardEvent( unsigned char c, int x, int y ){
if( c == 27 ){
exit(0);
}
}
//catching mouse click events
void mouseEvent( int button, int state, int x, int y ){
//checking if the mouse button is clicked or not using state para.
if( state == GLUT_DOWN ){
if( button == GLUT_LEFT_BUTTON ){
}
else if( button == GLUT_RIGHT_BUTTON ){
}
}
}
//adjusting window when it is moved or resized
void reshape( int w, int h ){
glViewport( 0, 0, w, h );
}
//initialising the window at startup
void initialise(){
glClearColor( 0.0, 0.0, 0.0, 1.0 );
gluOrtho2D( 0, MAX_WIDTH, 0, MAX_HEIGHT );
}
int main( int argc, char **argv ){
//initialising the glut library
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
glutInitWindowSize( MAX_WIDTH, MAX_HEIGHT );
glutInitWindowPosition( 100, 100 );
glutCreateWindow("DDA Assignment");
//calling normal functions
initialise();
//registering callback functions
glutDisplayFunc( display );
glutKeyboardFunc( keyboardEvent );
glutMouseFunc( mouseEvent );
glutReshapeFunc( reshape );
glutMainLoop();
return 0;
}
The glLoadIdentity() in display() is wiping out the matrix set by gluOrtho2D() in initialise().

glEvalCoord when used with glFeedback is not giving output as expected

I am trying to read the value from glEvalCoord, but not getting the exact values which I should get. My code is
GLfloat ctrlpoints[4][3] = {
{ -4.0, -4.0, 0.0}, { -2.0, 4.0, 0.0},
{ 2.0, -4.0, 0.0}, { 4.0, 4.0, 0.0}};
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glEnable(GL_LIGHTING);
glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints[0][0]);
glEnable(GL_MAP1_VERTEX_3);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
GLint size;
GLfloat feedBuffer[1024];
glFeedbackBuffer (1024, GL_3D, feedBuffer);
glRenderMode (GL_FEEDBACK);
glBegin (GL_POINTS);
for (int i=0; i<=30; ++i)
{
GLfloat t = GLfloat(i)/30;
glEvalCoord1f(t);
}
glEnd();
size = glRenderMode (GL_RENDER);
cerr<<size<<endl;
}
Now, I am not sure but shouldn't it give me 30*3 values for each of the x, y and z coordinates of the curve?? But I am getting only 7*3 values. And the output of size is 28.
I think your size is 28 because your projection/modelview pair is clipping out some points.
"In feedback mode, each primitive that would be rasterized ... generates a block of values that's copied into the feedback array."
Try this:
#include <GL/glut.h>
#include <iostream>
using namespace std;
void display()
{
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
double ar = w / h;
glOrtho( -5 * ar, 5 * ar, -5, 5, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
GLfloat ctrlpoints[4][3] =
{
{ -4.0, -4.0, 0.0 }, { -2.0, 4.0, 0.0 },
{ 2.0, -4.0, 0.0 }, { 4.0, 4.0, 0.0 }
};
glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints[0][0]);
glEnable(GL_MAP1_VERTEX_3);
GLfloat feedBuffer[1024];
glFeedbackBuffer (1024, GL_3D, feedBuffer);
glRenderMode (GL_FEEDBACK);
glPointSize( 5 );
glColor3ub( 255, 255, 255 );
glBegin (GL_POINTS);
for (int i=0; i<=30; ++i)
{
GLfloat t = GLfloat(i)/30;
glEvalCoord1f(t);
}
glEnd();
GLint size = glRenderMode (GL_RENDER);
cerr << size << endl;
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 640, 480 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutMainLoop();
return 0;
}
I added a slightly larger projection matrix.
With that I get a size of 124:
31 points * 3 floats per point = 93
31 points * 1 GL_POINT_TOKEN per point = 31
31 + 91 = 124

OpenGl not rendering .obj files correctly

I have been given the task of importing an obj file and loading it up in C++.
Its loading the file correctly but displainy it incorrectly. Can anybody see anything wrong with my setup of opengl stuff? :)
Here is a picture of what the render looks like atm
#define _USE_MATH_DEFINES
#include<stdio.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include "InitShader.h"
#include <math.h>
#include "MatrixStack.h"
#include "Object.h"
#include <time.h>
#define BUFFER_OFFSET( offset ) ((GLvoid*) (offset))
float x = 1.0;
const int NumVertices = 144;
const int NumIndicies = 104;
GLfloat vertices[NumVertices];
// RGBA olors
GLfloat vertexColours[NumVertices];
// each entry is an index into the vertices matrix
GLint vertexIndicies[NumIndicies];
//GLfloat vertices2[NumVertices];
// RGBA olors
//GLfloat vertexColours2[NumVertices];
// each entry is an index into the vertices matrix
//GLint vertexIndicies2[NumIndicies];
GLuint vao;
GLuint program;
GLuint buffers[2];
GLfloat radius = 1.0;
GLfloat theta = 0.0;
GLfloat phi = 0.0;
const GLfloat dr = 5.0 * M_PI/180.0;
// Projection transformation parameters
GLfloat left2 = -1.0, right2 = 1.0;
GLfloat bottom = -1.0, top = 1.0;
GLfloat zNear = 0.5, zFar = 3.0;
GLuint modelView; // model-view matrix uniform shader variable location
GLuint projection; // projection matrix uniform shader variable location
MatrixStack modelViewStack(5);
MatrixStack projectionStack(5);
// OpenGL initialization
void
init()
{
srand ( time(NULL) );
Object myst("assignment1.obj");
float *tempFloat = myst.verts();
float *tempFloat2 = myst.indis();
for (unsigned int i=0; i<NumVertices; vertices[i]=tempFloat[i],i++);
for (unsigned int i=0; i<NumIndicies; vertexIndicies[i]=tempFloat2[i],i++);
for (unsigned int i=0; i<NumVertices;i++){
float a = (float)(rand()%10);
a = a/10;
cout << a;
vertexColours[i]=a;
}
for (unsigned int i=0; i<NumVertices; cout << vertices[i] << endl ,i++);
for (unsigned int i=0; i<NumIndicies; cout << vertexIndicies[i] << endl ,i++);
glEnable( GL_DEPTH_TEST );
//make background yerpul in colour
glClearColor( 0.235, 0.194, 0.314, 1.0 );
// Load shaders and use the resulting shader program
program = InitShader( "vshader41.glsl", "fshader41.glsl" );
glUseProgram( program );
// Create a vertex array object
glGenVertexArrays( 1, &vao );
glBindVertexArray( vao );
// Create and initialize two buffer objects
glGenBuffers( 2, buffers);
//one buffer for the vertices and colours
glBindBuffer( GL_ARRAY_BUFFER, buffers[0]);
glBufferData( GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(vertexColours),NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(vertices), sizeof(vertexColours), vertexColours);
//one buffer for the indices
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, buffers[1]);
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(vertexIndicies),vertexIndicies, GL_STATIC_DRAW );
// set up vertex arrays
GLuint vPosition = glGetAttribLocation( program, "vPosition" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );
GLuint vColor = glGetAttribLocation( program, "vColor" );
glEnableVertexAttribArray( vColor );
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)) );
modelView = glGetUniformLocation( program, "model_view" );
projection = glGetUniformLocation( program, "projection" );
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
//----------------------------------------------------------------------------
void
display( void )
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
modelViewStack.loadIdentity();
modelViewStack.lookAt(radius*sin(theta)*cos(phi),
radius*sin(theta)*sin(phi),
radius*cos(theta),
0.0,0.0,0.0,
0.0,1.0,0.0);
glUniformMatrix4fv(modelView, 1, GL_FALSE, modelViewStack.getMatrixf());
projectionStack.loadIdentity();
projectionStack.ortho(left2,right2,bottom,top,zNear,zFar);
glUniformMatrix4fv(projection, 1, GL_FALSE, projectionStack.getMatrixf());
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);
//Indexing into vertices we need to use glDrawElements
glDrawElements (GL_TRIANGLES, NumIndicies, GL_UNSIGNED_INT, 0);
glutSwapBuffers();
}
//----------------------------------------------------------------------------
void keyboard( unsigned char key, int x, int y )
{
switch( key ) {
case 033: // Escape Key
case 'q': case 'Q':
exit( EXIT_SUCCESS );
break;
case 'x': left2 *= 1.1; right2 *= 1.1; break;
case 'X': left2 *= 0.9; right2 *= 0.9; break;
case 'y': bottom *= 1.1; top *= 1.1; break;
case 'Y': bottom *= 0.9; top *= 0.9; break;
case 'z': zNear *= 0.9; zFar *= 1.1; break;
case 'Z': if (zNear<zFar){zNear *= 1.1; zFar *= 0.9;} break;
case 'r': radius *= 2.0; break;
case 'R': radius *= 0.5; break;
case 'o': theta += dr; break;
case 'O': theta -= dr; break;
case 'p': phi += dr; break;
case 'P': phi -= dr; break;
case ' ': // reset values to their defaults
left2 = -1.0;
right2 = 1.0;
bottom = -1.0;
top = 1.0;
zNear = -1.0;
zFar = 1.0;
radius = 1.0;
theta = 0.0;
phi = 0.0;
break;
}
glutPostRedisplay();
}
//----------------------------------------------------------------------------
void idle(){
theta += .001;
left2 += .0001;
glutPostRedisplay();
}
//----------------------------------------------------------------------------
void
reshape( int width, int height )
{
glViewport( 0, 0, width, height );
}
//----------------------------------------------------------------------------
int
main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowSize( 512, 512 );
glutCreateWindow( "Orbit the Color Cube - Orthographic" );
glewInit();
init();
glutIdleFunc(idle);
glutDisplayFunc( display );
glutKeyboardFunc( keyboard );
glutReshapeFunc( reshape );
glutMainLoop();
return 0;
}
The vertex indexes of the faces in the .obj file starts at 1, not 0 as might be expected. Try to decrease each index with 1 when you load the file. If I read your code correctly, this line:
for (unsigned int i=0; i<NumIndicies; vertexIndicies[i]=tempFloat2[i],i++);
should be
for (unsigned int i=0; i<NumIndicies; vertexIndicies[i]=tempFloat2[i] - 1,i++);

OpenGl display animation and draw text

I want to display the solar system and draw a simple text saying " Hello world " :
This code below display the solar system and everything works:
#include <iostream>
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
void OpenGLInit(void);
static void Animate(void );
static void Key_r(void );
static void Key_s(void );
static void Key_up(void );
static void Key_down(void );
static void ResizeWindow(int w, int h);
static void KeyPressFunc( unsigned char Key, int x, int y );
static void SpecialKeyFunc( int Key, int x, int y );
static GLenum spinMode = GL_TRUE;
static GLenum singleStep = GL_FALSE;
// These three variables control the animation's state and speed.
static float HourOfDay = 0.0;
static float DayOfYear = 0.0;
static float AnimateIncrement = 24.0; // Time step for animation (hours)
// glutKeyboardFunc is called below to set this function to handle
// all normal key presses.
static void KeyPressFunc( unsigned char Key, int x, int y )
{
switch ( Key ) {
case 'R':
case 'r':
Key_r();
break;
case 's':
case 'S':
Key_s();
break;
case 27: // Escape key
exit(1);
}
}
// glutSpecialFunc is called below to set this function to handle
// all special key presses. See glut.h for the names of
// special keys.
static void SpecialKeyFunc( int Key, int x, int y )
{
switch ( Key ) {
case GLUT_KEY_UP:
Key_up();
break;
case GLUT_KEY_DOWN:
Key_down();
break;
}
}
static void Key_r(void)
{
if ( singleStep ) { // If ending single step mode
singleStep = GL_FALSE;
spinMode = GL_TRUE; // Restart animation
}
else {
spinMode = !spinMode; // Toggle animation on and off.
}
}
static void Key_s(void)
{
singleStep = GL_TRUE;
spinMode = GL_TRUE;
}
static void Key_up(void)
{
AnimateIncrement *= 2.0; // Double the animation time step
}
static void Key_down(void)
{
AnimateIncrement /= 2.0; // Halve the animation time step
}
/*
* Animate() handles the animation and the redrawing of the
* graphics window contents.
*/
static void Animate(void)
{
// Clear the redering window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (spinMode) {
// Update the animation state
HourOfDay += AnimateIncrement;
DayOfYear += AnimateIncrement/24.0;
HourOfDay = HourOfDay - ((int)(HourOfDay/24))*24;
DayOfYear = DayOfYear - ((int)(DayOfYear/365))*365;
}
// Clear the current matrix (Modelview)
glLoadIdentity();
// Back off eight units to be able to view from the origin.
glTranslatef ( 0.0, 0.0, -8.0 );
// Rotate the plane of the elliptic
// (rotate the model's plane about the x axis by fifteen degrees)
glRotatef( 15.0, 1.0, 0.0, 0.0 );
// Draw the sun -- as a yellow, wireframe sphere
glColor3f( 1.0, 1.0, 0.0 );
glutWireSphere( 1.0, 15, 15 );
// Draw the Earth
// First position it around the sun
// Use DayOfYear to determine its position
glRotatef( 360.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
glTranslatef( 4.0, 0.0, 0.0 );
glPushMatrix(); // Save matrix state
// Second, rotate the earth on its axis.
// Use HourOfDay to determine its rotation.
glRotatef( 360.0*HourOfDay/24.0, 0.0, 1.0, 0.0 );
// Third, draw the earth as a wireframe sphere.
glColor3f( 0.2, 0.2, 1.0 );
glutWireSphere( 0.4, 10, 10);
glPopMatrix(); // Restore matrix state
// Draw the moon.
// Use DayOfYear to control its rotation around the earth
glRotatef( 360.0*12.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
glTranslatef( 0.7, 0.0, 0.0 );
glColor3f( 0.3, 0.7, 0.3 );
glutWireSphere( 0.1, 5, 5 );
// Flush the pipeline, and swap the buffers
glFlush();
glutSwapBuffers();
if ( singleStep ) {
spinMode = GL_FALSE;
}
glutPostRedisplay(); // Request a re-draw for animation purposes
}
// Initialize OpenGL's rendering modes
void OpenGLInit(void)
{
glShadeModel( GL_FLAT );
glClearColor( 0.0, 0.0, 0.0, 0.0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
}
// ResizeWindow is called when the window is resized
static void ResizeWindow(int w, int h)
{
float aspectRatio;
h = (h == 0) ? 1 : h;
w = (w == 0) ? 1 : w;
glViewport( 0, 0, w, h ); // View port uses whole window
aspectRatio = (float)w/(float)h;
// Set up the projection view matrix (not very well!)
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 60.0, aspectRatio, 1.0, 30.0 );
// Select the Modelview matrix
glMatrixMode( GL_MODELVIEW );
}
// Main routine
// Set up OpenGL, hook up callbacks, and start the main loop
int main( int argc, char** argv )
{
// Need to double buffer for animation
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
// Create and position the graphics window
glutInitWindowPosition( 0, 0 );
glutInitWindowSize( 600, 360 );
glutCreateWindow( "Solar System Demo" );
// Initialize OpenGL.
OpenGLInit();
// Set up callback functions for key presses
glutKeyboardFunc( KeyPressFunc );
glutSpecialFunc( SpecialKeyFunc );
// Set up the callback function for resizing windows
glutReshapeFunc( ResizeWindow );
// Callback for graphics image redrawing
glutDisplayFunc( Animate );
// Start the main loop. glutMainLoop never returns.
glutMainLoop( );
return(0); // Compiler requires this to be here. (Never reached)
}
The code below draw text " Hello world " and works too:
#include <iostream>
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
void drawBitmapText(char *string,float x,float y,float z)
{
char *c;
glRasterPos3f(x, y,z);
for (c=string; *c != '\0'; c++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
}
}
void drawStrokeText(char*string,int x,int y,int z)
{
char *c;
glPushMatrix();
glTranslatef(x, y+8,z);
// glScalef(0.09f,-0.08f,z);
for (c=string; *c != '\0'; c++)
{
glutStrokeCharacter(GLUT_STROKE_ROMAN , *c);
}
glPopMatrix();
}
void reshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,w,h,0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void render(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glColor3f(0,1,0);
drawBitmapText("Hello world",200,200,0);
glutSwapBuffers();
}
// Main routine
// Set up OpenGL, hook up callbacks, and start the main loop
int main( int argc, char** argv )
{
// Need to double buffer for animation
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
// Create and position the graphics window
glutInitWindowPosition( 0, 0 );
glutInitWindowSize( 600, 360 );
glutCreateWindow( "Solar System Demo" );
glutDisplayFunc(render);
glutIdleFunc(render);
glutReshapeFunc(reshape);
// Start the main loop. glutMainLoop never returns.
glutMainLoop( );
return(0); // Compiler requires this to be here. (Never reached)
}
i'm trying to use both of them together to display the solar system and draw the text, but
i'm getting a blank, black screen:
#include <iostream>
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
void OpenGLInit(void);
static void Animate(void );
static void Key_r(void );
static void Key_s(void );
static void Key_up(void );
static void Key_down(void );
static void ResizeWindow(int w, int h);
static void KeyPressFunc( unsigned char Key, int x, int y );
static void SpecialKeyFunc( int Key, int x, int y );
static GLenum spinMode = GL_TRUE;
static GLenum singleStep = GL_FALSE;
// These three variables control the animation's state and speed.
static float HourOfDay = 0.0;
static float DayOfYear = 0.0;
static float AnimateIncrement = 24.0; // Time step for animation (hours)
// glutKeyboardFunc is called below to set this function to handle
// all normal key presses.
static void KeyPressFunc( unsigned char Key, int x, int y )
{
switch ( Key ) {
case 'R':
case 'r':
Key_r();
break;
case 's':
case 'S':
Key_s();
break;
case 27: // Escape key
exit(1);
}
}
// glutSpecialFunc is called below to set this function to handle
// all special key presses. See glut.h for the names of
// special keys.
static void SpecialKeyFunc( int Key, int x, int y )
{
switch ( Key ) {
case GLUT_KEY_UP:
Key_up();
break;
case GLUT_KEY_DOWN:
Key_down();
break;
}
}
static void Key_r(void)
{
if ( singleStep ) { // If ending single step mode
singleStep = GL_FALSE;
spinMode = GL_TRUE; // Restart animation
}
else {
spinMode = !spinMode; // Toggle animation on and off.
}
}
static void Key_s(void)
{
singleStep = GL_TRUE;
spinMode = GL_TRUE;
}
static void Key_up(void)
{
AnimateIncrement *= 2.0; // Double the animation time step
}
static void Key_down(void)
{
AnimateIncrement /= 2.0; // Halve the animation time step
}
/*
* Animate() handles the animation and the redrawing of the
* graphics window contents.
*/
static void Animate(void)
{
// Clear the redering window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (spinMode) {
// Update the animation state
HourOfDay += AnimateIncrement;
DayOfYear += AnimateIncrement/24.0;
HourOfDay = HourOfDay - ((int)(HourOfDay/24))*24;
DayOfYear = DayOfYear - ((int)(DayOfYear/365))*365;
}
// Clear the current matrix (Modelview)
glLoadIdentity();
// Back off eight units to be able to view from the origin.
glTranslatef ( 0.0, 0.0, -8.0 );
// Rotate the plane of the elliptic
// (rotate the model's plane about the x axis by fifteen degrees)
glRotatef( 15.0, 1.0, 0.0, 0.0 );
// Draw the sun -- as a yellow, wireframe sphere
glColor3f( 1.0, 1.0, 0.0 );
glutWireSphere( 1.0, 15, 15 );
// Draw the Earth
// First position it around the sun
// Use DayOfYear to determine its position
glRotatef( 360.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
glTranslatef( 4.0, 0.0, 0.0 );
glPushMatrix(); // Save matrix state
// Second, rotate the earth on its axis.
// Use HourOfDay to determine its rotation.
glRotatef( 360.0*HourOfDay/24.0, 0.0, 1.0, 0.0 );
// Third, draw the earth as a wireframe sphere.
glColor3f( 0.2, 0.2, 1.0 );
glutWireSphere( 0.4, 10, 10);
glPopMatrix(); // Restore matrix state
// Draw the moon.
// Use DayOfYear to control its rotation around the earth
glRotatef( 360.0*12.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
glTranslatef( 0.7, 0.0, 0.0 );
glColor3f( 0.3, 0.7, 0.3 );
glutWireSphere( 0.1, 5, 5 );
// Flush the pipeline, and swap the buffers
glFlush();
glutSwapBuffers();
if ( singleStep ) {
spinMode = GL_FALSE;
}
glutPostRedisplay(); // Request a re-draw for animation purposes
}
// Initialize OpenGL's rendering modes
void OpenGLInit(void)
{
glShadeModel( GL_FLAT );
glClearColor( 0.0, 0.0, 0.0, 0.0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
}
// ResizeWindow is called when the window is resized
static void ResizeWindow(int w, int h)
{
float aspectRatio;
h = (h == 0) ? 1 : h;
w = (w == 0) ? 1 : w;
glViewport( 0, 0, w, h ); // View port uses whole window
aspectRatio = (float)w/(float)h;
// Set up the projection view matrix (not very well!)
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 60.0, aspectRatio, 1.0, 30.0 );
// Select the Modelview matrix
glMatrixMode( GL_MODELVIEW );
}
void drawBitmapText(char *string,float x,float y,float z)
{
char *c;
glRasterPos3f(x, y,z);
for (c=string; *c != '\0'; c++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
}
}
void drawStrokeText(char*string,int x,int y,int z)
{
char *c;
glPushMatrix();
glTranslatef(x, y+8,z);
// glScalef(0.09f,-0.08f,z);
for (c=string; *c != '\0'; c++)
{
glutStrokeCharacter(GLUT_STROKE_ROMAN , *c);
}
glPopMatrix();
}
void reshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,w,h,0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void render(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glColor3f(0,1,0);
drawBitmapText("Hello world",200,200,0);
glutSwapBuffers();
}
// Main routine
// Set up OpenGL, hook up callbacks, and start the main loop
int main( int argc, char** argv )
{
// Need to double buffer for animation
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
// Create and position the graphics window
glutInitWindowPosition( 0, 0 );
glutInitWindowSize( 600, 360 );
glutCreateWindow( "Solar System Demo" );
// Initialize OpenGL.
OpenGLInit();
// Set up callback functions for key presses
glutKeyboardFunc( KeyPressFunc );
glutSpecialFunc( SpecialKeyFunc );
// Set up the callback function for resizing windows
glutReshapeFunc( ResizeWindow );
// Callback for graphics image redrawing
glutDisplayFunc( Animate );
glutDisplayFunc(render);
glutIdleFunc(render);
glutReshapeFunc(reshape);
// Start the main loop. glutMainLoop never returns.
glutMainLoop( );
return(0); // Compiler requires this to be here. (Never reached)
}
These lines in main() cause the problem:
glutKeyboardFunc( KeyPressFunc );
glutSpecialFunc( SpecialKeyFunc );
glutReshapeFunc( ResizeWindow );
glutDisplayFunc( Animate );
glutDisplayFunc(render);
glutIdleFunc(render);
The glutDisplayFunc() overwrites the internal function pointer inside the GLUT. So only the render() function gets called, not the Animate().
The second problem here: Idle function is also the render(), so it gets called twice. The same with Reshape function.
You need to combine the ResizeWindow() and reshape() functions, then render() and Animate() function and then remove the glutIdleFunc call since iteverything is done in the render() already.