Flickering lights: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: fixture (line 20), step (line 46), toggle (line 78).
1/// A light that flickers like fire or pulses like something magical, with a
2/// brightness that drives both the glow it draws and the light it casts.
3///
4/// Quoted by `light_fixtures.md` and shown whole in the Source tab.
5library;
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
9import 'package:flutter3d_sim/flutter3d_sim.dart';
11/// The `light-fixtures` page: a torch whose brightness drives its glow and
12/// its light. Its check is that a disabled fixture reports no brightness.
13final class LightFixturesDemo extends ShowcaseDemo {
14 /// Whether the torch pulses, rather than flickering like a flame.
15 bool pulseInstead = false;
17 late final LightNode _torchLight;
18 late final RenderMaterial _torchMaterial;
20 late LightFixture _fixture = LightFixture(
21 name: 'torch',
22 light: 'torch',
23 behavior: const FlameFlicker(),
24 );
27 Scene build(DemoContext context) {
28 _torchMaterial = RenderMaterial(
29 name: 'torch',
30 baseColor: LinearColor.fromSrgb(0.9, 0.6, 0.2, 1.0),
31 );
32 final ball = MeshNode(
33 DeviceMesh.upload(context.device, SphereShape(segments: 24).build()),
34 _torchMaterial,
35 name: 'torch-ball',
36 );
37 _torchLight = LightNode(
38 name: 'torch',
39 intensity: 4.0 * LightNode.legacyUnit,
40 )..setLocalForward(Vector3(-0.2, -1.0, -0.1));
41 return Scene()
42 ..add(ball)
43 ..add(_torchLight);
44 }
47 void update(DemoContext context, double dt) {
48 _fixture.step(dt);
49 _torchLight.intensity = 4.0 * _fixture.brightness * LightNode.legacyUnit;
50 _torchMaterial.emissive = LinearColor(
51 _fixture.brightness,
52 _fixture.brightness * 0.6,
53 _fixture.brightness * 0.2,
54 );
55 }
58 List<DemoControl> controls(DemoContext context) => <DemoControl>[
59 ToggleControl(
60 'Pulse instead of flicker',
61 value: () => pulseInstead,
62 onChanged: (bool v) {
63 pulseInstead = v;
64 _fixture = LightFixture(
65 name: 'torch',
66 light: 'torch',
67 behavior: pulseInstead ? const PulseLight() : const FlameFlicker(),
68 );
69 },
70 ),
71 ];
74 void verify(Scene scene, FrameResult frame) {
75 if (frame.drawCalls < 1) {
76 throw StateError('the torch ball was not drawn');
77 }
78 // Switching the fixture off drops its brightness to zero on the next
79 // step, whichever behaviour is driving it.
80 _fixture.enabled = false;
81 _fixture.step(1 / 60);
82 if (_fixture.brightness != 0.0) {
83 throw StateError('a disabled fixture should report no brightness');
84 }
85 }
86}