Actors, brains and health: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: brain (line 15), live (line 114), hit (line 131), actor (line 187), hurt (line 196).
1/// Who a collider is, and the components that make an actor: health that can
2/// run out, and a brain that has memory of its own.
3///
4/// Quoted by `actors.md` and shown whole in the Source tab.
5library;
7import 'dart:math' as math;
9import 'package:flutter3d/flutter3d.dart';
10import 'package:flutter3d_physics/flutter3d_physics.dart';
11import 'package:flutter3d_showcase/src/demo/demo.dart';
12import 'package:flutter3d_showcase/src/demo/run_physics.dart';
13import 'package:flutter3d_sim/flutter3d_sim.dart';
15/// A brain with one bit of memory: whether it has ever been hurt.
16final class _WaryBrain extends Brain {
17 bool everHurt = false;
20 void onHurt(BrainHurt hurt) => everHurt = true;
23 Map<String, Object?> save() => <String, Object?>{'everHurt': everHurt};
26 void restore(Map<String, Object?> from) =>
27 everHurt = from['everHurt'] == true;
28}
30/// The `actors` page: a goblin actor with health and a brain. Its check is
31/// that twelve damage leaves thirty health at eighteen and that the brain
32/// remembers being hurt.
33final class ActorsDemo extends ShowcaseDemo {
34 late final double _currentHealth;
35 late final bool _stillAlive;
36 late final bool _rememberedBeingHurt;
38 late final Actor _goblin;
39 late final _WaryBrain _brain;
40 late final MeshNode _body;
41 late final MeshNode _bar;
42 late final RenderMaterial _skin;
43 double _hitAsked = 0.0;
44 bool _resetAsked = false;
45 double _flash = 0.0;
47 static const double _barWidth = 1.4;
50 void configureView(DemoContext context) {
51 context.orbit
52 ..distance = 4.2
53 ..pitch = 0.25
54 ..yaw = 0.4;
55 context.orbit.target.setValues(0.0, 0.6, 0.0);
56 }
59 Scene build(DemoContext context) {
60 final (
61 String _,
62 double currentHealth,
63 bool stillAlive,
64 bool rememberedBeingHurt,
65 ) = _run();
66 _currentHealth = currentHealth;
67 _stillAlive = stillAlive;
68 _rememberedBeingHurt = rememberedBeingHurt;
70 _spawn();
71 _skin = RenderMaterial(name: 'goblin', baseColor: _fromSrgb(_healthy));
72 _body = MeshNode(
73 DeviceMesh.upload(context.device, SphereShape(segments: 24).build()),
74 _skin,
75 name: 'goblin',
76 );
77 MeshNode block(String name, Vector3 size, Vector4 color) => MeshNode(
78 DeviceMesh.upload(context.device, CuboidShape(size: size).build()),
79 RenderMaterial(name: name, baseColor: _fromSrgb(color)),
80 name: name,
81 );
82 _bar = block(
83 'health',
84 Vector3(_barWidth, 0.14, 0.14),
85 Vector4(0.3, 0.8, 0.3, 1.0),
86 );
87 return Scene()
88 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
89 ..ambientIntensity = 0.3 * LightNode.legacyUnit
90 ..add(
91 block('floor', Vector3(6.0, 0.1, 6.0), Vector4(0.36, 0.4, 0.38, 1.0))
92 ..setPosition(0.0, -0.05, 0.0),
93 )
94 ..add(
95 block(
96 'bar back',
97 Vector3(_barWidth + 0.08, 0.2, 0.1),
98 Vector4(0.1, 0.1, 0.12, 1.0),
99 )..setPosition(0.0, 1.5, -0.02),
100 )
101 ..add(_body)
102 ..add(_bar)
103 ..add(
104 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
105 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
106 );
107 }
109 static Vector4 get _healthy => Vector4(0.5, 0.7, 0.3, 1.0);
110 static Vector4 get _wary => Vector4(0.85, 0.6, 0.25, 1.0);
112 /// The goblin of the page, built the way the first step builds one.
113 void _spawn() {
114 final EcsWorld entities = EcsWorld();
115 final entity = entities.spawn();
116 _brain = _WaryBrain();
117 entities
118 ..set(entity, Vitality(Health(30.0)))
119 ..set(entity, Thinking(_brain));
120 _goblin = Actor(entities, entity, name: 'goblin');
121 }
124 void update(DemoContext context, double dt) {
125 if (_resetAsked) {
126 _resetAsked = false;
127 _spawn();
128 _flash = 0.0;
129 }
130 if (_hitAsked > 0.0) {
131 // The damage goes through `Health`; the brain hears of it separately.
132 _goblin.applyDamage(Damage(amount: _hitAsked));
133 _brain.onHurt(BrainHurt(mind: Mind(_stubSystem()), amount: _hitAsked));
134 _hitAsked = 0.0;
135 _flash = 1.0;
136 }
137 _flash = math.max(0.0, _flash - dt * 3.0);
139 final double fraction = (_goblin.health!.current / _goblin.health!.maximum)
140 .clamp(0.0, 1.0);
141 // The bar shrinks towards its left end, and goes red as it does.
142 _bar
143 ..setScale(math.max(fraction, 0.001), 1.0, 1.0)
144 ..setPosition(-(1.0 - fraction) * _barWidth / 2, 1.5, 0.05);
145 _bar.material.baseColor = LinearColor.fromSrgb(
146 1.0 - fraction * 0.7,
147 0.2 + 0.6 * fraction,
148 0.2,
149 1.0,
150 );
152 if (_goblin.isAlive) {
153 // A hit squashes it, and a goblin that has been hurt stays wary.
154 final double squash = 1.0 - 0.25 * _flash;
155 _body
156 ..setScale(1.0 + 0.2 * _flash, squash, 1.0 + 0.2 * _flash)
157 ..setPosition(0.0, 0.5 * squash, 0.0);
158 _skin.baseColor = _fromSrgb(_brain.everHurt ? _wary : _healthy);
159 } else {
160 // Dead: flat on the floor and grey.
161 _body
162 ..setScale(1.2, 0.2, 1.2)
163 ..setPosition(0.0, 0.1, 0.0);
164 _skin.baseColor = LinearColor.fromSrgb(0.35, 0.35, 0.37, 1.0);
165 }
166 }
169 List<DemoControl> controls(DemoContext context) => <DemoControl>[
170 ToggleControl(
171 'Hit it for 12',
172 value: () => false,
173 onChanged: (bool v) {
174 if (v) _hitAsked = 12.0;
175 },
176 ),
177 ToggleControl(
178 'A fresh goblin',
179 value: () => false,
180 onChanged: (bool v) {
181 if (v) _resetAsked = true;
182 },
183 ),
184 ];
186 static (String, double, bool, bool) _run() {
187 final entities = EcsWorld();
188 final entity = entities.spawn();
189 entities
190 ..set(entity, Vitality(Health(30.0)))
191 ..set(entity, Thinking(_WaryBrain()));
192 final goblin = Actor(entities, entity, name: 'goblin');
194 final aliveBefore = goblin.isAlive;
196 final brain = goblin.brain! as _WaryBrain;
197 goblin.applyDamage(Damage(amount: 12.0));
198 brain.onHurt(BrainHurt(mind: Mind(_stubSystem()), amount: 12.0));
199 final currentHealth = goblin.health!.current;
201 final report =
202 'a fresh goblin is alive: $aliveBefore, has ${goblin.health!.current} '
203 'health of ${goblin.health!.maximum}\n'
204 'after twelve damage: $currentHealth health, still alive: '
205 '${goblin.isAlive}, its brain remembers being hurt: ${brain.everHurt}';
206 return (report, currentHealth, goblin.isAlive, brain.everHurt);
207 }
209 /// A real `ActorSystem` needs a live level; `Brain.onHurt` only needs a
210 /// `Mind`, and a `Mind` only needs a system to ask `focus` of, which this
211 /// page never calls. A throwaway system is enough to build one.
212 static ActorSystem _stubSystem() =>
213 ActorSystem(world: onRunPhysics(CollisionWorld()), random: GameRandom(1));
216 void verify(Scene scene, FrameResult frame) {
217 if (frame.drawCalls < 1) {
218 throw StateError('the goblin marker was not drawn');
219 }
220 // Compared as numbers, not read back out of `_report`: a whole-number
221 // double loses its trailing `.0` when a web backend formats it, and a
222 // compiled `18` failing a substring match against `'18.0 health'` would
223 // be this check catching its own string, not the damage arithmetic.
224 if (_currentHealth != 18.0 || !_stillAlive) {
225 throw StateError(
226 'twelve damage on thirty health should leave the '
227 'goblin alive at eighteen',
228 );
229 }
230 if (!_rememberedBeingHurt) {
231 throw StateError('the brain should remember being hurt');
232 }
233 }
234}
236/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
237LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);