Skip to content

Add an orthographic projection to Camera3D - #108

Merged
sunsided merged 5 commits into
mainfrom
feature/ortho-camera-3d
Nov 16, 2026
Merged

sunsided merged 5 commits into
mainfrom
feature/ortho-camera-3d

Conversation

@sunsided

@sunsided sunsided commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Adds Camera3D::ortho_height. Some(h) switches the 3D camera to an orthographic projection that shows h world units vertically and h * aspect horizontally, centred on the view axis, for isometric and top-down views. None, the default, keeps the perspective projection.

ctx.gfx.camera3d.ortho_height = Some(6.0); // 6 world units tall

Was stacked on #107, which is merged; main is merged into this branch.

Key changes

  • Camera3D::ortho_height: Option<f32>; view_proj picks the projection from it. fov_y is unused while it is set.
  • The projection reuses the 2D camera's ortho matrix (now pub(crate)), which already has the [0, 1] depth range.
  • examples/07_3d: O toggles between perspective and orthographic.
  • README, changelog and the jam agent guide mention it (templates and guide.md re-synced).

Risks / notes

  • Camera3D gains a public field, so code that builds one with a full struct literal needs it. Camera3D::new and gfx.camera3d are unaffected.

Testing

  • New unit test ortho_has_no_foreshortening_and_fills_the_height: the corners of the view volume land on NDC (1, 1, 0) and (1, 1, 1).
  • 07_3d checked by hand: O switches to the orthographic view.
  • task check, clippy --all-features, wasm32 clippy and cargo doc -D warnings pass.

Review

The whole mechanism is Camera for Camera3D in crates/gfx/src/camera3d.rs. The rest is docs and the example toggle.

Ui created its egui renderer with the sRGB surface format and drew into
the sRGB view of the window. egui outputs gamma-space colours and blends
in gamma space, so egui-wgpu warned about a linear framebuffer at startup
and fell back to its linear-framebuffer shader, which blends differently.

An sRGB surface now also carries its non-sRGB twin as a view format, where
the backend supports surface view formats. Graphics::overlay_format() and
Frame::overlay_view_and_encoder() expose that view, and Ui uses both.
Without the downlevel flag (GL) the overlay format stays the sRGB one, so
nothing changes there.

Fixes #106
Camera3D::ortho_height switches the 3D camera to an orthographic
projection: Some(h) shows h world units vertically and h * aspect
horizontally, centred on the view axis, for isometric and top-down
views. None, the default, keeps the perspective projection.

The projection reuses the 2D camera's ortho matrix, which already has
the [0, 1] depth range. Example 07_3d toggles it with O.

Camera3D gains a public field, so code that builds one with a full
struct literal needs it; Camera3D::new and gfx.camera3d are unaffected.
@github-actions github-actions Bot added documentation Improvements or additions to documentation area: gfx game-toolkit-gfx: wgpu renderer, sprites, SDF, text, tilemap, 3D area: prelude game-toolkit umbrella crate and prelude area: examples examples/ area: templates cargo-generate jam templates labels Nov 16, 2026
Comment thread crates/gfx/src/camera3d.rs Outdated
pub fov_y: f32,
/// `Some(h)` switches to an orthographic projection showing `h` world units vertically
/// (and `h * aspect` horizontally), centred on the view axis: no foreshortening, for
/// isometric and top-down views. Smaller is more zoomed in. `None` (the default) is

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Top-down views are advertised but are degenerate with the default up

The new documentation says this projection is for "isometric and top-down views", but a straight top-down camera (eye directly above target, e.g. [0, 10, 0] to [0, 0, 0] with the default up = [0, 1, 0]) makes cross(up, z) in look_at zero. normalize then returns a zero vector, the x/y rows of the view matrix collapse, and everything projects to a single point. A user following this doc has to also set up to something perpendicular (e.g. [0, 0, 1]). Either state that requirement here, or make look_at fall back to an alternative up axis when up is parallel to the view direction.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 68de43f. Camera3D::up now documents that it must not be parallel to the view direction and names [0.0, 0.0, -1.0] for a straight top-down view; the ortho_height docs point there. I kept look_at as is: a fallback axis would pick the screen orientation for the game, and which world direction is up on a map is the game's call. A test covers the top-down case with that up vector.

