3d zoom fit (directX, perspective) implementation needs direction

Posted on 2006-10-25
Last Modified: 2013-12-26
I am creating a zoom fit function for a 3d model.  Using DirectX 9, VB.NET (C# and C++ OK), right hand coord system, and perspective view.  I have reviewed
but still have some problems.

Basically, I need some direction (psuedocode) on an overall approach.  The above post was for ortho projections, and did not seem to work completely in my case.  Currently, I can transform all my world space vertices to screen space using Vector3.TransformCoordinate(vertex(i),matView*matProj).  This gives me a cloud of screen points, some of which are outside the current screen display (-1 to 1 in x and y directions).  Next, I calculate the world space coordinate of the center of a 2D screen bounding box (bb) containing all the transformed points using Vector3.TransformCoordinate(bb_center,Inverse(matView*matProj)), and move my camera target to that world space location, while also moving the camera position the same relative amount to preserve the camera look direction.  The effectivly "centers" the model, but I still need to determine how to adjust distance between camera position and camera target to effectivly zoom in/out such that the bound box of transformed points fills the viewable screen area.

Some issues are:  
1.  first, the camera centering I described works great in ortho mode, after which I can manually zoom in/out as necessary until the model is completely within the screen. In perspective mode, manually zooming does not end up with a model that fits the screen edge to edge.  Probably because as the camera position changes, so does the matView matrix, which would change all my transformed screen verticies.

2.  how to move the camera to do the zoom in/out automatically such that the model fits the screen

I would prefer not to have to do an itterative method for camera fitting which some have suggested.
There is little to no examples of this on the web, but if you find one, let me know!

    Public Const FOV As Single = Math.PI / 4
    Public Const NEARCLIP As Single = 1
    Public Const FARCLIP As Single = 100000
    matProj = Matrix.PerspectiveFieldOfViewRightHanded(FOV, AspectRatio, NEARCLIP, FARCLIP)
    matView = Matrix.LookAtRightHanded(CameraPosition, CameraTarget, CameraUp)

Question by:grknight
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
LVL 18

Expert Comment

by:Jose Parrot
ID: 17815694

Zoom implics in fixed camera. Just the focal lens changes.
If the camera moves, it is a travelling (move) or panning (rotating around a vertical axis) or tilting (rotation around the viewing ray).

I understand you need to inverse calculate the perspective projection size to make its zoom to fit the screen.

Is it your understanding too?


Author Comment

ID: 17815760
I don't believe the perspective matrix needs to change, as that would basically change the viewing fustrum.  I need to know how to calculate the new camera position and target (effectivly the view matrix) to fit the model to the screen.
LVL 18

Accepted Solution

Jose Parrot earned 500 total points
ID: 17824349

So, what you are looking for is a moving camera, not zooming.
The zoom effect is obtained by changing the frustum angles, with the camera in the same position, not moved. Or simply by calculating the projection plane distance to the camera such that the perspective size equal to the screen size.

If you want to move the camera, by making it closer or farer to the target object, then we need a solver to find the camera position.

The entries are:
- camera initial position x0,y0,z0
- object dimensions and position
- target xt,yt,zt (which point the camera looks to) Suggestion: middle point of the object

The constraints are
- algorithm for object perspective width and height calculation
- maintain the new camera position in the line (x0,y0,z0) - (xt,yt,zt)
- screen width and height

The output is:
- camera x,y,z

The algorithm consists in moving the camera closer or farer to the object by smaller and smaller moves until the error (object perspective size - screen size) is less than the maximum acceptable error. This is needed because the perspective calculation is not a simple formula, but a sequence of matrices operations.

By zoming (no camera moving), we can simply:
  calculate the perspective
  find perspective size
  factor = screen size / perspective size
  find new camera position such that
      new camera position is in the line (x0,y0,z0) - (xt,yt,zt)
      new projection plane distance = factor * projection plane distance

I think this second approach is the best one.


Author Comment

ID: 17842794
I did some testing and here are the results.  First, moving the projection plane (near clip) distance does not cause any zooming effect, although changing the FOV in the projection matrix does.  However, I don't want to change the projection matrix since that would cause problems as the user continued to rotate/pan the model after the zoom fit operation.  Kinda like using the zoom on your camera,and then trying to navigate around your subject by just looking through the lens of a zoomed camera.  Tunnel vision.

Ultimately, I went with an iterative method that consists of calculating the bounding box of the model, transforming the box's corners to screen space and comparing with the current screen extents.  If they were outside the screen extents, I move the camera away from the model some fraction and then (because of perspective view) transform the box points again, move the camera in/out, etc... via a loop.  See the code below.

        Dim boundingPoints As New System.Collections.Generic.List(Of Vector3)
        Dim ProjBounds As New Bounds
        Dim BoundingBox As New BoundingBox

        BoundingBox.CreateFromVisibleObjects()   'create the bounding box from the model
        BoundingBox.BoxPoints(boundingPoints)     'get the box corner points (world space) and load into the array boundingPoints

        'Itterative Fit Procedure
        Dim ScreenBounds As New Bounds
        ScreenBounds.minX = -1
        ScreenBounds.maxX = 1
        ScreenBounds.minY = -1
        ScreenBounds.maxY = 1

        Dim relaxationFactor As Single = 0.25
        Dim Itt As Integer = 0
        Dim dx As Single = 0
        Dim dy As Single = 0

        Do While Not ApproxEqual(Math.Max(dx, dy), 1, 0.01) AndAlso Itt < 50
            '//CAMERA POSITION
            Canvas.UpdateViewProjMatrices(TrackBall.CamPosition, TrackBall.CamTarget)
            Canvas.TransformAllCoordinates(boundingPoints, ProjBounds)  'projBounds is a 2D rectangle in screen space around our transformed boundingPoints

            Dim ProjCenterInWorldSpace As Vector3 = Vector3.TransformCoordinate(ProjBounds.CenterPoint, _
                                                    Matrix.Invert(Matrix.Multiply(Canvas.matView, Canvas.matProj)))
            'move the camera target toward this point
            Dim CamTargettoProjCenterWS As Vector3 = Vector3.Subtract(ProjCenterInWorldSpace, TrackBall.CamTarget)
            TrackBall.CamPosition += CamTargettoProjCenterWS * relaxationFactor
            TrackBall.CamTarget += CamTargettoProjCenterWS * relaxationFactor

            '//CAMERA ZOOM====================================
            Canvas.UpdateViewProjMatrices(TrackBall.CamPosition, TrackBall.CamTarget)
            Canvas.TransformAllCoordinates(boundingPoints, ProjBounds)

            'adjust camera zoom
            dx = ProjBounds.deltaX / ScreenBounds.deltaX
            dy = ProjBounds.deltaY / ScreenBounds.deltaY

            If dx < 1 AndAlso dy < 1 Then
                'camera must move toward model
                'CamDirection is the un-normalized vector from cam position to cam target
                TrackBall.CamPosition += TrackBall.CamDirection * (1 - Math.Max(dx, dy)) * relaxationFactor
            ElseIf dx > 1 OrElse dy > 1 Then
                'camera must move away from model
                TrackBall.CamPosition += TrackBall.CamDirection * (1 - Math.Max(dx, dy)) * relaxationFactor
            End If

#If DEBUG Then
            frmMain.cfbCommandLine.AddMessage("Fit: " & Math.Max(dx, dy).ToString("F4") & "  Itt: " & Itt.ToString)
#End If
            Itt += 1

LVL 18

Expert Comment

by:Jose Parrot
ID: 17871702
And thanks for sharing your result with all of us.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

As game developers, we quickly learn that Artificial Intelligence (AI) doesn’t need to be so tough.  To reference Space Ghost: “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer. (http://www.youtu…
Recently, in one of the tech-blogs I usually read, I saw a post about the best-selling video games through history. The first place in the list is for the classic, extremely addictive Tetris. Well, a long time ago, in a galaxy far far away, I was…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question