Crimson Engine 1.0.0
A high-performance C++20 game engine prototype showcasing a custom ECS, Vulkan renderer, and ImGui editor.
Loading...
Searching...
No Matches
AnimationSystem.hpp
Go to the documentation of this file.
1#pragma once
2#include "ecs/System.hpp"
3#include "ecs/Registry.hpp"
12#include "core/JobSystem.hpp"
13#include "core/VulkanBuffer.hpp"
15#include <glm/gtc/matrix_transform.hpp>
16#include <glm/gtc/quaternion.hpp>
17
18#define GLM_ENABLE_EXPERIMENTAL
19#include <glm/gtx/quaternion.hpp>
20#include <algorithm>
21#include <fstream>
22#include <iostream>
23
28class AnimationSystem : public System {
29public:
32
37 struct JointPose {
38 glm::vec3 translation;
39 glm::quat rotation;
40 glm::vec3 scale;
41 };
42
47 void update(float dt) override {
48 // 0. Synchronize child animators & controllers with parent animators
49 for (auto [entity, hierarchy, animator] : registry.view<HierarchyComponent, AnimatorComponent>()) {
50 if (hierarchy.parent.getId() != Entity::INVALID_ENTITY && registry.isValid(hierarchy.parent)) {
51 // Skip synchronization if child has its own controller or independent animations
52 if (registry.has<AnimationControllerComponent>(entity) || !animator.animations.empty()) {
53 continue;
54 }
55 if (auto* parentAnimator = registry.get<AnimatorComponent>(hierarchy.parent)) {
56 animator.activeAnimationIndex = parentAnimator->activeAnimationIndex;
57 animator.currentTime = parentAnimator->currentTime;
58 animator.playbackSpeed = parentAnimator->playbackSpeed;
59 animator.loop = parentAnimator->loop;
60 animator.isPreviewing = parentAnimator->isPreviewing;
61 }
62 }
63 }
64
65 for (auto [entity, hierarchy, controller] : registry.view<HierarchyComponent, AnimationControllerComponent>()) {
66 if (hierarchy.parent.getId() != Entity::INVALID_ENTITY && registry.isValid(hierarchy.parent)) {
67 // Skip synchronization if child has its own independent animations
68 if (auto* animator = registry.get<AnimatorComponent>(entity)) {
69 if (!animator->animations.empty()) {
70 continue;
71 }
72 }
73 if (auto* parentController = registry.get<AnimationControllerComponent>(hierarchy.parent)) {
74 controller.currentState = parentController->currentState;
75 controller.currentStateTime = parentController->currentStateTime;
76 controller.fromState = parentController->fromState;
77 controller.fromStateTime = parentController->fromStateTime;
78 controller.crossfadeProgress = parentController->crossfadeProgress;
79 controller.crossfadeDuration = parentController->crossfadeDuration;
80 controller.isCrossfading = parentController->isCrossfading;
81 controller.parameters = parentController->parameters;
82 }
83 }
84 }
85
86 // 1. First Pass: Update all active Animation Controllers in parallel
87 controllerEntities.clear();
88 for (auto [entity, controller, animator] : registry.view<AnimationControllerComponent, AnimatorComponent>()) {
89 controllerEntities.push_back(entity);
90 }
91
92 Engine::JobSystem::getInstance().parallelFor(static_cast<int>(controllerEntities.size()), [&](int idx) {
93 Entity entity = controllerEntities[idx];
94 auto* controller = registry.get<AnimationControllerComponent>(entity);
95 auto* animator = registry.get<AnimatorComponent>(entity);
96 if (controller && animator) {
97 float entityDt = (editorMode.isPlaying || animator->isPreviewing || animator->playbackSpeed > 0.0f) ? dt : 0.0f;
98 updateController(*controller, *animator, entityDt);
99 }
100 });
101
102 // 2. Second Pass: Process skeletal transforms, blending, and IK adjustments in parallel
103 animatedEntities.clear();
104 for (auto [entity, skeleton, animator] : registry.view<SkeletonComponent, AnimatorComponent>()) {
105 if (!skeleton.joints.empty()) {
106 animatedEntities.push_back(entity);
107 }
108 }
109
110 Engine::JobSystem::getInstance().parallelFor(static_cast<int>(animatedEntities.size()), [&](int idx) {
111 Entity entity = animatedEntities[idx];
112 auto* skeleton = registry.get<SkeletonComponent>(entity);
113 auto* animator = registry.get<AnimatorComponent>(entity);
114 if (skeleton && animator) {
115 float entityDt = (editorMode.isPlaying || animator->isPreviewing || animator->playbackSpeed > 0.0f) ? dt : 0.0f;
116 updateEntityAnimation(entity, *skeleton, *animator, entityDt);
117 }
118 });
119
120 // 3. Third Pass: Process generic property-only animations for entities without skeletons (Main Thread)
121 for (auto [entity, animator] : registry.view<AnimatorComponent>()) {
122 auto* skeleton = registry.get<SkeletonComponent>(entity);
123 if (!skeleton || skeleton->joints.empty()) {
124 float entityDt = (editorMode.isPlaying || animator.isPreviewing || animator.playbackSpeed > 0.0f) ? dt : 0.0f;
125 updateGenericAnimation(entity, animator, entityDt);
126 }
127 }
128 }
129
130 private:
134 void updateController(AnimationControllerComponent& controller, AnimatorComponent& animator, float dt) {
135 if ((controller.currentState.empty() || controller.currentState == "Entry" || controller.currentState == "__Entry__") && !controller.states.empty()) {
136 controller.currentState = controller.states[0].name;
137 controller.currentStateTime = 0.0f;
138 }
139
140 if (controller.currentState.empty()) return;
141
142 // Advance play time for current state
143 const AnimationState* currState = nullptr;
144 for (const auto& state : controller.states) {
145 if (state.name == controller.currentState) {
146 currState = &state;
147 break;
148 }
149 }
150
151 if (currState) {
152 controller.currentStateTime += dt * currState->speed;
153
154 // Sync active clip & time in AnimatorComponent from current state
155 if (!currState->isBlendTree) {
156 int clipIdx = -1;
157 if (!currState->clipName.empty()) {
158 for (size_t i = 0; i < animator.animations.size(); ++i) {
159 if (animator.animations[i].name == currState->clipName) {
160 clipIdx = static_cast<int>(i);
161 break;
162 }
163 }
164 }
165 if (clipIdx == -1 && !animator.animations.empty()) {
166 clipIdx = 0;
167 }
168 if (clipIdx != -1) {
169 animator.activeAnimationIndex = clipIdx;
170 auto& clip = animator.animations[clipIdx];
171
172 float effectiveDur = clip.duration;
173 for (const auto& chan : clip.propertyChannels) {
174 if (!chan.keys.empty()) {
175 effectiveDur = std::max(effectiveDur, chan.keys.back().time);
176 }
177 }
178 if (effectiveDur <= 0.0f) effectiveDur = 1.0f;
179 clip.duration = effectiveDur;
180
181 if (currState->isLooping) {
182 animator.currentTime = std::fmod(controller.currentStateTime, effectiveDur);
183 } else {
184 animator.currentTime = std::min(controller.currentStateTime, effectiveDur);
185 }
186 animator.loop = currState->isLooping;
187 }
188 }
189 }
190
191 // Advance crossfade timing if active
192 if (controller.isCrossfading) {
193 const AnimationState* fState = nullptr;
194 for (const auto& state : controller.states) {
195 if (state.name == controller.fromState) {
196 fState = &state;
197 break;
198 }
199 }
200 if (fState) {
201 controller.fromStateTime += dt * fState->speed;
202 }
203
204 controller.crossfadeProgress += dt;
205 if (controller.crossfadeProgress >= controller.crossfadeDuration) {
206 controller.isCrossfading = false;
207 controller.fromState.clear();
208 }
209 }
210
211 // Check transition rules (only if not currently crossfading)
212 if (!controller.isCrossfading) {
213 for (const auto& trans : controller.transitions) {
214 if (trans.fromState == controller.currentState) {
215 bool allConditionsMet = true;
216 for (const auto& cond : trans.conditions) {
217 float paramVal = 0.0f;
218 auto it = controller.parameters.find(cond.parameterName);
219 if (it != controller.parameters.end()) {
220 paramVal = it->second;
221 }
222
223 if (cond.op == ">") {
224 if (!(paramVal > cond.value)) allConditionsMet = false;
225 } else if (cond.op == "<") {
226 if (!(paramVal < cond.value)) allConditionsMet = false;
227 } else if (cond.op == "==") {
228 if (!(std::abs(paramVal - cond.value) < 1e-4f)) allConditionsMet = false;
229 } else {
230 allConditionsMet = false;
231 }
232 }
233
234 bool shouldTransition = false;
235 if (!trans.conditions.empty()) {
236 shouldTransition = allConditionsMet;
237 } else {
238 float clipDur = 0.5f;
239 if (currState) {
240 for (const auto& c : animator.animations) {
241 if (c.name == currState->clipName) {
242 clipDur = c.duration;
243 break;
244 }
245 }
246 }
247 if (clipDur <= 0.0f || controller.currentStateTime >= clipDur) {
248 shouldTransition = true;
249 }
250 }
251
252 if (shouldTransition) {
253 // Trigger transition!
254 controller.fromState = controller.currentState;
255 controller.fromStateTime = controller.currentStateTime;
256 controller.currentState = trans.toState;
257 controller.currentStateTime = 0.0f;
258
259 controller.targetState = trans.toState;
260 controller.crossfadeProgress = 0.0f;
261 controller.crossfadeDuration = trans.crossfadeDuration;
262 controller.isCrossfading = true;
263 break; // only transition once per tick
264 }
265 }
266 }
267 }
268 }
269
270 const AnimationClip* findClip(const AnimatorComponent& animator, const std::string& name) {
271 for (const auto& clip : animator.animations) {
272 if (clip.name == name) return &clip;
273 }
274 return nullptr;
275 }
276
277 void sampleClip(const AnimationClip& clip, float time, const SkeletonComponent& skeleton, std::vector<JointPose>& outPose) {
278 for (const auto& channel : clip.channels) {
279 if (channel.jointIndex < 0 || channel.jointIndex >= static_cast<int>(skeleton.joints.size())) {
280 continue;
281 }
282 auto& joint = skeleton.joints[channel.jointIndex];
283 outPose[channel.jointIndex].translation = interpolateTranslation(channel.translationKeys, time, joint.bindTranslation);
284 outPose[channel.jointIndex].rotation = interpolateRotation(channel.rotationKeys, time, joint.bindRotation);
285 outPose[channel.jointIndex].scale = interpolateScale(channel.scaleKeys, time, joint.bindScale);
286 }
287 }
288
289 void blendPoses(const std::vector<JointPose>& poseA, const std::vector<JointPose>& poseB, float weight, std::vector<JointPose>& outPose) {
290 for (size_t i = 0; i < outPose.size(); ++i) {
291 outPose[i].translation = glm::mix(poseA[i].translation, poseB[i].translation, weight);
292 outPose[i].rotation = glm::slerp(poseA[i].rotation, poseB[i].rotation, weight);
293 outPose[i].scale = glm::mix(poseA[i].scale, poseB[i].scale, weight);
294 }
295 }
296
297 void evaluateStatePose(const AnimationControllerComponent& controller, const AnimationState& state, float stateTime, const AnimatorComponent& animator, const SkeletonComponent& skeleton, std::vector<JointPose>& outPose) {
298 if (state.isBlendTree) {
299 const auto& tree = state.blendTree;
300 if (tree.nodes.empty()) return;
301
302 float paramVal = 0.0f;
303 auto it = controller.parameters.find(tree.parameterName);
304 if (it != controller.parameters.end()) {
305 paramVal = it->second;
306 }
307
308 if (tree.is2D) {
309 float paramX = 0.0f;
310 auto itX = controller.parameters.find(tree.parameterName);
311 if (itX != controller.parameters.end()) {
312 paramX = itX->second;
313 }
314
315 float paramY = 0.0f;
316 auto itY = controller.parameters.find(tree.parameterYName);
317 if (itY != controller.parameters.end()) {
318 paramY = itY->second;
319 }
320
321 glm::vec2 p(paramX, paramY);
322 size_t numNodes = tree.nodes.size();
323 std::vector<float> weights(numNodes, 0.0f);
324 float totalWeight = 0.0f;
325
326 // 2D Freeform Cartesian / Gradient Band Blending algorithm
327 for (size_t i = 0; i < numNodes; ++i) {
328 glm::vec2 pi = tree.nodes[i].threshold2D;
329 float minVal = 1.0f;
330
331 for (size_t j = 0; j < numNodes; ++j) {
332 if (i == j) continue;
333 glm::vec2 pj = tree.nodes[j].threshold2D;
334 glm::vec2 v = pj - pi;
335 float lenSq = glm::dot(v, v);
336 if (lenSq < 1e-5f) continue;
337
338 glm::vec2 u = p - pi;
339 float t = glm::dot(u, v) / lenSq;
340 float val = 1.0f - t;
341 if (val < minVal) {
342 minVal = val;
343 }
344 }
345
346 weights[i] = std::max(0.0f, minVal);
347 totalWeight += weights[i];
348 }
349
350 // Normalize weights and sample/blend poses
351 if (totalWeight > 1e-5f) {
352 for (size_t i = 0; i < numNodes; ++i) {
353 weights[i] /= totalWeight;
354 }
355
356 std::vector<JointPose> blendedPose(skeleton.joints.size());
357 for (size_t j = 0; j < skeleton.joints.size(); ++j) {
358 blendedPose[j] = { skeleton.joints[j].bindTranslation, skeleton.joints[j].bindRotation, skeleton.joints[j].bindScale };
359 }
360
361 float cumulativeWeight = 0.0f;
362 bool firstPoseSet = false;
363
364 for (size_t i = 0; i < numNodes; ++i) {
365 float w = weights[i];
366 if (w < 1e-4f) continue;
367
368 if (const AnimationClip* clip = findClip(animator, tree.nodes[i].clipName)) {
369 std::vector<JointPose> tempPose(skeleton.joints.size());
370 for (size_t j = 0; j < skeleton.joints.size(); ++j) {
371 tempPose[j] = { skeleton.joints[j].bindTranslation, skeleton.joints[j].bindRotation, skeleton.joints[j].bindScale };
372 }
373 sampleClip(*clip, stateTime, skeleton, tempPose);
374
375 if (!firstPoseSet) {
376 blendedPose = tempPose;
377 cumulativeWeight = w;
378 firstPoseSet = true;
379 } else {
380 float blendFactor = w / (cumulativeWeight + w);
381 blendPoses(blendedPose, tempPose, blendFactor, blendedPose);
382 cumulativeWeight += w;
383 }
384 }
385 }
386 outPose = blendedPose;
387 }
388 } else {
389 // Sort nodes by threshold for robust linear 1D interpolation
390 std::vector<BlendNode> sortedNodes = tree.nodes;
391 std::sort(sortedNodes.begin(), sortedNodes.end(), [](const BlendNode& a, const BlendNode& b) {
392 return a.threshold < b.threshold;
393 });
394
395 if (paramVal <= sortedNodes.front().threshold) {
396 if (const AnimationClip* clip = findClip(animator, sortedNodes.front().clipName)) {
397 sampleClip(*clip, stateTime, skeleton, outPose);
398 }
399 } else if (paramVal >= sortedNodes.back().threshold) {
400 if (const AnimationClip* clip = findClip(animator, sortedNodes.back().clipName)) {
401 sampleClip(*clip, stateTime, skeleton, outPose);
402 }
403 } else {
404 for (size_t i = 0; i < sortedNodes.size() - 1; ++i) {
405 if (paramVal >= sortedNodes[i].threshold && paramVal <= sortedNodes[i+1].threshold) {
406 float t = (paramVal - sortedNodes[i].threshold) / (sortedNodes[i+1].threshold - sortedNodes[i].threshold);
407
408 std::vector<JointPose> poseA(skeleton.joints.size());
409 std::vector<JointPose> poseB(skeleton.joints.size());
410 for (size_t j = 0; j < skeleton.joints.size(); ++j) {
411 poseA[j] = { skeleton.joints[j].bindTranslation, skeleton.joints[j].bindRotation, skeleton.joints[j].bindScale };
412 poseB[j] = poseA[j];
413 }
414
415 if (const AnimationClip* clipA = findClip(animator, sortedNodes[i].clipName)) {
416 sampleClip(*clipA, stateTime, skeleton, poseA);
417 }
418 if (const AnimationClip* clipB = findClip(animator, sortedNodes[i+1].clipName)) {
419 sampleClip(*clipB, stateTime, skeleton, poseB);
420 }
421
422 blendPoses(poseA, poseB, t, outPose);
423 break;
424 }
425 }
426 }
427 }
428 } else {
429 if (const AnimationClip* clip = findClip(animator, state.clipName)) {
430 sampleClip(*clip, stateTime, skeleton, outPose);
431 }
432 }
433 }
434
435 int findJointIndex(const SkeletonComponent& skeleton, const std::string& name) {
436 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
437 if (skeleton.joints[i].name == name) {
438 return static_cast<int>(i);
439 }
440 }
441 return -1;
442 }
443
444 glm::quat rotationBetweenVectors(glm::vec3 u, glm::vec3 v) {
445 u = glm::normalize(u);
446 v = glm::normalize(v);
447 float cosTheta = glm::dot(u, v);
448 glm::vec3 rotationAxis;
449
450 if (cosTheta < -1.0f + 1e-6f) {
451 rotationAxis = glm::cross(glm::vec3(0.0f, 0.0f, 1.0f), u);
452 if (glm::dot(rotationAxis, rotationAxis) < 0.01f) {
453 rotationAxis = glm::cross(glm::vec3(1.0f, 0.0f, 0.0f), u);
454 }
455 rotationAxis = glm::normalize(rotationAxis);
456 return glm::angleAxis(glm::radians(180.0f), rotationAxis);
457 }
458
459 rotationAxis = glm::cross(u, v);
460 float s = std::sqrt((1.0f + cosTheta) * 2.0f);
461 float invs = 1.0f / s;
462
463 return glm::quat(
464 s * 0.5f,
465 rotationAxis.x * invs,
466 rotationAxis.y * invs,
467 rotationAxis.z * invs
468 );
469 }
470
471 void solve2BoneIK(SkeletonComponent& skeleton, const IKSolverComponent& ik, std::vector<glm::mat4>& globalTransforms) {
472 int idxA = findJointIndex(skeleton, ik.startJointName);
473 int idxB = findJointIndex(skeleton, ik.middleJointName);
474 int idxC = findJointIndex(skeleton, ik.endJointName);
475
476 if (idxA == -1 || idxB == -1 || idxC == -1) return;
477
478 glm::mat4 origGlobalA = globalTransforms[idxA];
479 glm::mat4 origGlobalB = globalTransforms[idxB];
480 glm::mat4 origGlobalC = globalTransforms[idxC];
481
482 glm::vec3 P_A = glm::vec3(origGlobalA[3]);
483 glm::vec3 P_B = glm::vec3(origGlobalB[3]);
484 glm::vec3 P_C = glm::vec3(origGlobalC[3]);
485 glm::vec3 P_T = ik.targetPosition;
486 glm::vec3 P_P = ik.polePosition;
487
488 float L1 = glm::distance(P_B, P_A);
489 float L2 = glm::distance(P_C, P_B);
490 float D = glm::distance(P_T, P_A);
491
492 if (L1 < 1e-4f || L2 < 1e-4f) return;
493
494 if (D > L1 + L2 - 0.001f) {
495 P_T = P_A + glm::normalize(P_T - P_A) * (L1 + L2 - 0.001f);
496 D = L1 + L2 - 0.001f;
497 }
498 if (D < 0.001f) {
499 P_T = P_A + glm::vec3(0.0f, 0.0f, 0.001f);
500 D = 0.001f;
501 }
502
503 float cosAlpha = (L1 * L1 + D * D - L2 * L2) / (2.0f * L1 * D);
504 cosAlpha = glm::clamp(cosAlpha, -1.0f, 1.0f);
505 float alpha = std::acos(cosAlpha);
506
507 glm::vec3 d_AT = glm::normalize(P_T - P_A);
508 glm::vec3 v_AP = P_P - P_A;
509 glm::vec3 N = glm::cross(d_AT, v_AP);
510 if (glm::dot(N, N) < 1e-6f) {
511 N = glm::cross(d_AT, glm::vec3(0.0f, 1.0f, 0.0f));
512 if (glm::dot(N, N) < 1e-6f) {
513 N = glm::cross(d_AT, glm::vec3(1.0f, 0.0f, 0.0f));
514 }
515 }
516 N = glm::normalize(N);
517 glm::vec3 B_dir = glm::normalize(glm::cross(N, d_AT));
518
519 glm::vec3 P_B_new = P_A + (d_AT * std::cos(alpha) + B_dir * std::sin(alpha)) * L1;
520 glm::vec3 P_C_new = P_T;
521
522 glm::vec3 origDirA = P_B - P_A;
523 glm::vec3 targetDirA = P_B_new - P_A;
524 glm::quat rotA = rotationBetweenVectors(origDirA, targetDirA);
525 glm::mat3 rotPartA = glm::mat3(glm::toMat4(rotA)) * glm::mat3(origGlobalA);
526 glm::mat4 newGlobalA = glm::mat4(rotPartA);
527 newGlobalA[3] = glm::vec4(P_A, 1.0f);
528
529 glm::vec3 origDirB = P_C - P_B;
530 glm::vec3 targetDirB = P_C_new - P_B_new;
531 glm::quat rotB = rotationBetweenVectors(origDirB, targetDirB);
532 glm::mat3 rotPartB = glm::mat3(glm::toMat4(rotB)) * glm::mat3(origGlobalB);
533 glm::mat4 newGlobalB = glm::mat4(rotPartB);
534 newGlobalB[3] = glm::vec4(P_B_new, 1.0f);
535
536 glm::mat4 newGlobalC = origGlobalC;
537 newGlobalC[3] = glm::vec4(P_C_new, 1.0f);
538
539 float w = glm::clamp(ik.targetWeight, 0.0f, 1.0f);
540 globalTransforms[idxA] = origGlobalA * (1.0f - w) + newGlobalA * w;
541 globalTransforms[idxB] = origGlobalB * (1.0f - w) + newGlobalB * w;
542 globalTransforms[idxC] = origGlobalC * (1.0f - w) + newGlobalC * w;
543
544 auto updateLocal = [&](int idx) {
545 int parentIdx = skeleton.joints[idx].parentIndex;
546 if (parentIdx != -1) {
547 skeleton.joints[idx].localTransform = glm::inverse(globalTransforms[parentIdx]) * globalTransforms[idx];
548 } else {
549 skeleton.joints[idx].localTransform = globalTransforms[idx];
550 }
551 };
552
553 updateLocal(idxA);
554 updateLocal(idxB);
555 updateLocal(idxC);
556
557 std::vector<bool> resolved(skeleton.joints.size(), false);
558 resolved[idxA] = true;
559 resolved[idxB] = true;
560 resolved[idxC] = true;
561
562 std::function<void(int)> propagate = [&](int jointIdx) {
563 int parentIdx = skeleton.joints[jointIdx].parentIndex;
564 if (parentIdx != -1 && resolved[parentIdx] && !resolved[jointIdx]) {
565 globalTransforms[jointIdx] = globalTransforms[parentIdx] * skeleton.joints[jointIdx].localTransform;
566 resolved[jointIdx] = true;
567 }
568 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
569 if (skeleton.joints[i].parentIndex == jointIdx) {
570 propagate(static_cast<int>(i));
571 }
572 }
573 };
574
575 propagate(idxA);
576 propagate(idxB);
577 propagate(idxC);
578 }
579
580 void solveFABRIK(SkeletonComponent& skeleton, const IKSolverComponent& ik, std::vector<glm::mat4>& globalTransforms) {
581 if (ik.jointChainNames.size() < 2) return;
582
583 std::vector<int> chainIndices;
584 for (const auto& name : ik.jointChainNames) {
585 int idx = findJointIndex(skeleton, name);
586 if (idx != -1) {
587 chainIndices.push_back(idx);
588 }
589 }
590
591 if (chainIndices.size() < 2) return;
592
593 int n = static_cast<int>(chainIndices.size()) - 1;
594 std::vector<glm::vec3> positions(chainIndices.size());
595 std::vector<float> boneLengths(n);
596 float totalLength = 0.0f;
597
598 for (size_t i = 0; i < chainIndices.size(); ++i) {
599 positions[i] = glm::vec3(globalTransforms[chainIndices[i]][3]);
600 if (i > 0) {
601 boneLengths[i - 1] = glm::distance(positions[i], positions[i - 1]);
602 totalLength += boneLengths[i - 1];
603 }
604 }
605
606 glm::vec3 target = ik.targetPosition;
607 glm::vec3 origin = positions[0];
608
609 float distToTarget = glm::distance(origin, target);
610 if (distToTarget > totalLength) {
611 for (int i = 0; i < n; ++i) {
612 glm::vec3 dir = glm::normalize(target - positions[i]);
613 positions[i + 1] = positions[i] + dir * boneLengths[i];
614 }
615 } else {
616 for (int iter = 0; iter < ik.maxIterations; ++iter) {
617 float err = glm::distance(positions[n], target);
618 if (err < ik.tolerance) break;
619
620 positions[n] = target;
621 for (int i = n - 1; i >= 0; --i) {
622 glm::vec3 dir = glm::normalize(positions[i] - positions[i + 1]);
623 positions[i] = positions[i + 1] + dir * boneLengths[i];
624 }
625
626 positions[0] = origin;
627 for (int i = 0; i < n; ++i) {
628 glm::vec3 dir = glm::normalize(positions[i + 1] - positions[i]);
629 positions[i + 1] = positions[i] + dir * boneLengths[i];
630 }
631 }
632 }
633
634 for (int i = 0; i < n; ++i) {
635 int idxCurrent = chainIndices[i];
636 int idxNext = chainIndices[i + 1];
637
638 glm::mat4 origGlobalCurrent = globalTransforms[idxCurrent];
639 // Compute current position of idxNext by evaluating relative to current idxCurrent transform
640 glm::mat4 currentGlobalNext = origGlobalCurrent * skeleton.joints[idxNext].localTransform;
641
642 glm::vec3 P_current = glm::vec3(origGlobalCurrent[3]);
643 glm::vec3 P_next = glm::vec3(currentGlobalNext[3]);
644
645 glm::vec3 origDir = P_next - P_current;
646 glm::vec3 solvedDir = positions[i + 1] - positions[i];
647
648 if (glm::dot(origDir, origDir) < 1e-6f || glm::dot(solvedDir, solvedDir) < 1e-6f) continue;
649
650 glm::quat rot = rotationBetweenVectors(origDir, solvedDir);
651 float w = glm::clamp(ik.targetWeight, 0.0f, 1.0f);
652 glm::quat blendedRot = glm::slerp(glm::quat(1.0f, 0.0f, 0.0f, 0.0f), rot, w);
653
654 // Rotate the current joint
655 glm::mat3 rotPart = glm::mat3(glm::toMat4(blendedRot)) * glm::mat3(origGlobalCurrent);
656 glm::mat4 newGlobal = glm::mat4(rotPart);
657 newGlobal[3] = glm::vec4(glm::mix(P_current, positions[i], w), 1.0f);
658
659 globalTransforms[idxCurrent] = newGlobal;
660
661 // Update local transform of current joint relative to parent
662 int parentIdx = skeleton.joints[idxCurrent].parentIndex;
663 if (parentIdx != -1) {
664 skeleton.joints[idxCurrent].localTransform = glm::inverse(globalTransforms[parentIdx]) * globalTransforms[idxCurrent];
665 } else {
666 skeleton.joints[idxCurrent].localTransform = globalTransforms[idxCurrent];
667 }
668
669 // Recalculate next joint global transform based on the newly rotated current joint
670 globalTransforms[idxNext] = globalTransforms[idxCurrent] * skeleton.joints[idxNext].localTransform;
671 }
672
673 std::vector<bool> resolved(skeleton.joints.size(), false);
674 for (int idx : chainIndices) {
675 resolved[idx] = true;
676 }
677
678 std::function<void(int)> propagate = [&](int jointIdx) {
679 int parentIdx = skeleton.joints[jointIdx].parentIndex;
680 if (parentIdx != -1 && resolved[parentIdx] && !resolved[jointIdx]) {
681 globalTransforms[jointIdx] = globalTransforms[parentIdx] * skeleton.joints[jointIdx].localTransform;
682 resolved[jointIdx] = true;
683 }
684 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
685 if (skeleton.joints[i].parentIndex == jointIdx) {
686 propagate(static_cast<int>(i));
687 }
688 }
689 };
690
691 for (int idx : chainIndices) {
692 propagate(idx);
693 }
694 }
695
699 void updateEntityAnimation(Entity entity, SkeletonComponent& skeleton, AnimatorComponent& animator, float dt) {
700 if (skeleton.joints.empty()) return;
701
702 // 1. Initialize temporary pose with bind-pose default TRS values
703 std::vector<JointPose> finalPose(skeleton.joints.size());
704 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
705 finalPose[i] = { skeleton.joints[i].bindTranslation, skeleton.joints[i].bindRotation, skeleton.joints[i].bindScale };
706 }
707
708 // 2. Sample poses according to State Machine or fallback to Single Clip Animator
709 if (auto* controller = registry.get<AnimationControllerComponent>(entity)) {
710 if (!controller->currentState.empty()) {
711 // Sample current state
712 const AnimationState* currState = nullptr;
713 for (const auto& state : controller->states) {
714 if (state.name == controller->currentState) {
715 currState = &state;
716 break;
717 }
718 }
719
720 if (currState) {
721 evaluateStatePose(*controller, *currState, controller->currentStateTime, animator, skeleton, finalPose);
722 }
723
724 // Handle crossfading transition
725 if (controller->isCrossfading && !controller->fromState.empty()) {
726 const AnimationState* fState = nullptr;
727 for (const auto& state : controller->states) {
728 if (state.name == controller->fromState) {
729 fState = &state;
730 break;
731 }
732 }
733
734 if (fState) {
735 std::vector<JointPose> fromPose(skeleton.joints.size());
736 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
737 fromPose[i] = { skeleton.joints[i].bindTranslation, skeleton.joints[i].bindRotation, skeleton.joints[i].bindScale };
738 }
739 evaluateStatePose(*controller, *fState, controller->fromStateTime, animator, skeleton, fromPose);
740
741 float weight = glm::clamp(controller->crossfadeProgress / controller->crossfadeDuration, 0.0f, 1.0f);
742 blendPoses(fromPose, finalPose, weight, finalPose);
743 }
744 }
745 }
746 } else {
747 // Fallback to single clip playback
748 AnimationClip* clip = nullptr;
749 if (!animator.animations.empty() &&
750 animator.activeAnimationIndex >= 0 &&
751 animator.activeAnimationIndex < static_cast<int>(animator.animations.size())) {
752 clip = &animator.animations[animator.activeAnimationIndex];
753 }
754
755 if (clip) {
756 if (editorMode.isPlaying) {
757 static int lastPrintedIndex = -999;
758 if (animator.activeAnimationIndex != lastPrintedIndex) {
759 std::cout << "[AnimationSystem] Entity plays animation index: " << animator.activeAnimationIndex
760 << " (Name: " << clip->name << ")" << std::endl;
761 lastPrintedIndex = animator.activeAnimationIndex;
762 }
763 }
764 float speed = editorMode.isPlaying ? (animator.playbackSpeed > 0.0f ? animator.playbackSpeed : 1.0f) : animator.playbackSpeed;
765 animator.currentTime += dt * speed;
766 if (animator.loop) {
767 if (clip->duration > 0.0f) {
768 animator.currentTime = std::fmod(animator.currentTime, clip->duration);
769 } else {
770 animator.currentTime = 0.0f;
771 }
772 } else {
773 animator.currentTime = std::min(animator.currentTime, clip->duration);
774 }
775
776 sampleClip(*clip, animator.currentTime, skeleton, finalPose);
777 }
778 }
779
780 // 3. Write blended pose back to localTransforms
781 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
782 glm::mat4 tMat = glm::translate(glm::mat4(1.0f), finalPose[i].translation);
783 glm::mat4 rMat = glm::toMat4(finalPose[i].rotation);
784 glm::mat4 sMat = glm::scale(glm::mat4(1.0f), finalPose[i].scale);
785 skeleton.joints[i].localTransform = tMat * rMat * sMat;
786 }
787
788 // 4. Resolve Hierarchical Global Transforms (Forward Kinematics)
789 std::vector<glm::mat4> globalTransforms(skeleton.joints.size(), glm::mat4(1.0f));
790 std::vector<bool> resolved(skeleton.joints.size(), false);
791
792 auto resolveJointGlobal = [&](auto& self, int jointIdx) -> glm::mat4 {
793 if (jointIdx == -1) return glm::mat4(1.0f);
794 if (resolved[jointIdx]) return globalTransforms[jointIdx];
795
796 glm::mat4 parentGlobal = self(self, skeleton.joints[jointIdx].parentIndex);
797 globalTransforms[jointIdx] = parentGlobal * skeleton.joints[jointIdx].localTransform;
798 resolved[jointIdx] = true;
799 return globalTransforms[jointIdx];
800 };
801
802 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
803 resolveJointGlobal(resolveJointGlobal, static_cast<int>(i));
804 }
805
806 // 5. Post-FK: Apply IK solver if present and enabled
807 if (auto* ik = registry.get<IKSolverComponent>(entity)) {
808 if (ik->enabled) {
809 if (ik->solverType == IKSolverType::TwoBone) {
810 solve2BoneIK(skeleton, *ik, globalTransforms);
811 } else if (ik->solverType == IKSolverType::FABRIK) {
812 solveFABRIK(skeleton, *ik, globalTransforms);
813 }
814 }
815 }
816
817 // 6. Generate final joint offset matrix palette
818 skeleton.jointMatrices.assign(256, glm::mat4(1.0f));
819 for (size_t i = 0; i < std::min(skeleton.joints.size(), size_t(256)); ++i) {
820 skeleton.jointMatrices[i] = globalTransforms[i] * skeleton.joints[i].inverseBindMatrix;
821 }
822
823 // 7. Upload Joint Matrices Palette to GPU Buffer
824 VkDeviceSize bufferSize = 256 * sizeof(glm::mat4);
825
826 if (!skeleton.gpuBuffer) {
827 skeleton.gpuBuffer = std::make_shared<VulkanBuffer>();
828 skeleton.gpuBuffer->create(
829 renderer.device.getDevice(),
830 renderer.device.getPhysicalDevice(),
831 bufferSize,
832 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
833 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
834 );
835
836 renderer.descriptors.allocateJointsDescriptorSet(
837 skeleton.descriptorSet,
838 skeleton.gpuBuffer->get(),
839 bufferSize
840 );
841 }
842
843 skeleton.gpuBuffer->uploadData(skeleton.jointMatrices.data(), bufferSize);
844 sampleAndApplyProperties(entity, animator);
845 }
846
847 // --- Keyframe Interpolation Helpers ---
848
849 glm::vec3 interpolateTranslation(const std::vector<Keyframe>& keys, float time, const glm::vec3& defaultValue) {
850 if (keys.empty()) return defaultValue;
851 if (keys.size() == 1 || time <= keys.front().time) return keys.front().value;
852 if (time >= keys.back().time) return keys.back().value;
853
854 size_t index = 0;
855 for (size_t i = 0; i < keys.size() - 1; ++i) {
856 if (time >= keys[i].time && time <= keys[i+1].time) {
857 index = i;
858 break;
859 }
860 }
861
862 const auto& k1 = keys[index];
863 const auto& k2 = keys[index+1];
864 float factor = (time - k1.time) / (k2.time - k1.time);
865 return glm::mix(k1.value, k2.value, factor);
866 }
867
868 glm::quat interpolateRotation(const std::vector<KeyframeRot>& keys, float time, const glm::quat& defaultValue) {
869 if (keys.empty()) return defaultValue;
870 if (keys.size() == 1 || time <= keys.front().time) return keys.front().value;
871 if (time >= keys.back().time) return keys.back().value;
872
873 size_t index = 0;
874 for (size_t i = 0; i < keys.size() - 1; ++i) {
875 if (time >= keys[i].time && time <= keys[i+1].time) {
876 index = i;
877 break;
878 }
879 }
880
881 const auto& k1 = keys[index];
882 const auto& k2 = keys[index+1];
883 float factor = (time - k1.time) / (k2.time - k1.time);
884 return glm::slerp(k1.value, k2.value, factor);
885 }
886
887 glm::vec3 interpolateScale(const std::vector<Keyframe>& keys, float time, const glm::vec3& defaultValue) {
888 if (keys.empty()) return defaultValue;
889 if (keys.size() == 1 || time <= keys.front().time) return keys.front().value;
890 if (time >= keys.back().time) return keys.back().value;
891
892 size_t index = 0;
893 for (size_t i = 0; i < keys.size() - 1; ++i) {
894 if (time >= keys[i].time && time <= keys[i+1].time) {
895 index = i;
896 break;
897 }
898 }
899
900 const auto& k1 = keys[index];
901 const auto& k2 = keys[index+1];
902 float factor = (time - k1.time) / (k2.time - k1.time);
903 return glm::mix(k1.value, k2.value, factor);
904 }
905
906 glm::vec4 interpolateProperty(const std::vector<PropertyKeyframe>& keys, float time, const glm::vec4& defaultValue) {
907 if (keys.empty()) return defaultValue;
908 if (keys.size() == 1 || time <= keys.front().time) return keys.front().value;
909 if (time >= keys.back().time) return keys.back().value;
910
911 size_t index = 0;
912 for (size_t i = 0; i < keys.size() - 1; ++i) {
913 if (time >= keys[i].time && time <= keys[i+1].time) {
914 index = i;
915 break;
916 }
917 }
918
919 const auto& k1 = keys[index];
920 const auto& k2 = keys[index+1];
921 float factor = (time - k1.time) / (k2.time - k1.time);
922 return glm::mix(k1.value, k2.value, factor);
923 }
924
925 std::string sampleStringProperty(const std::vector<PropertyKeyframe>& keys, float time) {
926 if (keys.empty()) return "";
927 if (time <= keys.front().time) return keys.front().stringValue;
928 if (time >= keys.back().time) return keys.back().stringValue;
929 for (size_t i = 0; i < keys.size() - 1; ++i) {
930 if (time >= keys[i].time && time < keys[i + 1].time) {
931 return keys[i].stringValue;
932 }
933 }
934 return keys.back().stringValue;
935 }
936
938 AnimationClip* clip = nullptr;
939 if (!animator.animations.empty()) {
940 if (animator.activeAnimationIndex >= 0 && animator.activeAnimationIndex < static_cast<int>(animator.animations.size())) {
941 clip = &animator.animations[animator.activeAnimationIndex];
942 } else {
943 animator.activeAnimationIndex = 0;
944 clip = &animator.animations[0];
945 }
946 }
947
948 if (!clip || clip->propertyChannels.empty()) return;
949
950 // Helper to strip spaces/special chars/Component suffix for flexible matching
951 auto normalizeName = [](const std::string& s) {
952 std::string res;
953 for (char c : s) {
954 if (c != ' ' && c != '_' && c != '&' && c != '/') {
955 res += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
956 }
957 }
958 if (res.size() > 9 && res.substr(res.size() - 9) == "component") {
959 res = res.substr(0, res.size() - 9);
960 }
961 return res;
962 };
963
964 // Collect target entity and all child entities in hierarchy
965 std::vector<Entity> targetEntities;
966 targetEntities.push_back(entity);
967
968 for (size_t readIdx = 0; readIdx < targetEntities.size(); ++readIdx) {
969 Entity curr = targetEntities[readIdx];
970 for (auto [childEntity, hierarchy] : registry.view<HierarchyComponent>()) {
971 if (hierarchy.parent.getId() == curr.getId()) {
972 targetEntities.push_back(childEntity);
973 }
974 }
975 }
976
978
979 for (const auto& channel : clip->propertyChannels) {
980 if (channel.keys.empty()) continue;
981
982 std::string normChanComp = normalizeName(channel.componentName);
983 std::string normChanField = normalizeName(channel.fieldName);
984
985 // Direct Type-Safe Access for SpriteRenderer
986 bool handledDirectly = false;
987 for (Entity targetEntity : targetEntities) {
988 if (auto* spr = registry.get<Engine::SpriteRenderer>(targetEntity)) {
989 bool isTex = (normChanField.find("texture") != std::string::npos || normChanField.find("image") != std::string::npos || normChanField.find("path") != std::string::npos);
990 bool isCol = (normChanField.find("color") != std::string::npos);
991 bool isFlipX = (normChanField.find("flipx") != std::string::npos);
992 bool isFlipY = (normChanField.find("flipy") != std::string::npos);
993 bool isSort = (normChanField.find("sort") != std::string::npos || normChanField.find("order") != std::string::npos);
994
995 if (isTex) {
996 std::string strVal = sampleStringProperty(channel.keys, animator.currentTime);
997 spr->texturePath = strVal;
998 spr->_dirty = true;
999 if (auto* mat = registry.get<Material>(targetEntity)) {
1000 mat->texturePath = strVal;
1001 renderer.resourceManager->updateMaterialDescriptorSet(*mat, renderer);
1002 spr->_loadedTexturePath = strVal;
1003 }
1004 handledDirectly = true;
1005 } else if (isCol) {
1006 glm::vec4 val = interpolateProperty(channel.keys, animator.currentTime, spr->color);
1007 spr->color = val;
1008 if (auto* mat = registry.get<Material>(targetEntity)) {
1009 mat->color = spr->color;
1010 }
1011 handledDirectly = true;
1012 } else if (isFlipX) {
1013 glm::vec4 val = interpolateProperty(channel.keys, animator.currentTime, glm::vec4(spr->flipX ? 1.0f : 0.0f));
1014 spr->flipX = (val.x > 0.5f);
1015 if (auto* mat = registry.get<Material>(targetEntity)) {
1016 mat->roughness = spr->flipX ? -1.0f : 1.0f;
1017 }
1018 handledDirectly = true;
1019 } else if (isFlipY) {
1020 glm::vec4 val = interpolateProperty(channel.keys, animator.currentTime, glm::vec4(spr->flipY ? 1.0f : 0.0f));
1021 spr->flipY = (val.x > 0.5f);
1022 if (auto* mat = registry.get<Material>(targetEntity)) {
1023 mat->metallic = spr->flipY ? -1.0f : 1.0f;
1024 }
1025 handledDirectly = true;
1026 } else if (isSort) {
1027 glm::vec4 val = interpolateProperty(channel.keys, animator.currentTime, glm::vec4(static_cast<float>(spr->sortOrder)));
1028 spr->sortOrder = static_cast<int>(val.x);
1029 if (auto* t = registry.get<Transform>(targetEntity)) {
1030 t->position.z = spr->sortOrder * 0.0001f;
1031 }
1032 handledDirectly = true;
1033 }
1034 }
1035 }
1036 if (handledDirectly) continue;
1037
1038 const Engine::ComponentReflection* targetRefl = nullptr;
1039 for (const auto& refl : reflReg.getReflections()) {
1040 if (refl.name == channel.componentName ||
1041 normalizeName(refl.name) == normChanComp ||
1042 normalizeName(refl.displayName) == normChanComp) {
1043 targetRefl = &refl;
1044 break;
1045 }
1046 }
1047
1048 if (!targetRefl) continue;
1049
1050 for (Entity targetEntity : targetEntities) {
1051 if (!targetRefl->has(registry, targetEntity)) continue;
1052
1053 void* compPtr = targetRefl->get(registry, targetEntity);
1054 if (!compPtr) continue;
1055
1056 auto stripPrefix = [](const std::string& s) {
1057 if (s.rfind("spr", 0) == 0 && s.size() > 3) return s.substr(3);
1058 if (s.rfind("m_", 0) == 0 && s.size() > 2) return s.substr(2);
1059 if (s.rfind("s_", 0) == 0 && s.size() > 2) return s.substr(2);
1060 return s;
1061 };
1062 std::string sfn = stripPrefix(normChanField);
1063
1064 const Engine::ComponentField* targetField = nullptr;
1065 for (const auto& f : targetRefl->fields) {
1066 std::string fn = normalizeName(f.name);
1067 std::string sfn2 = stripPrefix(fn);
1068 if (f.name == channel.fieldName || fn == normChanField || sfn == sfn2 ||
1069 (sfn.find("texture") != std::string::npos && sfn2.find("texture") != std::string::npos) ||
1070 (sfn.find("image") != std::string::npos && sfn2.find("texture") != std::string::npos) ||
1071 (sfn.find("texture") != std::string::npos && sfn2.find("image") != std::string::npos)) {
1072 targetField = &f;
1073 break;
1074 }
1075 }
1076
1077 if (!targetField) continue;
1078
1079 char* fieldPtr = static_cast<char*>(compPtr) + targetField->offset;
1080
1081 glm::vec4 val = interpolateProperty(channel.keys, animator.currentTime, glm::vec4(0.0f));
1082
1083 if (channel.type == Engine::FieldType::Float) {
1084 *reinterpret_cast<float*>(fieldPtr) = val.x;
1085 } else if (channel.type == Engine::FieldType::Int) {
1086 *reinterpret_cast<int*>(fieldPtr) = static_cast<int>(val.x);
1087 } else if (channel.type == Engine::FieldType::Bool) {
1088 *reinterpret_cast<bool*>(fieldPtr) = (val.x > 0.5f);
1089 } else if (channel.type == Engine::FieldType::Vec2) {
1090 *reinterpret_cast<glm::vec2*>(fieldPtr) = glm::vec2(val.x, val.y);
1091 } else if (channel.type == Engine::FieldType::Vec3) {
1092 *reinterpret_cast<glm::vec3*>(fieldPtr) = glm::vec3(val.x, val.y, val.z);
1093 } else if (channel.type == Engine::FieldType::Vec4) {
1094 *reinterpret_cast<glm::vec4*>(fieldPtr) = val;
1095 } else if (channel.type == Engine::FieldType::String) {
1096 std::string strVal = sampleStringProperty(channel.keys, animator.currentTime);
1097 *reinterpret_cast<std::string*>(fieldPtr) = strVal;
1098 }
1099
1100 if (auto* spr = registry.get<Engine::SpriteRenderer>(targetEntity)) {
1101 spr->_dirty = true;
1102 if (auto* mat = registry.get<Material>(targetEntity)) {
1103 mat->texturePath = spr->texturePath;
1104 renderer.resourceManager->updateMaterialDescriptorSet(*mat, renderer);
1105 spr->_loadedTexturePath = spr->texturePath;
1106 }
1107 }
1108 }
1109 }
1110 }
1111
1112 void updateGenericAnimation(Entity entity, AnimatorComponent& animator, float dt) {
1113 AnimationClip* clip = nullptr;
1114 if (!animator.animations.empty()) {
1115 if (animator.activeAnimationIndex >= 0 && animator.activeAnimationIndex < static_cast<int>(animator.animations.size())) {
1116 clip = &animator.animations[animator.activeAnimationIndex];
1117 } else {
1118 animator.activeAnimationIndex = 0;
1119 clip = &animator.animations[0];
1120 }
1121 }
1122
1123 if (clip) {
1124 float effectiveDur = clip->duration;
1125 for (const auto& chan : clip->propertyChannels) {
1126 if (!chan.keys.empty()) {
1127 effectiveDur = std::max(effectiveDur, chan.keys.back().time);
1128 }
1129 }
1130 if (effectiveDur <= 0.0f) effectiveDur = 1.0f;
1131 clip->duration = effectiveDur;
1132
1133 // If there is no AnimationControllerComponent, drive animator time directly
1134 if (!registry.has<AnimationControllerComponent>(entity)) {
1135 float speed = editorMode.isPlaying ? (animator.playbackSpeed > 0.0f ? animator.playbackSpeed : 1.0f) : animator.playbackSpeed;
1136 animator.currentTime += dt * speed;
1137 if (animator.loop) {
1138 animator.currentTime = std::fmod(animator.currentTime, effectiveDur);
1139 } else {
1140 animator.currentTime = std::min(animator.currentTime, effectiveDur);
1141 }
1142 }
1143 }
1144
1145 sampleAndApplyProperties(entity, animator);
1146 }
1147
1151 std::vector<Entity> controllerEntities;
1152 std::vector<Entity> animatedEntities;
1153 std::vector<Entity> genericAnimatedEntities;
1154 };
1155
@ TwoBone
Definition IKSolver.hpp:11
@ FABRIK
Definition IKSolver.hpp:12
void updateGenericAnimation(Entity entity, AnimatorComponent &animator, float dt)
Definition AnimationSystem.hpp:1112
int findJointIndex(const SkeletonComponent &skeleton, const std::string &name)
Definition AnimationSystem.hpp:435
void sampleAndApplyProperties(Entity entity, AnimatorComponent &animator)
Definition AnimationSystem.hpp:937
void updateController(AnimationControllerComponent &controller, AnimatorComponent &animator, float dt)
Updates high-level state machine progression and checks transitions.
Definition AnimationSystem.hpp:134
glm::vec3 interpolateTranslation(const std::vector< Keyframe > &keys, float time, const glm::vec3 &defaultValue)
Definition AnimationSystem.hpp:849
void updateEntityAnimation(Entity entity, SkeletonComponent &skeleton, AnimatorComponent &animator, float dt)
Updates the animation timing and calculates local/global joint matrices for an entity.
Definition AnimationSystem.hpp:699
void solve2BoneIK(SkeletonComponent &skeleton, const IKSolverComponent &ik, std::vector< glm::mat4 > &globalTransforms)
Definition AnimationSystem.hpp:471
void solveFABRIK(SkeletonComponent &skeleton, const IKSolverComponent &ik, std::vector< glm::mat4 > &globalTransforms)
Definition AnimationSystem.hpp:580
glm::quat rotationBetweenVectors(glm::vec3 u, glm::vec3 v)
Definition AnimationSystem.hpp:444
std::string sampleStringProperty(const std::vector< PropertyKeyframe > &keys, float time)
Definition AnimationSystem.hpp:925
glm::quat interpolateRotation(const std::vector< KeyframeRot > &keys, float time, const glm::quat &defaultValue)
Definition AnimationSystem.hpp:868
void update(float dt) override
Updates skeletal poses for all animated entities.
Definition AnimationSystem.hpp:47
const AnimationClip * findClip(const AnimatorComponent &animator, const std::string &name)
Definition AnimationSystem.hpp:270
glm::vec3 interpolateScale(const std::vector< Keyframe > &keys, float time, const glm::vec3 &defaultValue)
Definition AnimationSystem.hpp:887
std::vector< Entity > animatedEntities
Definition AnimationSystem.hpp:1152
void sampleClip(const AnimationClip &clip, float time, const SkeletonComponent &skeleton, std::vector< JointPose > &outPose)
Definition AnimationSystem.hpp:277
EditorModeState & editorMode
Definition AnimationSystem.hpp:1150
std::vector< Entity > controllerEntities
Definition AnimationSystem.hpp:1151
void evaluateStatePose(const AnimationControllerComponent &controller, const AnimationState &state, float stateTime, const AnimatorComponent &animator, const SkeletonComponent &skeleton, std::vector< JointPose > &outPose)
Definition AnimationSystem.hpp:297
AnimationSystem(Registry &reg, VulkanRenderer &renderer, EditorModeState &editorMode)
Definition AnimationSystem.hpp:30
std::vector< Entity > genericAnimatedEntities
Definition AnimationSystem.hpp:1153
void blendPoses(const std::vector< JointPose > &poseA, const std::vector< JointPose > &poseB, float weight, std::vector< JointPose > &outPose)
Definition AnimationSystem.hpp:289
Registry & registry
Definition AnimationSystem.hpp:1148
glm::vec4 interpolateProperty(const std::vector< PropertyKeyframe > &keys, float time, const glm::vec4 &defaultValue)
Definition AnimationSystem.hpp:906
VulkanRenderer & renderer
Definition AnimationSystem.hpp:1149
static ComponentReflectionRegistry & getInstance()
Definition ComponentReflection.cpp:6
static JobSystem & getInstance()
Get the singleton instance.
Definition JobSystem.hpp:23
void parallelFor(int count, std::function< void(int)> func)
Splits a total loop count into chunks and evaluates them in parallel.
Definition JobSystem.cpp:143
Lightweight identifier representing a game object in the Entity Component System.
Definition Entity.hpp:11
static constexpr IdType INVALID_ENTITY
Constant representing a null or invalid entity.
Definition Entity.hpp:16
IdType getId() const
Retrieve the raw identifier of the entity.
Definition Entity.hpp:32
Coordinates entities and components, providing creation, removal, lookup, and views.
Definition Registry.hpp:30
auto view()
Generates a filtered view of entities containing the requested components.
Definition Registry.hpp:279
Base class for ECS systems that process sets of entities.
Definition System.hpp:12
Manages core Vulkan pipeline states, device interaction, frames, buffers, and command submissions.
Definition VulkanRenderer.hpp:127
@ Vec3
Definition ComponentReflection.hpp:20
@ Int
Definition ComponentReflection.hpp:18
@ Float
Definition ComponentReflection.hpp:17
@ String
Definition ComponentReflection.hpp:23
@ Bool
Definition ComponentReflection.hpp:19
@ Vec4
Definition ComponentReflection.hpp:25
@ Vec2
Definition ComponentReflection.hpp:24
Collection of channels representing a single skeletal animation state.
Definition Animator.hpp:68
std::vector< AnimationChannel > channels
Bone channels mapping keyframe states.
Definition Animator.hpp:74
std::string name
Name of the clip (e.g. "Walk", "Run").
Definition Animator.hpp:70
float duration
Total duration of the animation in seconds.
Definition Animator.hpp:72
std::vector< PropertyChannel > propertyChannels
Reflected component field channels.
Definition Animator.hpp:76
Component that manages parameters, state machines, transitions, and blending.
Definition AnimationController.hpp:67
std::string fromState
Definition AnimationController.hpp:78
std::string currentState
Definition AnimationController.hpp:71
std::unordered_map< std::string, float > parameters
Definition AnimationController.hpp:75
float currentStateTime
Definition AnimationController.hpp:80
float crossfadeDuration
Definition AnimationController.hpp:83
float fromStateTime
Definition AnimationController.hpp:81
std::string targetState
Definition AnimationController.hpp:79
std::vector< AnimationState > states
Definition AnimationController.hpp:68
std::vector< AnimationTransition > transitions
Definition AnimationController.hpp:69
float crossfadeProgress
Definition AnimationController.hpp:82
bool isCrossfading
Definition AnimationController.hpp:84
Represents a state in the animation state machine, referencing a clip or a blend tree.
Definition AnimationController.hpp:32
BlendTree blendTree
Definition AnimationController.hpp:35
bool isBlendTree
Definition AnimationController.hpp:36
bool isLooping
Definition AnimationController.hpp:37
float speed
Definition AnimationController.hpp:38
std::string clipName
Definition AnimationController.hpp:34
Updates skeletal poses for all animated entities.
Definition AnimationSystem.hpp:37
glm::vec3 scale
Definition AnimationSystem.hpp:40
glm::quat rotation
Definition AnimationSystem.hpp:39
glm::vec3 translation
Definition AnimationSystem.hpp:38
Animator controller managing active clips and tracking playback timing.
Definition Animator.hpp:84
float currentTime
Current playback time offset in seconds.
Definition Animator.hpp:90
float playbackSpeed
Definition Animator.hpp:92
bool loop
Definition Animator.hpp:94
int activeAnimationIndex
Index of the active clip in playback.
Definition Animator.hpp:88
std::vector< AnimationClip > animations
List of all clips loaded from the model asset.
Definition Animator.hpp:86
Represents a single animation clip in a blend tree with its target threshold value.
Definition AnimationController.hpp:11
Struct keeping track of active editor states (e.g. fly mode vs editor UI interaction).
Definition EditorModeState.hpp:7
Reflection metadata for a single field inside a component.
Definition ComponentReflection.hpp:33
size_t offset
Definition ComponentReflection.hpp:36
Reflection metadata and ECS callbacks for a component.
Definition ComponentReflection.hpp:48
std::vector< ComponentField > fields
Definition ComponentReflection.hpp:56
std::function< void *(Registry &, Entity)> get
Definition ComponentReflection.hpp:62
std::function< bool(Registry &, Entity)> has
Definition ComponentReflection.hpp:60
Component that renders a textured 2D quad (sprite) on an entity.
Definition SpriteRenderer.hpp:24
Represents a parent-child relationship between ECS entities.
Definition Hierarchy.hpp:8
Specifies target joint chains and goal targets for analytical 2-Bone or iterative FABRIK IK.
Definition IKSolver.hpp:20
int maxIterations
Definition IKSolver.hpp:34
float tolerance
Definition IKSolver.hpp:36
std::string endJointName
Definition IKSolver.hpp:29
float targetWeight
Definition IKSolver.hpp:44
glm::vec3 polePosition
Definition IKSolver.hpp:41
glm::vec3 targetPosition
Definition IKSolver.hpp:39
std::vector< std::string > jointChainNames
Definition IKSolver.hpp:32
std::string middleJointName
Definition IKSolver.hpp:27
std::string startJointName
Definition IKSolver.hpp:25
Represents a material component defining rendering properties.
Definition Material.hpp:17
Component managing the list of joints and generating the offset matrices palette.
Definition Skeleton.hpp:37
std::shared_ptr< VulkanBuffer > gpuBuffer
Definition Skeleton.hpp:44
std::vector< Joint > joints
List of joints forming the skeleton hierarchy.
Definition Skeleton.hpp:40
VkDescriptorSet descriptorSet
Definition Skeleton.hpp:45
std::vector< glm::mat4 > jointMatrices
Calculated final joint offsets list uploaded to VRAM descriptors.
Definition Skeleton.hpp:42
Represents the position, rotation, and scale of an entity in 3D space.
Definition Transform.hpp:127
const char * name
Definition ufbx.cpp:9020
double scale
Definition ufbx.cpp:26002
double time
Definition ufbx.cpp:26005
static ufbxi_noinline void weight
Definition ufbx.cpp:25700
static ufbxi_noinline ufbxi_aa_node index
Definition ufbx.cpp:4444