centering loaded objects

I am loading objects into my program and I need a way (no matter how large or small the object) to center it on the screen. I can calculate the x y z max and min and the center of the object but I can’t figure out how to implement the viewing in opengl. Any suggestions.

You can achieve this by using a reshape function if using GLUT:

Sample:

void reshape( int w, int h ) {
if( h == 0 )
h = 1;

float ratio = 1.0 * w / h;

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glViewport( 0, 0, w, h );

gluPerspective( 25, ratio, 1, 1000 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt( 0.0, 0.0, 5.0, 0.0, 0.0, -1.0, 0.0f, 1.0f, 0.0f );
}

  • VC6-OGL - Hope this helps.

Yes this helps but does the size of the object not matter

It should not matter. It just center’s the screen no matter what screen resolution.

  • VC6-OGL

Example of a centering object:

#include <gl/glut.h>

void init( void ) {
glClearColor ( 0.0, 0.0, 0.0, 0.0 );
glShadeModel ( GL_SMOOTH );
glEnable ( GL_DEPTH_TEST );
}

void reshape( int w, int h ) {
if( h == 0 )
h = 1;

float ratio = 1.0 * w / h;

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glViewport( 0, 0, w, h );

gluPerspective( 25, ratio, 1, 1000 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt( 0.0, 0.0, 5.0, 0.0, 0.0, -1.0, 0.0f, 1.0f, 0.0f );
}

void display( void ) {
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glPushMatrix();

glBegin( GL_POLYGON );
glVertex3f( -1.0, 1.0, -1.0 );
glVertex3f( 1.0, 1.0, -1.0 );
glVertex3f( 1.0, -1.0, -1.0 );
glVertex3f( -1.0, -1.0, -1.0 );
glEnd();

glPopMatrix();

glutSwapBuffers();
}

void keyboard( unsigned char key, int x, int y ) {
switch ( key ) {
case 27:
exit( 0 );
break;
}
}

void main( int argc, char **argv ) {
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA );
glutEnterGameMode();
init();
glutDisplayFunc( display );
glutIdleFunc( display );
glutReshapeFunc( reshape );
glutKeyboardFunc( keyboard );

glutMainLoop();
}

I guess in most model/object loading code you would scale the model so it fits inside the unit cube. Then you scale it to whatever size you like. If you are using other peoples models this is a must since everyone uses their own “scales” when modelling.

[This message has been edited by roffe (edited 12-12-2002).]

ok thanks this helps alot

You are welcome!!!

  • VC6-OGL