Filling the view (using perspective or frustum)?

Hey all,
I am extremely new to OpenGL but I’ve had to jump right in and sink or swim for a project at work. I am writing a program that allows users to dynamically create models we want to display in 3d. I have the model drawing (at least the basic structures) completed and have a hard coded perspective view (using gluPerspective) that works with my test file so I can see it.

My question is this: Since this is a dynamically generated model, I want to be able to implement essentially a “Zoom to Extent” function. I know all the max and min values for x, y, and z in my model. How do I create a view so that the entire model is visible in the viewport? I also know the vector and angle of rotation at all times – the rotation is interactively defined. I’m still too fuzzy on the projection functions to be able to work it out in my head. :confused:

Any help would be greatly appreciated. Thanks.

A common approach to this problem is to find a suitable bounding object for the model, then fit the bounds in the screen. A sphere is a convenient shape to work with, and is a good fit for reasonably symmetric objects.

Since you already have the AABB (axis aligned bounding box), all we need to do is created a sphere centered at the box’s origin, with a radius equal to the distance of any box vertex to the sphere’s center.

Now, with a little trig, we can determine the information needed (field of view) for the gluPerspective() call call (this will work with glFrustum() too).

If you imagine the situation in 2D, with a sphere, and the viewpoint off to the left, the 2 lines from the viewpoint tangent to the sphere form an ice cream cone. Now, take one tangent line, and a line from the viewpoint to the sphere’s center, and a line from the sphere’s center to the tangent point, and you have a right triangle, all we need.

tan(fov/2) = r / d

where r is the radius of the sphere, d is the distance from the viewpoint to the sphere’s center, and fov is the field of view we seek.

Solving for fov in degrees

fov = 2 arctan( r / d ) * (180 / PI)

I hope this helps.

Originally posted by Q:
Solving for fov in degrees
fov = 2 arctan( r / d ) * (180 / PI)

I’m solving for d in my implementation to keep the fov always the same.

d = r / tan(fov/2)

The camera is then set to distance d to the object.

If you change the fov, the view warps. It should be 45 for a “normal” fov, I personally use 35 which looks realistic to me.