Skip to content

Camera centering

Nicolas Mattia edited this page Feb 12, 2025 · 1 revision

This is a brief overview of how we center the camera (focusing on near/far planes).

Because the part rotates, we can't just use the vertices' current positions but need to include wherever they might rotate to. Since we only rotate around the Z axis, we draw a circle around said Z axis and check for extremums of distance to the camera plane.

In particular, with c the camera position, n the camera direction (normal to camera plane) and v the vertex we're considering, we check for the projection of v - c on the normal n. We derive the general equation for all vertices at height v_z and solve for the local maximum and minimum.

The general expression as function of theta is:

$$d(\theta) = \mathbf{d} \cdot{} \mathbf{n} = (\mathbf{c} - \mathbf{v}) \cdot{} \mathbf{n}$$

Spelling it out that gives:

$$d(\theta) = \mathbf{c} \cdot{} \mathbf{n} - (r \cos{\theta} n_x + r \sin{\theta} n_y + v_z n_z)$$

where v_z is the correct height and r is the radius:

$$r = \sqrt{v_x^2 + v_y^2}$$

Deriving d wrt theta and setting d(d)/dtheta to zero to find the extrema we get

$$r ( \cos{\theta} n_y - \sin{\theta} n_x ) = 0 \rightarrow \theta = \arctan{\frac{n_y}{n_x}} (+ \pi)$$

(there are 2 solutions, arctan(...) and arctan(...) + pi

Injecting in the original equation:

$$d_e = \mathbf{c} \cdot{} \mathbf{n} - (r \cos{(\arctan{\frac{n_y}{n_x}}(+\pi))} n_x + r \sin({\arctan{\frac{n_y}{n_x}}}(+\pi)) n_y + v_z n_z)$$

expanding and noting that cos(x + pi) = -cos(x) and same for sine:

$$d_e = \mathbf{c} \cdot{} \mathbf{n} - v_z n_z \pm r (\cos{(\arctan{\frac{n_y}{n_x}}}) n_x + \sin({\arctan{\frac{n_y}{n_x}}}) n_y)$$

Using a couple of shortcuts for sin(atan) and cos(atan) from here (which both yield the same denominator), for the +/- part we get

$$\rightarrow r \frac{n_x + \frac{n_y}{n_x} n_y}{\sqrt{1 + (\frac{n_y}{n_x})^2}}$$

And since the normal n is normalized we have n_x^2 + n_y^2 + n_z^2 = 1 and finally:

$$d_e = \mathbf{c} \cdot{} \mathbf{n} - v_z n_z \pm r \sqrt{1 - n_z^2}$$

Lots of room for error but code seems to work

Clone this wiki locally