I'm currently working on a 3D editor and we can load very very small models or very very big ones...

The problem I have is during display, due to bad zNear and zFar... I got a lot of undesired effects.

I have search the web for a solution, but found nothing....

What I would like is to compute the zNear and zFar to use depending of my scene. By example by looking at the scene bounding box and the camera position & camera target...

I have try the following, but I can't acheive very good results... if someone can help ?

float viewportWidth = (float)surface->GetWidth(); float viewportHeight = (float)surface->GetHeight(); glViewport(0, 0, (GLsizei)viewportWidth, (GLsizei)viewportHeight); // Default float aspectRatio = viewportWidth / viewportHeight; //---- Set up the view glMatrixMode(GL_PROJECTION); // Set up the projection glLoadIdentity(); if (!camera) { gluPerspective(45, aspectRatio, 0.1f, 1000.f); return; } // reference : http://www.sjbaker.org/steve/omniv/love_your_z_buffer.html // delta = z * z / ( zNear * (1<<N) - z ) // // Where: // // N = number of bits of Z precision // zNear = distance from eye to near clip plane // z = distance from the eye to the object // delta = the smallest resolvable Z separation at this range. // Also see : http://sightations.wordpress.com/tag/opengl/ //---- Calculate optimal near and far Z clipping planes float sceneRadius; sceneRadius = (camera->GetEye() - camera->GetEyeAt()).Length() * 2.f; // Based on the current target BB // Get buffer properties GLint mDepthBufferResolution = 16; glGetIntegerv(GL_DEPTH_BITS, &mDepthBufferResolution); float zFar = 2.f * sceneRadius + (camera->GetEye() - camera->GetEyeAt()).Length(); if (zFar < 1e-20f) zFar = 1e-20f; float zNear; if (mDepthBufferResolution >= 24) zNear = 0.00001f * zFar; else zNear = 0.01f * zFar; if (zNear < 1e-20f) zNear = 1e-20f; float Zoom = 1.f; VNFilm* film = surface->GetScene()->GetFilm(); if (film && !film->GetAutoSize()) { float filmHeight = (float)film->GetHeight(); Zoom = viewportHeight / filmHeight; } // Reference : http://www.opengl.org/resources/faq/technical/transformations.htm float fov = camera->GetFOV() * 0.5f * (M_PI_F/180.f); float top = tan(fov) * zNear; float bottom = -top; float left = aspectRatio * bottom; float right = aspectRatio * top; glFrustum(Zoom * left, Zoom * right, Zoom * bottom, Zoom * top, zNear, zFar);