Free-look and walking: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: freelook (line 51), walk (line 119).
1/// Turning the head from where the camera stands, and walking it there, as
2/// opposed to orbiting a point somebody else chose. The posts are laid out
3/// again around the camera every frame, so there is always something to walk
4/// past.
5///
6/// Quoted by `free_look.md` and shown whole in the Source tab.
7library;
9import 'package:flutter3d/flutter3d.dart';
10import 'package:flutter3d_showcase/src/demo/demo.dart';
12/// The `free-look` page: a camera that turns its head and walks among posts
13/// laid out around it. Its check is that walking moved it as far as it
14/// should and that it stands among the posts.
15final class FreeLookDemo extends ShowcaseDemo {
16 /// Whether the camera walks forward on its own.
17 bool walkingForward = true;
19 /// How fast the head turns, -1 to 1: the share of a 75-pixel drag a second
20 /// fed to the look.
21 double turn = 0.3;
23 late final FreeLook _freeLook;
24 late Vector3 _targetBefore;
25 double _stepSeconds = 0.0;
27 late final MeshNode _floor;
28 final List<MeshNode> _posts = <MeshNode>[];
29 final List<RenderMaterial> _stones = <RenderMaterial>[];
31 /// Posts a side of the square laid out around the camera, and how far
32 /// apart they stand.
33 static const int _reach = 4;
34 static const double _spacing = 4.0;
36 /// Where the eyes are, in metres. Walking goes along the view axis, so a
37 /// camera tilted down walks down: level, and at this height, it walks along
38 /// the ground.
39 static const double _eyeHeight = 1.6;
42 void configureView(DemoContext context) {
43 context.orbit
44 ..distance = 4.0
45 ..pitch = 0.0;
46 context.orbit.target.y = _eyeHeight;
47 }
50 Scene build(DemoContext context) {
51 _freeLook = FreeLook(context.orbit);
53 RenderMaterial stone(String name, double r, double g, double b) =>
54 RenderMaterial(
55 name: name,
56 baseColor: LinearColor.fromSrgb(r, g, b, 1.0),
57 roughness: 0.8,
58 );
59 _stones.addAll(<RenderMaterial>[
60 stone('grey', 0.65, 0.62, 0.58),
61 stone('sand', 0.85, 0.75, 0.5),
62 stone('clay', 0.8, 0.45, 0.35),
63 stone('moss', 0.45, 0.7, 0.45),
64 ]);
66 final Scene scene = Scene()
67 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
68 ..ambientIntensity = 0.3 * LightNode.legacyUnit;
69 _floor = MeshNode(
70 DeviceMesh.upload(
71 context.device,
72 const PlaneShape(width: 80.0, depth: 80.0).build(),
73 ),
74 stone('floor', 0.3, 0.34, 0.32),
75 name: 'floor',
76 );
77 scene.add(_floor);
79 final DeviceMesh post = DeviceMesh.upload(
80 context.device,
81 CuboidShape(size: Vector3(0.5, 2.5, 0.5)).build(),
82 );
83 for (var i = 0; i < (2 * _reach + 1) * (2 * _reach + 1); i++) {
84 final MeshNode node = MeshNode(post, _stones.first, name: 'post $i');
85 _posts.add(node);
86 scene.add(node);
87 }
88 scene.add(
89 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
90 ..setLocalForward(Vector3(-0.3, -1.0, -0.4)),
91 );
92 _layOut(context);
93 return scene;
94 }
96 /// Puts every post on the lattice point nearest the camera and beyond, and
97 /// colours it by which point that is, so a post keeps its colour as the
98 /// camera passes it and a new one arrives ahead.
99 void _layOut(DemoContext context) {
100 final Vector3 eye = context.camera.readPosition();
101 final int cellX = (eye.x / _spacing).round();
102 final int cellZ = (eye.z / _spacing).round();
103 _floor.setPosition(cellX * _spacing, 0.0, cellZ * _spacing);
104 var index = 0;
105 for (var i = -_reach; i <= _reach; i++) {
106 for (var j = -_reach; j <= _reach; j++) {
107 final int x = cellX + i;
108 final int z = cellZ + j;
109 final MeshNode node = _posts[index++];
110 node.setPosition(x * _spacing, 1.25, z * _spacing);
111 node.material = _stones[(x * 7 + z * 13).abs() % _stones.length];
112 // One the camera is standing inside would fill the frame.
113 node.isVisible =
114 (node.readPosition() - Vector3(eye.x, 1.25, eye.z)).length > 1.2;
115 }
116 }
117 }
120 void update(DemoContext context, double dt) {
121 // Back to eye height first: a drag that tilted the view would otherwise
122 // have the walk climb or sink, and the camera would leave the floor.
123 context.orbit.target.y = _eyeHeight;
124 // The head turns with the eye held still; the walk then carries the eye
125 // the way the head now faces.
126 _freeLook.look(turn * 75.0 * dt, 0.0);
127 _targetBefore = context.orbit.target.clone();
128 _stepSeconds = dt;
129 if (walkingForward) {
130 _freeLook.walk(forward: 1.0, seconds: dt);
131 }
132 _layOut(context);
133 }
136 List<DemoControl> controls(DemoContext context) => <DemoControl>[
137 ToggleControl(
138 'Walk forward',
139 value: () => walkingForward,
140 onChanged: (bool v) => walkingForward = v,
141 ),
142 SliderControl(
143 'Speed',
144 min: 0,
145 max: 8,
146 value: () => _freeLook.metersPerSecond,
147 onChanged: (double v) => _freeLook.metersPerSecond = v,
148 format: (double v) => '${v.toStringAsFixed(1)} m/s',
149 ),
150 SliderControl(
151 'Turn the head',
152 min: -1,
153 max: 1,
154 value: () => turn,
155 onChanged: (double v) => turn = v,
156 format: (double v) => v.toStringAsFixed(2),
157 ),
158 ];
161 void verify(Scene scene, FrameResult frame) {
162 if (frame.drawCalls < 1) {
163 throw StateError('the posts were not drawn');
164 }
165 if (!walkingForward) return;
166 // walk moves the target by metersPerSecond * seconds along the view
167 // axis. The distance actually covered has to match that number exactly,
168 // rather than only be nonzero.
169 final double moved = (_freeLook.orbit.target - _targetBefore).length;
170 final double expected = _freeLook.metersPerSecond * _stepSeconds;
171 if ((moved - expected).abs() > 1e-6) {
172 throw StateError('walking moved $moved, expected $expected');
173 }
174 final int standing = _posts.where((MeshNode p) => p.isVisible).length;
175 if (standing < _posts.length - 2) {
176 throw StateError('the camera should be standing among the posts');
177 }
178 }
179}