flutter3d
Showcase Changelog 62 packages API reference

A Catmull-Rom path: the source

since 0.4.0 or earlier Simulation, audio and XR

Regions the guide quotes: track (line 18), sample (line 46), measure (line 69).

1/// A smooth curve through a list of points, measured in metres rather than
2/// in the unitless parameter a cubic spline is naturally described by.
3///
4/// Quoted by `splines.md` and shown whole in the Source tab.
5library;
6
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
9import 'package:flutter3d_sim/flutter3d_sim.dart';
11/// The `splines` page: a car driving a closed spline measured in metres. Its
12/// check is that the spline returns to its start after one full length.
13final class SplinesDemo extends ShowcaseDemo {
14 /// How far along the loop the car is, in metres, from 0 to its length;
15 /// advanced 2 m a second and wrapped.
16 double distance = 0.0;
18 late final CatmullRom _track = CatmullRom(<Vector3>[
19 Vector3(1.2, 0, 0),
20 Vector3(0, 0, 1.2),
21 Vector3(-1.2, 0, 0),
22 Vector3(0, 0, -1.2),
23 ]);
25 late final MeshNode _car;
26 final Vector3 _point = Vector3.zero();
28 @override
29 Scene build(DemoContext context) {
30 final material = RenderMaterial(
31 name: 'car',
32 baseColor: LinearColor.fromSrgb(0.9, 0.3, 0.3, 1.0),
33 );
34 _car = MeshNode(
35 DeviceMesh.upload(context.device, SphereShape(segments: 16).build()),
36 material,
37 );
38 return Scene()
39 ..add(_car)
40 ..add(
41 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
42 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
43 );
44 }
46 @override
47 void update(DemoContext context, double dt) {
48 distance = _track.wrap(distance + dt * 2.0);
49 _track.sampleAt(distance, _point);
50 _car.setPositionFrom(_point);
51 }
53 @override
54 List<DemoControl> controls(DemoContext context) => <DemoControl>[
55 SliderControl(
56 'Distance along the loop (m)',
57 min: 0,
58 max: _track.length,
59 value: () => distance,
60 onChanged: (double v) => distance = v,
61 ),
62 ];
64 @override
65 void verify(Scene scene, FrameResult frame) {
66 if (frame.drawCalls < 1) {
67 throw StateError('the car marker was not drawn');
68 }
69 // A closed loop through four points three metres from the centre comes
70 // back to its own start.
71 final start = Vector3.zero();
72 _track.sampleAt(0.0, start);
73 final afterALap = Vector3.zero();
74 _track.sampleAt(_track.length, afterALap);
75 final gap = (start - afterALap).length;
76 if (gap > 0.01) {
77 throw StateError(
78 'a closed spline should return to its own start '
79 'after one full length, gap was $gap',
80 );
81 }
82 }