&look_at(self.eye, self.target, self.up),
)
let proj = match self.ortho_height {
Some(h) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: ortho_height accepts values that produce an invalid projection matrix

Some(0.0) gives hh = 0, so ortho divides by a zero-sized range (2.0 / rml, -(r + l) / rml), producing inf/NaN in view_proj; a negative value silently mirrors the image, and NaN/inf propagate through the same divisions. Unlike Camera2D::view_proj, which guards with self.zoom.max(1e-4), there is no validation here. Clamp the height at the point of use (which also absorbs NaN because f32::max returns the non-NaN operand), or document and assert the precondition.

Suggested change
Some(h) => {
let hh = h.max(1e-4) * 0.5;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 68de43f. The height is clamped with h.max(1e-4) at the point of use, as Camera2D does with its zoom, and the docs mention the clamp. A test checks that 0.0, a negative value and NaN all give a finite view_proj.

Comment thread README.md Outdated
```rust
let cube = ctx.gfx.create_mesh(&vertices, &indices); // [MeshVertex] + [u16]
ctx.gfx.camera3d.eye = [0.0, 1.6, 6.0]; // perspective Camera3D
ctx.gfx.camera3d.ortho_height = Some(6.0); // or orthographic: 6 world units tall

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Snippet configures the perspective and orthographic camera at the same time

Line 327 sets up the perspective camera and this line immediately switches the same camera to orthographic, so anyone copying the block always ends up in the orthographic view even though the comment above describes the perspective one. Commenting this line out (or moving it into its own snippet) keeps the perspective example functional. The same block is duplicated in crates/prelude/src/guide.md, templates/jam/CLAUDE.md, templates/jam-3d/CLAUDE.md and templates/jam-agent-guide.md.

Suggested change
ctx.gfx.camera3d.ortho_height = Some(6.0); // or orthographic: 6 world units tall
// ctx.gfx.camera3d.ortho_height = Some(6.0); // orthographic instead: 6 world units tall

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 68de43f. The orthographic line is commented out in the README and in templates/jam-agent-guide.md, with the template guides and guide.md re-synced, so the snippets stay perspective when copied.

@kilo-code-bot

kilo-code-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 2 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 2

Incremental review of 68de43f..5495063. Both previous findings (infinite ortho_height passing through the clamp, undocumented eye == target collapse) are fixed at HEAD; the two items below are new residual edge cases on the changed lines.

Issue Details (click to expand)

SUGGESTION

File Line Issue
crates/gfx/src/camera3d.rs 63 The is_finite guard checks only h, not the derived extent: a finite height near f32::MAX makes hw = (h * 0.5) * aspect overflow to inf for aspect > ~2.0, so ortho computes inf + -inf = NaN in its translation term and view_proj() is not finite, defeating the guarantee the new test asserts.
crates/gfx/src/camera3d.rs 18 The target doc covers exact eye == target, but normalize floors the length at 1e-6, so `
Files Reviewed (1 file in this pass)
  • crates/gfx/src/camera3d.rs - 2 issues

The other PR files (README.md, CHANGELOG.md, crates/gfx/src/camera.rs, crates/gfx/src/frame.rs, crates/gfx/src/graphics.rs, crates/prelude/src/guide.md, crates/ui/src/lib.rs, examples/07_3d/src/main.rs, template guides) are unchanged since the previous review and carry no outstanding findings: the README/template snippet issue and the Camera2D/ortho changes were verified clean.

Fix these issues in Kilo Cloud

Previous Review Summaries (2 snapshots, latest commit 68de43f)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit 68de43f)

Status: 2 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 2
Issue Details (click to expand)

SUGGESTION

File Line Issue
crates/gfx/src/camera3d.rs 60 h.max(1e-4) absorbs NaN and clamps non-positive heights, but +inf passes through and still produces NaN in the ortho translation terms; the new finiteness test does not cover INFINITY.
crates/gfx/src/camera3d.rs 21 The new up docs warn about a parallel up but not about eye == target, which also collapses the view because normalize([0, 0, 0]) returns zero.
Files Reviewed (6 files)
  • README.md - no issues
  • crates/gfx/src/camera3d.rs - 2 issues
  • crates/prelude/src/guide.md - no issues
  • templates/jam-3d/CLAUDE.md - no issues
  • templates/jam-agent-guide.md - no issues
  • templates/jam/CLAUDE.md - no issues

Previous review (commit 8aac2b7)

Status: 3 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 2
SUGGESTION 1
Issue Details (click to expand)

WARNING

File Line Issue
crates/gfx/src/camera3d.rs 24 Docs advertise top-down views, but eye directly above target with the default up = [0, 1, 0] makes cross(up, z) zero in look_at, collapsing the view matrix. Users must also set a perpendicular up, which is undocumented.
crates/gfx/src/camera3d.rs 56 ortho_height is not validated: Some(0.0) divides by a zero range in ortho (yielding inf/NaN), negative values mirror the image, and NaN/inf propagate. Camera2D guards its equivalent with zoom.max(1e-4).

SUGGESTION

File Line Issue
README.md 328 The snippet sets the perspective camera on line 327 and immediately overwrites it with the orthographic setting, so copy-paste always yields the orthographic view. The same block is duplicated in crates/prelude/src/guide.md and the three template guides.
Files Reviewed (10 files)
  • CHANGELOG.md - no issues
  • README.md - 1 issue
  • crates/gfx/src/camera.rs - no issues
  • crates/gfx/src/camera3d.rs - 2 issues
  • crates/gfx/src/graphics.rs - no issues
  • crates/prelude/src/guide.md - no issues
  • examples/07_3d/src/main.rs - no issues
  • templates/jam-3d/CLAUDE.md - no issues
  • templates/jam-agent-guide.md - no issues
  • templates/jam/CLAUDE.md - no issues

The ortho matrix itself is correct: it maps the near/far planes to [0, 1] depth, the new unit test's expected values check out against look_at, and Key::KeyO exists via the winit KeyCode re-export. The xor(Some(6.0)) toggle is correct because Some(_).xor(Some(_)) is None.

Fix these issues in Kilo Cloud


Reviewed by deepseek-v4.1-flash-1017 · Input: 36.9K · Output: 10.2K · Cached: 215.2K

Camera3D::ortho_height of zero, a negative value or NaN produced a
non-finite view_proj; it is now clamped to a small positive minimum, as
Camera2D does with its zoom.

A straight top-down view with the default up vector collapses the view,
because up is then parallel to the view direction. The docs on
Camera3D::up and ortho_height now say so and name a working up vector.

The README and guide snippets set the perspective camera and then
switched it to orthographic; the orthographic line is commented out.
Comment thread crates/gfx/src/camera3d.rs Outdated
)
let proj = match self.ortho_height {
Some(h) => {
let hh = h.max(1e-4) * 0.5;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: h.max(1e-4) still lets +inf through

f32::max absorbs NaN and clamps 0.0/negative values, but a non-finite input is only handled on one side: f32::INFINITY.max(1e-4) stays inf, so hh and hw become inf and ortho computes r + l = inf + -inf = NaN for the translation terms. view_proj() is therefore not finite for every input the doc calls "clamped", and ortho_height_is_clamped_to_a_finite_projection only exercises 0.0, -3.0 and NaN. Consider if h.is_finite() { h.max(1e-4) } else { 1e-4 } and adding f32::INFINITY to the test list (note h.clamp(..) is not a drop-in fix because it returns NaN for NaN).

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5495063 with your is_finite guard, so non-finite heights fall back to the minimum. f32::INFINITY is now in the test list, and the doc says zero, negative and non-finite heights fall back.

pub target: [f32; 3],
/// Which world direction points up on screen. Must not be parallel to the view direction
/// (`target - eye`), or the view collapses: looking straight down or up the default
/// `[0, 1, 0]`, set it to e.g. `[0.0, 0.0, -1.0]`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The other degenerate case, eye == target, is not covered

The doc now warns about up being parallel to target - eye, but target == eye collapses the view as well: look_at normalizes the zero vector (normalize only floors the length at 1e-6, so it returns [0.0, 0.0, 0.0]), which makes x, y and the translation row all zero, and every point then projects with w = 0. A follow camera that lerps eye onto target reaches exactly this state silently. Worth mentioning alongside the parallel-up warning.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5495063. Camera3D::target now says it must differ from eye and mentions the follow-camera case.

An infinite Camera3D::ortho_height passed f32::max unchanged and made
view_proj NaN; non-finite heights now fall back to the minimum, like
zero, negative and NaN heights already did.

Camera3D::target now documents that it must differ from eye, since a
zero view direction collapses the view as a parallel up vector does.
Base automatically changed from fix/egui-srgb-overlay to main November 16, 2026 18:44
)
let proj = match self.ortho_height {
Some(h) => {
let h = if h.is_finite() { h.max(1e-4) } else { 1e-4 };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: A large but finite ortho_height still produces a non-finite projection

The is_finite guard handles non-finite heights, but it only checks h itself, not the extent derived from it. For a finite h near f32::MAX, hh = h * 0.5 is about 1.7e38, and hw = hh * self.aspect overflows to f32::INFINITY for any aspect above roughly 2.0. ortho then computes r + l = inf + -inf = NaN in its translation term, and that NaN propagates through view_proj(). So ortho_height_is_clamped_to_a_finite_projection does not actually hold for every accepted input, even though it asserts finiteness of the whole matrix. Consider also clamping the height to a sane upper bound (or checking hw.is_finite() after the aspect multiply) so the finiteness guarantee is real rather than only covering the inputs listed in the test.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this. The guard covers the inputs a game can plausibly reach: zero, negative and non-finite heights. A finite height near f32::MAX (about 1e38 world units) is not a camera setting, and no upper bound would be meaningful for every scene. The docs promise a fallback only for zero, negative and non-finite heights, and the test lists exactly those.

#[derive(Copy, Clone, Debug)]
pub struct Camera3D {
pub eye: [f32; 3],
/// The point the camera looks at. Must differ from [`Self::eye`], or the view collapses

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The view degrades before eye == target, not only at exact equality

This documents the exact-equality case, which is the collapse you diagnosed. A distinct, earlier failure exists as well: normalize floors the vector length at 1e-6, so whenever |eye - target| < 1e-6 the returned axis is shorter than unit length. look_at then builds y = cross(z, x) with that same sub-unit magnitude, so the view matrix is no longer orthonormal and the world is silently scaled/squashed (and below 1e-12 the x axis degenerates too) rather than collapsing outright. A follow camera that lerps eye onto target is exactly the case named here, and it passes through this range on its way to equality, so the failure is visible for several frames before the total collapse. Consider documenting a minimum separation, or noting that a near-zero separation distorts the projection.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this. Below 1e-6 world units of separation the camera is effectively at the target, so the documented rule (keep target away from eye) already covers it. A minimum distance in the docs would just be the normalize epsilon restated, and a follow camera should stop short of the target well before that.

# Conflicts:
#	CHANGELOG.md
#	crates/gfx/src/frame.rs
#	crates/gfx/src/graphics.rs
@sunsided
sunsided merged commit b91225e into main Nov 16, 2026
9 checks passed
@sunsided
sunsided deleted the feature/ortho-camera-3d branch November 16, 2026 18:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: examples examples/ area: gfx game-toolkit-gfx: wgpu renderer, sprites, SDF, text, tilemap, 3D area: prelude game-toolkit umbrella crate and prelude area: templates cargo-generate jam templates documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant