1

OH Great and Knowledgeable Stack Overflow, I humbly request your great minds assistance...

I'm using the three js library, and I need to implement a 'show extents' button. It will move the camera to a position such that all the objects in the world are visible in the camera view (given they are not blocked of course).

I can find the bounding box of all the objects in the world, say they are w0x,w0y,w0z and w1x,w1y,w1z

How can I, given these to bounds, place the camera such that it will have a clear view of the edges of the box?

Obviously there will have to be a 'side' chosen to view from...I've googled for an algorithm to no avail! Thanks!

user2016641
  • 59
  • 1
  • 8
  • See http://stackoverflow.com/questions/14614252/how-to-fit-camera-to-object/14614736#14614736 and http://stackoverflow.com/questions/11274358/adjusting-camera-for-visible-three-js-shape – WestLangley Feb 14 '13 at 22:10

1 Answers1

1

So Let's say that you have picked a face. and that you are picking a camera position so that the camera's line-of-sight is parallel to one of the axes.

Let's say that the face has a certain width, "w", and let's say that your camera has a horizontal field-of-view "a". What you want to figure out is what is the distance, "d" from the center of the face that the camera should be to see the whole width.

If you draw it out you will see that you basically have an isosceles triangle whose base is length w and with the angle a at the apex.

isoceles triangle

Not only that but the angle bisector of the apex angle forms two identical right triangles and it's length (to the base) is the distance we need to figure out.

Trig tells us that the tangent of an angle is the ratio of the oposite and adjacent sides of the triangle. So

tan(a/2) = (w/2) / d

simplifying to:

d = w / 2*tan(a/2)

So if you are placing the camera some axis-aligned distance from one of your bounding box faces then you just need to move d distance along the axis of choice.

Some caveats, make sure you are using radians for the javascript trig function input. Also you may have to compute this again for your face height and camera's vertical field-of-view and pick the farther distance if your face is not square.

If you want to fit the bounding box from an arbitrary angle you can use the same ideas - but first you have to find the (aligned) bounding box of the scene projected onto a plane perpendicular to the camera's line of sight

Superboggly
  • 5,804
  • 2
  • 24
  • 27