Drawing
Camera controllers and easing
A camera controller turns mouse moves, the wheel and held keys into a camera position and rotation, once per frame. This page explains the two common kinds, the fly camera and the orbit camera, and how to smooth their motion so it looks the same at any frame rate. The last part shows how RASM does it.
In short
- A controller keeps its own state (angles, a center, a distance) and writes a target pose. Smoothing then moves the rendered pose toward it.
- A fly camera stores yaw and pitch. Yaw turns around the world's up axis, pitch around the camera's right axis. Pitch is clamped short of ±90°.
- An orbit camera turns around a center point. A turntable uses yaw and pitch; an arcball maps the mouse onto a sphere.
- Mouse moves are distances: never multiply them by the frame time. Held keys are speeds: always multiply them by it.
- Exponential easing with t = 1 − e−k·dt gives the same motion at 30 or 144 frames per second. A fixed factor per frame does not.
1What a controller does
Each frame, the controller reads the input of that frame and updates a pose: a position and a rotation. The view matrix is then built from the pose (see the view matrix). Good controllers split this into two poses:
- Inputmouse move, wheel, held keys, frame time
- Controllerstate: yaw, pitch, center, distance
- Target posewhere the camera should be
- Smoothinga part of the way each frame
- Current poseused to render: the view matrix is built from it
- The controller never touches the current pose.
- The rendered camera is always a little behind the target.
- To jump without smoothing (a cut, a teleport), set both poses.
2Reading the input
Mouse positions in units that do not depend on the window
A mouse move arrives in pixels. A move of 100 pixels is a big part of a small window and a small part of a big one. So controllers first map pixels to a resolution-independent range, often −1..1 like NDC. Windows report y growing down, so y is flipped at the same time.
s = min(width, height)
x_n = (2 · x_px − width) / s
y_n = (height − 2 · y_px) / s (flipped: up is positive)
Mouse moves are distances, keys are speeds
This is the most common mistake in camera code. The same half second of input, cut into frames at 36 and at 144 frames per second:
A mouse move is a distance
A mouse move of 0.2 units is a distance the hand moved. At a high frame rate, the same hand motion is split into more, smaller moves; the sum is the same. So the turn angle is Δ · sensitivity, with no frame time in it.
A held key is a speed
A held key says "move while I am down", which is a speed. One frame at 144 fps is a quarter as long as one frame at 36 fps, so it must move a quarter as far: distance = speed · dt.
| Input | Kind | Per frame | Wrong version |
|---|---|---|---|
| Mouse move | distance | angle = Δ · sensitivity | × dt: looking gets slower as the frame rate rises |
| Wheel | distance (notches) | zoom by notches · step | × dt: the same |
| Held key | speed | move = speed · dt | no dt: moving gets faster as the frame rate rises |
Frame time, and held keys
Cap the frame time
Frame time dt is the time since the previous frame, from a monotonic clock. A debugger stop or a window drag can make one frame last seconds, so engines cap dt (for example to 0.1 s). Otherwise the camera jumps far on the next frame.
Read the physical key
Held keys are read as a state ("is W down now?"), not as events. Read the physical key (a scancode), not the letter: WASD then sits in the same place on an AZERTY keyboard.
Reset on focus loss
When the window loses focus, it misses the key-up event. Reset the key state then, or the camera keeps flying.
3The fly camera
A fly camera (also called FPS or free camera) turns where the mouse goes and moves with the keys. Its state is two angles, yaw and pitch, plus a position. There is no roll: the horizon stays level.
Why pitch is clamped
Pitch at ±90°
The view direction is parallel to the up axis. Then yaw and roll turn around the same line, and one degree of freedom is lost: this is gimbal lock. In practice the view flips over or spins when the mouse crosses the pole, and a lookAt built from this direction gets a zero cross product (lookAt).
Pitch clamped
Clamping to a value a little below 90° avoids all of it.
Moving with the keys
The forward and right directions come from the rotation: forward = R · (0, 0, −1), right = R · (1, 0, 0). Each held key adds or subtracts one of them.
move = 0
if W: move += forward if S: move −= forward
if D: move += right if A: move −= right
if |move| > 0: position += normalize(move) · speed · dt
The plain sum
Two keys at once (W and D) give a diagonal of length √2 ≈ 1.41: diagonal moves are 41% faster.
The normalized sum
The sum is normalized first, so every direction moves at the same speed.
Fly or walk
With forward taken from the full rotation, looking down and pressing W moves down: a fly camera. A walking camera uses the yaw alone for movement, so it stays on the ground, and adds separate keys for up and down.
Drag or capture
Games capture the mouse: it is hidden, and every move turns the view. Tools and viewers usually turn only while a button is held, so the mouse stays free for the rest of the user interface.
4The orbit camera
An orbit camera looks at a center point (a model, a map location) from a distance. Dragging turns the camera around the center; the wheel changes the distance. There are two classic ways to map the drag to a rotation.
How an arcball maps the mouse to a sphere
Imagine a glass ball of radius 1 under the screen, centered in the window. Each mouse point is lifted straight up onto the ball. Two points p0 (where the drag started this frame) and p1 (where it is now) give a rotation: around the axis p0 × p1, by the angle between them.
At the edge of the view
An orbit that maps where the pointer is breaks near the edges. With a view split in four, the edge is close; with a window at the screen's border, the pointer stops there.
Positions on a sphere, clamped to the rim
Shoemake's arcball clamps points outside the ball to its rim, so the turn suddenly becomes a roll; a pointer that leaves the view or reaches the screen's edge stops turning.
Motion, a smooth ball, and a grabbed pointer
A turntable reads only the drag's motion: the same drag turns the same at the centre and at the edge. An arcball lifts its points onto Holroyd's ball: a sphere near the centre and a hyperbola outside, which meet smoothly, so the turn never jumps; a step that starts far past the edge is moved back to start at the edge, so it turns as it would there. And while a button is held, the pointer is grabbed: it hides, and the motion goes on past the screen's edge.
turntable: yaw −= Δx · k, pitch += Δy · k, |pitch| ≤ 89°
Holroyd: z = √(1 − d²) for d² ≤ ½, z = 1 / (2 d) beyond
- Δx, Δy
- the drag's motion this frame, in units of half the view's smaller side
- k
- radians per unit: 90° times a sensitivity
- d
- the drag point's distance from the view's center, the point being the drag's start plus its motion so far
The details that differ between orbit cameras:
The angle
Shoemake's arcball turns by twice the angle between the points (it uses the quaternion p1 · p0*). Many simple trackballs use the angle itself, times a sensitivity.
Turn the object or the camera
"Grab" feel: the scene follows the cursor. For a camera, that means turning the camera the opposite way: by −angle, in its own frame.
Roll
Small circles with the mouse add up to a roll. A turntable cannot roll; an arcball can.
Zoom
Additive (distance −= notches · step) feels slow far away and too fast up close. Multiplicative (distance ×= 0.9 per notch) feels the same at any distance. Clamp at a minimum either way.
Position
Always center + distance · (R · (0, 0, 1)): the camera's +Z points away from what it looks at.
5Pan and zoom, and orthographic views
An orbit camera often needs two more moves: a pan slides the center across the view, and a zoom brings the camera nearer or farther. Both are grabs: the point under the pointer should stay under it. An orthographic view needs them most, since it has no distance to change: its zoom is the size of its box.
Pan: the scene follows the pointer
World units per pointer unit: r · tan(fov / 2) at the center's distance in perspective, half the box's smaller side in an orthographic view.
Orthographic zoom at the pointer
The box scales by f around the view's axis, and the camera moves by the pointer's offset · (1 − f): the point under the pointer is the same before and after.
f = 0.9steps perspective: r ← max(r · f, rmin) orthographic: box ← box · f, camera ← camera + offset · (1 − f)
- steps
- the frame's wheel steps; positive zooms in
- rmin
- a small floor, so a zoom out always works again
- offset
- the point under the pointer, from the view's axis, across the view
Multiplying by the same factor each step feels the same at a millimetre and at a kilometre; subtracting a fixed step does not. Why the orthographic zoom keeps the point: before, it is at camera + offset; after, at camera + offset · (1 − f) + offset · f, the same place.
Which button does what is a choice of the application. A common map: the left button orbits, the right or middle button pans, and Shift with the left button pans (a laptop has no middle button). CAD programs often pan with the left button in a flat view, where an orbit makes no sense.
6Smoothing: exponential easing
Raw input is jumpy: a mouse reports whole pixels, and frames are not evenly spaced. Smoothing moves the current pose a fraction t of the remaining way to the target each frame:
current = current + (target − current) · t
The question is how to choose t. A fixed number (say 0.1) looks right at one frame rate and wrong at all others: at 144 fps it runs 144 times a second, at 30 fps only 30 times. The fix comes from asking what the smoothing should do in time, not in frames: the remaining distance should shrink by the same factor every second.
remaining(time) = remaining(0) · e^(−k · time)
one frame of length dt: remaining ← remaining · e^(−k · dt)
so t = 1 − e^(−k · dt)
Many frames multiply: e−k·dt1 · e−k·dt2 · … = e−k·(dt1 + dt2 + …). Only the total time matters, not how it was cut into frames. k is the speed: half the distance is gone after ln 2 / k seconds (0.12 s for k = 6).
Try other frame rates. The picture steps both kinds of factor frame by frame, with the formula above.
Rotations and orbits
Positions blend with a straight mix. Rotations should not: mixing two quaternions number by number and normalizing moves at an uneven speed. Slerp (spherical linear interpolation) moves along the arc at a constant speed, and takes the same t.
An orbit camera needs one more step. For a 120° turn around the center:
Straight mix of positions
Halfway, a straight mix of positions is only half the distance from the center: the view zooms in and out during every turn.
Eased rotation, eased distance
Along the arc the camera keeps its distance.
- 1. Rotationslerp the rotation by t
- 2. Distancemix the distance by t
- 3. Positioncenter + distance · (R · +Z)
Try other angles. The picture blends one turn both ways, and plots the distance to the center on the right.
Stop when close enough
Exponential easing never reaches the target exactly. Worse, mixing two nearly equal values still rounds a little, by an amount that depends on dt, so a camera "at rest" moves by float noise. Snap to the target once the difference is below a tiny threshold.
A smoother option: a spring
Exponential easing starts at full speed and then slows down. A critically damped spring also keeps a velocity, so the camera speeds up gently too. It costs a few more lines and one more state variable per value.
7Worked example
A 1600 × 900 window, and a fly camera with easing:
1. The mouse moves 90 pixels right
Whether the yaw grows or shrinks for a move to the right depends on the sign convention; turning right is a negative turn around +Y in a right-handed world.
2. W and D are held for one frame
At 30 fps the step is 0.167 units, twice as far, in a frame twice as long: the same speed.
3. Easing toward the new target
| Frame rate | t per frame, k = 6 | Left after 0.5 s | Fixed t = 0.1: left after 0.5 s |
|---|---|---|---|
| 30 fps | 0.181 | 5.0% | 20.6% |
| 60 fps | 0.095 | 5.0% | 4.2% |
| 144 fps | 0.041 | 5.0% | 0.05% |
4. An arcball drag from the center to x = 0.5
A drag to the rim (x = 1) would give 90°, so half the window's height is a quarter turn.
8Who runs the controller
A small program is happy when the renderer reads the input and moves the camera for it. An editor, a game or a map application wants more: its own keys, two views with a camera each, a scripted camera path that the user can take over. Then the controller works better as a helper: a plain value the application keeps, and one function it calls each frame. The renderer only gets the pose.
The renderer runs it
No code in the application. But one controller for one camera, with the renderer's input only.
The application runs it
A few lines per frame. Any number of cameras, any input, and the application can change the input or the pose in between.
The helper is one value with everything a controller keeps: its state (angles, center, distance) and the two poses of section 1. Its function takes one frame's input and moves both poses. With no controller it still eases, so a pose the application sets as the target is smoothed too. To switch controllers, make the new one from the current pose: a fly camera takes its yaw and pitch from the rotation, so the view does not jump.
One input per view
With two views in one window, each camera needs its own input. Each view's input reads the same events, but only inside its own rectangle, and its mouse units are taken from that rectangle:
- A press starts a drag only in its own view, and not on a UI window.
- The drag stays with that view until the button goes up, even over another view.
- The wheel goes to the view under the pointer.
- Held keys go to the view the application picks: the one under the pointer, or the last one clicked.
9Pitfalls
- Looking around is slower at a high frame rate
- Mouse moves multiplied by dt.
- Walking is faster at a high frame rate
- Key movement not multiplied by dt.
- Smoothing feels different on another machine
- A fixed smoothing factor per frame instead of 1 − e−k·dt.
- The camera jumps after a breakpoint or a window drag
- dt not capped.
- The view flips at the top or bottom
- Pitch not clamped below 90°.
- The horizon slowly tilts in a fly camera
- Small turns added to the last rotation instead of rebuilding it from yaw and pitch.
- The camera keeps moving after alt-tab
- The key-up event was lost; the key state was not reset on focus loss.
- The orbit zooms in and out while turning
- The position eased in a straight line instead of along the sphere.
- A drag in one view also turns the other camera
- Both cameras read the whole window's input. Give each view its own input, limited to its rectangle.
- The view jumps when the controller changes
- The new controller kept its old angles. Make it from the current pose.
10In RASM
RASM has both kinds of controller: FREE_FLY (a fly camera, turned while a mouse button is held) and TRACK_BALL (an orbit camera, a turntable by default or an arcball). Easing is the exponential kind of section 6. The controllers are helpers, as in section 8: a CameraRig holds the controller, the rendered transform and the targetTransform, and updateCameraRig moves it by one CameraInput. They need no Engine. The engine runs the same function for the camera given to beginFrame, unless that camera's controller is CameraController::Type::NONE.
updateCameraRig, so a camera moves the same either way. Controllers write targetTransform; easing moves transform; setCameraTransform sets both, so the camera jumps there.An application that drives a camera itself turns the engine's controller off and keeps its own rig. pollEvents before the frame makes this frame's input readable at once; beginFrame then polls no more. examples/05_city does this with the input the engine read, and examples/19_embedding with its own CameraInputState:
engine.setCameraController(camera, rasm::CameraController{.type = rasm::CameraController::Type::NONE});
rasm::CameraRig rig = rasm::createCameraRig(freeFly, start);
while (engine.running())
{
engine.pollEvents();
rasm::updateCameraRig(rig, engine.getCameraInput());
engine.setCameraTransform(camera, rig.transform);
engine.render(scene, camera);
}
How events become a CameraInput: a CameraInputState takes them one by one (addCameraInputEvent), then gives the frame's input (takeCameraInput). The engine keeps one for the main window, and applies to it every event, from the SDL platform or from Renderer::addInputEvent (The platform layer). An application can keep one per view:
mouseStartis last frame's drag position,mouseEndthe newest one, both fromtoInputNdcin theInputArea: a rectangle in window points, the units ofInputEventmouse positions.- A press starts a drag only inside the area and not on the UI (
UiInputCapture, fromRenderer::getUiInputCapture). The drag goes on outside the area until the release. wheelDeltais summed over the frame while the pointer is in the area. A wheel event has no position, so before the first move it counts in every area.- W, A, S, D are held keys by position (
InputEvent::physicalKey), so they stay in the same place on an AZERTY keyboard. deltaTimecomes fromsteady_clock: 0 on the first frame, at most 0.1 s. WithEngineConfig::fixedDeltaTimeit is that step instead, so the easing is the same in every run.Renderer::getDeltaTimereturns it.- A
FOCUSevent that loses the focus lets go of every key and ends the drag, so no key stays held.
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Mouse units | divide by the smaller side, flip y | The same, in toInputNdc, by the smaller side of the InputArea, around its center. The engine's area is the main window in points (Window's width, height). A drag follows the motion: each MOUSE_MOVE adds its InputEvent::dx and dy (or, without them, its change of position) to the drag's end, so a drag that leaves the area, or runs while the pointer is grabbed, goes on at the same pace. A drag released within a frame still gives its motion to that frame, and a press before it is taken starts nothing. |
| The screen's edge | grab the pointer | Renderer::setMouseGrab asks the platform (Platform::setMouseGrab): the SDL platform turns on SDL's relative mouse mode, which hides the pointer and sends motion only, and puts the pointer back where the grab began. The engine's own camera input grabs during its drags (in beginFrame, for a camera with a controller); an application with its own CameraInputState calls it with dragActive (examples/27_cad_views), and one with its own window grabs it itself and sends dx, dy (examples/19_embedding). |
| Fly: angles | yaw around world up, pitch around right, clamp | yaw -= dx * lookSensitivity, pitch += dy * lookSensitivity, pitch clamped to ±89°, rotation angleAxis(yaw, +Y) * angleAxis(pitch, +X). lookSensitivity is radians per NDC unit. With FreeFly::up other than +Y (a globe's local up) there is no fixed frame: each update turns the camera's forward around up by the yaw, measures the pitch from the plane across up, and rebuilds the rotation with quatLookAt(forward, up), so the horizon stays level and up may follow a globe's normal anywhere, even every frame; zero or +Y changes nothing. |
| Fly: moving | normalized sum × speed × dt | The same. It flies along the full view direction, and has no keys for up, down or a faster speed. |
| Fly: mouse | drag or capture | Drag: the view turns while a mouse button that CameraButtons maps to ORBIT or PAN is held; both drags look. |
| Orbit kind | turntable or arcball | Both: TrackBall::style. OrbitStyle::TURNTABLE, the default, turns by the drag's motion only: yaw -dx * 90° * orbitSensitivity around TrackBall::up (zero: +Y), pitch dy * 90° * orbitSensitivity, clamped to ±89°, rebuilt with quatLookAt(forward, up), so it never rolls (the free-fly camera's turnAroundUp). OrbitStyle::ARCBALL lifts the drag's two points onto Holroyd's ball (projectOnTrackBall), so it can roll and never jumps at the rim; a step that starts more than one unit from the center moves back to start at that distance, so a grabbed drag far past the edge keeps turning as at the edge. |
| Orbit angle | 2 × or 1 × the angle between the points | The arcball: 1 × the angle, times orbitSensitivity, applied as rotation * angleAxis(-angle, axis): in the camera's frame, grab style. A turntable step of no motion changes nothing, so a plan view (orbitSensitivity 0) keeps looking straight down. |
| Zoom | additive or multiplicative | Multiplicative: radius *= CAMERA_WHEEL_ZOOM ^ wheelDelta (0.9 a step), between MIN_TRACK_BALL_RADIUS and 109. With an orthographic projection, the same factor scales the box at the pointer (CameraInput::pointer), and the radius stays. |
| Pan | a grab across the view | The trackball moves its center by the pan drag (panStart to panEnd), at once, with no easing, by the projection's units per pointer unit. updateCameraRig(rig, projection, input) reads the camera's projection and writes an orthographic zoom into it; updateCameraRig(rig, input) pans as a 45° perspective camera would, and zooms only the radius. Renderer::updateCamera and the engine's own path pass the camera's projection. The rendered pose moves with the center, so the easing does not pull the distance back. A plan view is a trackball with orbitSensitivity 0. |
| Buttons | the application's choice | CameraInputState::buttons, a CameraButtons: a CameraDrag (NONE, ORBIT, PAN) for the left, right, middle, back and forward buttons and Shift + left. Defaults: left orbits; right, middle and Shift + left pan; back and forward do nothing. One drag at a time; only its button's release ends it. Renderer::setCameraButtons sets the engine's own. |
| Easing | t = 1 − e−k·dt, slerp, orbit on the sphere | All three, in updateCameraRig. k is easingSpeed: 12 by default, 6 in the examples, ≤ 0 turns easing off. A trackball eases its radius and keeps the camera on the sphere; free-fly mixes the position. |
| Stop when close | snap below a threshold | Snaps once position, rotation and scale are within 1e-6, so a camera at rest does not move (B24). The position is a glm::dvec3, so the same absolute threshold holds far from the origin, and the trackball's center is a double too. |
| Long frames | cap dt | Capped at 0.1 s in pollEvents. |
| Switching controllers | make the new one from the pose | createCameraRig starts at the given pose; setCameraController passes the rendered one. For free-fly it computes pitch = asin(forward.y) and yaw = atan2(-forward.x, -forward.z), so the view does not jump; a roll is dropped. With its own up it takes the pitch from up and starts the yaw at 0. setCameraTransform starts the rig again at the new pose the same way. |
| Who runs the controller | the renderer or the application | Either, per camera. beginFrame runs the rig of the camera passed to it; a camera whose controller is NONE keeps the pose the application sets. The SDL platform reads its window's events, or the application sends its own with addInputEvent; getInputEvents gives them back after pollEvents. |
| Views | one input per view | One CameraInputState per view, kept by the application, with the view's InputArea from getInputArea(window, rect) (Many views of one scene; examples/20_views). The engine has one, for the whole main window, which moves the camera of the first view in the window. |
A new camera from createCamera is a trackball whose center is one unit in front of it, with radius 1, so the first update keeps the given pose. The fields are described in the API reference: CameraController, CameraRig, CameraInput and CameraInputState.
Where it lives in code
| What | Where |
|---|---|
| Types | CameraInput, CameraController, CameraRig, CAMERA_WHEEL_ZOOM in include/rasm/cameraController.h; CameraInputState, CameraButtons, CameraDrag, InputArea in include/rasm/cameraInput.h; Camera in include/rasm/camera.h |
| Controllers and easing | createCameraRig, updateCameraRig, projectOnTrackBall, turnAroundUp, zoomOrthographic in src/scene/cameraController.cpp; the grab: Renderer::setMouseGrab, Platform::setMouseGrab (SDL's relative mouse mode in src/platform/sdlPlatform.cpp) |
Events to CameraInput | addCameraInputEvent, takeCameraInput, toInputNdc in src/platform/cameraInput.cpp |
| The engine's path | Renderer::pollEvents and Renderer::beginFrame in src/renderer/renderer.cpp; Renderer::updateCamera, Renderer::setCameraController in src/scene/camera.cpp |
| Setup | Renderer::createCamera, Renderer::setCameraTransform in src/scene/camera.cpp |
| Examples | examples/05_city: a free-fly rig on the engine's input, a tour the user takes over; examples/19_embedding: its own CameraInputState, F switches orbit and fly; examples/27_cad_views: four views, orthographic ones that pan with the left button and zoom at the pointer |
| Tests | tests/cameraTests.cpp: frame-time movement, diagonal speed, the pitch clamp, orbit sphere, easing, rigs and NONE; tests/inputTests.cpp: areas, drags, the button map, the wheel, pollEvents; pans, the zoom at the pointer, the turntable at the centre and at the edge, its pole, the arcball past its rim in tests/cameraTests.cpp; a drag past the area's edge and during a grab in tests/inputTests.cpp |
- Controllers write
targetTransformonly.transformis written by easing and bysetCameraTransform. - The engine's path and an application's call the same
updateCameraRig: no controller math inEngine. - Mouse deltas are never multiplied by
deltaTime; key movement always is. - The easing factor comes from
1 - exp(-easingSpeed * deltaTime), never a fixed number per frame. - A camera at rest must stay bit-for-bit still: keep the snap in the easing of
updateCameraRig(B24). - Run
ctest --preset x64-debugafter a change;tests/cameraTests.cppcovers the controllers.
The engine's own input covers the whole main window; an application with several views (Renderer::render with a list of Views) keeps one CameraInputState per view. A view in another window (ViewOutput::window) reads that window's events: each InputEvent names its window. There is no walk mode, and a fly camera has no keys for up, down or a faster speed. A perspective zoom moves toward the center, not toward the point under the pointer: that needs the point's depth, which a pick (Picking) could give a frame later. An orthographic zoom reads the camera's stored box, so keep its aspect the view's: the engine fits the box's width to the view, not its height (D49).
Further reading
- Ken Shoemake, ARCBALL: A User Interface for Specifying Three-Dimensional Orientation Using a Mouse, Graphics Interface 1992.
- Michael Chen, S. Joy Mountford and Abigail Sellen, A Study in Interactive 3-D Rotation Using 2-D Control Devices, SIGGRAPH 1988.
- Mark Haigh-Hutchinson, Real-Time Cameras (2009).
- Thomas Lowe, Critically Damped Ease-In/Ease-Out Smoothing, in Game Programming Gems 4 (2004).