Debian Codegraph @

scene/animation/animation_mixer.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* animation_mixer.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "animation_mixer.h"
32 #include "animation_mixer.compat.inc"
33
34 #include "core/config/engine.h"
35 #include "core/config/project_settings.h"
36 #include "core/string/string_name.h"
37 #include "scene/2d/audio_stream_player_2d.h"
38 #include "scene/animation/animation_player.h"
39 #include "scene/audio/audio_stream_player.h"
40 #include "scene/resources/animation.h"
41 #include "servers/audio/audio_server.h"
42 #include "servers/audio/audio_stream.h"
43
44 #ifndef _3D_DISABLED
45 #include "scene/3d/audio_stream_player_3d.h"
46 #include "scene/3d/mesh_instance_3d.h"
47 #include "scene/3d/node_3d.h"
48 #include "scene/3d/skeleton_3d.h"
49 #endif // _3D_DISABLED
50
51 #ifdef TOOLS_ENABLED
52 #include "editor/editor_undo_redo_manager.h"
53 #endif // TOOLS_ENABLED
54
55 bool AnimationMixer::_set(const StringName &p_name, const Variant &p_value) {
56 String name = p_name;
57
58 #ifndef DISABLE_DEPRECATED
59 if (name.begins_with("anims/")) {
60 // Backwards compatibility with 3.x, add them to "default" library.
61 String which = name.get_slicec('/', 1);
62
63 Ref<Animation> anim = p_value;
64 Ref<AnimationLibrary> al;
65 if (!has_animation_library(StringName())) {
66 al.instantiate();
67 add_animation_library(StringName(), al);
68 } else {
69 al = get_animation_library(StringName());
70 }
71 al->add_animation(which, anim);
72 } else if (name == "libraries") {
73 Dictionary d = p_value;
74 while (animation_libraries.size()) {
75 remove_animation_library(animation_libraries[0].name);
76 }
77 for (const KeyValue<Variant, Variant> &kv : d) {
78 Ref<AnimationLibrary> lib = kv.value;
79 add_animation_library(kv.key, lib);
80 }
81 emit_signal(SNAME("animation_libraries_updated"));
82 } else if (name.begins_with("libraries/")) {
83 String which = name.get_slicec('/', 1);
84 if (has_animation_library(which)) {
85 remove_animation_library(which);
86 }
87 add_animation_library(which, p_value);
88 emit_signal(SNAME("animation_libraries_updated"));
89 } else {
90 return false;
91 }
92 #else
93 if (name.begins_with("libraries/")) {
94 String which = name.get_slicec('/', 1);
95 if (has_animation_library(which)) {
96 remove_animation_library(which);
97 }
98 add_animation_library(which, p_value);
99 emit_signal(SNAME("animation_libraries_updated"));
100 } else {
101 return false;
102 }
103 #endif // DISABLE_DEPRECATED
104
105 return true;
106 }
107
108 bool AnimationMixer::_get(const StringName &p_name, Variant &r_ret) const {
109 String name = p_name;
110
111 if (name.begins_with("libraries/")) {
112 String which = name.get_slicec('/', 1);
113 if (has_animation_library(which)) {
114 r_ret = get_animation_library(which);
115 } else {
116 return false;
117 }
118 } else {
119 return false;
120 }
121
122 return true;
123 }
124
125 uint32_t AnimationMixer::_get_libraries_property_usage() const {
126 return PROPERTY_USAGE_STORAGE;
127 }
128
129 void AnimationMixer::_get_property_list(List<PropertyInfo> *p_list) const {
130 for (uint32_t i = 0; i < animation_libraries.size(); i++) {
131 const String path = vformat("libraries/%s", animation_libraries[i].name);
132 p_list->push_back(PropertyInfo(Variant::OBJECT, path, PROPERTY_HINT_RESOURCE_TYPE, "AnimationLibrary", _get_libraries_property_usage()));
133 }
134 }
135
136 void AnimationMixer::_validate_property(PropertyInfo &p_property) const {
137 #ifdef TOOLS_ENABLED // `editing` is surrounded by TOOLS_ENABLED so this should also be.
138 if (Engine::get_singleton()->is_editor_hint() && editing && (p_property.name == "active" || p_property.name == "deterministic" || p_property.name == "root_motion_track")) {
139 p_property.usage |= PROPERTY_USAGE_READ_ONLY;
140 }
141 #endif // TOOLS_ENABLED
142 if (root_motion_track.is_empty() && p_property.name == "root_motion_local") {
143 p_property.usage = PROPERTY_USAGE_NONE;
144 }
145 }
146
147 /* -------------------------------------------- */
148 /* -- Data lists ------------------------------ */
149 /* -------------------------------------------- */
150
151 void AnimationMixer::_animation_set_cache_update() {
152 // Relatively fast function to update all animations.
153 animation_set_update_pass++;
154 bool clear_cache_needed = false;
155
156 // Update changed and add otherwise.
157 for (const AnimationLibraryData &lib : animation_libraries) {
158 for (const KeyValue<StringName, Ref<Animation>> &K : lib.library->animations) {
159 StringName key = lib.name == StringName() ? K.key : StringName(String(lib.name) + "/" + String(K.key));
160 if (!animation_set.has(key)) {
161 AnimationData ad;
162 ad.animation = K.value;
163 ad.animation_library = lib.name;
164 ad.name = key;
165 ad.last_update = animation_set_update_pass;
166 animation_set.insert(ad.name, ad);
167 cache_valid = false; // No need to delete the cache, but it must be updated to add track caches.
168 } else {
169 AnimationData &ad = animation_set[key];
170 if (ad.last_update != animation_set_update_pass) {
171 // Was not updated, update. If the animation is duplicated, the second one will be ignored.
172 if (ad.animation != K.value || ad.animation_library != lib.name) {
173 // Animation changed, update and clear caches.
174 clear_cache_needed = true;
175 ad.animation = K.value;
176 ad.animation_library = lib.name;
177 }
178
179 ad.last_update = animation_set_update_pass;
180 }
181 }
182 }
183 }
184
185 // Check removed.
186 List<StringName> to_erase;
187 for (const KeyValue<StringName, AnimationData> &E : animation_set) {
188 if (E.value.last_update != animation_set_update_pass) {
189 // Was not updated, must be erased.
190 to_erase.push_back(E.key);
191 clear_cache_needed = true;
192 }
193 }
194
195 while (to_erase.size()) {
196 animation_set.erase(to_erase.front()->get());
197 to_erase.pop_front();
198 }
199
200 if (clear_cache_needed) {
201 // If something was modified or removed, caches need to be cleared.
202 _clear_caches();
203 }
204
205 emit_signal(SNAME("animation_list_changed"));
206 }
207
208 void AnimationMixer::_animation_added(const StringName &p_name, const StringName &p_library) {
209 _animation_set_cache_update();
210 }
211
212 void AnimationMixer::_animation_removed(const StringName &p_name, const StringName &p_library) {
213 StringName name = p_library == StringName() ? p_name : StringName(String(p_library) + "/" + String(p_name));
214
215 if (!animation_set.has(name)) {
216 return; // No need to update because not the one from the library being used.
217 }
218
219 _animation_set_cache_update();
220
221 _remove_animation(name);
222 }
223
224 void AnimationMixer::_animation_renamed(const StringName &p_name, const StringName &p_to_name, const StringName &p_library) {
225 StringName from_name = p_library == StringName() ? p_name : StringName(String(p_library) + "/" + String(p_name));
226 StringName to_name = p_library == StringName() ? p_to_name : StringName(String(p_library) + "/" + String(p_to_name));
227
228 if (!animation_set.has(from_name)) {
229 return; // No need to update because not the one from the library being used.
230 }
231 _animation_set_cache_update();
232
233 _rename_animation(from_name, to_name);
234 }
235
236 void AnimationMixer::_animation_changed(const StringName &p_name) {
237 _clear_caches();
238 }
239
240 void AnimationMixer::_set_active(bool p_active) {
241 //
242 }
243
244 void AnimationMixer::_remove_animation(const StringName &p_name) {
245 //
246 }
247
248 void AnimationMixer::_rename_animation(const StringName &p_from_name, const StringName &p_to_name) {
249 //
250 }
251
252 TypedArray<StringName> AnimationMixer::_get_animation_library_list() const {
253 TypedArray<StringName> ret;
254 for (const AnimationLibraryData &lib : animation_libraries) {
255 ret.push_back(lib.name);
256 }
257 return ret;
258 }
259
260 void AnimationMixer::get_animation_library_list(List<StringName> *p_libraries) const {
261 for (const AnimationLibraryData &lib : animation_libraries) {
262 p_libraries->push_back(lib.name);
263 }
264 }
265
266 Ref<AnimationLibrary> AnimationMixer::get_animation_library(const StringName &p_name) const {
267 for (const AnimationLibraryData &lib : animation_libraries) {
268 if (lib.name == p_name) {
269 return lib.library;
270 }
271 }
272 ERR_FAIL_V(Ref<AnimationLibrary>());
273 }
274
275 bool AnimationMixer::has_animation_library(const StringName &p_name) const {
276 for (const AnimationLibraryData &lib : animation_libraries) {
277 if (lib.name == p_name) {
278 return true;
279 }
280 }
281
282 return false;
283 }
284
285 StringName AnimationMixer::get_animation_library_name(const Ref<AnimationLibrary> &p_animation_library) const {
286 ERR_FAIL_COND_V(p_animation_library.is_null(), StringName());
287 for (const AnimationLibraryData &lib : animation_libraries) {
288 if (lib.library == p_animation_library) {
289 return lib.name;
290 }
291 }
292 return StringName();
293 }
294
295 StringName AnimationMixer::find_animation_library(const Ref<Animation> &p_animation) const {
296 for (const KeyValue<StringName, AnimationData> &E : animation_set) {
297 if (E.value.animation == p_animation) {
298 return E.value.animation_library;
299 }
300 }
301 return StringName();
302 }
303
304 Error AnimationMixer::add_animation_library(const StringName &p_name, const Ref<AnimationLibrary> &p_animation_library) {
305 ERR_FAIL_COND_V(p_animation_library.is_null(), ERR_INVALID_PARAMETER);
306 #ifdef DEBUG_ENABLED
307 ERR_FAIL_COND_V_MSG(String(p_name).contains_char('/') || String(p_name).contains_char(':') || String(p_name).contains_char(',') || String(p_name).contains_char('['), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + ".");
308 #endif
309
310 int insert_pos = 0;
311
312 for (const AnimationLibraryData &lib : animation_libraries) {
313 ERR_FAIL_COND_V_MSG(lib.name == p_name, ERR_ALREADY_EXISTS, "Can't add animation library twice with name: " + String(p_name));
314 ERR_FAIL_COND_V_MSG(lib.library == p_animation_library, ERR_ALREADY_EXISTS, "Can't add animation library twice (adding as '" + p_name.operator String() + "', exists as '" + lib.name.operator String() + "'.");
315
316 if (lib.name.operator String() >= p_name.operator String()) {
317 break;
318 }
319
320 insert_pos++;
321 }
322
323 AnimationLibraryData ald;
324 ald.name = p_name;
325 ald.library = p_animation_library;
326
327 animation_libraries.insert(insert_pos, ald);
328
329 ald.library->connect(SNAME("animation_added"), callable_mp(this, &AnimationMixer::_animation_added).bind(p_name));
330 ald.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationMixer::_animation_removed).bind(p_name));
331 ald.library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationMixer::_animation_renamed).bind(p_name));
332 ald.library->connect(SceneStringName(animation_changed), callable_mp(this, &AnimationMixer::_animation_changed));
333
334 _animation_set_cache_update();
335
336 notify_property_list_changed();
337
338 return OK;
339 }
340
341 void AnimationMixer::remove_animation_library(const StringName &p_name) {
342 int at_pos = -1;
343
344 for (uint32_t i = 0; i < animation_libraries.size(); i++) {
345 if (animation_libraries[i].name == p_name) {
346 at_pos = i;
347 break;
348 }
349 }
350
351 ERR_FAIL_COND(at_pos == -1);
352
353 animation_libraries[at_pos].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationMixer::_animation_added));
354 animation_libraries[at_pos].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationMixer::_animation_removed));
355 animation_libraries[at_pos].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationMixer::_animation_renamed));
356 animation_libraries[at_pos].library->disconnect(SceneStringName(animation_changed), callable_mp(this, &AnimationMixer::_animation_changed));
357
358 animation_libraries.remove_at(at_pos);
359 _animation_set_cache_update();
360
361 notify_property_list_changed();
362 }
363
364 void AnimationMixer::rename_animation_library(const StringName &p_name, const StringName &p_new_name) {
365 if (p_name == p_new_name) {
366 return;
367 }
368 #ifdef DEBUG_ENABLED
369 ERR_FAIL_COND_MSG(String(p_new_name).contains_char('/') || String(p_new_name).contains_char(':') || String(p_new_name).contains_char(',') || String(p_new_name).contains_char('['), "Invalid animation library name: " + String(p_new_name) + ".");
370 #endif
371
372 bool found = false;
373 for (AnimationLibraryData &lib : animation_libraries) {
374 ERR_FAIL_COND_MSG(lib.name == p_new_name, "Can't rename animation library to another existing name: " + String(p_new_name) + ".");
375 if (lib.name == p_name) {
376 found = true;
377 lib.name = p_new_name;
378 // rename connections
379 lib.library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationMixer::_animation_added));
380 lib.library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationMixer::_animation_removed));
381 lib.library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationMixer::_animation_renamed));
382
383 lib.library->connect(SNAME("animation_added"), callable_mp(this, &AnimationMixer::_animation_added).bind(p_new_name));
384 lib.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationMixer::_animation_removed).bind(p_new_name));
385 lib.library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationMixer::_animation_renamed).bind(p_new_name));
386
387 for (const KeyValue<StringName, Ref<Animation>> &K : lib.library->animations) {
388 StringName old_name = p_name == StringName() ? K.key : StringName(String(p_name) + "/" + String(K.key));
389 StringName new_name = p_new_name == StringName() ? K.key : StringName(String(p_new_name) + "/" + String(K.key));
390 _rename_animation(old_name, new_name);
391 }
392 }
393 }
394
395 ERR_FAIL_COND(!found);
396
397 animation_libraries.sort(); // Must keep alphabetical order.
398
399 _animation_set_cache_update(); // Update cache.
400
401 notify_property_list_changed();
402 }
403
404 void AnimationMixer::get_animation_list(List<StringName> *p_animations) const {
405 List<String> anims;
406 for (const KeyValue<StringName, AnimationData> &E : animation_set) {
407 anims.push_back(E.key);
408 }
409 anims.sort();
410 for (const String &E : anims) {
411 p_animations->push_back(E);
412 }
413 }
414
415 Ref<Animation> AnimationMixer::get_animation(const StringName &p_name) const {
416 ERR_FAIL_COND_V_MSG(!animation_set.has(p_name), Ref<Animation>(), vformat("Animation not found: \"%s\".", p_name));
417 const AnimationData &anim_data = animation_set[p_name];
418 return anim_data.animation;
419 }
420
421 bool AnimationMixer::has_animation(const StringName &p_name) const {
422 return animation_set.has(p_name);
423 }
424
425 StringName AnimationMixer::find_animation(const Ref<Animation> &p_animation) const {
426 for (const KeyValue<StringName, AnimationData> &E : animation_set) {
427 if (E.value.animation == p_animation) {
428 return E.key;
429 }
430 }
431 return StringName();
432 }
433
434 /* -------------------------------------------- */
435 /* -- General settings for animation ---------- */
436 /* -------------------------------------------- */
437
438 void AnimationMixer::_set_process(bool p_process, bool p_force) {
439 if (processing == p_process && !p_force) {
440 return;
441 }
442
443 switch (callback_mode_process) {
444 case ANIMATION_CALLBACK_MODE_PROCESS_PHYSICS:
445 #ifdef TOOLS_ENABLED
446 set_physics_process_internal(p_process && active && !editing);
447 #else
448 set_physics_process_internal(p_process && active);
449 #endif // TOOLS_ENABLED
450 break;
451 case ANIMATION_CALLBACK_MODE_PROCESS_IDLE:
452 #ifdef TOOLS_ENABLED
453 set_process_internal(p_process && active && !editing);
454 #else
455 set_process_internal(p_process && active);
456 #endif // TOOLS_ENABLED
457 break;
458 case ANIMATION_CALLBACK_MODE_PROCESS_MANUAL:
459 break;
460 }
461
462 processing = p_process;
463 }
464
465 void AnimationMixer::set_active(bool p_active) {
466 if (active == p_active) {
467 return;
468 }
469
470 active = p_active;
471 _set_active(active);
472 _set_process(processing, true);
473
474 if (!active && is_inside_tree()) {
475 _clear_caches();
476 }
477 }
478
479 bool AnimationMixer::is_active() const {
480 return active;
481 }
482
483 void AnimationMixer::set_root_node(const NodePath &p_path) {
484 root_node = p_path;
485 _clear_caches();
486 }
487
488 NodePath AnimationMixer::get_root_node() const {
489 return root_node;
490 }
491
492 void AnimationMixer::set_deterministic(bool p_deterministic) {
493 deterministic = p_deterministic;
494 _clear_caches();
495 }
496
497 bool AnimationMixer::is_deterministic() const {
498 return deterministic;
499 }
500
501 void AnimationMixer::set_callback_mode_process(AnimationCallbackModeProcess p_mode) {
502 if (callback_mode_process == p_mode) {
503 return;
504 }
505
506 bool was_active = is_active();
507 if (was_active) {
508 set_active(false);
509 }
510
511 callback_mode_process = p_mode;
512
513 if (was_active) {
514 set_active(true);
515 }
516 }
517
518 AnimationMixer::AnimationCallbackModeProcess AnimationMixer::get_callback_mode_process() const {
519 return callback_mode_process;
520 }
521
522 void AnimationMixer::set_callback_mode_method(AnimationCallbackModeMethod p_mode) {
523 callback_mode_method = p_mode;
524 emit_signal(SNAME("mixer_updated"));
525 }
526
527 AnimationMixer::AnimationCallbackModeMethod AnimationMixer::get_callback_mode_method() const {
528 return callback_mode_method;
529 }
530
531 void AnimationMixer::set_callback_mode_discrete(AnimationCallbackModeDiscrete p_mode) {
532 callback_mode_discrete = p_mode;
533 _clear_caches();
534 emit_signal(SNAME("mixer_updated"));
535 }
536
537 AnimationMixer::AnimationCallbackModeDiscrete AnimationMixer::get_callback_mode_discrete() const {
538 return callback_mode_discrete;
539 }
540
541 void AnimationMixer::set_audio_max_polyphony(int p_audio_max_polyphony) {
542 ERR_FAIL_COND(p_audio_max_polyphony < 0 || p_audio_max_polyphony > 128);
543 audio_max_polyphony = p_audio_max_polyphony;
544 }
545
546 int AnimationMixer::get_audio_max_polyphony() const {
547 return audio_max_polyphony;
548 }
549
550 #ifdef TOOLS_ENABLED
551 void AnimationMixer::set_editing(bool p_editing) {
552 if (editing == p_editing) {
553 return;
554 }
555
556 editing = p_editing;
557 _set_process(processing, true);
558
559 if (editing && is_inside_tree()) {
560 _clear_caches();
561 }
562
563 notify_property_list_changed(); // To make active readonly.
564 }
565
566 bool AnimationMixer::is_editing() const {
567 return editing;
568 }
569
570 void AnimationMixer::set_dummy(bool p_dummy) {
571 dummy = p_dummy;
572 }
573
574 bool AnimationMixer::is_dummy() const {
575 return dummy;
576 }
577 #endif // TOOLS_ENABLED
578
579 /* -------------------------------------------- */
580 /* -- Caches for blending --------------------- */
581 /* -------------------------------------------- */
582
583 void AnimationMixer::_clear_caches() {
584 _init_root_motion_cache();
585 _clear_audio_streams();
586 _clear_playing_caches();
587 for (KeyValue<Animation::TypeHash, TrackCache *> &K : track_cache) {
588 memdelete(K.value);
589 }
590 track_cache.clear();
591 animation_track_num_to_track_cache.clear();
592 cache_valid = false;
593 capture_cache.clear();
594
595 emit_signal(SNAME("caches_cleared"));
596 }
597
598 void AnimationMixer::_clear_audio_streams() {
599 for (int i = 0; i < playing_audio_stream_players.size(); i++) {
600 playing_audio_stream_players[i]->call(SNAME("stop"));
601 playing_audio_stream_players[i]->call(SNAME("set_stream"), Ref<AudioStream>());
602 }
603 playing_audio_stream_players.clear();
604 }
605
606 void AnimationMixer::_clear_playing_caches() {
607 for (const TrackCache *E : playing_caches) {
608 Object *t_obj = ObjectDB::get_instance(E->object_id);
609 if (t_obj) {
610 t_obj->call(SNAME("stop"), true);
611 }
612 }
613 playing_caches.clear();
614 }
615
616 void AnimationMixer::_init_root_motion_cache() {
617 root_motion_cache.loc = Vector3(0, 0, 0);
618 root_motion_cache.rot = Quaternion(0, 0, 0, 1);
619 root_motion_cache.scale = Vector3(1, 1, 1);
620 root_motion_position = Vector3(0, 0, 0);
621 root_motion_rotation = Quaternion(0, 0, 0, 1);
622 root_motion_scale = Vector3(0, 0, 0);
623 root_motion_position_accumulator = Vector3(0, 0, 0);
624 root_motion_rotation_accumulator = Quaternion(0, 0, 0, 1);
625 root_motion_scale_accumulator = Vector3(1, 1, 1);
626 }
627
628 void AnimationMixer::_create_track_num_to_track_cache_for_animation(Ref<Animation> &p_animation) {
629 if (animation_track_num_to_track_cache.has(p_animation)) {
630 // In AnimationMixer::_update_caches, it retrieves all animations via AnimationMixer::get_animation_list
631 // Since multiple AnimationLibraries can share the same Animation, it is possible that the cache is already created.
632 return;
633 }
634 LocalVector<TrackCache *> &track_num_to_track_cache = animation_track_num_to_track_cache.insert_new(p_animation, LocalVector<TrackCache *>())->value;
635 const LocalVector<Animation::Track *> &tracks = p_animation->get_tracks();
636
637 track_num_to_track_cache.resize(tracks.size());
638 for (uint32_t i = 0; i < tracks.size(); i++) {
639 TrackCache **track_ptr = track_cache.getptr(tracks[i]->thash);
640 if (track_ptr == nullptr) {
641 track_num_to_track_cache[i] = nullptr;
642 } else {
643 track_num_to_track_cache[i] = *track_ptr;
644 }
645 }
646 }
647
648 bool AnimationMixer::_update_caches() {
649 setup_pass++;
650
651 root_motion_cache.loc = Vector3(0, 0, 0);
652 root_motion_cache.rot = Quaternion(0, 0, 0, 1);
653 root_motion_cache.scale = Vector3(1, 1, 1);
654
655 List<StringName> sname_list;
656 get_animation_list(&sname_list);
657
658 bool check_path = GLOBAL_GET_CACHED(bool, "animation/warnings/check_invalid_track_paths");
659 bool check_angle_interpolation = GLOBAL_GET_CACHED(bool, "animation/warnings/check_angle_interpolation_type_conflicting");
660
661 Node *parent = get_node_or_null(root_node);
662 if (!parent) {
663 WARN_PRINT_ONCE(vformat("'%s' is an invalid root_node path, caches will not be built, please check the root_node assignment on: %s", root_node, get_path()));
664 cache_valid = false;
665 return false;
666 }
667
668 #ifdef TOOLS_ENABLED
669 String mixer_name = "AnimationMixer";
670 const Node *owner = get_owner();
671 if (owner) {
672 const String scene_path = owner->get_scene_file_path();
673 if (!scene_path.is_empty()) {
674 mixer_name += vformat(" (at: %s)", scene_path.get_file());
675 }
676 }
677 #else
678 const String mixer_name = "AnimationMixer";
679 #endif
680
681 Ref<Animation> reset_anim;
682 bool has_reset_anim = has_animation(SceneStringName(RESET));
683 if (has_reset_anim) {
684 reset_anim = get_animation(SceneStringName(RESET));
685 }
686 for (const StringName &E : sname_list) {
687 Ref<Animation> anim = get_animation(E);
688 for (int i = 0; i < anim->get_track_count(); i++) {
689 if (!anim->track_is_enabled(i)) {
690 continue;
691 }
692 NodePath path = anim->track_get_path(i);
693 Animation::TypeHash thash = anim->track_get_type_hash(i);
694 Animation::TrackType track_src_type = anim->track_get_type(i);
695 Animation::TrackType track_cache_type = Animation::get_cache_type(track_src_type);
696
697 TrackCache *track = nullptr;
698 if (track_cache.has(thash)) {
699 track = track_cache.get(thash);
700 }
701
702 // If not valid, delete track.
703 if (track && (track->type != track_cache_type || ObjectDB::get_instance(track->object_id) == nullptr)) {
704 playing_caches.erase(track);
705 memdelete(track);
706 track_cache.erase(thash);
707 track = nullptr;
708 }
709
710 if (!track) {
711 Ref<Resource> resource;
712 Vector<StringName> leftover_path;
713
714 Node *child = parent->get_node_and_resource(path, resource, leftover_path);
715 if (!child) {
716 if (check_path) {
717 WARN_PRINT_ED(mixer_name + ": '" + String(E) + "', couldn't resolve track: '" + String(path) + "'. This warning can be disabled in Project Settings.");
718 }
719 continue;
720 }
721
722 switch (track_src_type) {
723 case Animation::TYPE_BEZIER:
724 case Animation::TYPE_VALUE: {
725 // If a value track without a key is cached first, the initial value cannot be determined.
726 // It is a corner case, but which may cause problems with blending.
727 ERR_CONTINUE_MSG(anim->track_get_key_count(i) == 0, mixer_name + ": '" + String(E) + "', Value Track: '" + String(path) + "' must have at least one key to cache for blending.");
728
729 TrackCacheValue *track_value = memnew(TrackCacheValue);
730
731 if (resource.is_valid()) {
732 track_value->object_id = resource->get_instance_id();
733 } else {
734 track_value->object_id = child->get_instance_id();
735 }
736
737 track_value->is_using_angle = anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_LINEAR_ANGLE || anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_CUBIC_ANGLE;
738
739 track_value->subpath = leftover_path;
740
741 track = track_value;
742
743 bool is_value = track_src_type == Animation::TYPE_VALUE;
744
745 track_value->init_value = is_value ? anim->track_get_key_value(i, 0) : (anim->track_get_key_value(i, 0).operator Array())[0];
746 track_value->init_value.zero();
747
748 track_value->is_init = false;
749
750 // Can't interpolate them, need to convert.
751 track_value->is_variant_interpolatable = Animation::is_variant_interpolatable(track_value->init_value);
752
753 // If there is a Reset Animation, it takes precedence by overwriting.
754 if (has_reset_anim) {
755 int rt = reset_anim->find_track(path, track_src_type);
756 if (rt >= 0 && reset_anim->track_is_enabled(rt) && reset_anim->track_get_key_count(rt) > 0) {
757 if (is_value) {
758 track_value->init_value = reset_anim->track_get_key_value(rt, 0);
759 } else {
760 track_value->init_value = (reset_anim->track_get_key_value(rt, 0).operator Array())[0];
761 }
762 }
763 }
764
765 if (is_value && callback_mode_discrete == ANIMATION_CALLBACK_MODE_DISCRETE_FORCE_CONTINUOUS) {
766 if (child) {
767 PropertyInfo prop_info;
768 ClassDB::get_property_info(child->get_class_name(), path.get_concatenated_subnames(), &prop_info);
769 if (prop_info.hint == PROPERTY_HINT_ONESHOT) {
770 WARN_PRINT_ED(vformat("%s: '%s', Value Track: '%s' is oneshot property, but will be continuously updated. Consider setting a value other than ANIMATION_CALLBACK_MODE_DISCRETE_FORCE_CONTINUOUS to AnimationMixer.callback_mode_dominant.", mixer_name, String(E), String(path)));
771 }
772 }
773 }
774 } break;
775 case Animation::TYPE_POSITION_3D:
776 case Animation::TYPE_ROTATION_3D:
777 case Animation::TYPE_SCALE_3D: {
778 #ifndef _3D_DISABLED
779 Node3D *node_3d = Object::cast_to<Node3D>(child);
780
781 if (!node_3d) {
782 ERR_PRINT(mixer_name + ": '" + String(E) + "', transform track does not point to Node3D: '" + String(path) + "'.");
783 continue;
784 }
785
786 TrackCacheTransform *track_xform = memnew(TrackCacheTransform);
787 track_xform->type = Animation::TYPE_POSITION_3D;
788
789 track_xform->bone_idx = -1;
790
791 bool has_rest = false;
792 Skeleton3D *sk = Object::cast_to<Skeleton3D>(node_3d);
793 if (sk && path.get_subname_count() == 1) {
794 track_xform->skeleton_id = sk->get_instance_id();
795 int bone_idx = sk->find_bone(path.get_subname(0));
796 if (bone_idx != -1) {
797 has_rest = true;
798 track_xform->bone_idx = bone_idx;
799 Transform3D rest = sk->get_bone_rest(bone_idx);
800 track_xform->init_loc = rest.origin;
801 track_xform->init_rot = rest.basis.get_rotation_quaternion();
802 track_xform->init_scale = rest.basis.get_scale();
803 }
804 }
805
806 track_xform->object_id = node_3d->get_instance_id();
807
808 track = track_xform;
809
810 switch (track_src_type) {
811 case Animation::TYPE_POSITION_3D: {
812 track_xform->loc_used = true;
813 } break;
814 case Animation::TYPE_ROTATION_3D: {
815 track_xform->rot_used = true;
816 } break;
817 case Animation::TYPE_SCALE_3D: {
818 track_xform->scale_used = true;
819 } break;
820 default: {
821 }
822 }
823
824 // For non Skeleton3D bone animation.
825 if (has_reset_anim && !has_rest) {
826 int rt = reset_anim->find_track(path, track_src_type);
827 if (rt >= 0 && reset_anim->track_is_enabled(rt) && reset_anim->track_get_key_count(rt) > 0) {
828 switch (track_src_type) {
829 case Animation::TYPE_POSITION_3D: {
830 track_xform->init_loc = reset_anim->track_get_key_value(rt, 0);
831 } break;
832 case Animation::TYPE_ROTATION_3D: {
833 track_xform->init_rot = reset_anim->track_get_key_value(rt, 0);
834 } break;
835 case Animation::TYPE_SCALE_3D: {
836 track_xform->init_scale = reset_anim->track_get_key_value(rt, 0);
837 } break;
838 default: {
839 }
840 }
841 }
842 }
843 #endif // _3D_DISABLED
844 } break;
845 case Animation::TYPE_BLEND_SHAPE: {
846 #ifndef _3D_DISABLED
847 if (path.get_subname_count() != 1) {
848 ERR_PRINT(mixer_name + ": '" + String(E) + "', blend shape track does not contain a blend shape subname: '" + String(path) + "'.");
849 continue;
850 }
851 MeshInstance3D *mesh_3d = Object::cast_to<MeshInstance3D>(child);
852
853 if (!mesh_3d) {
854 ERR_PRINT(mixer_name + ": '" + String(E) + "', blend shape track does not point to MeshInstance3D: '" + String(path) + "'.");
855 continue;
856 }
857
858 StringName blend_shape_name = path.get_subname(0);
859 int blend_shape_idx = mesh_3d->find_blend_shape_by_name(blend_shape_name);
860 if (blend_shape_idx == -1) {
861 ERR_PRINT(mixer_name + ": '" + String(E) + "', blend shape track points to a non-existing name: '" + String(blend_shape_name) + "'.");
862 continue;
863 }
864
865 TrackCacheBlendShape *track_bshape = memnew(TrackCacheBlendShape);
866
867 track_bshape->shape_index = blend_shape_idx;
868 track_bshape->object_id = mesh_3d->get_instance_id();
869 track = track_bshape;
870
871 if (has_reset_anim) {
872 int rt = reset_anim->find_track(path, track_src_type);
873 if (rt >= 0 && reset_anim->track_is_enabled(rt) && reset_anim->track_get_key_count(rt) > 0) {
874 track_bshape->init_value = reset_anim->track_get_key_value(rt, 0);
875 }
876 }
877 #endif
878 } break;
879 case Animation::TYPE_METHOD: {
880 TrackCacheMethod *track_method = memnew(TrackCacheMethod);
881
882 if (resource.is_valid()) {
883 track_method->object_id = resource->get_instance_id();
884 } else {
885 track_method->object_id = child->get_instance_id();
886 }
887
888 track = track_method;
889
890 } break;
891 case Animation::TYPE_AUDIO: {
892 TrackCacheAudio *track_audio = memnew(TrackCacheAudio);
893
894 track_audio->object_id = child->get_instance_id();
895 track_audio->audio_stream.instantiate();
896 track_audio->audio_stream->set_polyphony(audio_max_polyphony);
897 track_audio->playback_type = (AudioServer::PlaybackType)(int)(child->call(SNAME("get_playback_type")));
898 track_audio->bus = (StringName)(child->call(SNAME("get_bus")));
899
900 track = track_audio;
901
902 } break;
903 case Animation::TYPE_ANIMATION: {
904 TrackCacheAnimation *track_animation = memnew(TrackCacheAnimation);
905
906 track_animation->object_id = child->get_instance_id();
907
908 track = track_animation;
909
910 } break;
911 default: {
912 ERR_PRINT("Animation corrupted (invalid track type).");
913 continue;
914 }
915 }
916 track->path = path;
917 track_cache[thash] = track;
918 } else if (track_cache_type == Animation::TYPE_POSITION_3D) {
919 TrackCacheTransform *track_xform = static_cast<TrackCacheTransform *>(track);
920 if (track->setup_pass != setup_pass) {
921 track_xform->loc_used = false;
922 track_xform->rot_used = false;
923 track_xform->scale_used = false;
924 }
925 switch (track_src_type) {
926 case Animation::TYPE_POSITION_3D: {
927 track_xform->loc_used = true;
928 } break;
929 case Animation::TYPE_ROTATION_3D: {
930 track_xform->rot_used = true;
931 } break;
932 case Animation::TYPE_SCALE_3D: {
933 track_xform->scale_used = true;
934 } break;
935 default: {
936 }
937 }
938 } else if (track_cache_type == Animation::TYPE_VALUE) {
939 TrackCacheValue *track_value = static_cast<TrackCacheValue *>(track);
940 // If it has at least one angle interpolation, it also uses angle interpolation for blending.
941 bool was_using_angle = track_value->is_using_angle;
942 if (track_src_type == Animation::TYPE_VALUE) {
943 if (track_value->init_value.is_string() && anim->value_track_get_update_mode(i) != Animation::UPDATE_DISCRETE) {
944 WARN_PRINT_ONCE_ED(mixer_name + ": '" + String(E) + "', Value Track: '" + String(path) + "' blends String types. This is an experimental algorithm.");
945 }
946 track_value->is_using_angle = track_value->is_using_angle || anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_LINEAR_ANGLE || anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_CUBIC_ANGLE;
947 }
948 if (check_angle_interpolation && (was_using_angle != track_value->is_using_angle)) {
949 WARN_PRINT_ED(mixer_name + ": '" + String(E) + "', Value Track: '" + String(path) + "' has different interpolation types for rotation between some animations which may be blended together. Blending prioritizes angle interpolation, so the blending result uses the shortest path referenced to the initial (RESET animation) value.");
950 }
951 }
952
953 track->setup_pass = setup_pass;
954 }
955 }
956
957 List<Animation::TypeHash> to_delete;
958
959 for (const KeyValue<Animation::TypeHash, TrackCache *> &K : track_cache) {
960 if (K.value->setup_pass != setup_pass) {
961 to_delete.push_back(K.key);
962 }
963 }
964
965 while (to_delete.front()) {
966 Animation::TypeHash thash = to_delete.front()->get();
967 memdelete(track_cache[thash]);
968 track_cache.erase(thash);
969 to_delete.pop_front();
970 }
971
972 track_map.clear();
973
974 int idx = 0;
975 for (const KeyValue<Animation::TypeHash, TrackCache *> &K : track_cache) {
976 track_map[K.value->path] = idx;
977 idx++;
978 }
979
980 for (KeyValue<Animation::TypeHash, TrackCache *> &K : track_cache) {
981 K.value->blend_idx = track_map[K.value->path];
982 }
983
984 animation_track_num_to_track_cache.clear();
985 for (const StringName &E : sname_list) {
986 Ref<Animation> anim = get_animation(E);
987 _create_track_num_to_track_cache_for_animation(anim);
988 }
989
990 track_count = idx;
991
992 cache_valid = true;
993
994 return true;
995 }
996
997 /* -------------------------------------------- */
998 /* -- Blending processor ---------------------- */
999 /* -------------------------------------------- */
1000
1001 void AnimationMixer::_process_animation(double p_delta, bool p_update_only) {
1002 _blend_init();
1003 if (cache_valid && _blend_pre_process(p_delta, track_count, track_map)) {
1004 _blend_capture(p_delta);
1005 _blend_calc_total_weight();
1006 _blend_process(p_delta, p_update_only);
1007 clear_animation_instances();
1008 _blend_apply();
1009 _blend_post_process();
1010 emit_signal(SNAME("mixer_applied"));
1011 } else {
1012 clear_animation_instances();
1013 }
1014 }
1015
1016 Variant AnimationMixer::_post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant &p_value, ObjectID p_object_id, int p_object_sub_idx) {
1017 #ifndef _3D_DISABLED
1018 switch (p_anim->track_get_type(p_track)) {
1019 case Animation::TYPE_POSITION_3D: {
1020 if (p_object_sub_idx >= 0) {
1021 Skeleton3D *skel = ObjectDB::get_instance<Skeleton3D>(p_object_id);
1022 if (skel) {
1023 return Vector3(p_value) * skel->get_motion_scale();
1024 }
1025 }
1026 return p_value;
1027 } break;
1028 default: {
1029 } break;
1030 }
1031 #endif // _3D_DISABLED
1032 return p_value;
1033 }
1034
1035 Variant AnimationMixer::post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, ObjectID p_object_id, int p_object_sub_idx) {
1036 if (is_GDVIRTUAL_CALL_post_process_key_value) {
1037 Variant res;
1038 if (GDVIRTUAL_CALL(_post_process_key_value, p_anim, p_track, p_value, p_object_id, p_object_sub_idx, res)) {
1039 return res;
1040 }
1041 is_GDVIRTUAL_CALL_post_process_key_value = false;
1042 }
1043 return _post_process_key_value(p_anim, p_track, p_value, p_object_id, p_object_sub_idx);
1044 }
1045
1046 void AnimationMixer::_blend_init() {
1047 // Check all tracks, see if they need modification.
1048 root_motion_position = Vector3(0, 0, 0);
1049 root_motion_rotation = Quaternion(0, 0, 0, 1);
1050 root_motion_scale = Vector3(0, 0, 0);
1051 root_motion_position_accumulator = Vector3(0, 0, 0);
1052 root_motion_rotation_accumulator = Quaternion(0, 0, 0, 1);
1053 root_motion_scale_accumulator = Vector3(1, 1, 1);
1054
1055 if (!cache_valid) {
1056 if (!_update_caches()) {
1057 return;
1058 }
1059 }
1060
1061 // Init all value/transform/blend/bezier tracks that track_cache has.
1062 for (const KeyValue<Animation::TypeHash, TrackCache *> &K : track_cache) {
1063 TrackCache *track = K.value;
1064
1065 track->total_weight = 0.0;
1066
1067 switch (track->type) {
1068 case Animation::TYPE_POSITION_3D: {
1069 TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
1070 if (track->root_motion) {
1071 root_motion_cache.loc = Vector3(0, 0, 0);
1072 root_motion_cache.rot = Quaternion(0, 0, 0, 1);
1073 root_motion_cache.scale = Vector3(1, 1, 1);
1074 }
1075 t->loc = t->init_loc;
1076 t->rot = t->init_rot;
1077 t->scale = t->init_scale;
1078 } break;
1079 case Animation::TYPE_BLEND_SHAPE: {
1080 TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
1081 t->value = t->init_value;
1082 } break;
1083 case Animation::TYPE_VALUE: {
1084 TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
1085 t->value = Animation::cast_to_blendwise(t->init_value);
1086 t->element_size = t->init_value.is_string() ? (real_t)(t->init_value.operator String()).length() : 0;
1087 t->use_continuous = false;
1088 t->use_discrete = false;
1089 } break;
1090 case Animation::TYPE_AUDIO: {
1091 TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
1092 for (KeyValue<ObjectID, PlayingAudioTrackInfo> &L : t->playing_streams) {
1093 PlayingAudioTrackInfo &track_info = L.value;
1094 track_info.volume = 0.0;
1095 }
1096 } break;
1097 default: {
1098 } break;
1099 }
1100 }
1101 }
1102
1103 bool AnimationMixer::_blend_pre_process(double p_delta, int p_track_count, const AHashMap<NodePath, int> &p_track_map) {
1104 return true;
1105 }
1106
1107 void AnimationMixer::_blend_post_process() {
1108 //
1109 }
1110
1111 void AnimationMixer::_blend_capture(double p_delta) {
1112 blend_capture(p_delta);
1113 }
1114
1115 void AnimationMixer::blend_capture(double p_delta) {
1116 if (capture_cache.animation.is_null()) {
1117 return;
1118 }
1119
1120 capture_cache.remain -= p_delta * capture_cache.step;
1121 if (Animation::is_less_or_equal_approx(capture_cache.remain, 0)) {
1122 if (capture_cache.animation.is_valid()) {
1123 animation_track_num_to_track_cache.erase(capture_cache.animation);
1124 }
1125 capture_cache.clear();
1126 return;
1127 }
1128
1129 real_t weight = Tween::run_equation(capture_cache.trans_type, capture_cache.ease_type, capture_cache.remain, 0.0, 1.0, 1.0);
1130
1131 // Blend with other animations.
1132 real_t inv = 1.0 - weight;
1133 for (AnimationInstance &ai : animation_instances) {
1134 ai.playback_info.weight *= inv;
1135 }
1136
1137 // Build capture animation instance.
1138 AnimationData ad;
1139 ad.animation = capture_cache.animation;
1140
1141 PlaybackInfo pi;
1142 pi.weight = weight;
1143
1144 AnimationInstance ai;
1145 ai.animation_data = ad;
1146 ai.playback_info = pi;
1147
1148 animation_instances.push_back(ai);
1149 }
1150
1151 void AnimationMixer::_blend_calc_total_weight() {
1152 for (const AnimationInstance &ai : animation_instances) {
1153 Ref<Animation> a = ai.animation_data.animation;
1154 real_t weight = ai.playback_info.weight;
1155 const real_t *track_weights_ptr = ai.playback_info.track_weights.ptr();
1156 int track_weights_count = ai.playback_info.track_weights.size();
1157 ERR_CONTINUE_EDMSG(!animation_track_num_to_track_cache.has(a), "No animation in cache.");
1158 LocalVector<TrackCache *> &track_num_to_track_cache = animation_track_num_to_track_cache[a];
1159 thread_local HashSet<Animation::TypeHash, HashHasher> processed_hashes;
1160 processed_hashes.clear();
1161 const LocalVector<Animation::Track *> &tracks = a->get_tracks();
1162 Animation::Track *const *tracks_ptr = tracks.ptr();
1163 int count = tracks.size();
1164 for (int i = 0; i < count; i++) {
1165 Animation::Track *animation_track = tracks_ptr[i];
1166 if (!animation_track->enabled) {
1167 continue;
1168 }
1169 Animation::TypeHash thash = animation_track->thash;
1170 TrackCache *track = track_num_to_track_cache[i];
1171 if (track == nullptr || processed_hashes.has(thash)) {
1172 // No path, but avoid error spamming.
1173 // Or, there is the case different track type with same path; These can be distinguished by hash. So don't add the weight doubly.
1174 continue;
1175 }
1176 int blend_idx = track->blend_idx;
1177 ERR_CONTINUE(blend_idx < 0 || blend_idx >= track_count);
1178 real_t blend = blend_idx < track_weights_count ? track_weights_ptr[blend_idx] * weight : weight;
1179 track->total_weight += blend;
1180 processed_hashes.insert(thash);
1181 }
1182 }
1183 }
1184
1185 void AnimationMixer::_blend_process(double p_delta, bool p_update_only) {
1186 // Apply value/transform/blend/bezier blends to track caches and execute method/audio/animation tracks.
1187 #ifdef TOOLS_ENABLED
1188 bool can_call = is_inside_tree() && !Engine::get_singleton()->is_editor_hint();
1189 #endif // TOOLS_ENABLED
1190 for (const AnimationInstance &ai : animation_instances) {
1191 Ref<Animation> a = ai.animation_data.animation;
1192 double time = ai.playback_info.time;
1193 double delta = ai.playback_info.delta;
1194 double start = ai.playback_info.start;
1195 double end = ai.playback_info.end;
1196 bool seeked = ai.playback_info.seeked;
1197 Animation::LoopedFlag looped_flag = ai.playback_info.looped_flag;
1198 bool is_external_seeking = ai.playback_info.is_external_seeking;
1199 real_t weight = ai.playback_info.weight;
1200 const real_t *track_weights_ptr = ai.playback_info.track_weights.ptr();
1201 int track_weights_count = ai.playback_info.track_weights.size();
1202 bool backward = std::signbit(delta); // This flag is used by the root motion calculates or detecting the end of audio stream.
1203 bool seeked_backward = std::signbit(p_delta);
1204 #ifndef _3D_DISABLED
1205 bool calc_root = !seeked || is_external_seeking;
1206 #endif // _3D_DISABLED
1207 ERR_CONTINUE_EDMSG(!animation_track_num_to_track_cache.has(a), "No animation in cache.");
1208 LocalVector<TrackCache *> &track_num_to_track_cache = animation_track_num_to_track_cache[a];
1209 const LocalVector<Animation::Track *> &tracks = a->get_tracks();
1210 Animation::Track *const *tracks_ptr = tracks.ptr();
1211 real_t a_length = a->get_length();
1212 int count = tracks.size();
1213 for (int i = 0; i < count; i++) {
1214 const Animation::Track *animation_track = tracks_ptr[i];
1215 if (!animation_track->enabled) {
1216 continue;
1217 }
1218 TrackCache *track = track_num_to_track_cache[i];
1219 if (track == nullptr) {
1220 continue; // No path, but avoid error spamming.
1221 }
1222 int blend_idx = track->blend_idx;
1223 ERR_CONTINUE(blend_idx < 0 || blend_idx >= track_count);
1224 real_t blend = blend_idx < track_weights_count ? track_weights_ptr[blend_idx] * weight : weight;
1225 if (!deterministic) {
1226 // If non-deterministic, do normalization.
1227 // It would be better to make this if statement outside the for loop, but come here since too much code...
1228 if (Math::is_zero_approx(track->total_weight)) {
1229 continue;
1230 }
1231 blend = blend / track->total_weight;
1232 }
1233 Animation::TrackType ttype = animation_track->type;
1234 track->root_motion = root_motion_track == animation_track->path;
1235 switch (ttype) {
1236 case Animation::TYPE_POSITION_3D: {
1237 #ifndef _3D_DISABLED
1238 if (Math::is_zero_approx(blend)) {
1239 continue; // Nothing to blend.
1240 }
1241 TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
1242 if (track->root_motion && calc_root) {
1243 int rot_track = -1;
1244 if (root_motion_local) {
1245 rot_track = a->find_track(a->track_get_path(i), Animation::TYPE_ROTATION_3D);
1246 }
1247 double prev_time = time - delta;
1248 if (!backward) {
1249 if (Animation::is_less_approx(prev_time, start)) {
1250 switch (a->get_loop_mode()) {
1251 case Animation::LOOP_NONE: {
1252 prev_time = start;
1253 } break;
1254 case Animation::LOOP_LINEAR: {
1255 prev_time = Math::fposmod(prev_time - start, end - start) + start;
1256 } break;
1257 case Animation::LOOP_PINGPONG: {
1258 prev_time = Math::pingpong(prev_time - start, end - start) + start;
1259 } break;
1260 default:
1261 break;
1262 }
1263 }
1264 } else {
1265 if (Animation::is_greater_approx(prev_time, end)) {
1266 switch (a->get_loop_mode()) {
1267 case Animation::LOOP_NONE: {
1268 prev_time = end;
1269 } break;
1270 case Animation::LOOP_LINEAR: {
1271 prev_time = Math::fposmod(prev_time - start, end - start) + start;
1272 } break;
1273 case Animation::LOOP_PINGPONG: {
1274 prev_time = Math::pingpong(prev_time - start, end - start) + start;
1275 } break;
1276 default:
1277 break;
1278 }
1279 }
1280 }
1281 if (rot_track >= 0) {
1282 Vector3 loc[2];
1283 Quaternion rot;
1284 if (!backward) {
1285 if (Animation::is_greater_approx(prev_time, time)) {
1286 Error err = a->try_position_track_interpolate(i, prev_time, &loc[0]);
1287 if (err != OK) {
1288 continue;
1289 }
1290 loc[0] = post_process_key_value(a, i, loc[0], t->object_id, t->bone_idx);
1291 a->try_position_track_interpolate(i, end, &loc[1]);
1292 loc[1] = post_process_key_value(a, i, loc[1], t->object_id, t->bone_idx);
1293
1294 a->try_rotation_track_interpolate(rot_track, end, &rot);
1295 rot = post_process_key_value(a, rot_track, rot, t->object_id, t->bone_idx);
1296
1297 root_motion_cache.loc += rot.xform_inv(loc[1] - loc[0]) * blend;
1298 prev_time = start;
1299 }
1300 } else {
1301 if (Animation::is_less_approx(prev_time, time)) {
1302 Error err = a->try_position_track_interpolate(i, prev_time, &loc[0]);
1303 if (err != OK) {
1304 continue;
1305 }
1306 loc[0] = post_process_key_value(a, i, loc[0], t->object_id, t->bone_idx);
1307 a->try_position_track_interpolate(i, start, &loc[1]);
1308 loc[1] = post_process_key_value(a, i, loc[1], t->object_id, t->bone_idx);
1309
1310 a->try_rotation_track_interpolate(rot_track, start, &rot);
1311 rot = post_process_key_value(a, rot_track, rot, t->object_id, t->bone_idx);
1312
1313 root_motion_cache.loc += rot.xform_inv(loc[1] - loc[0]) * blend;
1314 prev_time = end;
1315 }
1316 }
1317 Error err = a->try_position_track_interpolate(i, prev_time, &loc[0]);
1318 if (err != OK) {
1319 continue;
1320 }
1321 loc[0] = post_process_key_value(a, i, loc[0], t->object_id, t->bone_idx);
1322 a->try_position_track_interpolate(i, time, &loc[1]);
1323 loc[1] = post_process_key_value(a, i, loc[1], t->object_id, t->bone_idx);
1324
1325 a->try_rotation_track_interpolate(rot_track, time, &rot);
1326 rot = post_process_key_value(a, rot_track, rot, t->object_id, t->bone_idx);
1327
1328 root_motion_cache.loc += rot.xform_inv(loc[1] - loc[0]) * blend;
1329 prev_time = !backward ? start : end;
1330 } else {
1331 Vector3 loc[2];
1332 if (!backward) {
1333 if (Animation::is_greater_approx(prev_time, time)) {
1334 Error err = a->try_position_track_interpolate(i, prev_time, &loc[0]);
1335 if (err != OK) {
1336 continue;
1337 }
1338 loc[0] = post_process_key_value(a, i, loc[0], t->object_id, t->bone_idx);
1339 a->try_position_track_interpolate(i, end, &loc[1]);
1340 loc[1] = post_process_key_value(a, i, loc[1], t->object_id, t->bone_idx);
1341 root_motion_cache.loc += (loc[1] - loc[0]) * blend;
1342 prev_time = start;
1343 }
1344 } else {
1345 if (Animation::is_less_approx(prev_time, time)) {
1346 Error err = a->try_position_track_interpolate(i, prev_time, &loc[0]);
1347 if (err != OK) {
1348 continue;
1349 }
1350 loc[0] = post_process_key_value(a, i, loc[0], t->object_id, t->bone_idx);
1351 a->try_position_track_interpolate(i, start, &loc[1]);
1352 loc[1] = post_process_key_value(a, i, loc[1], t->object_id, t->bone_idx);
1353 root_motion_cache.loc += (loc[1] - loc[0]) * blend;
1354 prev_time = end;
1355 }
1356 }
1357 Error err = a->try_position_track_interpolate(i, prev_time, &loc[0]);
1358 if (err != OK) {
1359 continue;
1360 }
1361 loc[0] = post_process_key_value(a, i, loc[0], t->object_id, t->bone_idx);
1362 a->try_position_track_interpolate(i, time, &loc[1]);
1363 loc[1] = post_process_key_value(a, i, loc[1], t->object_id, t->bone_idx);
1364 root_motion_cache.loc += (loc[1] - loc[0]) * blend;
1365 prev_time = !backward ? start : end;
1366 }
1367 }
1368 {
1369 Vector3 loc;
1370 Error err = a->try_position_track_interpolate(i, time, &loc);
1371 if (err != OK) {
1372 continue;
1373 }
1374 loc = post_process_key_value(a, i, loc, t->object_id, t->bone_idx);
1375 t->loc += (loc - t->init_loc) * blend;
1376 }
1377 #endif // _3D_DISABLED
1378 } break;
1379 case Animation::TYPE_ROTATION_3D: {
1380 #ifndef _3D_DISABLED
1381 if (Math::is_zero_approx(blend)) {
1382 continue; // Nothing to blend.
1383 }
1384 TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
1385 if (track->root_motion && calc_root) {
1386 double prev_time = time - delta;
1387 if (!backward) {
1388 if (Animation::is_less_approx(prev_time, start)) {
1389 switch (a->get_loop_mode()) {
1390 case Animation::LOOP_NONE: {
1391 prev_time = start;
1392 } break;
1393 case Animation::LOOP_LINEAR: {
1394 prev_time = Math::fposmod(prev_time - start, end - start) + start;
1395 } break;
1396 case Animation::LOOP_PINGPONG: {
1397 prev_time = Math::pingpong(prev_time - start, end - start) + start;
1398 } break;
1399 default:
1400 break;
1401 }
1402 }
1403 } else {
1404 if (Animation::is_greater_approx(prev_time, end)) {
1405 switch (a->get_loop_mode()) {
1406 case Animation::LOOP_NONE: {
1407 prev_time = end;
1408 } break;
1409 case Animation::LOOP_LINEAR: {
1410 prev_time = Math::fposmod(prev_time - start, end - start) + start;
1411 } break;
1412 case Animation::LOOP_PINGPONG: {
1413 prev_time = Math::pingpong(prev_time - start, end - start) + start;
1414 } break;
1415 default:
1416 break;
1417 }
1418 }
1419 }
1420 Quaternion rot[2];
1421 if (!backward) {
1422 if (Animation::is_greater_approx(prev_time, time)) {
1423 Error err = a->try_rotation_track_interpolate(i, prev_time, &rot[0]);
1424 if (err != OK) {
1425 continue;
1426 }
1427 rot[0] = post_process_key_value(a, i, rot[0], t->object_id, t->bone_idx);
1428 a->try_rotation_track_interpolate(i, end, &rot[1]);
1429 rot[1] = post_process_key_value(a, i, rot[1], t->object_id, t->bone_idx);
1430 root_motion_cache.rot = Animation::interpolate_via_rest(root_motion_cache.rot, rot[1], blend, rot[0]);
1431 prev_time = start;
1432 }
1433 } else {
1434 if (Animation::is_less_approx(prev_time, time)) {
1435 Error err = a->try_rotation_track_interpolate(i, prev_time, &rot[0]);
1436 if (err != OK) {
1437 continue;
1438 }
1439 rot[0] = post_process_key_value(a, i, rot[0], t->object_id, t->bone_idx);
1440 a->try_rotation_track_interpolate(i, start, &rot[1]);
1441 rot[1] = post_process_key_value(a, i, rot[1], t->object_id, t->bone_idx);
1442 root_motion_cache.rot = Animation::interpolate_via_rest(root_motion_cache.rot, rot[1], blend, rot[0]);
1443 prev_time = end;
1444 }
1445 }
1446 Error err = a->try_rotation_track_interpolate(i, prev_time, &rot[0]);
1447 if (err != OK) {
1448 continue;
1449 }
1450 rot[0] = post_process_key_value(a, i, rot[0], t->object_id, t->bone_idx);
1451 a->try_rotation_track_interpolate(i, time, &rot[1]);
1452 rot[1] = post_process_key_value(a, i, rot[1], t->object_id, t->bone_idx);
1453 root_motion_cache.rot = Animation::interpolate_via_rest(root_motion_cache.rot, rot[1], blend, rot[0]);
1454 prev_time = !backward ? start : end;
1455 }
1456 {
1457 Quaternion rot;
1458 Error err = a->try_rotation_track_interpolate(i, time, &rot);
1459 if (err != OK) {
1460 continue;
1461 }
1462 rot = post_process_key_value(a, i, rot, t->object_id, t->bone_idx);
1463 t->rot = Animation::interpolate_via_rest(t->rot, rot, blend, t->init_rot);
1464 }
1465 #endif // _3D_DISABLED
1466 } break;
1467 case Animation::TYPE_SCALE_3D: {
1468 #ifndef _3D_DISABLED
1469 if (Math::is_zero_approx(blend)) {
1470 continue; // Nothing to blend.
1471 }
1472 TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
1473 if (track->root_motion && calc_root) {
1474 double prev_time = time - delta;
1475 if (!backward) {
1476 if (Animation::is_less_approx(prev_time, start)) {
1477 switch (a->get_loop_mode()) {
1478 case Animation::LOOP_NONE: {
1479 prev_time = start;
1480 } break;
1481 case Animation::LOOP_LINEAR: {
1482 prev_time = Math::fposmod(prev_time - start, end - start) + start;
1483 } break;
1484 case Animation::LOOP_PINGPONG: {
1485 prev_time = Math::pingpong(prev_time - start, end - start) + start;
1486 } break;
1487 default:
1488 break;
1489 }
1490 }
1491 } else {
1492 if (Animation::is_greater_approx(prev_time, end)) {
1493 switch (a->get_loop_mode()) {
1494 case Animation::LOOP_NONE: {
1495 prev_time = end;
1496 } break;
1497 case Animation::LOOP_LINEAR: {
1498 prev_time = Math::fposmod(prev_time - start, end - start) + start;
1499 } break;
1500 case Animation::LOOP_PINGPONG: {
1501 prev_time = Math::pingpong(prev_time - start, end - start) + start;
1502 } break;
1503 default:
1504 break;
1505 }
1506 }
1507 }
1508 Vector3 scale[2];
1509 if (!backward) {
1510 if (Animation::is_greater_approx(prev_time, time)) {
1511 Error err = a->try_scale_track_interpolate(i, prev_time, &scale[0]);
1512 if (err != OK) {
1513 continue;
1514 }
1515 scale[0] = post_process_key_value(a, i, scale[0], t->object_id, t->bone_idx);
1516 a->try_scale_track_interpolate(i, end, &scale[1]);
1517 scale[1] = post_process_key_value(a, i, scale[1], t->object_id, t->bone_idx);
1518 root_motion_cache.scale += (scale[1] - scale[0]) * blend;
1519 prev_time = start;
1520 }
1521 } else {
1522 if (Animation::is_less_approx(prev_time, time)) {
1523 Error err = a->try_scale_track_interpolate(i, prev_time, &scale[0]);
1524 if (err != OK) {
1525 continue;
1526 }
1527 scale[0] = post_process_key_value(a, i, scale[0], t->object_id, t->bone_idx);
1528 a->try_scale_track_interpolate(i, start, &scale[1]);
1529 scale[1] = post_process_key_value(a, i, scale[1], t->object_id, t->bone_idx);
1530 root_motion_cache.scale += (scale[1] - scale[0]) * blend;
1531 prev_time = end;
1532 }
1533 }
1534 Error err = a->try_scale_track_interpolate(i, prev_time, &scale[0]);
1535 if (err != OK) {
1536 continue;
1537 }
1538 scale[0] = post_process_key_value(a, i, scale[0], t->object_id, t->bone_idx);
1539 a->try_scale_track_interpolate(i, time, &scale[1]);
1540 scale[1] = post_process_key_value(a, i, scale[1], t->object_id, t->bone_idx);
1541 root_motion_cache.scale += (scale[1] - scale[0]) * blend;
1542 prev_time = !backward ? start : end;
1543 }
1544 {
1545 Vector3 scale;
1546 Error err = a->try_scale_track_interpolate(i, time, &scale);
1547 if (err != OK) {
1548 continue;
1549 }
1550 scale = post_process_key_value(a, i, scale, t->object_id, t->bone_idx);
1551 t->scale += (scale - t->init_scale) * blend;
1552 }
1553 #endif // _3D_DISABLED
1554 } break;
1555 case Animation::TYPE_BLEND_SHAPE: {
1556 #ifndef _3D_DISABLED
1557 if (Math::is_zero_approx(blend)) {
1558 continue; // Nothing to blend.
1559 }
1560 TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
1561 float value;
1562 Error err = a->try_blend_shape_track_interpolate(i, time, &value);
1563 //ERR_CONTINUE(err!=OK); //used for testing, should be removed
1564 if (err != OK) {
1565 continue;
1566 }
1567 value = post_process_key_value(a, i, value, t->object_id, t->shape_index);
1568 t->value += (value - t->init_value) * blend;
1569 #endif // _3D_DISABLED
1570 } break;
1571 case Animation::TYPE_BEZIER:
1572 case Animation::TYPE_VALUE: {
1573 if (Math::is_zero_approx(blend)) {
1574 continue; // Nothing to blend.
1575 }
1576 TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
1577 bool is_value = ttype == Animation::TYPE_VALUE;
1578 bool is_discrete = is_value && a->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE;
1579 bool force_continuous = callback_mode_discrete == ANIMATION_CALLBACK_MODE_DISCRETE_FORCE_CONTINUOUS;
1580 if (!is_discrete || force_continuous) {
1581 t->use_continuous = true;
1582
1583 Variant value;
1584 if (t->is_variant_interpolatable) {
1585 value = is_value ? a->value_track_interpolate(i, time, is_discrete && force_continuous ? backward : false) : Variant(a->bezier_track_interpolate(i, time));
1586 value = post_process_key_value(a, i, value, t->object_id);
1587 if (value == Variant()) {
1588 continue;
1589 }
1590 } else {
1591 // Discrete track sets the value in the current _blend_process() function,
1592 // but Force Continuous track does not set the value here because the value must be set in the _blend_apply() function later.
1593 int idx = a->track_find_key(i, time, Animation::FIND_MODE_NEAREST, false, backward);
1594 if (idx < 0) {
1595 continue;
1596 }
1597 value = a->track_get_key_value(i, idx);
1598 value = post_process_key_value(a, i, value, t->object_id);
1599 if (value == Variant()) {
1600 continue;
1601 }
1602 t->value = value;
1603 continue;
1604 }
1605
1606 // Special case for angle interpolation.
1607 if (t->is_using_angle) {
1608 // For blending consistency, it prevents rotation of more than 180 degrees from init_value.
1609 // This is the same with Quaternion blending.
1610 t->value = Animation::interpolate_via_rest((double)t->value, (double)value, blend, (double)t->init_value);
1611 } else {
1612 value = Animation::cast_to_blendwise(value);
1613 if (t->init_value.is_array()) {
1614 t->element_size = MAX(t->element_size.operator int(), (value.operator Array()).size());
1615 } else if (t->init_value.is_string()) {
1616 real_t length = Animation::subtract_variant((real_t)(value.operator Array()).size(), (real_t)(t->init_value.operator String()).length());
1617 t->element_size = Animation::blend_variant(t->element_size, length, blend);
1618 }
1619 value = Animation::subtract_variant(value, Animation::cast_to_blendwise(t->init_value));
1620 t->value = Animation::blend_variant(t->value, value, blend);
1621 }
1622 } else {
1623 if (seeked) {
1624 int idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT, false, seeked_backward);
1625 if (idx < 0) {
1626 continue;
1627 }
1628 t->use_discrete = true;
1629 Variant value = a->track_get_key_value(i, idx);
1630 value = post_process_key_value(a, i, value, t->object_id);
1631 Object *t_obj = ObjectDB::get_instance(t->object_id);
1632 if (t_obj) {
1633 t_obj->set_indexed(t->subpath, value);
1634 }
1635 } else {
1636 List<int> indices;
1637 a->track_get_key_indices_in_range(i, time, delta, start, end, &indices, looped_flag);
1638 for (int &F : indices) {
1639 t->use_discrete = true;
1640 Variant value = a->track_get_key_value(i, F);
1641 value = post_process_key_value(a, i, value, t->object_id);
1642 Object *t_obj = ObjectDB::get_instance(t->object_id);
1643 if (t_obj) {
1644 t_obj->set_indexed(t->subpath, value);
1645 }
1646 }
1647 }
1648 }
1649 } break;
1650 case Animation::TYPE_METHOD: {
1651 #ifdef TOOLS_ENABLED
1652 if (!can_call) {
1653 continue;
1654 }
1655 #endif // TOOLS_ENABLED
1656 if (p_update_only || Math::is_zero_approx(blend)) {
1657 continue;
1658 }
1659 TrackCacheMethod *t = static_cast<TrackCacheMethod *>(track);
1660 if (seeked) {
1661 int idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT, true);
1662 if (idx < 0) {
1663 continue;
1664 }
1665 StringName method = a->method_track_get_name(i, idx);
1666 Vector<Variant> params = a->method_track_get_params(i, idx);
1667 _call_object(t->object_id, method, params, callback_mode_method == ANIMATION_CALLBACK_MODE_METHOD_DEFERRED);
1668 } else {
1669 List<int> indices;
1670 a->track_get_key_indices_in_range(i, time, delta, start, end, &indices, looped_flag);
1671 for (int &F : indices) {
1672 StringName method = a->method_track_get_name(i, F);
1673 Vector<Variant> params = a->method_track_get_params(i, F);
1674 _call_object(t->object_id, method, params, callback_mode_method == ANIMATION_CALLBACK_MODE_METHOD_DEFERRED);
1675 }
1676 }
1677 } break;
1678 case Animation::TYPE_AUDIO: {
1679 // The end of audio should be observed even if the blend value is 0, build up the information and store to the cache for that.
1680 TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
1681 Object *t_obj = ObjectDB::get_instance(t->object_id);
1682 Node *asp = t_obj ? Object::cast_to<Node>(t_obj) : nullptr;
1683 if (!t_obj || !asp) {
1684 t->playing_streams.clear();
1685 continue;
1686 }
1687 ObjectID oid = a->get_instance_id();
1688 if (!t->playing_streams.has(oid)) {
1689 t->playing_streams[oid] = PlayingAudioTrackInfo();
1690 }
1691
1692 PlayingAudioTrackInfo &track_info = t->playing_streams[oid];
1693 track_info.length = a_length;
1694 track_info.time = time;
1695 track_info.volume += blend;
1696 track_info.loop = a->get_loop_mode() != Animation::LOOP_NONE;
1697 track_info.backward = backward;
1698 track_info.use_blend = a->audio_track_is_use_blend(i);
1699 AHashMap<int, PlayingAudioStreamInfo> &map = track_info.stream_info;
1700
1701 // Main process to fire key is started from here.
1702 if (p_update_only) {
1703 continue;
1704 }
1705 // Find stream.
1706 int idx = -1;
1707 if (seeked) {
1708 // Audio key may be playbacked from the middle, should use FIND_MODE_NEAREST.
1709 // Then, check the current playing stream to prevent to playback doubly.
1710 idx = a->track_find_key(i, time, Animation::FIND_MODE_NEAREST, true);
1711 // Discard previous stream when seeking.
1712 if (map.has(idx)) {
1713 t->audio_stream_playback->stop_stream(map[idx].index);
1714 map.erase(idx);
1715 }
1716 } else {
1717 List<int> to_play;
1718 a->track_get_key_indices_in_range(i, time, delta, start, end, &to_play, looped_flag);
1719 if (to_play.size()) {
1720 idx = to_play.back()->get();
1721 }
1722 }
1723 if (idx < 0) {
1724 continue;
1725 }
1726
1727 // Play stream.
1728 Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
1729 if (stream.is_valid()) {
1730 double start_ofs = a->audio_track_get_key_start_offset(i, idx);
1731 double end_ofs = a->audio_track_get_key_end_offset(i, idx);
1732 double len = stream->get_length();
1733 if (seeked) {
1734 start_ofs += time - a->track_get_key_time(i, idx);
1735 }
1736
1737 if (t_obj->call(SNAME("get_stream")) != t->audio_stream) {
1738 t_obj->call(SNAME("set_stream"), t->audio_stream);
1739 t->audio_stream_playback.unref();
1740 if (!playing_audio_stream_players.has(asp)) {
1741 playing_audio_stream_players.push_back(asp);
1742 }
1743 }
1744 if (!t_obj->call(SNAME("is_playing"))) {
1745 t_obj->call(SNAME("play"));
1746 }
1747 if (!t_obj->call(SNAME("has_stream_playback"))) {
1748 t->audio_stream_playback.unref();
1749 continue;
1750 }
1751 if (t->audio_stream_playback.is_null()) {
1752 t->audio_stream_playback = t_obj->call(SNAME("get_stream_playback"));
1753 }
1754
1755 if (t_obj->call(SNAME("get_is_sample"))) {
1756 if (t->audio_stream_playback->get_sample_playback().is_valid()) {
1757 AudioServer::get_singleton()->stop_sample_playback(t->audio_stream_playback->get_sample_playback());
1758 }
1759 Ref<AudioSamplePlayback> sample_playback;
1760 sample_playback.instantiate();
1761 sample_playback->stream = stream;
1762 t->audio_stream_playback->set_sample_playback(sample_playback);
1763 AudioServer::get_singleton()->start_sample_playback(sample_playback);
1764 continue;
1765 }
1766
1767 PlayingAudioStreamInfo pasi;
1768 pasi.index = t->audio_stream_playback->play_stream(stream, start_ofs, 0, 1.0, t->playback_type, t->bus);
1769 pasi.start = time;
1770 if (len && Animation::is_greater_approx(end_ofs, 0)) { // Force an end at a time.
1771 pasi.len = len - start_ofs - end_ofs;
1772 } else {
1773 pasi.len = 0;
1774 }
1775 map[idx] = pasi;
1776 }
1777 } break;
1778 case Animation::TYPE_ANIMATION: {
1779 if (Math::is_zero_approx(blend)) {
1780 continue;
1781 }
1782 TrackCacheAnimation *t = static_cast<TrackCacheAnimation *>(track);
1783 Object *t_obj = ObjectDB::get_instance(t->object_id);
1784 if (!t_obj) {
1785 continue;
1786 }
1787 AnimationPlayer *player2 = Object::cast_to<AnimationPlayer>(t_obj);
1788 if (!player2) {
1789 continue;
1790 }
1791 // TODO: Make it possible to embed section info in animation track keys.
1792 if (seeked) {
1793 // Seek.
1794 int idx = a->track_find_key(i, time, Animation::FIND_MODE_NEAREST, true);
1795 if (idx < 0) {
1796 continue;
1797 }
1798 double pos = a->track_get_key_time(i, idx);
1799 StringName anim_name = a->animation_track_get_key_animation(i, idx);
1800 if (String(anim_name) == "[stop]" || !player2->has_animation(anim_name)) {
1801 continue;
1802 }
1803 Ref<Animation> anim = player2->get_animation(anim_name);
1804 double at_anim_pos = start;
1805 switch (anim->get_loop_mode()) {
1806 case Animation::LOOP_NONE: {
1807 if (!is_external_seeking && ((!backward && Animation::is_greater_or_equal_approx(time, pos + end)) || (backward && Animation::is_less_or_equal_approx(time, pos + start)))) {
1808 continue; // Do nothing if current time is outside of length when started.
1809 }
1810 at_anim_pos = MIN(end, time - pos); // Seek to end.
1811 } break;
1812 case Animation::LOOP_LINEAR: {
1813 at_anim_pos = Math::fposmod(time - pos - start, end - start) + start; // Seek to loop.
1814 } break;
1815 case Animation::LOOP_PINGPONG: {
1816 at_anim_pos = Math::pingpong(time - pos - start, end - start) + start;
1817 } break;
1818 default:
1819 break;
1820 }
1821 if (player2->is_playing() || !is_external_seeking) {
1822 player2->seek(at_anim_pos, false, p_update_only);
1823 player2->play(anim_name);
1824 t->playing = true;
1825 playing_caches.insert(t);
1826 } else {
1827 player2->set_assigned_animation(anim_name);
1828 player2->seek(at_anim_pos, true, p_update_only);
1829 }
1830 } else {
1831 // Find stuff to play.
1832 List<int> to_play;
1833 a->track_get_key_indices_in_range(i, time, delta, start, end, &to_play, looped_flag);
1834 if (to_play.size()) {
1835 int idx = to_play.back()->get();
1836 StringName anim_name = a->animation_track_get_key_animation(i, idx);
1837 if (String(anim_name) == "[stop]" || !player2->has_animation(anim_name)) {
1838 if (playing_caches.has(t)) {
1839 playing_caches.erase(t);
1840 player2->stop();
1841 t->playing = false;
1842 }
1843 } else {
1844 player2->play(anim_name);
1845 t->playing = true;
1846 playing_caches.insert(t);
1847 }
1848 }
1849 }
1850 } break;
1851 }
1852 }
1853 }
1854 is_GDVIRTUAL_CALL_post_process_key_value = true;
1855 }
1856
1857 void AnimationMixer::_blend_apply() {
1858 // Finally, set the tracks.
1859 for (const KeyValue<Animation::TypeHash, TrackCache *> &K : track_cache) {
1860 TrackCache *track = K.value;
1861 bool is_zero_amount = Math::is_zero_approx(track->total_weight);
1862 if (!deterministic && is_zero_amount) {
1863 continue;
1864 }
1865 switch (track->type) {
1866 case Animation::TYPE_POSITION_3D: {
1867 #ifndef _3D_DISABLED
1868 TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
1869
1870 if (t->root_motion) {
1871 root_motion_position = root_motion_cache.loc;
1872 root_motion_rotation = root_motion_cache.rot;
1873 root_motion_scale = root_motion_cache.scale - Vector3(1, 1, 1);
1874 root_motion_position_accumulator = t->loc;
1875 root_motion_rotation_accumulator = t->rot;
1876 root_motion_scale_accumulator = t->scale;
1877 } else if (t->skeleton_id.is_valid() && t->bone_idx >= 0) {
1878 Skeleton3D *t_skeleton = ObjectDB::get_instance<Skeleton3D>(t->skeleton_id);
1879 if (!t_skeleton) {
1880 return;
1881 }
1882 if (t->loc_used) {
1883 t_skeleton->set_bone_pose_position(t->bone_idx, t->loc);
1884 }
1885 if (t->rot_used) {
1886 t_skeleton->set_bone_pose_rotation(t->bone_idx, t->rot);
1887 }
1888 if (t->scale_used) {
1889 t_skeleton->set_bone_pose_scale(t->bone_idx, t->scale);
1890 }
1891
1892 } else if (!t->skeleton_id.is_valid()) {
1893 Node3D *t_node_3d = ObjectDB::get_instance<Node3D>(t->object_id);
1894 if (!t_node_3d) {
1895 return;
1896 }
1897 if (t->loc_used) {
1898 t_node_3d->set_position(t->loc);
1899 }
1900 if (t->rot_used) {
1901 t_node_3d->set_rotation(t->rot.get_euler());
1902 }
1903 if (t->scale_used) {
1904 t_node_3d->set_scale(t->scale);
1905 }
1906 }
1907 #endif // _3D_DISABLED
1908 } break;
1909 case Animation::TYPE_BLEND_SHAPE: {
1910 #ifndef _3D_DISABLED
1911 TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
1912
1913 MeshInstance3D *t_mesh_3d = ObjectDB::get_instance<MeshInstance3D>(t->object_id);
1914 if (t_mesh_3d) {
1915 t_mesh_3d->set_blend_shape_value(t->shape_index, t->value);
1916 }
1917 #endif // _3D_DISABLED
1918 } break;
1919 case Animation::TYPE_VALUE: {
1920 TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
1921
1922 if (callback_mode_discrete == ANIMATION_CALLBACK_MODE_DISCRETE_FORCE_CONTINUOUS) {
1923 t->is_init = false; // Always update in Force Continuous.
1924 } else if (!t->use_continuous && (t->use_discrete || !deterministic)) {
1925 t->is_init = true; // If there is no continuous value and only disctere value is applied or just started, don't RESET.
1926 }
1927
1928 if ((t->is_init && (is_zero_amount || !t->use_continuous)) ||
1929 (callback_mode_discrete != ANIMATION_CALLBACK_MODE_DISCRETE_FORCE_CONTINUOUS &&
1930 !is_zero_amount &&
1931 callback_mode_discrete == ANIMATION_CALLBACK_MODE_DISCRETE_DOMINANT &&
1932 t->use_discrete)) {
1933 break; // Don't overwrite the value set by UPDATE_DISCRETE.
1934 }
1935
1936 if (callback_mode_discrete != ANIMATION_CALLBACK_MODE_DISCRETE_FORCE_CONTINUOUS) {
1937 t->is_init = !t->use_continuous; // If there is no Continuous in non-Force Continuous type, it means RESET.
1938 }
1939
1940 // Trim unused elements if init array/string is not blended.
1941 if (t->value.is_array()) {
1942 int actual_blended_size = (int)Math::round(Math::abs(t->element_size.operator real_t()));
1943 if (actual_blended_size < (t->value.operator Array()).size()) {
1944 real_t abs_weight = Math::abs(track->total_weight);
1945 if (abs_weight >= 1.0) {
1946 (t->value.operator Array()).resize(actual_blended_size);
1947 } else if (t->init_value.is_string()) {
1948 (t->value.operator Array()).resize(Animation::interpolate_variant((t->init_value.operator String()).length(), actual_blended_size, abs_weight));
1949 }
1950 }
1951 }
1952
1953 Object *t_obj = ObjectDB::get_instance(t->object_id);
1954 if (t_obj) {
1955 t_obj->set_indexed(t->subpath, Animation::cast_from_blendwise(t->value, t->init_value.get_type()));
1956 }
1957
1958 } break;
1959 case Animation::TYPE_AUDIO: {
1960 TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
1961
1962 // Audio ending process.
1963 LocalVector<ObjectID> erase_maps;
1964 for (KeyValue<ObjectID, PlayingAudioTrackInfo> &L : t->playing_streams) {
1965 PlayingAudioTrackInfo &track_info = L.value;
1966 float db = Math::linear_to_db(track_info.use_blend ? track_info.volume : 1.0);
1967 LocalVector<int> erase_streams;
1968 AHashMap<int, PlayingAudioStreamInfo> &map = track_info.stream_info;
1969 for (const KeyValue<int, PlayingAudioStreamInfo> &M : map) {
1970 PlayingAudioStreamInfo pasi = M.value;
1971
1972 bool stop = false;
1973 if (!t->audio_stream_playback->is_stream_playing(pasi.index)) {
1974 stop = true;
1975 }
1976 if (!track_info.loop) {
1977 if (!track_info.backward) {
1978 if (Animation::is_less_approx(track_info.time, pasi.start)) {
1979 stop = true;
1980 }
1981 } else if (track_info.backward) {
1982 if (Animation::is_greater_approx(track_info.time, pasi.start)) {
1983 stop = true;
1984 }
1985 }
1986 }
1987 if (Animation::is_greater_approx(pasi.len, 0)) {
1988 double len = 0.0;
1989 if (!track_info.backward) {
1990 len = Animation::is_greater_approx(pasi.start, track_info.time) ? (track_info.length - pasi.start) + track_info.time : track_info.time - pasi.start;
1991 } else {
1992 len = Animation::is_less_approx(pasi.start, track_info.time) ? (track_info.length - track_info.time) + pasi.start : pasi.start - track_info.time;
1993 }
1994 if (Animation::is_greater_approx(len, pasi.len)) {
1995 stop = true;
1996 }
1997 }
1998 if (stop) {
1999 // Time to stop.
2000 t->audio_stream_playback->stop_stream(pasi.index);
2001 erase_streams.push_back(M.key);
2002 } else {
2003 t->audio_stream_playback->set_stream_volume(pasi.index, db);
2004 }
2005 }
2006 for (uint32_t erase_idx = 0; erase_idx < erase_streams.size(); erase_idx++) {
2007 map.erase(erase_streams[erase_idx]);
2008 }
2009 if (map.is_empty()) {
2010 erase_maps.push_back(L.key);
2011 }
2012 }
2013 for (uint32_t erase_idx = 0; erase_idx < erase_maps.size(); erase_idx++) {
2014 t->playing_streams.erase(erase_maps[erase_idx]);
2015 }
2016 } break;
2017 default: {
2018 } // The rest don't matter.
2019 }
2020 }
2021 }
2022
2023 void AnimationMixer::_call_object(ObjectID p_object_id, const StringName &p_method, const Vector<Variant> &p_params, bool p_deferred) {
2024 // Separate function to use alloca() more efficiently
2025 const Variant **argptrs = (const Variant **)alloca(sizeof(Variant *) * p_params.size());
2026 const Variant *args = p_params.ptr();
2027 uint32_t argcount = p_params.size();
2028 for (uint32_t i = 0; i < argcount; i++) {
2029 argptrs[i] = &args[i];
2030 }
2031 Object *t_obj = ObjectDB::get_instance(p_object_id);
2032 if (!t_obj) {
2033 return;
2034 }
2035 if (p_deferred) {
2036 Callable(t_obj, p_method).call_deferredp(argptrs, argcount);
2037 } else {
2038 Callable::CallError ce;
2039 t_obj->callp(p_method, argptrs, argcount, ce);
2040 }
2041 }
2042
2043 void AnimationMixer::make_animation_instance(const StringName &p_name, const PlaybackInfo p_playback_info) {
2044 ERR_FAIL_COND(!has_animation(p_name));
2045
2046 AnimationData ad;
2047 ad.name = p_name;
2048 ad.animation = get_animation(p_name);
2049 ad.animation_library = find_animation_library(ad.animation);
2050
2051 AnimationInstance ai;
2052 ai.animation_data = ad;
2053 ai.playback_info = p_playback_info;
2054
2055 animation_instances.push_back(ai);
2056 }
2057
2058 void AnimationMixer::clear_animation_instances() {
2059 animation_instances.clear();
2060 }
2061
2062 void AnimationMixer::advance(double p_time) {
2063 _process_animation(p_time);
2064 }
2065
2066 void AnimationMixer::clear_caches() {
2067 _clear_caches();
2068 }
2069
2070 /* -------------------------------------------- */
2071 /* -- Root motion ----------------------------- */
2072 /* -------------------------------------------- */
2073
2074 void AnimationMixer::set_root_motion_track(const NodePath &p_track) {
2075 root_motion_track = p_track;
2076 notify_property_list_changed();
2077 }
2078
2079 NodePath AnimationMixer::get_root_motion_track() const {
2080 return root_motion_track;
2081 }
2082
2083 void AnimationMixer::set_root_motion_local(bool p_enabled) {
2084 root_motion_local = p_enabled;
2085 }
2086
2087 bool AnimationMixer::is_root_motion_local() const {
2088 return root_motion_local;
2089 }
2090
2091 Vector3 AnimationMixer::get_root_motion_position() const {
2092 return root_motion_position;
2093 }
2094
2095 Quaternion AnimationMixer::get_root_motion_rotation() const {
2096 return root_motion_rotation;
2097 }
2098
2099 Vector3 AnimationMixer::get_root_motion_scale() const {
2100 return root_motion_scale;
2101 }
2102
2103 Vector3 AnimationMixer::get_root_motion_position_accumulator() const {
2104 return root_motion_position_accumulator;
2105 }
2106
2107 Quaternion AnimationMixer::get_root_motion_rotation_accumulator() const {
2108 return root_motion_rotation_accumulator;
2109 }
2110
2111 Vector3 AnimationMixer::get_root_motion_scale_accumulator() const {
2112 return root_motion_scale_accumulator;
2113 }
2114
2115 /* -------------------------------------------- */
2116 /* -- Reset on save --------------------------- */
2117 /* -------------------------------------------- */
2118
2119 void AnimationMixer::set_reset_on_save_enabled(bool p_enabled) {
2120 reset_on_save = p_enabled;
2121 }
2122
2123 bool AnimationMixer::is_reset_on_save_enabled() const {
2124 return reset_on_save;
2125 }
2126
2127 bool AnimationMixer::can_apply_reset() const {
2128 return has_animation(SceneStringName(RESET));
2129 }
2130
2131 void AnimationMixer::_build_backup_track_cache() {
2132 for (const KeyValue<Animation::TypeHash, TrackCache *> &K : track_cache) {
2133 TrackCache *track = K.value;
2134 track->total_weight = 1.0;
2135 switch (track->type) {
2136 case Animation::TYPE_POSITION_3D: {
2137 #ifndef _3D_DISABLED
2138 TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
2139 if (t->root_motion) {
2140 // Do nothing.
2141 } else if (t->skeleton_id.is_valid() && t->bone_idx >= 0) {
2142 Skeleton3D *t_skeleton = ObjectDB::get_instance<Skeleton3D>(t->skeleton_id);
2143 if (!t_skeleton) {
2144 return;
2145 }
2146 if (t->loc_used) {
2147 t->loc = t_skeleton->get_bone_pose_position(t->bone_idx);
2148 }
2149 if (t->rot_used) {
2150 t->rot = t_skeleton->get_bone_pose_rotation(t->bone_idx);
2151 }
2152 if (t->scale_used) {
2153 t->scale = t_skeleton->get_bone_pose_scale(t->bone_idx);
2154 }
2155 } else if (!t->skeleton_id.is_valid()) {
2156 Node3D *t_node_3d = ObjectDB::get_instance<Node3D>(t->object_id);
2157 if (!t_node_3d) {
2158 return;
2159 }
2160 if (t->loc_used) {
2161 t->loc = t_node_3d->get_position();
2162 }
2163 if (t->rot_used) {
2164 t->rot = t_node_3d->get_quaternion();
2165 }
2166 if (t->scale_used) {
2167 t->scale = t_node_3d->get_scale();
2168 }
2169 }
2170 #endif // _3D_DISABLED
2171 } break;
2172 case Animation::TYPE_BLEND_SHAPE: {
2173 #ifndef _3D_DISABLED
2174 TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
2175 MeshInstance3D *t_mesh_3d = ObjectDB::get_instance<MeshInstance3D>(t->object_id);
2176 if (t_mesh_3d) {
2177 t->value = t_mesh_3d->get_blend_shape_value(t->shape_index);
2178 }
2179 #endif // _3D_DISABLED
2180 } break;
2181 case Animation::TYPE_VALUE: {
2182 TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
2183 Object *t_obj = ObjectDB::get_instance(t->object_id);
2184 if (t_obj) {
2185 t->value = Animation::cast_to_blendwise(t_obj->get_indexed(t->subpath));
2186 }
2187 t->use_continuous = true;
2188 t->use_discrete = false;
2189 if (t->init_value.is_array()) {
2190 t->element_size = MAX(t->element_size.operator int(), (t->value.operator Array()).size());
2191 } else if (t->init_value.is_string()) {
2192 t->element_size = (real_t)(t->value.operator Array()).size();
2193 }
2194 } break;
2195 case Animation::TYPE_AUDIO: {
2196 TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
2197 Object *t_obj = ObjectDB::get_instance(t->object_id);
2198 if (t_obj) {
2199 Node *asp = Object::cast_to<Node>(t_obj);
2200 if (asp) {
2201 asp->call(SNAME("set_stream"), Ref<AudioStream>());
2202 }
2203 }
2204 } break;
2205 default: {
2206 } // The rest don't matter.
2207 }
2208 }
2209 }
2210
2211 Ref<AnimatedValuesBackup> AnimationMixer::make_backup() {
2212 Ref<AnimatedValuesBackup> backup;
2213 backup.instantiate();
2214
2215 Ref<Animation> reset_anim = animation_set[SceneStringName(RESET)].animation;
2216 ERR_FAIL_COND_V(reset_anim.is_null(), Ref<AnimatedValuesBackup>());
2217
2218 _blend_init();
2219 PlaybackInfo pi;
2220 pi.time = 0;
2221 pi.delta = 0;
2222 pi.start = 0;
2223 pi.end = reset_anim->get_length();
2224 pi.seeked = true;
2225 pi.weight = 1.0;
2226 make_animation_instance(SceneStringName(RESET), pi);
2227 _build_backup_track_cache();
2228
2229 backup->set_data(track_cache);
2230 clear_animation_instances();
2231
2232 return backup;
2233 }
2234
2235 void AnimationMixer::reset() {
2236 ERR_FAIL_COND(!can_apply_reset());
2237
2238 Ref<Animation> reset_anim = animation_set[SceneStringName(RESET)].animation;
2239 ERR_FAIL_COND(reset_anim.is_null());
2240
2241 Node *root_node_object = get_node_or_null(root_node);
2242 ERR_FAIL_NULL(root_node_object);
2243
2244 AnimationPlayer *aux_player = memnew(AnimationPlayer);
2245 root_node_object->add_child(aux_player);
2246 Ref<AnimationLibrary> al;
2247 al.instantiate();
2248 al->add_animation(SceneStringName(RESET), reset_anim);
2249 aux_player->set_reset_on_save_enabled(false);
2250 aux_player->set_root_node(aux_player->get_path_to(root_node_object));
2251 aux_player->add_animation_library("", al);
2252 aux_player->set_assigned_animation(SceneStringName(RESET));
2253 aux_player->seek(0.0f, true);
2254 aux_player->queue_free();
2255 }
2256
2257 void AnimationMixer::restore(const Ref<AnimatedValuesBackup> &p_backup) {
2258 ERR_FAIL_COND(p_backup.is_null());
2259 track_cache = p_backup->get_data();
2260 _blend_apply();
2261 track_cache = AHashMap<Animation::TypeHash, AnimationMixer::TrackCache *, HashHasher>();
2262 cache_valid = false;
2263 }
2264
2265 #ifdef TOOLS_ENABLED
2266 Ref<AnimatedValuesBackup> AnimationMixer::apply_reset(bool p_user_initiated) {
2267 if (!p_user_initiated && dummy) {
2268 return Ref<AnimatedValuesBackup>();
2269 }
2270 ERR_FAIL_COND_V(!can_apply_reset(), Ref<AnimatedValuesBackup>());
2271
2272 Ref<Animation> reset_anim = animation_set[SceneStringName(RESET)].animation;
2273 ERR_FAIL_COND_V(reset_anim.is_null(), Ref<AnimatedValuesBackup>());
2274
2275 Ref<AnimatedValuesBackup> backup_current = make_backup();
2276 if (p_user_initiated) {
2277 EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
2278 ur->create_action(TTR("Animation Apply Reset"));
2279 ur->add_do_method(this, "_reset");
2280 ur->add_undo_method(this, "_restore", backup_current);
2281 ur->commit_action();
2282 } else {
2283 reset();
2284 }
2285
2286 return backup_current;
2287 }
2288 #endif // TOOLS_ENABLED
2289
2290 /* -------------------------------------------- */
2291 /* -- Capture feature ------------------------- */
2292 /* -------------------------------------------- */
2293
2294 void AnimationMixer::capture(const StringName &p_name, double p_duration, Tween::TransitionType p_trans_type, Tween::EaseType p_ease_type) {
2295 ERR_FAIL_COND(!active);
2296 ERR_FAIL_COND(!has_animation(p_name));
2297 ERR_FAIL_COND(p_duration <= 0);
2298 Ref<Animation> reference_animation = get_animation(p_name);
2299
2300 if (!cache_valid) {
2301 _update_caches(); // Need to retrieve object id.
2302 }
2303
2304 capture_cache.remain = 1.0;
2305 capture_cache.step = 1.0 / p_duration;
2306 capture_cache.trans_type = p_trans_type;
2307 capture_cache.ease_type = p_ease_type;
2308 if (capture_cache.animation.is_valid()) {
2309 animation_track_num_to_track_cache.erase(capture_cache.animation);
2310 }
2311 capture_cache.animation.instantiate();
2312
2313 bool is_valid = false;
2314 for (int i = 0; i < reference_animation->get_track_count(); i++) {
2315 if (!reference_animation->track_is_enabled(i)) {
2316 continue;
2317 }
2318 if (reference_animation->track_get_type(i) == Animation::TYPE_VALUE && reference_animation->value_track_get_update_mode(i) == Animation::UPDATE_CAPTURE) {
2319 TrackCacheValue *t = static_cast<TrackCacheValue *>(track_cache[reference_animation->track_get_type_hash(i)]);
2320 Object *t_obj = ObjectDB::get_instance(t->object_id);
2321 if (t_obj) {
2322 Variant value = t_obj->get_indexed(t->subpath);
2323 int inserted_idx = capture_cache.animation->add_track(Animation::TYPE_VALUE);
2324 capture_cache.animation->track_set_path(inserted_idx, reference_animation->track_get_path(i));
2325 capture_cache.animation->track_insert_key(inserted_idx, 0, value);
2326 capture_cache.animation->value_track_set_update_mode(inserted_idx, Animation::UPDATE_CONTINUOUS);
2327 capture_cache.animation->track_set_interpolation_type(inserted_idx, Animation::INTERPOLATION_LINEAR);
2328 is_valid = true;
2329 }
2330 }
2331 }
2332 if (!is_valid) {
2333 capture_cache.clear();
2334 } else {
2335 _create_track_num_to_track_cache_for_animation(capture_cache.animation);
2336 }
2337 }
2338
2339 /* -------------------------------------------- */
2340 /* -- General functions ----------------------- */
2341 /* -------------------------------------------- */
2342
2343 void AnimationMixer::_node_removed(Node *p_node) {
2344 _clear_caches();
2345 }
2346
2347 void AnimationMixer::_notification(int p_what) {
2348 switch (p_what) {
2349 case NOTIFICATION_ENTER_TREE: {
2350 if (!processing) {
2351 set_physics_process_internal(false);
2352 set_process_internal(false);
2353 }
2354 _clear_caches();
2355 } break;
2356
2357 case NOTIFICATION_INTERNAL_PROCESS: {
2358 if (active && callback_mode_process == ANIMATION_CALLBACK_MODE_PROCESS_IDLE) {
2359 _process_animation(get_process_delta_time());
2360 }
2361 } break;
2362
2363 case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
2364 if (active && callback_mode_process == ANIMATION_CALLBACK_MODE_PROCESS_PHYSICS) {
2365 _process_animation(get_physics_process_delta_time());
2366 }
2367 } break;
2368
2369 case NOTIFICATION_EXIT_TREE: {
2370 _clear_caches();
2371 } break;
2372 }
2373 }
2374
2375 #ifdef TOOLS_ENABLED
2376 void AnimationMixer::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
2377 const String pf = p_function;
2378 if (p_idx == 0) {
2379 if (pf == "get_animation" || pf == "has_animation") {
2380 List<StringName> al;
2381 get_animation_list(&al);
2382 for (const StringName &name : al) {
2383 r_options->push_back(String(name).quote());
2384 }
2385 } else if (pf == "get_animation_library" || pf == "has_animation_library" || pf == "remove_animation_library" || pf == "rename_animation_library") {
2386 List<StringName> al;
2387 get_animation_library_list(&al);
2388 for (const StringName &name : al) {
2389 r_options->push_back(String(name).quote());
2390 }
2391 }
2392 }
2393 Node::get_argument_options(p_function, p_idx, r_options);
2394 }
2395 #endif
2396
2397 void AnimationMixer::_bind_methods() {
2398 /* ---- Data lists ---- */
2399 ClassDB::bind_method(D_METHOD("add_animation_library", "name", "library"), &AnimationMixer::add_animation_library);
2400 ClassDB::bind_method(D_METHOD("remove_animation_library", "name"), &AnimationMixer::remove_animation_library);
2401 ClassDB::bind_method(D_METHOD("rename_animation_library", "name", "newname"), &AnimationMixer::rename_animation_library);
2402 ClassDB::bind_method(D_METHOD("has_animation_library", "name"), &AnimationMixer::has_animation_library);
2403 ClassDB::bind_method(D_METHOD("get_animation_library", "name"), &AnimationMixer::get_animation_library);
2404 ClassDB::bind_method(D_METHOD("get_animation_library_list"), &AnimationMixer::_get_animation_library_list);
2405
2406 ClassDB::bind_method(D_METHOD("has_animation", "name"), &AnimationMixer::has_animation);
2407 ClassDB::bind_method(D_METHOD("get_animation", "name"), &AnimationMixer::get_animation);
2408 ClassDB::bind_method(D_METHOD("get_animation_list"), &AnimationMixer::_get_animation_list);
2409
2410 /* ---- General settings for animation ---- */
2411 ClassDB::bind_method(D_METHOD("set_active", "active"), &AnimationMixer::set_active);
2412 ClassDB::bind_method(D_METHOD("is_active"), &AnimationMixer::is_active);
2413
2414 ClassDB::bind_method(D_METHOD("set_deterministic", "deterministic"), &AnimationMixer::set_deterministic);
2415 ClassDB::bind_method(D_METHOD("is_deterministic"), &AnimationMixer::is_deterministic);
2416
2417 ClassDB::bind_method(D_METHOD("set_root_node", "path"), &AnimationMixer::set_root_node);
2418 ClassDB::bind_method(D_METHOD("get_root_node"), &AnimationMixer::get_root_node);
2419
2420 ClassDB::bind_method(D_METHOD("set_callback_mode_process", "mode"), &AnimationMixer::set_callback_mode_process);
2421 ClassDB::bind_method(D_METHOD("get_callback_mode_process"), &AnimationMixer::get_callback_mode_process);
2422
2423 ClassDB::bind_method(D_METHOD("set_callback_mode_method", "mode"), &AnimationMixer::set_callback_mode_method);
2424 ClassDB::bind_method(D_METHOD("get_callback_mode_method"), &AnimationMixer::get_callback_mode_method);
2425
2426 ClassDB::bind_method(D_METHOD("set_callback_mode_discrete", "mode"), &AnimationMixer::set_callback_mode_discrete);
2427 ClassDB::bind_method(D_METHOD("get_callback_mode_discrete"), &AnimationMixer::get_callback_mode_discrete);
2428
2429 /* ---- Audio ---- */
2430 ClassDB::bind_method(D_METHOD("set_audio_max_polyphony", "max_polyphony"), &AnimationMixer::set_audio_max_polyphony);
2431 ClassDB::bind_method(D_METHOD("get_audio_max_polyphony"), &AnimationMixer::get_audio_max_polyphony);
2432
2433 /* ---- Root motion accumulator for Skeleton3D ---- */
2434 ClassDB::bind_method(D_METHOD("set_root_motion_track", "path"), &AnimationMixer::set_root_motion_track);
2435 ClassDB::bind_method(D_METHOD("get_root_motion_track"), &AnimationMixer::get_root_motion_track);
2436 ClassDB::bind_method(D_METHOD("set_root_motion_local", "enabled"), &AnimationMixer::set_root_motion_local);
2437 ClassDB::bind_method(D_METHOD("is_root_motion_local"), &AnimationMixer::is_root_motion_local);
2438
2439 ClassDB::bind_method(D_METHOD("get_root_motion_position"), &AnimationMixer::get_root_motion_position);
2440 ClassDB::bind_method(D_METHOD("get_root_motion_rotation"), &AnimationMixer::get_root_motion_rotation);
2441 ClassDB::bind_method(D_METHOD("get_root_motion_scale"), &AnimationMixer::get_root_motion_scale);
2442 ClassDB::bind_method(D_METHOD("get_root_motion_position_accumulator"), &AnimationMixer::get_root_motion_position_accumulator);
2443 ClassDB::bind_method(D_METHOD("get_root_motion_rotation_accumulator"), &AnimationMixer::get_root_motion_rotation_accumulator);
2444 ClassDB::bind_method(D_METHOD("get_root_motion_scale_accumulator"), &AnimationMixer::get_root_motion_scale_accumulator);
2445
2446 /* ---- Blending processor ---- */
2447 ClassDB::bind_method(D_METHOD("clear_caches"), &AnimationMixer::clear_caches);
2448 ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationMixer::advance);
2449 GDVIRTUAL_BIND(_post_process_key_value, "animation", "track", "value", "object_id", "object_sub_idx");
2450
2451 /* ---- Capture feature ---- */
2452 ClassDB::bind_method(D_METHOD("capture", "name", "duration", "trans_type", "ease_type"), &AnimationMixer::capture, DEFVAL(Tween::TRANS_LINEAR), DEFVAL(Tween::EASE_IN));
2453
2454 /* ---- Reset on save ---- */
2455 ClassDB::bind_method(D_METHOD("set_reset_on_save_enabled", "enabled"), &AnimationMixer::set_reset_on_save_enabled);
2456 ClassDB::bind_method(D_METHOD("is_reset_on_save_enabled"), &AnimationMixer::is_reset_on_save_enabled);
2457
2458 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "active"), "set_active", "is_active");
2459 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "deterministic"), "set_deterministic", "is_deterministic");
2460 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reset_on_save", PROPERTY_HINT_NONE, ""), "set_reset_on_save_enabled", "is_reset_on_save_enabled");
2461 ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_node"), "set_root_node", "get_root_node");
2462
2463 ADD_GROUP("Root Motion", "root_motion_");
2464 ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_motion_track"), "set_root_motion_track", "get_root_motion_track");
2465 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "root_motion_local"), "set_root_motion_local", "is_root_motion_local");
2466
2467 ADD_GROUP("Audio", "audio_");
2468 ADD_PROPERTY(PropertyInfo(Variant::INT, "audio_max_polyphony", PROPERTY_HINT_RANGE, "1,127,1"), "set_audio_max_polyphony", "get_audio_max_polyphony");
2469
2470 ADD_GROUP("Callback Mode", "callback_mode_");
2471 ADD_PROPERTY(PropertyInfo(Variant::INT, "callback_mode_process", PROPERTY_HINT_ENUM, "Physics,Idle,Manual"), "set_callback_mode_process", "get_callback_mode_process");
2472 ADD_PROPERTY(PropertyInfo(Variant::INT, "callback_mode_method", PROPERTY_HINT_ENUM, "Deferred,Immediate"), "set_callback_mode_method", "get_callback_mode_method");
2473 ADD_PROPERTY(PropertyInfo(Variant::INT, "callback_mode_discrete", PROPERTY_HINT_ENUM, "Dominant,Recessive,Force Continuous"), "set_callback_mode_discrete", "get_callback_mode_discrete");
2474
2475 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_PROCESS_PHYSICS);
2476 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_PROCESS_IDLE);
2477 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_PROCESS_MANUAL);
2478
2479 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_METHOD_DEFERRED);
2480 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_METHOD_IMMEDIATE);
2481
2482 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_DISCRETE_DOMINANT);
2483 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_DISCRETE_RECESSIVE);
2484 BIND_ENUM_CONSTANT(ANIMATION_CALLBACK_MODE_DISCRETE_FORCE_CONTINUOUS);
2485
2486 ADD_SIGNAL(MethodInfo(SNAME("animation_list_changed")));
2487 ADD_SIGNAL(MethodInfo(SNAME("animation_libraries_updated")));
2488 ADD_SIGNAL(MethodInfo(SNAME("animation_finished"), PropertyInfo(Variant::STRING_NAME, "anim_name")));
2489 ADD_SIGNAL(MethodInfo(SNAME("animation_started"), PropertyInfo(Variant::STRING_NAME, "anim_name")));
2490 ADD_SIGNAL(MethodInfo(SNAME("caches_cleared")));
2491 ADD_SIGNAL(MethodInfo(SNAME("mixer_applied")));
2492 ADD_SIGNAL(MethodInfo(SNAME("mixer_updated"))); // For updating dummy player.
2493
2494 ClassDB::bind_method(D_METHOD("_reset"), &AnimationMixer::reset);
2495 ClassDB::bind_method(D_METHOD("_restore", "backup"), &AnimationMixer::restore);
2496 }
2497
2498 AnimationMixer::AnimationMixer() {
2499 root_node = SceneStringName(path_pp);
2500 }
2501
2502 AnimationMixer::~AnimationMixer() {
2503 }
2504
2505 void AnimatedValuesBackup::set_data(const AHashMap<Animation::TypeHash, AnimationMixer::TrackCache *, HashHasher> p_data) {
2506 clear_data();
2507
2508 for (const KeyValue<Animation::TypeHash, AnimationMixer::TrackCache *> &E : p_data) {
2509 AnimationMixer::TrackCache *track = get_cache_copy(E.value);
2510 if (!track) {
2511 continue; // Some types of tracks do not get a copy and must be ignored.
2512 }
2513
2514 data.insert(E.key, track);
2515 }
2516 }
2517
2518 AHashMap<Animation::TypeHash, AnimationMixer::TrackCache *, HashHasher> AnimatedValuesBackup::get_data() const {
2519 AHashMap<Animation::TypeHash, AnimationMixer::TrackCache *, HashHasher> ret;
2520 for (const KeyValue<Animation::TypeHash, AnimationMixer::TrackCache *> &E : data) {
2521 AnimationMixer::TrackCache *track = get_cache_copy(E.value);
2522 ERR_CONTINUE(!track); // Backup shouldn't contain tracks that cannot be copied, this is a mistake.
2523
2524 ret.insert(E.key, track);
2525 }
2526 return ret;
2527 }
2528
2529 void AnimatedValuesBackup::clear_data() {
2530 for (KeyValue<Animation::TypeHash, AnimationMixer::TrackCache *> &K : data) {
2531 memdelete(K.value);
2532 }
2533 data.clear();
2534 }
2535
2536 AnimationMixer::TrackCache *AnimatedValuesBackup::get_cache_copy(AnimationMixer::TrackCache *p_cache) const {
2537 switch (p_cache->type) {
2538 case Animation::TYPE_BEZIER:
2539 case Animation::TYPE_VALUE: {
2540 AnimationMixer::TrackCacheValue *src = static_cast<AnimationMixer::TrackCacheValue *>(p_cache);
2541 AnimationMixer::TrackCacheValue *tc = memnew(AnimationMixer::TrackCacheValue(*src));
2542 return tc;
2543 }
2544
2545 case Animation::TYPE_POSITION_3D:
2546 case Animation::TYPE_ROTATION_3D:
2547 case Animation::TYPE_SCALE_3D: {
2548 AnimationMixer::TrackCacheTransform *src = static_cast<AnimationMixer::TrackCacheTransform *>(p_cache);
2549 AnimationMixer::TrackCacheTransform *tc = memnew(AnimationMixer::TrackCacheTransform(*src));
2550 return tc;
2551 }
2552
2553 case Animation::TYPE_BLEND_SHAPE: {
2554 AnimationMixer::TrackCacheBlendShape *src = static_cast<AnimationMixer::TrackCacheBlendShape *>(p_cache);
2555 AnimationMixer::TrackCacheBlendShape *tc = memnew(AnimationMixer::TrackCacheBlendShape(*src));
2556 return tc;
2557 }
2558
2559 case Animation::TYPE_AUDIO: {
2560 AnimationMixer::TrackCacheAudio *src = static_cast<AnimationMixer::TrackCacheAudio *>(p_cache);
2561 AnimationMixer::TrackCacheAudio *tc = memnew(AnimationMixer::TrackCacheAudio(*src));
2562 return tc;
2563 }
2564
2565 case Animation::TYPE_METHOD:
2566 case Animation::TYPE_ANIMATION: {
2567 // Nothing to do here.
2568 } break;
2569 }
2570 return nullptr;
2571 }