Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
SpringBoneSystem.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
4
8
9#include <algorithm>
10#include <cmath>
11
12namespace esengine::springbone {
13
14void SpringBoneSystem::collectBones(ecs::Registry& registry, Entity root, std::vector<Entity>& out) {
15 out.clear();
16 stack_.clear();
17 stack_.push_back(root);
18 // Preorder: a bone comes before everything below it, which is the order the solver wants.
19 while (!stack_.empty()) {
20 const Entity e = stack_.back();
21 stack_.pop_back();
22 out.push_back(e);
23 if (const auto* children = registry.tryGet<ecs::Children>(e)) {
24 for (auto it = children->entities.rbegin(); it != children->entities.rend(); ++it) {
25 if (registry.valid(*it) && registry.has<ecs::Transform>(*it)) stack_.push_back(*it);
26 }
27 }
28 }
29}
30
31bool SpringBoneSystem::gatherColliders(ecs::Registry& registry, const std::vector<Entity>& entities, std::vector<Collider>& out) {
32 out.clear();
33 for (const Entity e : entities) {
34 if (!registry.valid(e)) continue;
35 const auto* shape = registry.tryGet<ecs::SpringBoneCollider>(e);
36 auto* t = registry.tryGet<ecs::Transform>(e);
37 if (!shape || !t) continue;
38 t->ensureDecomposed();
39 const glm::vec3 centre = t->worldPosition + t->worldRotation * (shape->offset * t->worldScale);
40 const f32 scale = std::max({std::abs(t->worldScale.x), std::abs(t->worldScale.y), std::abs(t->worldScale.z)});
41 Collider c;
42 c.radius = shape->radius * scale;
43 if (shape->shape == ecs::SpringBoneShape::Capsule) {
44 const glm::vec3 axis = t->worldRotation * glm::vec3(0.0f, 1.0f, 0.0f);
45 const f32 half = shape->height * std::abs(t->worldScale.y) * 0.5f;
46 c.a = centre - axis * half;
47 c.b = centre + axis * half;
48 } else {
49 c.a = c.b = centre;
50 }
51 out.push_back(c);
52 }
53 return !out.empty();
54}
55
56void SpringBoneSystem::restoreBones(ecs::Registry& registry, State& state) {
57 for (size_t i = 1; i < state.entities.size() && i < state.animated.size(); ++i) {
58 if (!registry.valid(state.entities[i])) continue;
59 auto* t = registry.tryGet<ecs::Transform>(state.entities[i]);
60 if (t && state.hasWritten[i] && t->rotation == state.written[i]) {
61 t->rotation = state.animated[i];
62 registry.markChanged<ecs::Transform>(state.entities[i]);
64 }
65 }
66}
67
69 const auto it = states_.find(root);
70 if (it == states_.end()) return;
71 restoreBones(registry, it->second);
72 states_.erase(it);
73}
74
76 auto it = states_.find(root);
77 if (it != states_.end()) it->second.primed = false;
78}
79
80void SpringBoneSystem::snapshot(Entity root, std::vector<f32>& out) const {
81 out.clear();
82 const auto it = states_.find(root);
83 if (it == states_.end()) return;
84 for (const Particle& p : it->second.particles) {
85 out.insert(out.end(), {p.position.x, p.position.y, p.position.z, p.target.x, p.target.y, p.target.z, static_cast<f32>(p.parent)});
86 }
87}
88
89const std::vector<Particle>* SpringBoneSystem::chain(Entity root) const {
90 const auto it = states_.find(root);
91 return it == states_.end() ? nullptr : &it->second.particles;
92}
93
95 if (!destroyConn_.isConnected()) {
96 destroyConn_ = registry.onDestroy([this](Entity entity) {
97 states_.erase(entity);
98 });
99 }
100 simulated_ = 0;
101
102 // A chain whose component is gone, or switched off, gives its bones back to the animation as the animation had them.
103 for (auto it = states_.begin(); it != states_.end();) {
104 const Entity root = it->first;
105 const auto* sb = registry.valid(root) ? registry.tryGet<ecs::SpringBone>(root) : nullptr;
106 if (sb && sb->enabled && sb->weight > 0.0f) { ++it; continue; }
107 restoreBones(registry, it->second);
108 it = states_.erase(it);
109 }
110
111 auto view = registry.activeView<ecs::Transform, ecs::SpringBone>();
112 bool any = false;
113 for (auto entity : view) { (void)entity; any = true; break; }
114 if (!any) return;
115
116 // The animation has written local rotations; the world transforms this reads are composed from them.
117 if (transforms) transforms->ensureComposed(registry);
118
119 for (auto entity : view) {
120 const auto& sb = view.get<ecs::SpringBone>(entity);
121 if (!sb.enabled || sb.weight <= 0.0f) continue;
122
123 collectBones(registry, entity, found_);
124 const size_t bones = found_.size();
125 if (bones < 2 && !(bones == 1 && sb.endLength > 0.0f)) continue;
126
127 State& st = states_[entity];
128
129 // The bones this chain has, and which are leaves (those get a virtual tip when the chain has an end length).
130 size_t leaves = 0;
131 childCount_.assign(bones, 0);
132 parentOf_.assign(bones, -1);
133 auto& childCount = childCount_;
134 auto& parentOf = parentOf_;
135 for (size_t i = 1; i < bones; ++i) {
136 const auto* p = registry.tryGet<ecs::Parent>(found_[i]);
137 i32 parent = 0;
138 if (p) {
139 for (size_t j = i; j-- > 0;) if (found_[j] == p->entity) { parent = static_cast<i32>(j); break; }
140 }
141 parentOf[i] = parent;
142 childCount[static_cast<size_t>(parent)]++;
143 }
144 for (size_t i = 0; i < bones; ++i) if (childCount[i] == 0) ++leaves;
145 const size_t tips = sb.endLength > 0.0f ? leaves : 0;
146
147 if (st.entities != found_ || st.particles.size() != bones + tips) {
148 st.entities = found_;
149 st.particles.assign(bones + tips, Particle{});
150 st.nodes.assign(bones + tips, Node{});
151 for (size_t i = 0; i < bones; ++i) {
152 st.nodes[i].entity = found_[i];
153 st.particles[i].parent = parentOf[i];
154 }
155 for (size_t i = 1; i < bones; ++i) {
156 Node& parent = st.nodes[static_cast<size_t>(parentOf[i])];
157 if (parent.firstChild < 0) parent.firstChild = static_cast<i32>(i);
158 }
159 size_t next = bones;
160 if (tips > 0) {
161 for (size_t i = 0; i < bones; ++i) {
162 if (childCount[i] != 0) continue;
163 st.nodes[i].firstChild = static_cast<i32>(next);
164 st.particles[next].parent = static_cast<i32>(i);
165 ++next;
166 }
167 }
168 st.primed = false;
169 st.animated.assign(bones, glm::quat(1.0f, 0.0f, 0.0f, 0.0f));
170 st.written.assign(bones, glm::quat(1.0f, 0.0f, 0.0f, 0.0f));
171 st.hasWritten.assign(bones, false);
172 }
173
174 // Read the pose the animation gave: a bone whose rotation is still the one this system wrote was not animated this frame,
175 // so the animation's own value is the one kept from before (otherwise the chain would spring toward its own last result).
176 poses_.resize(bones);
177 tipOffsets_.assign(bones + tips, glm::vec3(0.0f));
178 for (size_t i = 0; i < bones; ++i) {
179 auto& t = registry.get<ecs::Transform>(found_[i]);
181 Pose& pose = poses_[i];
182 pose.animScale = t.worldScale;
183 pose.localPosition = t.position;
184 if (i > 0) {
185 if (st.hasWritten[i] && t.rotation == st.written[i]) {
186 pose.localRotation = st.animated[i];
187 } else {
188 pose.localRotation = t.rotation;
189 st.animated[i] = t.rotation;
190 st.hasWritten[i] = false;
191 }
192 // The pose the animation gave, worked out down the chain from the root with the animation's own rotations: the composed world
193 // transforms of the bones below the root include what this system wrote last frame, and a target taken from them would be the chain's own result.
194 const Pose& parent = poses_[static_cast<size_t>(parentOf[i])];
195 pose.animRot = parent.animRot * pose.localRotation;
196 pose.animPos = parent.animPos + parent.animRot * (pose.localPosition * parent.animScale);
197 } else {
198 pose.localRotation = t.rotation;
199 pose.animPos = t.worldPosition;
200 pose.animRot = t.worldRotation;
201 }
202 }
203
204 // Targets: where the animation puts each bone, and the distance each keeps from its parent.
205 f32 totalRest = 0.0f;
206 for (size_t i = 0; i < bones; ++i) {
207 Particle& p = st.particles[i];
208 p.target = poses_[i].animPos;
209 if (p.parent >= 0) {
210 p.restLength = glm::length(p.target - poses_[static_cast<size_t>(p.parent)].animPos);
211 totalRest += p.restLength;
212 }
213 }
214 for (size_t i = 0; i < bones; ++i) {
215 const i32 tip = st.nodes[i].firstChild;
216 if (tip < static_cast<i32>(bones) || tip < 0) continue;
217 glm::vec3 direction = poses_[i].animRot * glm::vec3(0.0f, 1.0f, 0.0f);
218 if (parentOf[i] >= 0) {
219 const glm::vec3 along = poses_[i].animPos - poses_[static_cast<size_t>(parentOf[i])].animPos;
220 if (glm::dot(along, along) > 1e-12f) direction = glm::normalize(along);
221 }
222 Particle& p = st.particles[static_cast<size_t>(tip)];
223 p.target = poses_[i].animPos + direction * sb.endLength;
224 p.restLength = sb.endLength;
225 totalRest += sb.endLength;
226 // The tip as the bone sees it in its own animated frame, so forward kinematics with the animated rotation lands on the target.
227 tipOffsets_[static_cast<size_t>(tip)] = glm::inverse(poses_[i].animRot) * (p.target - poses_[i].animPos);
228 }
229
230 // A jump of the root, or a long stall, is not motion the hair should trail through: put it back at its pose.
231 const glm::vec3 rootPosition = poses_[0].animPos;
232 const bool teleported = st.primed && glm::length(rootPosition - st.rootPosition) > std::max(totalRest, 1e-3f) * 4.0f;
233 if (!st.primed || teleported || dt > 0.5f) {
234 springbone::reset(st.particles);
235 st.primed = true;
236 }
237 st.rootPosition = rootPosition;
238
239 gatherColliders(registry, sb.colliders, colliders_);
240 StepParams params;
241 params.stiffness = sb.stiffness;
242 params.drag = sb.drag;
243 params.gravity = sb.gravity;
244 params.radius = sb.radius;
245 params.wind = sb.wind;
246 params.windGust = sb.windGust;
247 params.windFrequency = sb.windFrequency;
248 params.time = st.clock;
249 step(st.particles, params, colliders_, dt);
250 st.clock += std::min(dt, springbone::kMaxStep);
251 ++simulated_;
252
253 // Write back: each bone is turned to aim at where its child's simulated point is, going down the chain so a bone's own position
254 // already follows its turned parent.
255 fkPosition_.resize(bones);
256 fkRotation_.resize(bones);
257 const f32 weight = std::clamp(sb.weight, 0.0f, 1.0f);
258 bool wrote = false;
259 for (size_t i = 0; i < bones; ++i) {
260 glm::quat unaimed;
261 if (i == 0) {
262 fkPosition_[0] = poses_[0].animPos;
263 fkRotation_[0] = poses_[0].animRot;
264 unaimed = fkRotation_[0];
265 } else {
266 const size_t b = static_cast<size_t>(parentOf[i]);
267 fkPosition_[i] = fkPosition_[b] + fkRotation_[b] * (poses_[i].localPosition * poses_[b].animScale);
268 unaimed = fkRotation_[b] * poses_[i].localRotation;
269 fkRotation_[i] = unaimed;
270 }
271 const i32 c = st.nodes[i].firstChild;
272 if (i == 0 || c < 0) continue;
273 const glm::vec3 offset = static_cast<size_t>(c) < bones
274 ? poses_[static_cast<size_t>(c)].localPosition * poses_[i].animScale
275 : tipOffsets_[static_cast<size_t>(c)];
276 const glm::vec3 current = fkRotation_[i] * offset;
277 const glm::vec3 wanted = st.particles[static_cast<size_t>(c)].position - fkPosition_[i];
278 glm::quat aimed = shortestArc(current, wanted) * fkRotation_[i];
279 if (weight < 1.0f) aimed = glm::slerp(unaimed, aimed, weight);
280 fkRotation_[i] = aimed;
281
282 const size_t b = static_cast<size_t>(parentOf[i]);
283 const glm::quat local = glm::normalize(glm::inverse(fkRotation_[b]) * aimed);
284 auto& t = registry.get<ecs::Transform>(found_[i]);
285 if (t.rotation != local) {
286 t.rotation = local;
287 registry.markChanged<ecs::Transform>(found_[i]);
288 }
289 st.written[i] = local;
290 st.hasWritten[i] = true;
291 wrote = true;
292 }
294 }
295}
296
297} // namespace esengine::springbone
Hierarchy components for parent-child relationships.
Per-App secondary motion: runs every SpringBone chain after the animation has posed the skeleton and ...
Secondary motion for a chain of bones: hair, tails, cords, cloth edges.
Unified Transform component with local and world-space data.
Central container for all entities and components.
Definition Registry.hpp:73
T & get(Entity entity)
Gets a component from an entity (must exist).
Definition Registry.hpp:649
Connection onDestroy(DestroyCallback callback)
Subscribe to entity destruction.
Definition Registry.hpp:509
void markChanged(Entity entity)
Says entity's T was written, through a reference held from before.
Definition Registry.hpp:196
bool valid(Entity entity) const
Checks if an entity is currently valid.
Definition Registry.hpp:518
T * tryGet(Entity entity)
Tries to get a component from an entity.
Definition Registry.hpp:670
void ensureComposed(Registry &registry)
Compose if anything changed since the last one; O(1) if not.
void update(ecs::Registry &registry, ecs::TransformSystem *transforms, f32 dt)
Advance every enabled chain by dt seconds. Composes world transforms first if the animation moved any...
const std::vector< Particle > * chain(Entity root) const
The simulated world positions of a chain, root first, in the order its bones were found (tips last); ...
void snapshot(Entity root, std::vector< f32 > &out) const
A chain's particles as flat floats for the editor to draw: seven a particle, the simulated position,...
void release(ecs::Registry &registry, Entity root)
Give a chain's bones back as the animation had them and forget its state: what stops a preview in the...
void reset(Entity root)
Forget a chain's state: it starts again from the animated pose on its next frame (a teleport,...
void invalidateTransformComposition()
Say that composed world transforms are stale.
constexpr f32 kMaxStep
Longest stretch of time one call integrates; a stall must not become a lurch.
glm::quat shortestArc(const glm::vec3 &from, const glm::vec3 &to)
The shortest rotation that turns direction from onto direction to; identity when either has no length...
void step(std::vector< Particle > &chain, const StepParams &params, const std::vector< Collider > &colliders, f32 dt)
Advances the chain by dt seconds.
void reset(std::vector< Particle > &chain)
Sets every particle to rest at its target: the state a chain starts in and the one it is put back in ...
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
float f32
32-bit floating point
Definition Types.hpp:59
Entity identifier with packed index + generation.
Definition Types.hpp:135
Parent reference component.
Definition Hierarchy.hpp:46
Unified transform component.
Definition Transform.hpp:45
One simulated point of a chain.
i32 parent
Index of the parent particle, -1 for the root, which the animation drives.
f32 restLength
Its distance from its parent, which the chain keeps.
glm::vec3 target
Where the animation puts it this frame.
f32 time
Seconds on the chain's own clock at the start of the call; gusts are a function of it,...
glm::vec3 wind
Steady wind acceleration, world units a second squared.
f32 radius
The strand's own thickness, kept clear of colliders.
f32 stiffness
Pull toward the animated pose per 60 Hz frame, 0 to 1.
f32 windGust
How far gusts swing the wind's strength, 0 to 1: 0.5 takes it between half and one and a half times w...
f32 drag
Share of speed lost per 60 Hz frame, 0 to 1.