1 /*************************************************************************/
2 /*  skeleton.cpp                                                         */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
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 "skeleton.h"
32 
33 #include "core/message_queue.h"
34 
35 #include "core/project_settings.h"
36 #include "scene/3d/physics_body.h"
37 #include "scene/resources/surface_tool.h"
38 
_skin_changed()39 void SkinReference::_skin_changed() {
40 	if (skeleton_node) {
41 		skeleton_node->_make_dirty();
42 	}
43 	skeleton_version = 0;
44 }
45 
_bind_methods()46 void SkinReference::_bind_methods() {
47 	ClassDB::bind_method(D_METHOD("_skin_changed"), &SkinReference::_skin_changed);
48 	ClassDB::bind_method(D_METHOD("get_skeleton"), &SkinReference::get_skeleton);
49 	ClassDB::bind_method(D_METHOD("get_skin"), &SkinReference::get_skin);
50 }
51 
get_skeleton() const52 RID SkinReference::get_skeleton() const {
53 	return skeleton;
54 }
55 
get_skin() const56 Ref<Skin> SkinReference::get_skin() const {
57 	return skin;
58 }
59 
~SkinReference()60 SkinReference::~SkinReference() {
61 	if (skeleton_node) {
62 		skeleton_node->skin_bindings.erase(this);
63 	}
64 
65 	VS::get_singleton()->free(skeleton);
66 }
67 
_set(const StringName & p_path,const Variant & p_value)68 bool Skeleton::_set(const StringName &p_path, const Variant &p_value) {
69 
70 	String path = p_path;
71 
72 	if (!path.begins_with("bones/"))
73 		return false;
74 
75 	int which = path.get_slicec('/', 1).to_int();
76 	String what = path.get_slicec('/', 2);
77 
78 	if (which == bones.size() && what == "name") {
79 
80 		add_bone(p_value);
81 		return true;
82 	}
83 
84 	ERR_FAIL_INDEX_V(which, bones.size(), false);
85 
86 	if (what == "parent")
87 		set_bone_parent(which, p_value);
88 	else if (what == "rest")
89 		set_bone_rest(which, p_value);
90 	else if (what == "enabled")
91 		set_bone_enabled(which, p_value);
92 	else if (what == "pose")
93 		set_bone_pose(which, p_value);
94 	else if (what == "bound_children") {
95 		Array children = p_value;
96 
97 		if (is_inside_tree()) {
98 			bones.write[which].nodes_bound.clear();
99 
100 			for (int i = 0; i < children.size(); i++) {
101 
102 				NodePath npath = children[i];
103 				ERR_CONTINUE(npath.operator String() == "");
104 				Node *node = get_node(npath);
105 				ERR_CONTINUE(!node);
106 				bind_child_node_to_bone(which, node);
107 			}
108 		}
109 	} else {
110 		return false;
111 	}
112 
113 	return true;
114 }
115 
_get(const StringName & p_path,Variant & r_ret) const116 bool Skeleton::_get(const StringName &p_path, Variant &r_ret) const {
117 
118 	String path = p_path;
119 
120 	if (!path.begins_with("bones/"))
121 		return false;
122 
123 	int which = path.get_slicec('/', 1).to_int();
124 	String what = path.get_slicec('/', 2);
125 
126 	ERR_FAIL_INDEX_V(which, bones.size(), false);
127 
128 	if (what == "name")
129 		r_ret = get_bone_name(which);
130 	else if (what == "parent")
131 		r_ret = get_bone_parent(which);
132 	else if (what == "rest")
133 		r_ret = get_bone_rest(which);
134 	else if (what == "enabled")
135 		r_ret = is_bone_enabled(which);
136 	else if (what == "pose")
137 		r_ret = get_bone_pose(which);
138 	else if (what == "bound_children") {
139 		Array children;
140 
141 		for (const List<uint32_t>::Element *E = bones[which].nodes_bound.front(); E; E = E->next()) {
142 
143 			Object *obj = ObjectDB::get_instance(E->get());
144 			ERR_CONTINUE(!obj);
145 			Node *node = Object::cast_to<Node>(obj);
146 			ERR_CONTINUE(!node);
147 			NodePath npath = get_path_to(node);
148 			children.push_back(npath);
149 		}
150 
151 		r_ret = children;
152 	} else
153 		return false;
154 
155 	return true;
156 }
_get_property_list(List<PropertyInfo> * p_list) const157 void Skeleton::_get_property_list(List<PropertyInfo> *p_list) const {
158 
159 	for (int i = 0; i < bones.size(); i++) {
160 
161 		String prep = "bones/" + itos(i) + "/";
162 		p_list->push_back(PropertyInfo(Variant::STRING, prep + "name"));
163 		p_list->push_back(PropertyInfo(Variant::INT, prep + "parent", PROPERTY_HINT_RANGE, "-1," + itos(bones.size() - 1) + ",1"));
164 		p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "rest"));
165 		p_list->push_back(PropertyInfo(Variant::BOOL, prep + "enabled"));
166 		p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "pose", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
167 		p_list->push_back(PropertyInfo(Variant::ARRAY, prep + "bound_children"));
168 	}
169 }
170 
_update_process_order()171 void Skeleton::_update_process_order() {
172 
173 	if (!process_order_dirty)
174 		return;
175 
176 	Bone *bonesptr = bones.ptrw();
177 	int len = bones.size();
178 
179 	process_order.resize(len);
180 	int *order = process_order.ptrw();
181 	for (int i = 0; i < len; i++) {
182 
183 		if (bonesptr[i].parent >= len) {
184 			//validate this just in case
185 			ERR_PRINTS("Bone " + itos(i) + " has invalid parent: " + itos(bonesptr[i].parent));
186 			bonesptr[i].parent = -1;
187 		}
188 		order[i] = i;
189 		bonesptr[i].sort_index = i;
190 	}
191 	//now check process order
192 	int pass_count = 0;
193 	while (pass_count < len * len) {
194 		//using bubblesort because of simplicity, it won't run every frame though.
195 		//bublesort worst case is O(n^2), and this may be an infinite loop if cyclic
196 		bool swapped = false;
197 		for (int i = 0; i < len; i++) {
198 			int parent_idx = bonesptr[order[i]].parent;
199 			if (parent_idx < 0)
200 				continue; //do nothing because it has no parent
201 			//swap indices
202 			int parent_order = bonesptr[parent_idx].sort_index;
203 			if (parent_order > i) {
204 				bonesptr[order[i]].sort_index = parent_order;
205 				bonesptr[parent_idx].sort_index = i;
206 				//swap order
207 				SWAP(order[i], order[parent_order]);
208 				swapped = true;
209 			}
210 		}
211 
212 		if (!swapped)
213 			break;
214 		pass_count++;
215 	}
216 
217 	if (pass_count == len * len) {
218 		ERR_PRINT("Skeleton parenthood graph is cyclic");
219 	}
220 
221 	process_order_dirty = false;
222 }
223 
_notification(int p_what)224 void Skeleton::_notification(int p_what) {
225 
226 	switch (p_what) {
227 
228 		case NOTIFICATION_UPDATE_SKELETON: {
229 
230 			VisualServer *vs = VisualServer::get_singleton();
231 			Bone *bonesptr = bones.ptrw();
232 			int len = bones.size();
233 
234 			_update_process_order();
235 
236 			const int *order = process_order.ptr();
237 
238 			for (int i = 0; i < len; i++) {
239 
240 				Bone &b = bonesptr[order[i]];
241 
242 				if (b.global_pose_override_amount >= 0.999) {
243 					b.pose_global = b.global_pose_override;
244 				} else {
245 					if (b.disable_rest) {
246 						if (b.enabled) {
247 
248 							Transform pose = b.pose;
249 							if (b.custom_pose_enable) {
250 								pose = b.custom_pose * pose;
251 							}
252 							if (b.parent >= 0) {
253 
254 								b.pose_global = bonesptr[b.parent].pose_global * pose;
255 							} else {
256 
257 								b.pose_global = pose;
258 							}
259 						} else {
260 
261 							if (b.parent >= 0) {
262 
263 								b.pose_global = bonesptr[b.parent].pose_global;
264 							} else {
265 
266 								b.pose_global = Transform();
267 							}
268 						}
269 
270 					} else {
271 						if (b.enabled) {
272 
273 							Transform pose = b.pose;
274 							if (b.custom_pose_enable) {
275 								pose = b.custom_pose * pose;
276 							}
277 							if (b.parent >= 0) {
278 
279 								b.pose_global = bonesptr[b.parent].pose_global * (b.rest * pose);
280 							} else {
281 
282 								b.pose_global = b.rest * pose;
283 							}
284 						} else {
285 
286 							if (b.parent >= 0) {
287 
288 								b.pose_global = bonesptr[b.parent].pose_global * b.rest;
289 							} else {
290 
291 								b.pose_global = b.rest;
292 							}
293 						}
294 					}
295 
296 					if (b.global_pose_override_amount >= CMP_EPSILON) {
297 						b.pose_global = b.pose_global.interpolate_with(b.global_pose_override, b.global_pose_override_amount);
298 					}
299 				}
300 
301 				if (b.global_pose_override_reset) {
302 					b.global_pose_override_amount = 0.0;
303 				}
304 
305 				for (List<uint32_t>::Element *E = b.nodes_bound.front(); E; E = E->next()) {
306 
307 					Object *obj = ObjectDB::get_instance(E->get());
308 					ERR_CONTINUE(!obj);
309 					Spatial *sp = Object::cast_to<Spatial>(obj);
310 					ERR_CONTINUE(!sp);
311 					sp->set_transform(b.pose_global);
312 				}
313 			}
314 
315 			//update skins
316 			for (Set<SkinReference *>::Element *E = skin_bindings.front(); E; E = E->next()) {
317 
318 				const Skin *skin = E->get()->skin.operator->();
319 				RID skeleton = E->get()->skeleton;
320 				uint32_t bind_count = skin->get_bind_count();
321 
322 				if (E->get()->bind_count != bind_count) {
323 					VS::get_singleton()->skeleton_allocate(skeleton, bind_count);
324 					E->get()->bind_count = bind_count;
325 					E->get()->skin_bone_indices.resize(bind_count);
326 					E->get()->skin_bone_indices_ptrs = E->get()->skin_bone_indices.ptrw();
327 				}
328 
329 				if (E->get()->skeleton_version != version) {
330 
331 					for (uint32_t i = 0; i < bind_count; i++) {
332 						StringName bind_name = skin->get_bind_name(i);
333 
334 						if (bind_name != StringName()) {
335 							//bind name used, use this
336 							bool found = false;
337 							for (int j = 0; j < len; j++) {
338 								if (bonesptr[j].name == bind_name) {
339 									E->get()->skin_bone_indices_ptrs[i] = j;
340 									found = true;
341 									break;
342 								}
343 							}
344 
345 							if (!found) {
346 								ERR_PRINT("Skin bind #" + itos(i) + " contains named bind '" + String(bind_name) + "' but Skeleton has no bone by that name.");
347 								E->get()->skin_bone_indices_ptrs[i] = 0;
348 							}
349 						} else if (skin->get_bind_bone(i) >= 0) {
350 							int bind_index = skin->get_bind_bone(i);
351 							if (bind_index >= len) {
352 								ERR_PRINT("Skin bind #" + itos(i) + " contains bone index bind: " + itos(bind_index) + " , which is greater than the skeleton bone count: " + itos(len) + ".");
353 								E->get()->skin_bone_indices_ptrs[i] = 0;
354 							} else {
355 								E->get()->skin_bone_indices_ptrs[i] = bind_index;
356 							}
357 						} else {
358 							ERR_PRINT("Skin bind #" + itos(i) + " does not contain a name nor a bone index.");
359 							E->get()->skin_bone_indices_ptrs[i] = 0;
360 						}
361 					}
362 
363 					E->get()->skeleton_version = version;
364 				}
365 
366 				for (uint32_t i = 0; i < bind_count; i++) {
367 					uint32_t bone_index = E->get()->skin_bone_indices_ptrs[i];
368 					ERR_CONTINUE(bone_index >= (uint32_t)len);
369 					vs->skeleton_bone_set_transform(skeleton, i, bonesptr[bone_index].pose_global * skin->get_bind_pose(i));
370 				}
371 			}
372 
373 			dirty = false;
374 		} break;
375 	}
376 }
377 
clear_bones_global_pose_override()378 void Skeleton::clear_bones_global_pose_override() {
379 	for (int i = 0; i < bones.size(); i += 1) {
380 		bones.write[i].global_pose_override_amount = 0;
381 	}
382 	_make_dirty();
383 }
384 
set_bone_global_pose_override(int p_bone,const Transform & p_pose,float p_amount,bool p_persistent)385 void Skeleton::set_bone_global_pose_override(int p_bone, const Transform &p_pose, float p_amount, bool p_persistent) {
386 
387 	ERR_FAIL_INDEX(p_bone, bones.size());
388 	bones.write[p_bone].global_pose_override_amount = p_amount;
389 	bones.write[p_bone].global_pose_override = p_pose;
390 	bones.write[p_bone].global_pose_override_reset = !p_persistent;
391 	_make_dirty();
392 }
393 
get_bone_global_pose(int p_bone) const394 Transform Skeleton::get_bone_global_pose(int p_bone) const {
395 
396 	ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
397 	if (dirty)
398 		const_cast<Skeleton *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
399 	return bones[p_bone].pose_global;
400 }
401 
402 // skeleton creation api
add_bone(const String & p_name)403 void Skeleton::add_bone(const String &p_name) {
404 
405 	ERR_FAIL_COND(p_name == "" || p_name.find(":") != -1 || p_name.find("/") != -1);
406 
407 	for (int i = 0; i < bones.size(); i++) {
408 
409 		ERR_FAIL_COND(bones[i].name == p_name);
410 	}
411 
412 	Bone b;
413 	b.name = p_name;
414 	bones.push_back(b);
415 	process_order_dirty = true;
416 	version++;
417 	_make_dirty();
418 	update_gizmo();
419 }
find_bone(const String & p_name) const420 int Skeleton::find_bone(const String &p_name) const {
421 
422 	for (int i = 0; i < bones.size(); i++) {
423 
424 		if (bones[i].name == p_name)
425 			return i;
426 	}
427 
428 	return -1;
429 }
get_bone_name(int p_bone) const430 String Skeleton::get_bone_name(int p_bone) const {
431 
432 	ERR_FAIL_INDEX_V(p_bone, bones.size(), "");
433 
434 	return bones[p_bone].name;
435 }
436 
is_bone_parent_of(int p_bone,int p_parent_bone_id) const437 bool Skeleton::is_bone_parent_of(int p_bone, int p_parent_bone_id) const {
438 
439 	int parent_of_bone = get_bone_parent(p_bone);
440 
441 	if (-1 == parent_of_bone)
442 		return false;
443 
444 	if (parent_of_bone == p_parent_bone_id)
445 		return true;
446 
447 	return is_bone_parent_of(parent_of_bone, p_parent_bone_id);
448 }
449 
get_bone_count() const450 int Skeleton::get_bone_count() const {
451 
452 	return bones.size();
453 }
454 
set_bone_parent(int p_bone,int p_parent)455 void Skeleton::set_bone_parent(int p_bone, int p_parent) {
456 
457 	ERR_FAIL_INDEX(p_bone, bones.size());
458 	ERR_FAIL_COND(p_parent != -1 && (p_parent < 0));
459 
460 	bones.write[p_bone].parent = p_parent;
461 	process_order_dirty = true;
462 	_make_dirty();
463 }
464 
unparent_bone_and_rest(int p_bone)465 void Skeleton::unparent_bone_and_rest(int p_bone) {
466 
467 	ERR_FAIL_INDEX(p_bone, bones.size());
468 
469 	_update_process_order();
470 
471 	int parent = bones[p_bone].parent;
472 	while (parent >= 0) {
473 		bones.write[p_bone].rest = bones[parent].rest * bones[p_bone].rest;
474 		parent = bones[parent].parent;
475 	}
476 
477 	bones.write[p_bone].parent = -1;
478 	process_order_dirty = true;
479 
480 	_make_dirty();
481 }
482 
set_bone_disable_rest(int p_bone,bool p_disable)483 void Skeleton::set_bone_disable_rest(int p_bone, bool p_disable) {
484 
485 	ERR_FAIL_INDEX(p_bone, bones.size());
486 	bones.write[p_bone].disable_rest = p_disable;
487 }
488 
is_bone_rest_disabled(int p_bone) const489 bool Skeleton::is_bone_rest_disabled(int p_bone) const {
490 
491 	ERR_FAIL_INDEX_V(p_bone, bones.size(), false);
492 	return bones[p_bone].disable_rest;
493 }
494 
get_bone_parent(int p_bone) const495 int Skeleton::get_bone_parent(int p_bone) const {
496 
497 	ERR_FAIL_INDEX_V(p_bone, bones.size(), -1);
498 
499 	return bones[p_bone].parent;
500 }
501 
set_bone_rest(int p_bone,const Transform & p_rest)502 void Skeleton::set_bone_rest(int p_bone, const Transform &p_rest) {
503 
504 	ERR_FAIL_INDEX(p_bone, bones.size());
505 
506 	bones.write[p_bone].rest = p_rest;
507 	_make_dirty();
508 }
get_bone_rest(int p_bone) const509 Transform Skeleton::get_bone_rest(int p_bone) const {
510 
511 	ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
512 
513 	return bones[p_bone].rest;
514 }
515 
set_bone_enabled(int p_bone,bool p_enabled)516 void Skeleton::set_bone_enabled(int p_bone, bool p_enabled) {
517 
518 	ERR_FAIL_INDEX(p_bone, bones.size());
519 
520 	bones.write[p_bone].enabled = p_enabled;
521 	_make_dirty();
522 }
is_bone_enabled(int p_bone) const523 bool Skeleton::is_bone_enabled(int p_bone) const {
524 
525 	ERR_FAIL_INDEX_V(p_bone, bones.size(), false);
526 	return bones[p_bone].enabled;
527 }
528 
bind_child_node_to_bone(int p_bone,Node * p_node)529 void Skeleton::bind_child_node_to_bone(int p_bone, Node *p_node) {
530 
531 	ERR_FAIL_NULL(p_node);
532 	ERR_FAIL_INDEX(p_bone, bones.size());
533 
534 	uint32_t id = p_node->get_instance_id();
535 
536 	for (const List<uint32_t>::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) {
537 
538 		if (E->get() == id)
539 			return; // already here
540 	}
541 
542 	bones.write[p_bone].nodes_bound.push_back(id);
543 }
unbind_child_node_from_bone(int p_bone,Node * p_node)544 void Skeleton::unbind_child_node_from_bone(int p_bone, Node *p_node) {
545 
546 	ERR_FAIL_NULL(p_node);
547 	ERR_FAIL_INDEX(p_bone, bones.size());
548 
549 	uint32_t id = p_node->get_instance_id();
550 	bones.write[p_bone].nodes_bound.erase(id);
551 }
get_bound_child_nodes_to_bone(int p_bone,List<Node * > * p_bound) const552 void Skeleton::get_bound_child_nodes_to_bone(int p_bone, List<Node *> *p_bound) const {
553 
554 	ERR_FAIL_INDEX(p_bone, bones.size());
555 
556 	for (const List<uint32_t>::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) {
557 
558 		Object *obj = ObjectDB::get_instance(E->get());
559 		ERR_CONTINUE(!obj);
560 		p_bound->push_back(Object::cast_to<Node>(obj));
561 	}
562 }
563 
clear_bones()564 void Skeleton::clear_bones() {
565 
566 	bones.clear();
567 	process_order_dirty = true;
568 	version++;
569 	_make_dirty();
570 }
571 
572 // posing api
573 
set_bone_pose(int p_bone,const Transform & p_pose)574 void Skeleton::set_bone_pose(int p_bone, const Transform &p_pose) {
575 
576 	ERR_FAIL_INDEX(p_bone, bones.size());
577 
578 	bones.write[p_bone].pose = p_pose;
579 	if (is_inside_tree()) {
580 		_make_dirty();
581 	}
582 }
get_bone_pose(int p_bone) const583 Transform Skeleton::get_bone_pose(int p_bone) const {
584 
585 	ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
586 	return bones[p_bone].pose;
587 }
588 
set_bone_custom_pose(int p_bone,const Transform & p_custom_pose)589 void Skeleton::set_bone_custom_pose(int p_bone, const Transform &p_custom_pose) {
590 
591 	ERR_FAIL_INDEX(p_bone, bones.size());
592 	//ERR_FAIL_COND( !is_inside_scene() );
593 
594 	bones.write[p_bone].custom_pose_enable = (p_custom_pose != Transform());
595 	bones.write[p_bone].custom_pose = p_custom_pose;
596 
597 	_make_dirty();
598 }
599 
get_bone_custom_pose(int p_bone) const600 Transform Skeleton::get_bone_custom_pose(int p_bone) const {
601 
602 	ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
603 	return bones[p_bone].custom_pose;
604 }
605 
_make_dirty()606 void Skeleton::_make_dirty() {
607 
608 	if (dirty)
609 		return;
610 
611 	MessageQueue::get_singleton()->push_notification(this, NOTIFICATION_UPDATE_SKELETON);
612 	dirty = true;
613 }
614 
get_process_order(int p_idx)615 int Skeleton::get_process_order(int p_idx) {
616 	ERR_FAIL_INDEX_V(p_idx, bones.size(), -1);
617 	_update_process_order();
618 	return process_order[p_idx];
619 }
620 
localize_rests()621 void Skeleton::localize_rests() {
622 
623 	_update_process_order();
624 
625 	for (int i = bones.size() - 1; i >= 0; i--) {
626 		int idx = process_order[i];
627 		if (bones[idx].parent >= 0) {
628 			set_bone_rest(idx, bones[bones[idx].parent].rest.affine_inverse() * bones[idx].rest);
629 		}
630 	}
631 }
632 
633 #ifndef _3D_DISABLED
634 
bind_physical_bone_to_bone(int p_bone,PhysicalBone * p_physical_bone)635 void Skeleton::bind_physical_bone_to_bone(int p_bone, PhysicalBone *p_physical_bone) {
636 	ERR_FAIL_INDEX(p_bone, bones.size());
637 	ERR_FAIL_COND(bones[p_bone].physical_bone);
638 	ERR_FAIL_COND(!p_physical_bone);
639 	bones.write[p_bone].physical_bone = p_physical_bone;
640 
641 	_rebuild_physical_bones_cache();
642 }
643 
unbind_physical_bone_from_bone(int p_bone)644 void Skeleton::unbind_physical_bone_from_bone(int p_bone) {
645 	ERR_FAIL_INDEX(p_bone, bones.size());
646 	bones.write[p_bone].physical_bone = NULL;
647 
648 	_rebuild_physical_bones_cache();
649 }
650 
get_physical_bone(int p_bone)651 PhysicalBone *Skeleton::get_physical_bone(int p_bone) {
652 	ERR_FAIL_INDEX_V(p_bone, bones.size(), NULL);
653 
654 	return bones[p_bone].physical_bone;
655 }
656 
get_physical_bone_parent(int p_bone)657 PhysicalBone *Skeleton::get_physical_bone_parent(int p_bone) {
658 	ERR_FAIL_INDEX_V(p_bone, bones.size(), NULL);
659 
660 	if (bones[p_bone].cache_parent_physical_bone) {
661 		return bones[p_bone].cache_parent_physical_bone;
662 	}
663 
664 	return _get_physical_bone_parent(p_bone);
665 }
666 
_get_physical_bone_parent(int p_bone)667 PhysicalBone *Skeleton::_get_physical_bone_parent(int p_bone) {
668 	ERR_FAIL_INDEX_V(p_bone, bones.size(), NULL);
669 
670 	const int parent_bone = bones[p_bone].parent;
671 	if (0 > parent_bone) {
672 		return NULL;
673 	}
674 
675 	PhysicalBone *pb = bones[parent_bone].physical_bone;
676 	if (pb) {
677 		return pb;
678 	} else {
679 		return get_physical_bone_parent(parent_bone);
680 	}
681 }
682 
_rebuild_physical_bones_cache()683 void Skeleton::_rebuild_physical_bones_cache() {
684 	const int b_size = bones.size();
685 	for (int i = 0; i < b_size; ++i) {
686 		PhysicalBone *parent_pb = _get_physical_bone_parent(i);
687 		if (parent_pb != bones[i].physical_bone) {
688 			bones.write[i].cache_parent_physical_bone = parent_pb;
689 			if (bones[i].physical_bone)
690 				bones[i].physical_bone->_on_bone_parent_changed();
691 		}
692 	}
693 }
694 
_pb_stop_simulation(Node * p_node)695 void _pb_stop_simulation(Node *p_node) {
696 
697 	for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
698 		_pb_stop_simulation(p_node->get_child(i));
699 	}
700 
701 	PhysicalBone *pb = Object::cast_to<PhysicalBone>(p_node);
702 	if (pb) {
703 		pb->set_simulate_physics(false);
704 		pb->set_static_body(false);
705 	}
706 }
707 
physical_bones_stop_simulation()708 void Skeleton::physical_bones_stop_simulation() {
709 	_pb_stop_simulation(this);
710 }
711 
_pb_start_simulation(const Skeleton * p_skeleton,Node * p_node,const Vector<int> & p_sim_bones)712 void _pb_start_simulation(const Skeleton *p_skeleton, Node *p_node, const Vector<int> &p_sim_bones) {
713 
714 	for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
715 		_pb_start_simulation(p_skeleton, p_node->get_child(i), p_sim_bones);
716 	}
717 
718 	PhysicalBone *pb = Object::cast_to<PhysicalBone>(p_node);
719 	if (pb) {
720 		bool sim = false;
721 		for (int i = p_sim_bones.size() - 1; 0 <= i; --i) {
722 			if (p_sim_bones[i] == pb->get_bone_id() || p_skeleton->is_bone_parent_of(pb->get_bone_id(), p_sim_bones[i])) {
723 				sim = true;
724 				break;
725 			}
726 		}
727 
728 		pb->set_simulate_physics(true);
729 		if (sim) {
730 			pb->set_static_body(false);
731 		} else {
732 			pb->set_static_body(true);
733 		}
734 	}
735 }
736 
physical_bones_start_simulation_on(const Array & p_bones)737 void Skeleton::physical_bones_start_simulation_on(const Array &p_bones) {
738 
739 	Vector<int> sim_bones;
740 	if (p_bones.size() <= 0) {
741 		sim_bones.push_back(0); // if no bones is specified, activate ragdoll on full body
742 	} else {
743 		sim_bones.resize(p_bones.size());
744 		int c = 0;
745 		for (int i = sim_bones.size() - 1; 0 <= i; --i) {
746 			if (Variant::STRING == p_bones.get(i).get_type()) {
747 				int bone_id = find_bone(p_bones.get(i));
748 				if (bone_id != -1)
749 					sim_bones.write[c++] = bone_id;
750 			}
751 		}
752 		sim_bones.resize(c);
753 	}
754 
755 	_pb_start_simulation(this, this, sim_bones);
756 }
757 
_physical_bones_add_remove_collision_exception(bool p_add,Node * p_node,RID p_exception)758 void _physical_bones_add_remove_collision_exception(bool p_add, Node *p_node, RID p_exception) {
759 
760 	for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
761 		_physical_bones_add_remove_collision_exception(p_add, p_node->get_child(i), p_exception);
762 	}
763 
764 	CollisionObject *co = Object::cast_to<CollisionObject>(p_node);
765 	if (co) {
766 		if (p_add) {
767 			PhysicsServer::get_singleton()->body_add_collision_exception(co->get_rid(), p_exception);
768 		} else {
769 			PhysicsServer::get_singleton()->body_remove_collision_exception(co->get_rid(), p_exception);
770 		}
771 	}
772 }
773 
physical_bones_add_collision_exception(RID p_exception)774 void Skeleton::physical_bones_add_collision_exception(RID p_exception) {
775 	_physical_bones_add_remove_collision_exception(true, this, p_exception);
776 }
777 
physical_bones_remove_collision_exception(RID p_exception)778 void Skeleton::physical_bones_remove_collision_exception(RID p_exception) {
779 	_physical_bones_add_remove_collision_exception(false, this, p_exception);
780 }
781 
782 #endif // _3D_DISABLED
783 
_skin_changed()784 void Skeleton::_skin_changed() {
785 	_make_dirty();
786 }
787 
register_skin(const Ref<Skin> & p_skin)788 Ref<SkinReference> Skeleton::register_skin(const Ref<Skin> &p_skin) {
789 
790 	for (Set<SkinReference *>::Element *E = skin_bindings.front(); E; E = E->next()) {
791 		if (E->get()->skin == p_skin) {
792 			return Ref<SkinReference>(E->get());
793 		}
794 	}
795 
796 	Ref<Skin> skin = p_skin;
797 
798 	if (skin.is_null()) {
799 		//need to create one from existing code, this is for compatibility only
800 		//when skeletons did not support skins. It is also used by gizmo
801 		//to display the skeleton.
802 
803 		skin.instance();
804 		skin->set_bind_count(bones.size());
805 		_update_process_order(); //just in case
806 
807 		// pose changed, rebuild cache of inverses
808 		const Bone *bonesptr = bones.ptr();
809 		int len = bones.size();
810 		const int *order = process_order.ptr();
811 
812 		// calculate global rests and invert them
813 		for (int i = 0; i < len; i++) {
814 			const Bone &b = bonesptr[order[i]];
815 			if (b.parent >= 0) {
816 				skin->set_bind_pose(order[i], skin->get_bind_pose(b.parent) * b.rest);
817 			} else {
818 				skin->set_bind_pose(order[i], b.rest);
819 			}
820 		}
821 
822 		for (int i = 0; i < len; i++) {
823 			//the inverse is what is actually required
824 			skin->set_bind_bone(i, i);
825 			skin->set_bind_pose(i, skin->get_bind_pose(i).affine_inverse());
826 		}
827 	}
828 
829 	ERR_FAIL_COND_V(skin.is_null(), Ref<SkinReference>());
830 
831 	Ref<SkinReference> skin_ref;
832 	skin_ref.instance();
833 
834 	skin_ref->skeleton_node = this;
835 	skin_ref->bind_count = 0;
836 	skin_ref->skeleton = VisualServer::get_singleton()->skeleton_create();
837 	skin_ref->skeleton_node = this;
838 	skin_ref->skin = skin;
839 
840 	skin_bindings.insert(skin_ref.operator->());
841 
842 	skin->connect("changed", skin_ref.operator->(), "_skin_changed");
843 	_make_dirty();
844 	return skin_ref;
845 }
846 
_bind_methods()847 void Skeleton::_bind_methods() {
848 
849 	ClassDB::bind_method(D_METHOD("add_bone", "name"), &Skeleton::add_bone);
850 	ClassDB::bind_method(D_METHOD("find_bone", "name"), &Skeleton::find_bone);
851 	ClassDB::bind_method(D_METHOD("get_bone_name", "bone_idx"), &Skeleton::get_bone_name);
852 
853 	ClassDB::bind_method(D_METHOD("get_bone_parent", "bone_idx"), &Skeleton::get_bone_parent);
854 	ClassDB::bind_method(D_METHOD("set_bone_parent", "bone_idx", "parent_idx"), &Skeleton::set_bone_parent);
855 
856 	ClassDB::bind_method(D_METHOD("get_bone_count"), &Skeleton::get_bone_count);
857 
858 	ClassDB::bind_method(D_METHOD("unparent_bone_and_rest", "bone_idx"), &Skeleton::unparent_bone_and_rest);
859 
860 	ClassDB::bind_method(D_METHOD("get_bone_rest", "bone_idx"), &Skeleton::get_bone_rest);
861 	ClassDB::bind_method(D_METHOD("set_bone_rest", "bone_idx", "rest"), &Skeleton::set_bone_rest);
862 
863 	ClassDB::bind_method(D_METHOD("register_skin", "skin"), &Skeleton::register_skin);
864 
865 	ClassDB::bind_method(D_METHOD("localize_rests"), &Skeleton::localize_rests);
866 
867 	ClassDB::bind_method(D_METHOD("set_bone_disable_rest", "bone_idx", "disable"), &Skeleton::set_bone_disable_rest);
868 	ClassDB::bind_method(D_METHOD("is_bone_rest_disabled", "bone_idx"), &Skeleton::is_bone_rest_disabled);
869 
870 	ClassDB::bind_method(D_METHOD("bind_child_node_to_bone", "bone_idx", "node"), &Skeleton::bind_child_node_to_bone);
871 	ClassDB::bind_method(D_METHOD("unbind_child_node_from_bone", "bone_idx", "node"), &Skeleton::unbind_child_node_from_bone);
872 	ClassDB::bind_method(D_METHOD("get_bound_child_nodes_to_bone", "bone_idx"), &Skeleton::_get_bound_child_nodes_to_bone);
873 
874 	ClassDB::bind_method(D_METHOD("clear_bones"), &Skeleton::clear_bones);
875 
876 	ClassDB::bind_method(D_METHOD("get_bone_pose", "bone_idx"), &Skeleton::get_bone_pose);
877 	ClassDB::bind_method(D_METHOD("set_bone_pose", "bone_idx", "pose"), &Skeleton::set_bone_pose);
878 
879 	ClassDB::bind_method(D_METHOD("clear_bones_global_pose_override"), &Skeleton::clear_bones_global_pose_override);
880 	ClassDB::bind_method(D_METHOD("set_bone_global_pose_override", "bone_idx", "pose", "amount", "persistent"), &Skeleton::set_bone_global_pose_override, DEFVAL(false));
881 	ClassDB::bind_method(D_METHOD("get_bone_global_pose", "bone_idx"), &Skeleton::get_bone_global_pose);
882 
883 	ClassDB::bind_method(D_METHOD("get_bone_custom_pose", "bone_idx"), &Skeleton::get_bone_custom_pose);
884 	ClassDB::bind_method(D_METHOD("set_bone_custom_pose", "bone_idx", "custom_pose"), &Skeleton::set_bone_custom_pose);
885 
886 #ifndef _3D_DISABLED
887 
888 	ClassDB::bind_method(D_METHOD("physical_bones_stop_simulation"), &Skeleton::physical_bones_stop_simulation);
889 	ClassDB::bind_method(D_METHOD("physical_bones_start_simulation", "bones"), &Skeleton::physical_bones_start_simulation_on, DEFVAL(Array()));
890 	ClassDB::bind_method(D_METHOD("physical_bones_add_collision_exception", "exception"), &Skeleton::physical_bones_add_collision_exception);
891 	ClassDB::bind_method(D_METHOD("physical_bones_remove_collision_exception", "exception"), &Skeleton::physical_bones_remove_collision_exception);
892 
893 #endif // _3D_DISABLED
894 
895 	BIND_CONSTANT(NOTIFICATION_UPDATE_SKELETON);
896 }
897 
Skeleton()898 Skeleton::Skeleton() {
899 
900 	dirty = false;
901 	version = 1;
902 	process_order_dirty = true;
903 }
904 
~Skeleton()905 Skeleton::~Skeleton() {
906 
907 	//some skins may remain bound
908 	for (Set<SkinReference *>::Element *E = skin_bindings.front(); E; E = E->next()) {
909 		E->get()->skeleton_node = nullptr;
910 	}
911 }
912