Baking a lightmap: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: live (line 72), level (line 218), layout (line 232), bake (line 234).
1/// Unwrapping a level's brush faces onto an atlas, and baking the light the
2/// walls throw on each other into it.
3///
4/// Quoted by `lightmap_bake.md` and shown whole in the Source tab.
5library;
7import 'dart:async';
8import 'dart:math' as math;
9import 'dart:typed_data';
10import 'dart:ui' as ui;
12import 'package:flutter/widgets.dart';
13import 'package:flutter3d/flutter3d.dart';
14import 'package:flutter3d_build/lightmap.dart';
15import 'package:flutter3d_showcase/src/demo/demo.dart';
16import 'package:flutter3d_sim/flutter3d_sim.dart';
18/// The `lightmap-bake` page: a closet with a light, its faces unwrapped and
19/// baked. Its check is that the lightmap is not entirely black.
20final class LightmapBakeDemo extends ShowcaseDemo {
21 late final String _report;
23 /// The light's x in the closet, in metres, 0.4 to 3.6.
24 double lightX = 2.0;
26 /// How many bounces the bake follows, 0 to 3, in whole steps.
27 double bounces = 1.0;
29 /// How many rays each texel casts, 1 to 32, in whole steps.
30 double samples = 8.0;
32 /// The atlas's density, in texels per metre, 1 to 8.
33 double texels = 2.0;
35 bool _dirty = true;
36 bool _busy = false;
37 ui.Image? _atlas;
38 String _stats = '';
41 Scene build(DemoContext context) {
42 _report = _run();
43 final material = RenderMaterial(
44 name: 'closet',
45 baseColor: LinearColor.fromSrgb(0.8, 0.8, 0.7, 1.0),
46 );
47 final node = MeshNode(
48 DeviceMesh.upload(context.device, SphereShape(segments: 16).build()),
49 material,
50 );
51 return Scene()
52 ..add(node)
53 ..add(
54 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
55 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
56 );
57 }
60 void update(DemoContext context, double dt) {
61 if (_dirty && !_busy) {
62 _dirty = false;
63 _busy = true;
64 unawaited(_rebake().whenComplete(() => _busy = false));
65 }
66 }
68 /// Bakes the closet again with whatever the sliders say, and turns the
69 /// atlas into a picture: each texel's irradiance, clamped to what a screen
70 /// can show.
71 Future<void> _rebake() async {
72 final Level level = Level(
73 name: 'closet',
74 brushes: <Brush>[
75 Brush(center: WorldPosition(2, 0, 2), size: Vector3(4, 0.2, 4)),
76 Brush(center: WorldPosition(2, 2, 0), size: Vector3(4, 4, 0.2)),
77 ],
78 lights: <LevelLight>[
79 LevelLight(
80 position: WorldPosition(lightX, 3, 2),
81 intensity: 6.0 * LevelLight.absentIntensity,
82 ),
83 ],
84 );
85 final LightmapLayout layout = LightmapLayout.plan(
86 level,
87 texelsPerMeter: texels,
88 );
89 final Lightmap lightmap = LightmapBaker(
90 bounces: bounces.round(),
91 samples: samples.round(),
92 ).bake(level, layout: layout);
93 // A closet's light is a small number, so the picture is exposed for the
94 // brightest texel in it, the way a photograph would be.
95 var brightest = 1e-6;
96 for (var y = 0; y < lightmap.height; y++) {
97 for (var x = 0; x < lightmap.width; x++) {
98 final Vector3 light = lightmap.irradianceAt(x, y);
99 brightest = math.max(
100 brightest,
101 math.max(light.x, math.max(light.y, light.z)),
102 );
103 }
104 }
105 final Uint8List rgba = Uint8List(lightmap.texelCount * 4);
106 var lit = 0;
107 for (var y = 0; y < lightmap.height; y++) {
108 for (var x = 0; x < lightmap.width; x++) {
109 final Vector3 light = lightmap.irradianceAt(x, y);
110 final int at = (y * lightmap.width + x) * 4;
111 // Square-rooted, since a screen shows most of its range in the darks.
112 rgba[at] = (math.sqrt(light.x / brightest) * 255).round();
113 rgba[at + 1] = (math.sqrt(light.y / brightest) * 255).round();
114 rgba[at + 2] = (math.sqrt(light.z / brightest) * 255).round();
115 rgba[at + 3] = 255;
116 if (light.x + light.y + light.z > 0.0) lit++;
117 }
118 }
119 final Completer<ui.Image> decoded = Completer<ui.Image>();
120 ui.decodeImageFromPixels(
121 rgba,
122 lightmap.width,
123 lightmap.height,
124 ui.PixelFormat.rgba8888,
125 decoded.complete,
126 );
127 final ui.Image image = await decoded.future;
128 _stats =
129 '${layout.faces.length} faces in a ${layout.width}x${layout.height} '
130 'atlas, $lit of ${lightmap.texelCount} texels lit';
131 _atlas = image;
132 }
135 Widget? customBody(BuildContext buildContext, DemoContext context) {
136 final ui.Image? atlas = _atlas;
137 return ColoredBox(
138 color: const Color(0xFF14161A),
139 child: Padding(
140 padding: const EdgeInsets.all(24),
141 child: Column(
142 crossAxisAlignment: CrossAxisAlignment.start,
143 children: <Widget>[
144 Text(
145 'the baked atlas: what each texel of the closet receives. $_stats',
146 style: const TextStyle(color: Color(0xFFE8E8EC), fontSize: 15),
147 ),
148 const SizedBox(height: 16),
149 Expanded(
150 child: atlas == null
151 ? const Center(child: Text('baking…'))
152 : Center(
153 child: AspectRatio(
154 aspectRatio: atlas.width / atlas.height,
155 child: RawImage(
156 image: atlas,
157 fit: BoxFit.fill,
158 filterQuality: FilterQuality.none,
159 ),
160 ),
161 ),
162 ),
163 ],
164 ),
165 ),
166 );
167 }
170 List<DemoControl> controls(DemoContext context) => <DemoControl>[
171 SliderControl(
172 'Light position',
173 min: 0.4,
174 max: 3.6,
175 value: () => lightX,
176 onChanged: (double v) {
177 lightX = v;
178 _dirty = true;
179 },
180 format: (double v) => '${v.toStringAsFixed(1)} m',
181 ),
182 SliderControl(
183 'Bounces',
184 min: 0,
185 max: 3,
186 value: () => bounces,
187 onChanged: (double v) {
188 bounces = v.roundToDouble();
189 _dirty = true;
190 },
191 format: (double v) => v.round().toString(),
192 ),
193 SliderControl(
194 'Samples per texel',
195 min: 1,
196 max: 32,
197 value: () => samples,
198 onChanged: (double v) {
199 samples = v.roundToDouble();
200 _dirty = true;
201 },
202 format: (double v) => v.round().toString(),
203 ),
204 SliderControl(
205 'Texels per metre',
206 min: 1,
207 max: 8,
208 value: () => texels,
209 onChanged: (double v) {
210 texels = v.roundToDouble();
211 _dirty = true;
212 },
213 format: (double v) => v.round().toString(),
214 ),
215 ];
217 static String _run() {
218 final level = Level(
219 name: 'closet',
220 brushes: <Brush>[
221 Brush(center: WorldPosition(2, 0, 2), size: Vector3(4, 0.2, 4)),
222 Brush(center: WorldPosition(2, 2, 0), size: Vector3(4, 4, 0.2)),
223 ],
224 lights: <LevelLight>[
225 LevelLight(
226 position: WorldPosition(2, 3, 2),
227 intensity: 6.0 * LevelLight.absentIntensity,
228 ),
229 ],
230 );
232 final layout = LightmapLayout.plan(level, texelsPerMeter: 2.0);
234 const baker = LightmapBaker(bounces: 1, samples: 8);
235 final lightmap = baker.bake(level, layout: layout);
236 final anyLight = lightmap.pixels.any((int byte) => byte > 0);
238 return '${layout.faces.length} faces packed into a '
239 '${layout.width}x${layout.height} atlas\n'
240 'the baked map is ${lightmap.width}x${lightmap.height}, '
241 'and holds some light: $anyLight';
242 }
245 void verify(Scene scene, FrameResult frame) {
246 if (frame.drawCalls < 1) {
247 throw StateError('the closet marker was not drawn');
248 }
249 if (!_report.contains('holds some light: true')) {
250 throw StateError(
251 'a room with a light in it should bake a lightmap '
252 'that is not entirely black',
253 );
254 }
255 }
256}