Widgets in the scene: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: surface (line 50), tick (line 105), hit (line 131).
1/// A live Flutter widget drawn as a mesh in the scene: a plane whose texture
2/// is the widget's own pixels, redrawn when the widget changes. This one is a
3/// little console with a clock and a progress bar, standing on a floor.
4///
5/// Quoted by `widget_surface.md` and shown whole in the Source tab.
6library;
8import 'dart:async';
9import 'dart:math' as math;
11import 'package:flutter/foundation.dart' show ValueListenable;
12import 'package:flutter/widgets.dart';
13import 'package:flutter3d/flutter3d.dart';
14import 'package:flutter3d/flutter3d.dart' as f3d show RenderMaterial;
15import 'package:flutter3d_app/flutter3d_app.dart';
16import 'package:flutter3d_showcase/src/demo/demo.dart';
18/// The `widget-surface` page: a console widget with a clock and a progress
19/// bar drawn on a plane on a stand. Its check is that the surface is drawn
20/// and that changing the widget marks it dirty.
21final class WidgetSurfaceDemo extends ShowcaseDemo {
22 /// How fast the console's clock runs, 0 to 4 times real time.
23 double speed = 1.0;
25 late final WidgetSurface _surface;
26 final ValueNotifier<double> _seconds = ValueNotifier<double>(0.0);
27 bool _uploading = false;
29 /// Where the middle of the surface stands, in metres.
30 static const double _height = 0.9;
33 void configureView(DemoContext context) {
34 context.orbit
35 ..distance = 3.4
36 ..pitch = 0.15
37 // At -Z, the side the plane's front faces at yaw zero.
38 ..yaw = math.pi + 0.4;
39 context.orbit.target.setValues(0.0, _height, 0.0);
40 }
43 Scene build(DemoContext context) {
44 // A widget surface renders a widget off the visible tree, which needs a
45 // binding to exist. `runApp` has already made one by the time a real
46 // session opens this page; idempotent here for the software-device test
47 // that builds a page directly.
48 WidgetsFlutterBinding.ensureInitialized();
50 _surface = WidgetSurface(
51 device: context.device,
52 width: 1.6,
53 height: 1.0,
54 // A surface's content lands on its mesh turned half way round, so the
55 // widget is turned half way round to meet it. A workaround the
56 // pendulum lab applies for the same reason, not a property of the
57 // widget: without it the clock reads upside down.
58 child: Transform.flip(
59 flipX: true,
60 flipY: true,
61 child: _Console(seconds: _seconds),
62 ),
63 )..setPosition(Vector3(0.0, _height, 0.0));
64 // The plane's front faces -Z at yaw zero, which is where this page's
65 // camera stands. Drawn from both sides, so orbiting behind it shows the
66 // back of the screen rather than nothing.
67 _surface.node.material.doubleSided = true;
69 final floor = MeshNode(
70 DeviceMesh.upload(
71 context.device,
72 CuboidShape(size: Vector3(5, 0.2, 5)).build(),
73 ),
74 f3d.RenderMaterial(
75 name: 'floor',
76 baseColor: LinearColor.fromSrgb(0.4, 0.44, 0.42, 1.0),
77 ),
78 name: 'floor',
79 )..setPosition(0, -0.1, 0);
80 // A stand for it, so it reads as a screen and not a card in mid-air.
81 final stand = MeshNode(
82 DeviceMesh.upload(
83 context.device,
84 CuboidShape(size: Vector3(0.12, _height - 0.4, 0.12)).build(),
85 ),
86 f3d.RenderMaterial(
87 name: 'stand',
88 baseColor: LinearColor.fromSrgb(0.25, 0.27, 0.3, 1.0),
89 ),
90 name: 'stand',
91 )..setPosition(0, (_height - 0.4) / 2, 0.06);
92 return Scene()
93 ..add(_surface.node)
94 ..add(floor)
95 ..add(stand)
96 ..add(
97 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
98 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
99 );
100 }
103 void update(DemoContext context, double dt) {
104 _seconds.value += dt * speed;
105 // Called once a game frame; redraws only when the widget's own pixels
106 // have changed since the last call. One upload at a time: a slow one is
107 // not queued behind by another.
108 if (!_uploading) {
109 _uploading = true;
110 unawaited(_surface.update().whenComplete(() => _uploading = false));
111 }
112 }
115 List<DemoControl> controls(DemoContext context) => <DemoControl>[
116 SliderControl(
117 'Clock speed',
118 min: 0,
119 max: 4,
120 value: () => speed,
121 onChanged: (double v) => speed = v,
122 format: (double v) => '${v.toStringAsFixed(1)}x',
123 ),
124 ];
127 void verify(Scene scene, FrameResult frame) {
128 if (frame.drawCalls < 1) {
129 throw StateError('the widget surface was not drawn');
130 }
131 // A point in the middle of the surface's own plane maps back to the
132 // middle of its UV space.
133 final uv = _surface.uvAt(Vector3(0.0, _height, 0.0));
134 if (uv == null ||
135 (uv.dx - 0.5).abs() > 0.01 ||
136 (uv.dy - 0.5).abs() > 0.01) {
137 throw StateError(
138 'the plane\'s own centre should map to uv (0.5, 0.5), '
139 'got $uv',
140 );
141 }
142 // The widget is drawn to the texture as soon as it is built, so the
143 // surface has redrawn by the time the clock has moved on.
144 _seconds.value += 1.0;
145 if (!_surface.pipeline.isDirty) {
146 throw StateError('changing what the widget shows should mark it dirty');
147 }
148 }
149}
151/// What appears on the surface: a title, a running clock and a bar that fills
152/// every four seconds. An ordinary widget tree, drawn off the visible one.
153class _Console extends StatelessWidget {
154 const _Console({required this.seconds});
156 final ValueListenable<double> seconds;
158 static const TextStyle _mono = TextStyle(
159 fontFamily: 'RobotoMono',
160 color: Color(0xFFFFFFFF),
161 );
164 Widget build(BuildContext context) {
165 return ValueListenableBuilder<double>(
166 valueListenable: seconds,
167 builder: (BuildContext context, double t, Widget? _) {
168 final int whole = t.floor();
169 final String clock =
170 '${(whole ~/ 60).toString().padLeft(2, '0')}:'
171 '${(whole % 60).toString().padLeft(2, '0')}.'
172 '${((t - whole) * 10).floor()}';
173 return DecoratedBox(
174 decoration: const BoxDecoration(
175 gradient: LinearGradient(
176 begin: Alignment.topLeft,
177 end: Alignment.bottomRight,
178 colors: <Color>[Color(0xFF14204A), Color(0xFF3355AA)],
179 ),
180 ),
181 child: Padding(
182 padding: const EdgeInsets.all(44),
183 child: Column(
184 crossAxisAlignment: CrossAxisAlignment.start,
185 children: <Widget>[
186 Text(
187 'FLUTTER WIDGET, ON A MESH',
188 style: _mono.copyWith(
189 fontSize: 30,
190 color: const Color(0xFFB8C7FF),
191 ),
192 ),
193 const Spacer(),
194 Text(clock, style: _mono.copyWith(fontSize: 150)),
195 const SizedBox(height: 28),
196 Container(
197 height: 34,
198 decoration: BoxDecoration(
199 color: const Color(0x33FFFFFF),
200 borderRadius: BorderRadius.circular(17),
201 ),
202 alignment: Alignment.centerLeft,
203 child: FractionallySizedBox(
204 widthFactor: ((t % 4.0) / 4.0).clamp(0.02, 1.0),
205 child: DecoratedBox(
206 decoration: BoxDecoration(
207 color: const Color(0xFFFFB03B),
208 borderRadius: BorderRadius.circular(17),
209 ),
210 ),
211 ),
212 ),
213 ],
214 ),
215 ),
216 );
217 },
218 );
219 }
220}