title: Move camera to fit 3D scene
body: <p>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.</p>
  
  <p><strong>I have most of the data:</strong></p>
  
  <ul>
  <li>I have the up-vector for the camera</li>
  <li>I have the center point of the bounding box</li>
  <li>I have the look-at vector (direction and distance) from the camera point to the box center</li>
  <li>I have projected the points on a plane perpendicular to the camera and retrieved the coefficients describing how much the max/min X and Y coords are within or outside the viewing plane.</li>
  </ul>
  
  <p><strong>Problems I have:</strong></p>
  
  <ul>
  <li>Center of the bounding box isn't necessarily in the center of the viewport (that is, it's bounding rectangle after projection).</li>
  <li>Since the field of view "skew" the projection (see <a href="http://en.wikipedia.org/wiki/File:Perspective-foreshortening.svg" rel="noreferrer">http://en.wikipedia.org/wiki/File:Perspective-foreshortening.svg</a>) I cannot simply use the coefficients as a scale factor to move the camera because it will overshoot/undershoot the desired camera position</li>
  </ul>
  
  <p>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)?</p>
  
  <p><strong>I've tried some other things:</strong></p>
  
  <ul>
  <li>Using a bounding sphere and Tangent to find a scale factor to move the camera. This doesn't work well, because, it doesn't take into account the perspective projection, and secondly spheres are bad bounding volumes for my use because I have a lot of flat and long geometries.</li>
  <li>Iterating calls to the function to get a smaller and smaller error in the camera position. This has worked somewhat, but I can sometimes run into weird edge cases where the camera position overshoots too much and the error factor increases. Also, when doing this I didn't recenter the model based on the position of the bounding rectangle. I couldn't find a solid, robust way to do that reliably.</li>
  </ul>
  
  <p>Help please!</p>