Perspective and orthographic: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: box (line 21), perspective (line 35), orthographic (line 46).
1/// Two ways to turn a scene into a flat picture: perspective, where things
2/// shrink with distance, and orthographic, where they do not.
3///
4/// Quoted by `projections.md` and shown whole in the Source tab.
5library;
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
10/// The `projections` page: a box through a perspective or an orthographic
11/// lens. Its check is that the orthographic matrix keeps w at 1 and the
12/// perspective one does not.
13final class ProjectionsDemo extends ShowcaseDemo {
14 /// Which lens the camera uses: 0 perspective, 1 orthographic.
15 int choice = 0;
17 late Projection _projection;
20 Scene build(DemoContext context) {
21 final RenderMaterial stone = RenderMaterial(
22 name: 'stone',
23 baseColor: LinearColor.fromSrgb(0.7, 0.68, 0.64, 1.0),
24 roughness: 0.8,
25 );
26 final MeshNode box = MeshNode(
27 DeviceMesh.upload(
28 context.device,
29 CuboidShape(size: Vector3.all(1.4)).build(),
30 ),
31 stone,
32 name: 'box',
33 );
35 _projection = const PerspectiveProjection(fieldOfView: 0.9);
36 context.camera.projection = _projection;
38 return Scene()
39 ..add(box)
40 ..add(
41 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
42 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
43 );
44 }
46 void _choose(int value) {
47 choice = value;
48 _projection = value == 0
49 ? const PerspectiveProjection(fieldOfView: 0.9)
50 : const OrthographicProjection(height: 3.0);
51 }
54 void update(DemoContext context, double dt) {
55 context.camera.projection = _projection;
56 }
59 List<DemoControl> controls(DemoContext context) => <DemoControl>[
60 ChoiceControl(
61 'Lens',
62 options: const <String>['Perspective', 'Orthographic'],
63 index: () => choice,
64 onChanged: _choose,
65 ),
66 ];
69 void verify(Scene scene, FrameResult frame) {
70 if (frame.drawCalls < 1) {
71 throw StateError('the box was not drawn');
72 }
73 // A perspective matrix divides by depth: row 3 sends w to -z, so the
74 // bottom-right entry of the 4x4 is 0. An orthographic one does not: a
75 // point at any depth keeps w = 1, so that entry is 1. This is the one
76 // number that tells the two matrices apart.
77 final Matrix4 matrix = _projection.toMatrix(
78 ProjectionRequest(aspect: 16 / 9),
79 );
80 final double bottomRight = matrix.storage[15];
81 final bool isOrthographic = _projection is OrthographicProjection;
82 if (isOrthographic && bottomRight != 1.0) {
83 throw StateError('an orthographic matrix should keep w at 1');
84 }
85 if (!isOrthographic && bottomRight != 0.0) {
86 throw StateError('a perspective matrix should not keep w at 1');
87 }
88 }
89}