Alpha modes: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: texture (line 38), materials (line 66), panels (line 77), live (line 118).
1/// The four ways a material treats its alpha channel: opaque, mask, blend and
2/// hashed.
3///
4/// Quoted by `alpha_modes.md` and shown whole in the Source tab.
5library;
7import 'dart:math' as math;
8import 'dart:typed_data';
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_showcase/src/demo/demo.dart';
13/// The `alpha-modes` page: one panel per alpha mode in front of a wall. Its
14/// check is that every mode has a panel and that the scene pass drew what
15/// each mode should.
16final class AlphaModesDemo extends ShowcaseDemo {
17 /// The panels' alpha, 0.1 to 1, written into each base colour.
18 double opacity = 0.9;
20 /// The alpha below which a masked panel is cut away, 0.05 to 0.95.
21 double cutoff = 0.5;
23 /// Whether the panels draw their back faces too.
24 bool doubleSided = false;
26 static const int _size = 64;
28 late final List<RenderMaterial> _materials;
31 void configureView(DemoContext context) {
32 context.orbit
33 ..distance = 7.0
34 ..yaw = 0.0
35 ..pitch = 0.05;
36 }
38 /// White everywhere, with an alpha that is one at the centre and falls to
39 /// zero at the rim: a soft disc.
40 ByteData _softDisc() {
41 final Uint8List bytes = Uint8List(_size * _size * 4);
42 for (var y = 0; y < _size; y++) {
43 for (var x = 0; x < _size; x++) {
44 final double dx = (x + 0.5) / _size * 2.0 - 1.0;
45 final double dy = (y + 0.5) / _size * 2.0 - 1.0;
46 final double alpha = (1.0 - math.sqrt(dx * dx + dy * dy)).clamp(0, 1);
47 final int at = (y * _size + x) * 4;
48 bytes[at] = 255;
49 bytes[at + 1] = 255;
50 bytes[at + 2] = 255;
51 bytes[at + 3] = (alpha * 255).round();
52 }
53 }
54 return bytes.buffer.asByteData();
55 }
58 Scene build(DemoContext context) {
59 final TextureHandle disc = context.device.createTextureFromPixels(
60 width: _size,
61 height: _size,
62 format: TextureFormat.r8g8b8a8UNormInt,
63 pixels: _softDisc(),
64 );
66 _materials = <RenderMaterial>[
67 for (final MaterialAlphaMode mode in MaterialAlphaMode.values)
68 RenderMaterial(
69 name: mode.name,
70 baseColor: LinearColor.fromSrgb(0.95, 0.55, 0.2, opacity),
71 albedo: disc,
72 albedoSampler: SamplerDescriptor.linearClamp,
73 alphaMode: mode,
74 ),
75 ];
77 final DeviceMesh panel = DeviceMesh.upload(
78 context.device,
79 const PlaneShape(width: 1.4, depth: 1.4).build(),
80 );
81 final Quaternion upright = Quaternion.axisAngle(
82 Vector3(1.0, 0.0, 0.0),
83 math.pi / 2,
84 );
85 final Scene scene = Scene();
86 for (var i = 0; i < _materials.length; i++) {
87 scene.add(
88 MeshNode(panel, _materials[i], name: _materials[i].name)
89 ..setRotation(upright)
90 ..setPosition((i - 1.5) * 1.6, 0.0, 0.0),
91 );
92 }
94 final MeshNode wall =
95 MeshNode(
96 DeviceMesh.upload(
97 context.device,
98 const PlaneShape(width: 9, depth: 3).build(),
99 ),
100 RenderMaterial(
101 name: 'wall',
102 baseColor: LinearColor.fromSrgb(0.2, 0.35, 0.55, 1.0),
103 ),
104 name: 'wall',
105 )
106 ..setRotation(upright)
107 ..setPosition(0.0, 0.0, -0.6);
108 return scene
109 ..add(wall)
110 ..add(
111 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
112 ..setLocalForward(Vector3(-0.2, -0.3, -1.0)),
113 );
114 }
117 void update(DemoContext context, double dt) {
118 for (final RenderMaterial material in _materials) {
119 material
120 ..baseColor = material.baseColor.withAlpha(opacity)
121 ..alphaCutoff = cutoff
122 ..doubleSided = doubleSided;
123 }
124 }
127 List<DemoControl> controls(DemoContext context) => <DemoControl>[
128 SliderControl(
129 'Opacity',
130 min: 0.1,
131 max: 1,
132 value: () => opacity,
133 onChanged: (double v) => opacity = v,
134 ),
135 SliderControl(
136 'Alpha cutoff',
137 min: 0.05,
138 max: 0.95,
139 value: () => cutoff,
140 onChanged: (double v) => cutoff = v,
141 ),
142 ToggleControl(
143 'Double sided',
144 value: () => doubleSided,
145 onChanged: (bool v) => doubleSided = v,
146 ),
147 ];
150 void verify(Scene scene, FrameResult frame) {
151 final Set<MaterialAlphaMode> modes = <MaterialAlphaMode>{
152 for (final MeshNode mesh in scene.meshes) mesh.material.alphaMode,
153 };
154 if (modes.length != MaterialAlphaMode.values.length) {
155 throw StateError('the panels do not cover every alpha mode: $modes');
156 }
157 // A masked or hashed panel is drawn twice: a depth pre-draw makes the
158 // cut, and the lit draw follows through the opaque stage, tested equal.
159 // Every other mesh is one draw.
160 final int cut = scene.meshes.where((MeshNode mesh) {
161 final RenderMaterial m = mesh.material;
162 return (m.alphaMode == MaterialAlphaMode.mask && !m.alphaToCoverage) ||
163 m.alphaMode == MaterialAlphaMode.hashed;
164 }).length;
165 final int expected = scene.meshes.length + cut;
166 final int sceneDraws = frame.passes
167 .where((FramePass pass) => pass.name == 'scene')
168 .fold(0, (int sum, FramePass pass) => sum + pass.drawCalls);
169 if (sceneDraws != expected) {
170 throw StateError(
171 'the scene pass drew $sceneDraws draws for ${scene.meshes.length} '
172 'meshes, $cut of them cut by a pre-draw; $expected expected',
173 );
174 }
175 }
176}