Flickering lights: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: fixture (line 18), step (line 42), toggle (line 74).
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';
10import 'package:vector_math/vector_math.dart';
12final class LightFixturesDemo extends ShowcaseDemo {
13 bool pulseInstead = false;
15 late final LightNode _torchLight;
16 late final Material _torchMaterial;
18 late LightFixture _fixture = LightFixture(
19 name: 'torch',
20 light: 'torch',
21 behaviour: const FlameFlicker(),
22 );
25 Scene build(DemoContext context) {
26 _torchMaterial = Material(
27 name: 'torch',
28 baseColor: Vector4(0.9, 0.6, 0.2, 1.0),
29 );
30 final ball = MeshNode(
31 DeviceMesh.upload(context.device, SphereShape(segments: 24).build()),
32 _torchMaterial,
33 name: 'torch-ball',
34 );
35 _torchLight = LightNode(name: 'torch', intensity: 4.0)
36 ..setLocalForward(Vector3(-0.2, -1.0, -0.1));
37 return Scene()
38 ..add(ball)
39 ..add(_torchLight);
40 }
43 void update(DemoContext context, double dt) {
44 _fixture.step(dt);
45 _torchLight.intensity = 4.0 * _fixture.brightness;
46 _torchMaterial.emissive.setValues(
47 _fixture.brightness,
48 _fixture.brightness * 0.6,
49 _fixture.brightness * 0.2,
50 );
51 }
54 List<DemoControl> controls(DemoContext context) => <DemoControl>[
55 ToggleControl(
56 'Pulse instead of flicker',
57 value: () => pulseInstead,
58 onChanged: (bool v) {
59 pulseInstead = v;
60 _fixture = LightFixture(
61 name: 'torch',
62 light: 'torch',
63 behaviour: pulseInstead ? const PulseLight() : const FlameFlicker(),
64 );
65 },
66 ),
67 ];
70 void verify(Scene scene, FrameResult frame) {
71 if (frame.drawCalls < 1) {
72 throw StateError('the torch ball was not drawn');
73 }
74 // Switching the fixture off drops its brightness to zero on the next
75 // step, whichever behaviour is driving it.
76 _fixture.enabled = false;
77 _fixture.step(1 / 60);
78 if (_fixture.brightness != 0.0) {
79 throw StateError('a disabled fixture should report no brightness');
80 }
81 }
82}