I'm looking for an algorithm to fit a bounding box inside a viewport (in my case a DirectX scene). I know about algorithms for centering a bounding sphere in a orthographic camera but would need the same for a bounding box and a perspective camera. I can not just change the FOV because this app has FOV as a user editable variable, so it must move the camera.
I have most of the data:
Problems I have:
How do I find the camera position so that it fills the viewport as pixel perfect as possible (exception being if the aspect ratio is far from 1.0, it only needs to fill one of the screen axis)?
I've tried some other things:
Help please!
There are many possible camera positions + orientations where the bounding box would fit inside the view frustum. But any procedure would select one specific camera position and orientation.
If you would consider bounding spheres, one solution could be to
With bounding boxes you could consider an earlier step of first positioning the camera at perpendicular to the center of the largest (or smallest, whatever you prefer) cube face.
I have no experience with DirectX, but moving and changing the looking direction of the camera to center a certain point should be easy. The hard part is to do the math of deciding how far to move to view the object.
If you know the bounding size s
of the object in world coordinates (we are not interested in pixels or camera coordinates, since those are dependent on your distance) from the orientation of the camera, you can compute the required distance d
of the camera to the bounding shape if you know the x and y Field-Of-View angle a
of the perspective projection.
frustum ------
------ ***** -
----- * * |
-=== ) FOV a *bounding box | BB size s
camera ----- * * |
------ ***** -
------
|-------------------|
distance d
So, the math is tan(a/2) = (s/2) / d
=> d = (s/2) / tan(a/2)
Which will give you the distance the camera should be placed from the closest bounding surface.