flutter3d
Showcase Changelog 62 packages API reference

Off-axis frustum: the source

since 0.7.0 Views, picking and input

Regions the guide quotes: symmetric (line 35), skew (line 40).

1/// A frustum whose axis is not down the middle of the view: what a headset
2/// lens or a portal window needs instead of an ordinary field of view.
3///
4/// Quoted by `off_axis_projection.md` and shown whole in the Source tab.
5library;
6
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
9
10/// The `off-axis-projection` page: a ball seen through a frustum shifted
11/// sideways. Its check is that the shifted frustum is not symmetric.
12final class OffAxisProjectionDemo extends ShowcaseDemo {
13 /// How far the frustum's axis is shifted, in tangent units, -0.6 to 0.6:
14 /// taken from both the left and the right edge.
15 double shift = 0.5;
17 late OffAxisProjection _off;
19 @override
20 Scene build(DemoContext context) {
21 final RenderMaterial stone = RenderMaterial(
22 name: 'stone',
23 baseColor: LinearColor.fromSrgb(0.68, 0.72, 0.78, 1.0),
24 roughness: 0.7,
25 );
26 final MeshNode ball = MeshNode(
27 DeviceMesh.upload(
28 context.device,
29 SphereShape(segments: 32, rings: 16).build(),
30 ),
31 stone,
32 name: 'ball',
33 );
35 final OffAxisProjection symmetric = OffAxisProjection.symmetric(
36 fieldOfView: 0.9,
37 aspect: 16 / 9,
38 );
40 _off = symmetric.copyWith(
41 tanLeft: symmetric.tanLeft - shift,
42 tanRight: symmetric.tanRight - shift,
43 );
44 context.camera.projection = _off;
46 return Scene()
47 ..add(ball)
48 ..add(
49 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
50 ..setLocalForward(Vector3(-0.3, -1.0, -0.4)),
51 );
52 }
54 @override
55 void update(DemoContext context, double dt) {
56 final OffAxisProjection symmetric = OffAxisProjection.symmetric(
57 fieldOfView: 0.9,
58 aspect: 16 / 9,
59 );
60 _off = symmetric.copyWith(
61 tanLeft: symmetric.tanLeft - shift,
62 tanRight: symmetric.tanRight - shift,
63 );
64 context.camera.projection = _off;
65 }
67 @override
68 List<DemoControl> controls(DemoContext context) => <DemoControl>[
69 SliderControl(
70 'Shift',
71 min: -0.6,
72 max: 0.6,
73 value: () => shift,
74 onChanged: (double v) => shift = v,
75 ),
76 ];
78 @override
79 void verify(Scene scene, FrameResult frame) {
80 if (frame.drawCalls < 1) {
81 throw StateError('the ball was not drawn');
82 }
83 // The off-centre term in column 2 of the matrix is what shears the
84 // frustum. It is zero only when the frustum is symmetric: away from
85 // shift == 0 it must be non-zero, or the shift did nothing.
86 final Matrix4 matrix = _off.toMatrix(ProjectionRequest(aspect: 16 / 9));
87 final double offCentre = matrix.storage[8];
88 if (shift != 0.0 && offCentre == 0.0) {
89 throw StateError('a shifted frustum should not be symmetric');
90 }
91 }