PageRenderTime 76ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/blender/source/blender/blenkernel/intern/armature.c

https://bitbucket.org/duangle/mender
C | 2598 lines | 1663 code | 426 blank | 509 comment | 473 complexity | 1052e29044417b2b6a3d6a57dec2d69f MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0, BSD-2-Clause, Apache-2.0, AGPL-1.0, GPL-3.0, Unlicense, GPL-2.0, LGPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * ***** BEGIN GPL LICENSE BLOCK *****
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; either version 2
  7. * of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software Foundation,
  16. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. *
  18. * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
  19. * All rights reserved.
  20. *
  21. * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
  22. *
  23. * ***** END GPL LICENSE BLOCK *****
  24. */
  25. /** \file blender/blenkernel/intern/armature.c
  26. * \ingroup bke
  27. */
  28. #include <ctype.h>
  29. #include <stdlib.h>
  30. #include <math.h>
  31. #include <string.h>
  32. #include <stdio.h>
  33. #include <float.h>
  34. #include "MEM_guardedalloc.h"
  35. #include "BLI_bpath.h"
  36. #include "BLI_math.h"
  37. #include "BLI_blenlib.h"
  38. #include "BLI_utildefines.h"
  39. #include "DNA_anim_types.h"
  40. #include "DNA_armature_types.h"
  41. #include "DNA_constraint_types.h"
  42. #include "DNA_mesh_types.h"
  43. #include "DNA_lattice_types.h"
  44. #include "DNA_meshdata_types.h"
  45. #include "DNA_nla_types.h"
  46. #include "DNA_scene_types.h"
  47. #include "DNA_object_types.h"
  48. #include "BKE_animsys.h"
  49. #include "BKE_armature.h"
  50. #include "BKE_action.h"
  51. #include "BKE_anim.h"
  52. #include "BKE_constraint.h"
  53. #include "BKE_curve.h"
  54. #include "BKE_depsgraph.h"
  55. #include "BKE_DerivedMesh.h"
  56. #include "BKE_deform.h"
  57. #include "BKE_displist.h"
  58. #include "BKE_global.h"
  59. #include "BKE_idprop.h"
  60. #include "BKE_library.h"
  61. #include "BKE_lattice.h"
  62. #include "BKE_main.h"
  63. #include "BKE_object.h"
  64. #include "BKE_scene.h"
  65. #include "BIK_api.h"
  66. #include "BKE_sketch.h"
  67. /* **************** Generic Functions, data level *************** */
  68. bArmature *BKE_armature_add(const char *name)
  69. {
  70. bArmature *arm;
  71. arm = BKE_libblock_alloc(&G.main->armature, ID_AR, name);
  72. arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE;
  73. arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
  74. arm->layer = 1;
  75. return arm;
  76. }
  77. bArmature *BKE_armature_from_object(Object *ob)
  78. {
  79. if (ob->type == OB_ARMATURE)
  80. return (bArmature *)ob->data;
  81. return NULL;
  82. }
  83. void BKE_armature_bonelist_free(ListBase *lb)
  84. {
  85. Bone *bone;
  86. for (bone = lb->first; bone; bone = bone->next) {
  87. if (bone->prop) {
  88. IDP_FreeProperty(bone->prop);
  89. MEM_freeN(bone->prop);
  90. }
  91. BKE_armature_bonelist_free(&bone->childbase);
  92. }
  93. BLI_freelistN(lb);
  94. }
  95. void BKE_armature_free(bArmature *arm)
  96. {
  97. if (arm) {
  98. BKE_armature_bonelist_free(&arm->bonebase);
  99. /* free editmode data */
  100. if (arm->edbo) {
  101. BLI_freelistN(arm->edbo);
  102. MEM_freeN(arm->edbo);
  103. arm->edbo = NULL;
  104. }
  105. /* free sketch */
  106. if (arm->sketch) {
  107. freeSketch(arm->sketch);
  108. arm->sketch = NULL;
  109. }
  110. /* free animation data */
  111. if (arm->adt) {
  112. BKE_free_animdata(&arm->id);
  113. arm->adt = NULL;
  114. }
  115. }
  116. }
  117. void BKE_armature_make_local(bArmature *arm)
  118. {
  119. Main *bmain = G.main;
  120. int is_local = FALSE, is_lib = FALSE;
  121. Object *ob;
  122. if (arm->id.lib == NULL)
  123. return;
  124. if (arm->id.us == 1) {
  125. id_clear_lib_data(bmain, &arm->id);
  126. return;
  127. }
  128. for (ob = bmain->object.first; ob && ELEM(0, is_lib, is_local); ob = ob->id.next) {
  129. if (ob->data == arm) {
  130. if (ob->id.lib)
  131. is_lib = TRUE;
  132. else
  133. is_local = TRUE;
  134. }
  135. }
  136. if (is_local && is_lib == FALSE) {
  137. id_clear_lib_data(bmain, &arm->id);
  138. }
  139. else if (is_local && is_lib) {
  140. bArmature *arm_new = BKE_armature_copy(arm);
  141. arm_new->id.us = 0;
  142. /* Remap paths of new ID using old library as base. */
  143. BKE_id_lib_local_paths(bmain, arm->id.lib, &arm_new->id);
  144. for (ob = bmain->object.first; ob; ob = ob->id.next) {
  145. if (ob->data == arm) {
  146. if (ob->id.lib == NULL) {
  147. ob->data = arm_new;
  148. arm_new->id.us++;
  149. arm->id.us--;
  150. }
  151. }
  152. }
  153. }
  154. }
  155. static void copy_bonechildren(Bone *newBone, Bone *oldBone, Bone *actBone, Bone **newActBone)
  156. {
  157. Bone *curBone, *newChildBone;
  158. if (oldBone == actBone)
  159. *newActBone = newBone;
  160. if (oldBone->prop)
  161. newBone->prop = IDP_CopyProperty(oldBone->prop);
  162. /* Copy this bone's list */
  163. BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
  164. /* For each child in the list, update it's children */
  165. newChildBone = newBone->childbase.first;
  166. for (curBone = oldBone->childbase.first; curBone; curBone = curBone->next) {
  167. newChildBone->parent = newBone;
  168. copy_bonechildren(newChildBone, curBone, actBone, newActBone);
  169. newChildBone = newChildBone->next;
  170. }
  171. }
  172. bArmature *BKE_armature_copy(bArmature *arm)
  173. {
  174. bArmature *newArm;
  175. Bone *oldBone, *newBone;
  176. Bone *newActBone = NULL;
  177. newArm = BKE_libblock_copy(&arm->id);
  178. BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
  179. /* Duplicate the childrens' lists*/
  180. newBone = newArm->bonebase.first;
  181. for (oldBone = arm->bonebase.first; oldBone; oldBone = oldBone->next) {
  182. newBone->parent = NULL;
  183. copy_bonechildren(newBone, oldBone, arm->act_bone, &newActBone);
  184. newBone = newBone->next;
  185. }
  186. newArm->act_bone = newActBone;
  187. newArm->edbo = NULL;
  188. newArm->act_edbone = NULL;
  189. newArm->sketch = NULL;
  190. return newArm;
  191. }
  192. static Bone *get_named_bone_bonechildren(Bone *bone, const char *name)
  193. {
  194. Bone *curBone, *rbone;
  195. if (!strcmp(bone->name, name))
  196. return bone;
  197. for (curBone = bone->childbase.first; curBone; curBone = curBone->next) {
  198. rbone = get_named_bone_bonechildren(curBone, name);
  199. if (rbone)
  200. return rbone;
  201. }
  202. return NULL;
  203. }
  204. /* Walk the list until the bone is found */
  205. Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name)
  206. {
  207. Bone *bone = NULL, *curBone;
  208. if (!arm)
  209. return NULL;
  210. for (curBone = arm->bonebase.first; curBone; curBone = curBone->next) {
  211. bone = get_named_bone_bonechildren(curBone, name);
  212. if (bone)
  213. return bone;
  214. }
  215. return bone;
  216. }
  217. /* Finds the best possible extension to the name on a particular axis. (For renaming, check for
  218. * unique names afterwards) strip_number: removes number extensions (TODO: not used)
  219. * axis: the axis to name on
  220. * head/tail: the head/tail co-ordinate of the bone on the specified axis */
  221. int bone_autoside_name(char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
  222. {
  223. unsigned int len;
  224. char basename[MAXBONENAME] = "";
  225. char extension[5] = "";
  226. len = strlen(name);
  227. if (len == 0)
  228. return 0;
  229. BLI_strncpy(basename, name, sizeof(basename));
  230. /* Figure out extension to append:
  231. * - The extension to append is based upon the axis that we are working on.
  232. * - If head happens to be on 0, then we must consider the tail position as well to decide
  233. * which side the bone is on
  234. * -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
  235. * -> Otherwise, extension is added from perspective of object based on which side tail goes to
  236. * - If head is non-zero, extension is added from perspective of object based on side head is on
  237. */
  238. if (axis == 2) {
  239. /* z-axis - vertical (top/bottom) */
  240. if (IS_EQ(head, 0)) {
  241. if (tail < 0)
  242. strcpy(extension, "Bot");
  243. else if (tail > 0)
  244. strcpy(extension, "Top");
  245. }
  246. else {
  247. if (head < 0)
  248. strcpy(extension, "Bot");
  249. else
  250. strcpy(extension, "Top");
  251. }
  252. }
  253. else if (axis == 1) {
  254. /* y-axis - depth (front/back) */
  255. if (IS_EQ(head, 0)) {
  256. if (tail < 0)
  257. strcpy(extension, "Fr");
  258. else if (tail > 0)
  259. strcpy(extension, "Bk");
  260. }
  261. else {
  262. if (head < 0)
  263. strcpy(extension, "Fr");
  264. else
  265. strcpy(extension, "Bk");
  266. }
  267. }
  268. else {
  269. /* x-axis - horizontal (left/right) */
  270. if (IS_EQ(head, 0)) {
  271. if (tail < 0)
  272. strcpy(extension, "R");
  273. else if (tail > 0)
  274. strcpy(extension, "L");
  275. }
  276. else {
  277. if (head < 0)
  278. strcpy(extension, "R");
  279. /* XXX Shouldn't this be simple else, as for z and y axes? */
  280. else if (head > 0)
  281. strcpy(extension, "L");
  282. }
  283. }
  284. /* Simple name truncation
  285. * - truncate if there is an extension and it wouldn't be able to fit
  286. * - otherwise, just append to end
  287. */
  288. if (extension[0]) {
  289. int change = 1;
  290. while (change) { /* remove extensions */
  291. change = 0;
  292. if (len > 2 && basename[len - 2] == '.') {
  293. if (basename[len - 1] == 'L' || basename[len - 1] == 'R') { /* L R */
  294. basename[len - 2] = '\0';
  295. len -= 2;
  296. change = 1;
  297. }
  298. }
  299. else if (len > 3 && basename[len - 3] == '.') {
  300. if ((basename[len - 2] == 'F' && basename[len - 1] == 'r') || /* Fr */
  301. (basename[len - 2] == 'B' && basename[len - 1] == 'k')) /* Bk */
  302. {
  303. basename[len - 3] = '\0';
  304. len -= 3;
  305. change = 1;
  306. }
  307. }
  308. else if (len > 4 && basename[len - 4] == '.') {
  309. if ((basename[len - 3] == 'T' && basename[len - 2] == 'o' && basename[len - 1] == 'p') || /* Top */
  310. (basename[len - 3] == 'B' && basename[len - 2] == 'o' && basename[len - 1] == 't')) /* Bot */
  311. {
  312. basename[len - 4] = '\0';
  313. len -= 4;
  314. change = 1;
  315. }
  316. }
  317. }
  318. if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
  319. strncpy(name, basename, len - strlen(extension));
  320. }
  321. BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
  322. return 1;
  323. }
  324. else
  325. return 0;
  326. }
  327. /* ************* B-Bone support ******************* */
  328. #define MAX_BBONE_SUBDIV 32
  329. /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
  330. static void equalize_bezier(float *data, int desired)
  331. {
  332. float *fp, totdist, ddist, dist, fac1, fac2;
  333. float pdist[MAX_BBONE_SUBDIV + 1];
  334. float temp[MAX_BBONE_SUBDIV + 1][4];
  335. int a, nr;
  336. pdist[0] = 0.0f;
  337. for (a = 0, fp = data; a < MAX_BBONE_SUBDIV; a++, fp += 4) {
  338. copy_qt_qt(temp[a], fp);
  339. pdist[a + 1] = pdist[a] + len_v3v3(fp, fp + 4);
  340. }
  341. /* do last point */
  342. copy_qt_qt(temp[a], fp);
  343. totdist = pdist[a];
  344. /* go over distances and calculate new points */
  345. ddist = totdist / ((float)desired);
  346. nr = 1;
  347. for (a = 1, fp = data + 4; a < desired; a++, fp += 4) {
  348. dist = ((float)a) * ddist;
  349. /* we're looking for location (distance) 'dist' in the array */
  350. while ((dist >= pdist[nr]) && nr < MAX_BBONE_SUBDIV)
  351. nr++;
  352. fac1 = pdist[nr] - pdist[nr - 1];
  353. fac2 = pdist[nr] - dist;
  354. fac1 = fac2 / fac1;
  355. fac2 = 1.0f - fac1;
  356. fp[0] = fac1 * temp[nr - 1][0] + fac2 * temp[nr][0];
  357. fp[1] = fac1 * temp[nr - 1][1] + fac2 * temp[nr][1];
  358. fp[2] = fac1 * temp[nr - 1][2] + fac2 * temp[nr][2];
  359. fp[3] = fac1 * temp[nr - 1][3] + fac2 * temp[nr][3];
  360. }
  361. /* set last point, needed for orientation calculus */
  362. copy_qt_qt(fp, temp[MAX_BBONE_SUBDIV]);
  363. }
  364. /* returns pointer to static array, filled with desired amount of bone->segments elements */
  365. /* this calculation is done within unit bone space */
  366. Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest)
  367. {
  368. static Mat4 bbone_array[MAX_BBONE_SUBDIV];
  369. static Mat4 bbone_rest_array[MAX_BBONE_SUBDIV];
  370. Mat4 *result_array = (rest) ? bbone_rest_array : bbone_array;
  371. bPoseChannel *next, *prev;
  372. Bone *bone = pchan->bone;
  373. float h1[3], h2[3], scale[3], length, hlength1, hlength2, roll1 = 0.0f, roll2;
  374. float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
  375. float data[MAX_BBONE_SUBDIV + 1][4], *fp;
  376. int a, do_scale = 0;
  377. length = bone->length;
  378. if (!rest) {
  379. /* check if we need to take non-uniform bone scaling into account */
  380. scale[0] = len_v3(pchan->pose_mat[0]);
  381. scale[1] = len_v3(pchan->pose_mat[1]);
  382. scale[2] = len_v3(pchan->pose_mat[2]);
  383. if (fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
  384. unit_m4(scalemat);
  385. scalemat[0][0] = scale[0];
  386. scalemat[1][1] = scale[1];
  387. scalemat[2][2] = scale[2];
  388. invert_m4_m4(iscalemat, scalemat);
  389. length *= scale[1];
  390. do_scale = 1;
  391. }
  392. }
  393. hlength1 = bone->ease1 * length * 0.390464f; /* 0.5f * sqrt(2) * kappa, the handle length for near-perfect circles */
  394. hlength2 = bone->ease2 * length * 0.390464f;
  395. /* evaluate next and prev bones */
  396. if (bone->flag & BONE_CONNECTED)
  397. prev = pchan->parent;
  398. else
  399. prev = NULL;
  400. next = pchan->child;
  401. /* find the handle points, since this is inside bone space, the
  402. * first point = (0, 0, 0)
  403. * last point = (0, length, 0) */
  404. if (rest) {
  405. invert_m4_m4(imat, pchan->bone->arm_mat);
  406. }
  407. else if (do_scale) {
  408. copy_m4_m4(posemat, pchan->pose_mat);
  409. normalize_m4(posemat);
  410. invert_m4_m4(imat, posemat);
  411. }
  412. else
  413. invert_m4_m4(imat, pchan->pose_mat);
  414. if (prev) {
  415. float difmat[4][4], result[3][3], imat3[3][3];
  416. /* transform previous point inside this bone space */
  417. if (rest)
  418. copy_v3_v3(h1, prev->bone->arm_head);
  419. else
  420. copy_v3_v3(h1, prev->pose_head);
  421. mul_m4_v3(imat, h1);
  422. if (prev->bone->segments > 1) {
  423. /* if previous bone is B-bone too, use average handle direction */
  424. h1[1] -= length;
  425. roll1 = 0.0f;
  426. }
  427. normalize_v3(h1);
  428. mul_v3_fl(h1, -hlength1);
  429. if (prev->bone->segments == 1) {
  430. /* find the previous roll to interpolate */
  431. if (rest)
  432. mult_m4_m4m4(difmat, imat, prev->bone->arm_mat);
  433. else
  434. mult_m4_m4m4(difmat, imat, prev->pose_mat);
  435. copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
  436. vec_roll_to_mat3(h1, 0.0f, mat3); /* the result of vec_roll without roll */
  437. invert_m3_m3(imat3, mat3);
  438. mul_m3_m3m3(mat3, result, imat3); /* the matrix transforming vec_roll to desired roll */
  439. roll1 = (float)atan2(mat3[2][0], mat3[2][2]);
  440. }
  441. }
  442. else {
  443. h1[0] = 0.0f; h1[1] = hlength1; h1[2] = 0.0f;
  444. roll1 = 0.0f;
  445. }
  446. if (next) {
  447. float difmat[4][4], result[3][3], imat3[3][3];
  448. /* transform next point inside this bone space */
  449. if (rest)
  450. copy_v3_v3(h2, next->bone->arm_tail);
  451. else
  452. copy_v3_v3(h2, next->pose_tail);
  453. mul_m4_v3(imat, h2);
  454. /* if next bone is B-bone too, use average handle direction */
  455. if (next->bone->segments > 1)
  456. ;
  457. else
  458. h2[1] -= length;
  459. normalize_v3(h2);
  460. /* find the next roll to interpolate as well */
  461. if (rest)
  462. mult_m4_m4m4(difmat, imat, next->bone->arm_mat);
  463. else
  464. mult_m4_m4m4(difmat, imat, next->pose_mat);
  465. copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
  466. vec_roll_to_mat3(h2, 0.0f, mat3); /* the result of vec_roll without roll */
  467. invert_m3_m3(imat3, mat3);
  468. mul_m3_m3m3(mat3, imat3, result); /* the matrix transforming vec_roll to desired roll */
  469. roll2 = (float)atan2(mat3[2][0], mat3[2][2]);
  470. /* and only now negate handle */
  471. mul_v3_fl(h2, -hlength2);
  472. }
  473. else {
  474. h2[0] = 0.0f; h2[1] = -hlength2; h2[2] = 0.0f;
  475. roll2 = 0.0;
  476. }
  477. /* make curve */
  478. if (bone->segments > MAX_BBONE_SUBDIV)
  479. bone->segments = MAX_BBONE_SUBDIV;
  480. BKE_curve_forward_diff_bezier(0.0f, h1[0], h2[0], 0.0f, data[0], MAX_BBONE_SUBDIV, 4 * sizeof(float));
  481. BKE_curve_forward_diff_bezier(0.0f, h1[1], length + h2[1], length, data[0] + 1, MAX_BBONE_SUBDIV, 4 * sizeof(float));
  482. BKE_curve_forward_diff_bezier(0.0f, h1[2], h2[2], 0.0f, data[0] + 2, MAX_BBONE_SUBDIV, 4 * sizeof(float));
  483. BKE_curve_forward_diff_bezier(roll1, roll1 + 0.390464f * (roll2 - roll1), roll2 - 0.390464f * (roll2 - roll1), roll2, data[0] + 3, MAX_BBONE_SUBDIV, 4 * sizeof(float));
  484. equalize_bezier(data[0], bone->segments); /* note: does stride 4! */
  485. /* make transformation matrices for the segments for drawing */
  486. for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) {
  487. sub_v3_v3v3(h1, fp + 4, fp);
  488. vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */
  489. copy_m4_m3(result_array[a].mat, mat3);
  490. copy_v3_v3(result_array[a].mat[3], fp);
  491. if (do_scale) {
  492. /* correct for scaling when this matrix is used in scaled space */
  493. mul_serie_m4(result_array[a].mat, iscalemat, result_array[a].mat, scalemat, NULL, NULL, NULL, NULL, NULL);
  494. }
  495. }
  496. return result_array;
  497. }
  498. /* ************ Armature Deform ******************* */
  499. typedef struct bPoseChanDeform {
  500. Mat4 *b_bone_mats;
  501. DualQuat *dual_quat;
  502. DualQuat *b_bone_dual_quats;
  503. } bPoseChanDeform;
  504. static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, int use_quaternion)
  505. {
  506. Bone *bone = pchan->bone;
  507. Mat4 *b_bone = b_bone_spline_setup(pchan, 0);
  508. Mat4 *b_bone_rest = b_bone_spline_setup(pchan, 1);
  509. Mat4 *b_bone_mats;
  510. DualQuat *b_bone_dual_quats = NULL;
  511. float tmat[4][4] = MAT4_UNITY;
  512. int a;
  513. /* allocate b_bone matrices and dual quats */
  514. b_bone_mats = MEM_mallocN((1 + bone->segments) * sizeof(Mat4), "BBone defmats");
  515. pdef_info->b_bone_mats = b_bone_mats;
  516. if (use_quaternion) {
  517. b_bone_dual_quats = MEM_mallocN((bone->segments) * sizeof(DualQuat), "BBone dqs");
  518. pdef_info->b_bone_dual_quats = b_bone_dual_quats;
  519. }
  520. /* first matrix is the inverse arm_mat, to bring points in local bone space
  521. * for finding out which segment it belongs to */
  522. invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
  523. /* then we make the b_bone_mats:
  524. * - first transform to local bone space
  525. * - translate over the curve to the bbone mat space
  526. * - transform with b_bone matrix
  527. * - transform back into global space */
  528. for (a = 0; a < bone->segments; a++) {
  529. invert_m4_m4(tmat, b_bone_rest[a].mat);
  530. mul_serie_m4(b_bone_mats[a + 1].mat, pchan->chan_mat, bone->arm_mat, b_bone[a].mat, tmat, b_bone_mats[0].mat,
  531. NULL, NULL, NULL);
  532. if (use_quaternion)
  533. mat4_to_dquat(&b_bone_dual_quats[a], bone->arm_mat, b_bone_mats[a + 1].mat);
  534. }
  535. }
  536. static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], DualQuat *dq, float defmat[][3])
  537. {
  538. Mat4 *b_bone = pdef_info->b_bone_mats;
  539. float (*mat)[4] = b_bone[0].mat;
  540. float segment, y;
  541. int a;
  542. /* need to transform co back to bonespace, only need y */
  543. y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1];
  544. /* now calculate which of the b_bones are deforming this */
  545. segment = bone->length / ((float)bone->segments);
  546. a = (int)(y / segment);
  547. /* note; by clamping it extends deform at endpoints, goes best with
  548. * straight joints in restpos. */
  549. CLAMP(a, 0, bone->segments - 1);
  550. if (dq) {
  551. copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
  552. }
  553. else {
  554. mul_m4_v3(b_bone[a + 1].mat, co);
  555. if (defmat) {
  556. copy_m3_m4(defmat, b_bone[a + 1].mat);
  557. }
  558. }
  559. }
  560. /* using vec with dist to bone b1 - b2 */
  561. float distfactor_to_bone(const float vec[3], const float b1[3], const float b2[3], float rad1, float rad2, float rdist)
  562. {
  563. float dist = 0.0f;
  564. float bdelta[3];
  565. float pdelta[3];
  566. float hsqr, a, l, rad;
  567. sub_v3_v3v3(bdelta, b2, b1);
  568. l = normalize_v3(bdelta);
  569. sub_v3_v3v3(pdelta, vec, b1);
  570. a = dot_v3v3(bdelta, pdelta);
  571. hsqr = dot_v3v3(pdelta, pdelta);
  572. if (a < 0.0f) {
  573. /* If we're past the end of the bone, do a spherical field attenuation thing */
  574. dist = len_squared_v3v3(b1, vec);
  575. rad = rad1;
  576. }
  577. else if (a > l) {
  578. /* If we're past the end of the bone, do a spherical field attenuation thing */
  579. dist = len_squared_v3v3(b2, vec);
  580. rad = rad2;
  581. }
  582. else {
  583. dist = (hsqr - (a * a));
  584. if (l != 0.0f) {
  585. rad = a / l;
  586. rad = rad * rad2 + (1.0f - rad) * rad1;
  587. }
  588. else
  589. rad = rad1;
  590. }
  591. a = rad * rad;
  592. if (dist < a)
  593. return 1.0f;
  594. else {
  595. l = rad + rdist;
  596. l *= l;
  597. if (rdist == 0.0f || dist >= l)
  598. return 0.0f;
  599. else {
  600. a = sqrtf(dist) - rad;
  601. return 1.0f - (a * a) / (rdist * rdist);
  602. }
  603. }
  604. }
  605. static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[][3], float mat[][3])
  606. {
  607. float wmat[3][3];
  608. if (pchan->bone->segments > 1)
  609. copy_m3_m3(wmat, bbonemat);
  610. else
  611. copy_m3_m4(wmat, pchan->chan_mat);
  612. mul_m3_fl(wmat, weight);
  613. add_m3_m3m3(mat, mat, wmat);
  614. }
  615. static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float vec[3], DualQuat *dq,
  616. float mat[][3], const float co[3])
  617. {
  618. Bone *bone = pchan->bone;
  619. float fac, contrib = 0.0;
  620. float cop[3], bbonemat[3][3];
  621. DualQuat bbonedq;
  622. if (bone == NULL)
  623. return 0.0f;
  624. copy_v3_v3(cop, co);
  625. fac = distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
  626. if (fac > 0.0f) {
  627. fac *= bone->weight;
  628. contrib = fac;
  629. if (contrib > 0.0f) {
  630. if (vec) {
  631. if (bone->segments > 1)
  632. /* applies on cop and bbonemat */
  633. b_bone_deform(pdef_info, bone, cop, NULL, (mat) ? bbonemat : NULL);
  634. else
  635. mul_m4_v3(pchan->chan_mat, cop);
  636. /* Make this a delta from the base position */
  637. sub_v3_v3(cop, co);
  638. madd_v3_v3fl(vec, cop, fac);
  639. if (mat)
  640. pchan_deform_mat_add(pchan, fac, bbonemat, mat);
  641. }
  642. else {
  643. if (bone->segments > 1) {
  644. b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
  645. add_weighted_dq_dq(dq, &bbonedq, fac);
  646. }
  647. else
  648. add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
  649. }
  650. }
  651. }
  652. return contrib;
  653. }
  654. static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float vec[3], DualQuat *dq,
  655. float mat[][3], const float co[3], float *contrib)
  656. {
  657. float cop[3], bbonemat[3][3];
  658. DualQuat bbonedq;
  659. if (!weight)
  660. return;
  661. copy_v3_v3(cop, co);
  662. if (vec) {
  663. if (pchan->bone->segments > 1)
  664. /* applies on cop and bbonemat */
  665. b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat) ? bbonemat : NULL);
  666. else
  667. mul_m4_v3(pchan->chan_mat, cop);
  668. vec[0] += (cop[0] - co[0]) * weight;
  669. vec[1] += (cop[1] - co[1]) * weight;
  670. vec[2] += (cop[2] - co[2]) * weight;
  671. if (mat)
  672. pchan_deform_mat_add(pchan, weight, bbonemat, mat);
  673. }
  674. else {
  675. if (pchan->bone->segments > 1) {
  676. b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
  677. add_weighted_dq_dq(dq, &bbonedq, weight);
  678. }
  679. else
  680. add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
  681. }
  682. (*contrib) += weight;
  683. }
  684. void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3],
  685. float (*defMats)[3][3], int numVerts, int deformflag,
  686. float (*prevCos)[3], const char *defgrp_name)
  687. {
  688. bPoseChanDeform *pdef_info_array;
  689. bPoseChanDeform *pdef_info = NULL;
  690. bArmature *arm = armOb->data;
  691. bPoseChannel *pchan, **defnrToPC = NULL;
  692. int *defnrToPCIndex = NULL;
  693. MDeformVert *dverts = NULL;
  694. bDeformGroup *dg;
  695. DualQuat *dualquats = NULL;
  696. float obinv[4][4], premat[4][4], postmat[4][4];
  697. const short use_envelope = deformflag & ARM_DEF_ENVELOPE;
  698. const short use_quaternion = deformflag & ARM_DEF_QUATERNION;
  699. const short invert_vgroup = deformflag & ARM_DEF_INVERT_VGROUP;
  700. int defbase_tot = 0; /* safety for vertexgroup index overflow */
  701. int i, target_totvert = 0; /* safety for vertexgroup overflow */
  702. int use_dverts = FALSE;
  703. int armature_def_nr;
  704. int totchan;
  705. if (arm->edbo) return;
  706. invert_m4_m4(obinv, target->obmat);
  707. copy_m4_m4(premat, target->obmat);
  708. mult_m4_m4m4(postmat, obinv, armOb->obmat);
  709. invert_m4_m4(premat, postmat);
  710. /* bone defmats are already in the channels, chan_mat */
  711. /* initialize B_bone matrices and dual quaternions */
  712. totchan = BLI_countlist(&armOb->pose->chanbase);
  713. if (use_quaternion) {
  714. dualquats = MEM_callocN(sizeof(DualQuat) * totchan, "dualquats");
  715. }
  716. pdef_info_array = MEM_callocN(sizeof(bPoseChanDeform) * totchan, "bPoseChanDeform");
  717. totchan = 0;
  718. pdef_info = pdef_info_array;
  719. for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
  720. if (!(pchan->bone->flag & BONE_NO_DEFORM)) {
  721. if (pchan->bone->segments > 1)
  722. pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
  723. if (use_quaternion) {
  724. pdef_info->dual_quat = &dualquats[totchan++];
  725. mat4_to_dquat(pdef_info->dual_quat, pchan->bone->arm_mat, pchan->chan_mat);
  726. }
  727. }
  728. }
  729. /* get the def_nr for the overall armature vertex group if present */
  730. armature_def_nr = defgroup_name_index(target, defgrp_name);
  731. if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
  732. defbase_tot = BLI_countlist(&target->defbase);
  733. if (target->type == OB_MESH) {
  734. Mesh *me = target->data;
  735. dverts = me->dvert;
  736. if (dverts)
  737. target_totvert = me->totvert;
  738. }
  739. else {
  740. Lattice *lt = target->data;
  741. dverts = lt->dvert;
  742. if (dverts)
  743. target_totvert = lt->pntsu * lt->pntsv * lt->pntsw;
  744. }
  745. }
  746. /* get a vertex-deform-index to posechannel array */
  747. if (deformflag & ARM_DEF_VGROUP) {
  748. if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
  749. /* if we have a DerivedMesh, only use dverts if it has them */
  750. if (dm) {
  751. use_dverts = (dm->getVertData(dm, 0, CD_MDEFORMVERT) != NULL);
  752. }
  753. else if (dverts) {
  754. use_dverts = TRUE;
  755. }
  756. if (use_dverts) {
  757. defnrToPC = MEM_callocN(sizeof(*defnrToPC) * defbase_tot, "defnrToBone");
  758. defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * defbase_tot, "defnrToIndex");
  759. for (i = 0, dg = target->defbase.first; dg; i++, dg = dg->next) {
  760. defnrToPC[i] = BKE_pose_channel_find_name(armOb->pose, dg->name);
  761. /* exclude non-deforming bones */
  762. if (defnrToPC[i]) {
  763. if (defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
  764. defnrToPC[i] = NULL;
  765. }
  766. else {
  767. defnrToPCIndex[i] = BLI_findindex(&armOb->pose->chanbase, defnrToPC[i]);
  768. }
  769. }
  770. }
  771. }
  772. }
  773. }
  774. for (i = 0; i < numVerts; i++) {
  775. MDeformVert *dvert;
  776. DualQuat sumdq, *dq = NULL;
  777. float *co, dco[3];
  778. float sumvec[3], summat[3][3];
  779. float *vec = NULL, (*smat)[3] = NULL;
  780. float contrib = 0.0f;
  781. float armature_weight = 1.0f; /* default to 1 if no overall def group */
  782. float prevco_weight = 1.0f; /* weight for optional cached vertexcos */
  783. if (use_quaternion) {
  784. memset(&sumdq, 0, sizeof(DualQuat));
  785. dq = &sumdq;
  786. }
  787. else {
  788. sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
  789. vec = sumvec;
  790. if (defMats) {
  791. zero_m3(summat);
  792. smat = summat;
  793. }
  794. }
  795. if (use_dverts || armature_def_nr >= 0) {
  796. if (dm)
  797. dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
  798. else if (dverts && i < target_totvert)
  799. dvert = dverts + i;
  800. else
  801. dvert = NULL;
  802. }
  803. else
  804. dvert = NULL;
  805. if (armature_def_nr >= 0 && dvert) {
  806. armature_weight = defvert_find_weight(dvert, armature_def_nr);
  807. if (invert_vgroup)
  808. armature_weight = 1.0f - armature_weight;
  809. /* hackish: the blending factor can be used for blending with prevCos too */
  810. if (prevCos) {
  811. prevco_weight = armature_weight;
  812. armature_weight = 1.0f;
  813. }
  814. }
  815. /* check if there's any point in calculating for this vert */
  816. if (armature_weight == 0.0f)
  817. continue;
  818. /* get the coord we work on */
  819. co = prevCos ? prevCos[i] : vertexCos[i];
  820. /* Apply the object's matrix */
  821. mul_m4_v3(premat, co);
  822. if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */
  823. MDeformWeight *dw = dvert->dw;
  824. int deformed = 0;
  825. unsigned int j;
  826. for (j = dvert->totweight; j != 0; j--, dw++) {
  827. const int index = dw->def_nr;
  828. if (index >= 0 && index < defbase_tot && (pchan = defnrToPC[index])) {
  829. float weight = dw->weight;
  830. Bone *bone = pchan->bone;
  831. pdef_info = pdef_info_array + defnrToPCIndex[index];
  832. deformed = 1;
  833. if (bone && bone->flag & BONE_MULT_VG_ENV) {
  834. weight *= distfactor_to_bone(co, bone->arm_head, bone->arm_tail,
  835. bone->rad_head, bone->rad_tail, bone->dist);
  836. }
  837. pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
  838. }
  839. }
  840. /* if there are vertexgroups but not groups with bones
  841. * (like for softbody groups) */
  842. if (deformed == 0 && use_envelope) {
  843. pdef_info = pdef_info_array;
  844. for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
  845. if (!(pchan->bone->flag & BONE_NO_DEFORM))
  846. contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
  847. }
  848. }
  849. }
  850. else if (use_envelope) {
  851. pdef_info = pdef_info_array;
  852. for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
  853. if (!(pchan->bone->flag & BONE_NO_DEFORM))
  854. contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
  855. }
  856. }
  857. /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
  858. if (contrib > 0.0001f) {
  859. if (use_quaternion) {
  860. normalize_dq(dq, contrib);
  861. if (armature_weight != 1.0f) {
  862. copy_v3_v3(dco, co);
  863. mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq);
  864. sub_v3_v3(dco, co);
  865. mul_v3_fl(dco, armature_weight);
  866. add_v3_v3(co, dco);
  867. }
  868. else
  869. mul_v3m3_dq(co, (defMats) ? summat : NULL, dq);
  870. smat = summat;
  871. }
  872. else {
  873. mul_v3_fl(vec, armature_weight / contrib);
  874. add_v3_v3v3(co, vec, co);
  875. }
  876. if (defMats) {
  877. float pre[3][3], post[3][3], tmpmat[3][3];
  878. copy_m3_m4(pre, premat);
  879. copy_m3_m4(post, postmat);
  880. copy_m3_m3(tmpmat, defMats[i]);
  881. if (!use_quaternion) /* quaternion already is scale corrected */
  882. mul_m3_fl(smat, armature_weight / contrib);
  883. mul_serie_m3(defMats[i], tmpmat, pre, smat, post, NULL, NULL, NULL, NULL);
  884. }
  885. }
  886. /* always, check above code */
  887. mul_m4_v3(postmat, co);
  888. /* interpolate with previous modifier position using weight group */
  889. if (prevCos) {
  890. float mw = 1.0f - prevco_weight;
  891. vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0];
  892. vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1];
  893. vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2];
  894. }
  895. }
  896. if (dualquats)
  897. MEM_freeN(dualquats);
  898. if (defnrToPC)
  899. MEM_freeN(defnrToPC);
  900. if (defnrToPCIndex)
  901. MEM_freeN(defnrToPCIndex);
  902. /* free B_bone matrices */
  903. pdef_info = pdef_info_array;
  904. for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
  905. if (pdef_info->b_bone_mats)
  906. MEM_freeN(pdef_info->b_bone_mats);
  907. if (pdef_info->b_bone_dual_quats)
  908. MEM_freeN(pdef_info->b_bone_dual_quats);
  909. }
  910. MEM_freeN(pdef_info_array);
  911. }
  912. /* ************ END Armature Deform ******************* */
  913. void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[][4], int UNUSED(root),
  914. int UNUSED(posed))
  915. {
  916. copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
  917. }
  918. /* **************** Space to Space API ****************** */
  919. /* Convert World-Space Matrix to Pose-Space Matrix */
  920. void BKE_armature_mat_world_to_pose(Object *ob, float inmat[][4], float outmat[][4])
  921. {
  922. float obmat[4][4];
  923. /* prevent crashes */
  924. if (ob == NULL)
  925. return;
  926. /* get inverse of (armature) object's matrix */
  927. invert_m4_m4(obmat, ob->obmat);
  928. /* multiply given matrix by object's-inverse to find pose-space matrix */
  929. mult_m4_m4m4(outmat, inmat, obmat);
  930. }
  931. /* Convert World-Space Location to Pose-Space Location
  932. * NOTE: this cannot be used to convert to pose-space location of the supplied
  933. * pose-channel into its local space (i.e. 'visual'-keyframing) */
  934. void BKE_armature_loc_world_to_pose(Object *ob, const float inloc[3], float outloc[3])
  935. {
  936. float xLocMat[4][4] = MAT4_UNITY;
  937. float nLocMat[4][4];
  938. /* build matrix for location */
  939. copy_v3_v3(xLocMat[3], inloc);
  940. /* get bone-space cursor matrix and extract location */
  941. BKE_armature_mat_world_to_pose(ob, xLocMat, nLocMat);
  942. copy_v3_v3(outloc, nLocMat[3]);
  943. }
  944. /* Simple helper, computes the offset bone matrix.
  945. * offs_bone = yoffs(b-1) + root(b) + bonemat(b).
  946. * Not exported, as it is only used in this file currently... */
  947. static void get_offset_bone_mat(Bone *bone, float offs_bone[][4])
  948. {
  949. if (!bone->parent)
  950. return;
  951. /* Bone transform itself. */
  952. copy_m4_m3(offs_bone, bone->bone_mat);
  953. /* The bone's root offset (is in the parent's coordinate system). */
  954. copy_v3_v3(offs_bone[3], bone->head);
  955. /* Get the length translation of parent (length along y axis). */
  956. offs_bone[3][1] += bone->parent->length;
  957. }
  958. /* Construct the matrices (rot/scale and loc) to apply the PoseChannels into the armature (object) space.
  959. * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the
  960. * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
  961. * ...function.
  962. *
  963. * This allows to get the transformations of a bone in its object space, *before* constraints (and IK)
  964. * get applied (used by pose evaluation code).
  965. * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale
  966. * in object space (used by interactive transform, and snapping code).
  967. *
  968. * Note that, with the HINGE/NO_SCALE/NO_LOCAL_LOCATION options, the location matrix
  969. * will differ from the rotation/scale matrix...
  970. *
  971. * NOTE: This cannot be used to convert to pose-space transforms of the supplied
  972. * pose-channel into its local space (i.e. 'visual'-keyframing).
  973. * (note: I don't understand that, so I keep it :p --mont29).
  974. */
  975. void BKE_pchan_to_pose_mat(bPoseChannel *pchan, float rotscale_mat[][4], float loc_mat[][4])
  976. {
  977. Bone *bone, *parbone;
  978. bPoseChannel *parchan;
  979. /* set up variables for quicker access below */
  980. bone = pchan->bone;
  981. parbone = bone->parent;
  982. parchan = pchan->parent;
  983. if (parchan) {
  984. float offs_bone[4][4];
  985. /* yoffs(b-1) + root(b) + bonemat(b). */
  986. get_offset_bone_mat(bone, offs_bone);
  987. /* Compose the rotscale matrix for this bone. */
  988. if ((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) {
  989. /* Parent rest rotation and scale. */
  990. mult_m4_m4m4(rotscale_mat, parbone->arm_mat, offs_bone);
  991. }
  992. else if (bone->flag & BONE_HINGE) {
  993. /* Parent rest rotation and pose scale. */
  994. float tmat[4][4], tscale[3];
  995. /* Extract the scale of the parent pose matrix. */
  996. mat4_to_size(tscale, parchan->pose_mat);
  997. size_to_mat4(tmat, tscale);
  998. /* Applies the parent pose scale to the rest matrix. */
  999. mult_m4_m4m4(tmat, tmat, parbone->arm_mat);
  1000. mult_m4_m4m4(rotscale_mat, tmat, offs_bone);
  1001. }
  1002. else if (bone->flag & BONE_NO_SCALE) {
  1003. /* Parent pose rotation and rest scale (i.e. no scaling). */
  1004. float tmat[4][4];
  1005. copy_m4_m4(tmat, parchan->pose_mat);
  1006. normalize_m4(tmat);
  1007. mult_m4_m4m4(rotscale_mat, tmat, offs_bone);
  1008. }
  1009. else
  1010. mult_m4_m4m4(rotscale_mat, parchan->pose_mat, offs_bone);
  1011. /* Compose the loc matrix for this bone. */
  1012. /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */
  1013. /* In this case, use the object's space *orientation*. */
  1014. if (bone->flag & BONE_NO_LOCAL_LOCATION) {
  1015. /* XXX I'm sure that code can be simplified! */
  1016. float bone_loc[4][4], bone_rotscale[3][3], tmat4[4][4], tmat3[3][3];
  1017. unit_m4(bone_loc);
  1018. unit_m4(loc_mat);
  1019. unit_m4(tmat4);
  1020. mul_v3_m4v3(bone_loc[3], parchan->pose_mat, offs_bone[3]);
  1021. unit_m3(bone_rotscale);
  1022. copy_m3_m4(tmat3, parchan->pose_mat);
  1023. mul_m3_m3m3(bone_rotscale, tmat3, bone_rotscale);
  1024. copy_m4_m3(tmat4, bone_rotscale);
  1025. mult_m4_m4m4(loc_mat, bone_loc, tmat4);
  1026. }
  1027. /* Those flags do not affect position, use plain parent transform space! */
  1028. else if (bone->flag & (BONE_HINGE | BONE_NO_SCALE)) {
  1029. mult_m4_m4m4(loc_mat, parchan->pose_mat, offs_bone);
  1030. }
  1031. /* Else (i.e. default, usual case), just use the same matrix for rotation/scaling, and location. */
  1032. else
  1033. copy_m4_m4(loc_mat, rotscale_mat);
  1034. }
  1035. /* Root bones. */
  1036. else {
  1037. /* Rotation/scaling. */
  1038. copy_m4_m4(rotscale_mat, pchan->bone->arm_mat);
  1039. /* Translation. */
  1040. if (pchan->bone->flag & BONE_NO_LOCAL_LOCATION) {
  1041. /* Translation of arm_mat, without the rotation. */
  1042. unit_m4(loc_mat);
  1043. copy_v3_v3(loc_mat[3], pchan->bone->arm_mat[3]);
  1044. }
  1045. else
  1046. copy_m4_m4(loc_mat, rotscale_mat);
  1047. }
  1048. }
  1049. /* Convert Pose-Space Matrix to Bone-Space Matrix.
  1050. * NOTE: this cannot be used to convert to pose-space transforms of the supplied
  1051. * pose-channel into its local space (i.e. 'visual'-keyframing) */
  1052. void BKE_armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
  1053. {
  1054. float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
  1055. /* Security, this allows to call with inmat == outmat! */
  1056. copy_m4_m4(inmat_, inmat);
  1057. BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
  1058. invert_m4(rotscale_mat);
  1059. invert_m4(loc_mat);
  1060. mult_m4_m4m4(outmat, rotscale_mat, inmat_);
  1061. mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
  1062. }
  1063. /* Convert Bone-Space Matrix to Pose-Space Matrix. */
  1064. void BKE_armature_mat_bone_to_pose(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
  1065. {
  1066. float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
  1067. /* Security, this allows to call with inmat == outmat! */
  1068. copy_m4_m4(inmat_, inmat);
  1069. BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
  1070. mult_m4_m4m4(outmat, rotscale_mat, inmat_);
  1071. mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
  1072. }
  1073. /* Convert Pose-Space Location to Bone-Space Location
  1074. * NOTE: this cannot be used to convert to pose-space location of the supplied
  1075. * pose-channel into its local space (i.e. 'visual'-keyframing) */
  1076. void BKE_armature_loc_pose_to_bone(bPoseChannel *pchan, const float inloc[3], float outloc[3])
  1077. {
  1078. float xLocMat[4][4] = MAT4_UNITY;
  1079. float nLocMat[4][4];
  1080. /* build matrix for location */
  1081. copy_v3_v3(xLocMat[3], inloc);
  1082. /* get bone-space cursor matrix and extract location */
  1083. BKE_armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
  1084. copy_v3_v3(outloc, nLocMat[3]);
  1085. }
  1086. void BKE_armature_mat_pose_to_bone_ex(Object *ob, bPoseChannel *pchan, float inmat[][4], float outmat[][4])
  1087. {
  1088. bPoseChannel work_pchan = *pchan;
  1089. /* recalculate pose matrix with only parent transformations,
  1090. * bone loc/sca/rot is ignored, scene and frame are not used. */
  1091. BKE_pose_where_is_bone(NULL, ob, &work_pchan, 0.0f, FALSE);
  1092. /* find the matrix, need to remove the bone transforms first so this is
  1093. * calculated as a matrix to set rather then a difference ontop of whats
  1094. * already there. */
  1095. unit_m4(outmat);
  1096. BKE_pchan_apply_mat4(&work_pchan, outmat, FALSE);
  1097. BKE_armature_mat_pose_to_bone(&work_pchan, inmat, outmat);
  1098. }
  1099. /* same as BKE_object_mat3_to_rot() */
  1100. void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, float mat[][3], short use_compat)
  1101. {
  1102. switch (pchan->rotmode) {
  1103. case ROT_MODE_QUAT:
  1104. mat3_to_quat(pchan->quat, mat);
  1105. break;
  1106. case ROT_MODE_AXISANGLE:
  1107. mat3_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
  1108. break;
  1109. default: /* euler */
  1110. if (use_compat)
  1111. mat3_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
  1112. else
  1113. mat3_to_eulO(pchan->eul, pchan->rotmode, mat);
  1114. }
  1115. }
  1116. /* Apply a 4x4 matrix to the pose bone,
  1117. * similar to BKE_object_apply_mat4() */
  1118. void BKE_pchan_apply_mat4(bPoseChannel *pchan, float mat[][4], short use_compat)
  1119. {
  1120. float rot[3][3];
  1121. mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
  1122. BKE_pchan_mat3_to_rot(pchan, rot, use_compat);
  1123. }
  1124. /* Remove rest-position effects from pose-transform for obtaining
  1125. * 'visual' transformation of pose-channel.
  1126. * (used by the Visual-Keyframing stuff) */
  1127. void BKE_armature_mat_pose_to_delta(float delta_mat[][4], float pose_mat[][4], float arm_mat[][4])
  1128. {
  1129. float imat[4][4];
  1130. invert_m4_m4(imat, arm_mat);
  1131. mult_m4_m4m4(delta_mat, imat, pose_mat);
  1132. }
  1133. /* **************** Rotation Mode Conversions ****************************** */
  1134. /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
  1135. /* Called from RNA when rotation mode changes
  1136. * - the result should be that the rotations given in the provided pointers have had conversions
  1137. * applied (as appropriate), such that the rotation of the element hasn't 'visually' changed */
  1138. void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
  1139. {
  1140. /* check if any change - if so, need to convert data */
  1141. if (newMode > 0) { /* to euler */
  1142. if (oldMode == ROT_MODE_AXISANGLE) {
  1143. /* axis-angle to euler */
  1144. axis_angle_to_eulO(eul, newMode, axis, *angle);
  1145. }
  1146. else if (oldMode == ROT_MODE_QUAT) {
  1147. /* quat to euler */
  1148. normalize_qt(quat);
  1149. quat_to_eulO(eul, newMode, quat);
  1150. }
  1151. /* else { no conversion needed } */
  1152. }
  1153. else if (newMode == ROT_MODE_QUAT) { /* to quat */
  1154. if (oldMode == ROT_MODE_AXISANGLE) {
  1155. /* axis angle to quat */
  1156. axis_angle_to_quat(quat, axis, *angle);
  1157. }
  1158. else if (oldMode > 0) {
  1159. /* euler to quat */
  1160. eulO_to_quat(quat, eul, oldMode);
  1161. }
  1162. /* else { no conversion needed } */
  1163. }
  1164. else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
  1165. if (oldMode > 0) {
  1166. /* euler to axis angle */
  1167. eulO_to_axis_angle(axis, angle, eul, oldMode);
  1168. }
  1169. else if (oldMode == ROT_MODE_QUAT) {
  1170. /* quat to axis angle */
  1171. normalize_qt(quat);
  1172. quat_to_axis_angle(axis, angle, quat);
  1173. }
  1174. /* when converting to axis-angle, we need a special exception for the case when there is no axis */
  1175. if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
  1176. /* for now, rotate around y-axis then (so that it simply becomes the roll) */
  1177. axis[1] = 1.0f;
  1178. }
  1179. }
  1180. }
  1181. /* **************** The new & simple (but OK!) armature evaluation ********* */
  1182. /* ****************** And how it works! ****************************************
  1183. *
  1184. * This is the bone transformation trick; they're hierarchical so each bone(b)
  1185. * is in the coord system of bone(b-1):
  1186. *
  1187. * arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
  1188. *
  1189. * -> yoffs is just the y axis translation in parent's coord system
  1190. * -> d_root is the translation of the bone root, also in parent's coord system
  1191. *
  1192. * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
  1193. *
  1194. * we then - in init deform - store the deform in chan_mat, such that:
  1195. *
  1196. * pose_mat(b)= arm_mat(b) * chan_mat(b)
  1197. *
  1198. * *************************************************************************** */
  1199. /* Computes vector and roll based on a rotation.
  1200. * "mat" must contain only a rotation, and no scaling. */
  1201. void mat3_to_vec_roll(float mat[][3], float vec[3], float *roll)
  1202. {
  1203. if (vec)
  1204. copy_v3_v3(vec, mat[1]);
  1205. if (roll) {
  1206. float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
  1207. vec_roll_to_mat3(mat[1], 0.0f, vecmat);
  1208. invert_m3_m3(vecmatinv, vecmat);
  1209. mul_m3_m3m3(rollmat, vecmatinv, mat);
  1210. *roll = (float)atan2(rollmat[2][0], rollmat[2][2]);
  1211. }
  1212. }
  1213. /* Calculates the rest matrix of a bone based
  1214. * On its vector and a roll around that vector */
  1215. void vec_roll_to_mat3(const float vec[3], const float roll, float mat[][3])
  1216. {
  1217. float nor[3], axis[3], target[3] = {0, 1, 0};
  1218. float theta;
  1219. float rMatrix[3][3], bMatrix[3][3];
  1220. normalize_v3_v3(nor, vec);
  1221. /* Find Axis & Amount for bone matrix */
  1222. cross_v3_v3v3(axis, target, nor);
  1223. /* was 0.0000000000001, caused bug [#23954], smaller values give unstable
  1224. * roll when toggling editmode.
  1225. *
  1226. * was 0.00001, causes bug [#27675], with 0.00000495,
  1227. * so a value inbetween these is needed.
  1228. *
  1229. * was 0.000001, causes bug [#30438] (which is same as [#27675, imho).
  1230. * Reseting it to org value seems to cause no more [#23954]...
  1231. *
  1232. * was 0.0000000000001, caused bug [#31333], smaller values give unstable
  1233. * roll when toggling editmode again...
  1234. * No good value here, trying 0.000000001 as best compromize. :/
  1235. */
  1236. if (dot_v3v3(axis, axis) > 1.0e-9f) {
  1237. /* if nor is *not* a multiple of target ... */
  1238. normalize_v3(axis);
  1239. theta = angle_normalized_v3v3(target, nor);
  1240. /* Make Bone matrix*/
  1241. vec_rot_to_mat3(bMatrix, axis, theta);
  1242. }
  1243. else {
  1244. /* if nor is a multiple of target ... */
  1245. float updown;
  1246. /* point same direction, or opposite? */
  1247. updown = (dot_v3v3(target, nor) > 0) ? 1.0f : -1.0f;
  1248. /* I think this should work... */
  1249. bMatrix[0][0] = updown; bMatrix[0][1] = 0.0; bMatrix[0][2] = 0.0;
  1250. bMatrix[1][0] = 0.0; bMatrix[1][1] = updown; bMatrix[1][2] = 0.0;
  1251. bMatrix[2][0] = 0.0; bMatrix[2][1] = 0.0; bMatrix[2][2] = 1.0;
  1252. }
  1253. /* Make Roll matrix */
  1254. vec_rot_to_mat3(rMatrix, nor, roll);
  1255. /* Combine and output result */
  1256. mul_m3_m3m3(mat, rMatrix, bMatrix);
  1257. }
  1258. /* recursive part, calculates restposition of entire tree of children */
  1259. /* used by exiting editmode too */
  1260. void BKE_armature_where_is_bone(Bone *bone, Bone *prevbone)
  1261. {
  1262. float vec[3];
  1263. /* Bone Space */
  1264. sub_v3_v3v3(vec, bone->tail, bone->head);
  1265. vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
  1266. bone->length = len_v3v3(bone->head, bone->tail);
  1267. /* this is called on old file reading too... */
  1268. if (bone->xwidth == 0.0f) {
  1269. bone->xwidth = 0.1f;
  1270. bone->zwidth = 0.1f;
  1271. bone->segments = 1;
  1272. }
  1273. if (prevbone) {
  1274. float offs_bone[4][4];
  1275. /* yoffs(b-1) + root(b) + bonemat(b) */
  1276. get_offset_bone_mat(bone, offs_bone);
  1277. /* Compose the matrix for this bone */
  1278. mult_m4_m4m4(bone->arm_mat, prevbone->arm_mat, offs_bone);
  1279. }
  1280. else {
  1281. copy_m4_m3(bone->arm_mat, bone->bone_mat);
  1282. copy_v3_v3(bone->arm_mat[3], bone->head);
  1283. }
  1284. /* and the kiddies */
  1285. prevbone = bone;
  1286. for (bone = bone->childbase.first; bone; bone = bone->next) {
  1287. BKE_armature_where_is_bone(bone, prevbone);
  1288. }
  1289. }
  1290. /* updates vectors and matrices on rest-position level, only needed
  1291. * after editing armature itself, now only on reading file */
  1292. void BKE_armature_where_is(bArmature *arm)
  1293. {
  1294. Bone *bone;
  1295. /* hierarchical from root to children */
  1296. for (bone = arm->bonebase.first; bone; bone = bone->next) {
  1297. BKE_armature_where_is_bone(bone, NULL);
  1298. }
  1299. }
  1300. /* if bone layer is protected, copy the data from from->pose
  1301. * when used with linked libraries this copies from the linked pose into the local pose */
  1302. static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
  1303. {
  1304. bPose *pose = ob->pose, *frompose = from->pose;
  1305. bPoseChannel *pchan, *pchanp, pchanw;
  1306. bConstraint *con;
  1307. int error = 0;
  1308. if (frompose == NULL)
  1309. return;
  1310. /* in some cases when rigs change, we cant synchronize
  1311. * to avoid crashing check for possible errors here */
  1312. for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
  1313. if (pchan->bone->layer & layer_protected) {
  1314. if (BKE_pose_channel_find_name(frompose, pchan->name) == NULL) {
  1315. printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n",
  1316. from->id.name, pchan->name);
  1317. error = 1;
  1318. }
  1319. }
  1320. }
  1321. if (error)
  1322. return;
  1323. /* clear all transformation values from library */
  1324. BKE_pose_rest(frompose);
  1325. /* copy over all of the proxy's bone groups */
  1326. /* TODO for later
  1327. * - implement 'local' bone groups as for constraints
  1328. * Note: this isn't trivial, as bones reference groups by index not by pointer,
  1329. * so syncing things correctly needs careful attention */
  1330. BLI_freelistN(&pose->agroups);
  1331. BLI_duplicatelist(&pose->agroups, &frompose->agroups);
  1332. pose->active_group = frompose->active_group;
  1333. for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
  1334. pchanp = BKE_pose_channel_find_name(frompose, pchan->name);
  1335. if (UNLIKELY(pchanp == NULL)) {
  1336. /* happens for proxies that become invalid because of a missing link
  1337. * for regulat cases it shouldn't happen at all */
  1338. }
  1339. else if (pchan->bone->layer & layer_protected) {
  1340. ListBase proxylocal_constraints = {NULL, NULL};
  1341. /* copy posechannel to temp, but restore important pointers */
  1342. pchanw = *pchanp;
  1343. pchanw.prev = pchan->prev;
  1344. pchanw.next = pchan->next;
  1345. pchanw.parent = pchan->parent;
  1346. pchanw.child = pchan->child;
  1347. /* this is freed so copy a copy, else undo crashes */
  1348. if (pchanw.prop) {
  1349. pchanw.prop = IDP_CopyProperty(pchanw.prop);
  1350. /* use the values from the the existing props */
  1351. if (pchan->prop) {
  1352. IDP_SyncGroupValues(pchanw.prop, pchan->prop);
  1353. }
  1354. }
  1355. /* constraints - proxy constraints are flushed... local ones are added after
  1356. * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
  1357. * 2. copy proxy-pchan's constraints on-to new
  1358. * 3. add extracted local constraints back on top
  1359. *
  1360. * Note for copy_constraints: when copying constraints, disable 'do_extern' otherwise
  1361. * we get the libs direct linked in this blend. */
  1362. extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
  1363. copy_constraints(&pchanw.constraints, &pchanp->constraints, FALSE);
  1364. BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
  1365. /* constraints - set target ob pointer to own object */
  1366. for (con = pchanw.constraints.first; con; con = con->next) {
  1367. bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
  1368. ListBase targets = {NULL, NULL};
  1369. bConstraintTarget *ct;
  1370. if (cti && cti->get_constraint_targets) {
  1371. cti->get_constraint_targets(con, &targets);
  1372. for (ct = targets.first; ct; ct = ct->next) {
  1373. if (ct->tar == from)
  1374. ct->tar = ob;
  1375. }
  1376. if (cti->flush_constraint_targets)
  1377. cti->flush_constraint_targets(con, &targets, 0);
  1378. }
  1379. }
  1380. /* free stuff from current channel */
  1381. BKE_pose_channel_free(pchan);
  1382. /* the final copy */
  1383. *pchan = pchanw;
  1384. }
  1385. else {
  1386. /* always copy custom shape */
  1387. pchan->custom = pchanp->custom;
  1388. pchan->custom_tx = pchanp->custom_tx;
  1389. /* ID-Property Syncing */
  1390. {
  1391. IDProperty *prop_orig = pchan->prop;
  1392. if (pchanp->prop) {
  1393. pchan->prop = IDP_CopyProperty(pchanp->prop);
  1394. if (prop_orig) {
  1395. /* copy existing values across when types match */
  1396. IDP_SyncGroupValues(pchan->prop, prop_orig);
  1397. }
  1398. }
  1399. else {
  1400. pchan->prop = NULL;
  1401. }
  1402. if (prop_orig) {
  1403. IDP_FreeProperty(prop_orig);
  1404. MEM_freeN(prop_orig);
  1405. }
  1406. }
  1407. }
  1408. }
  1409. }
  1410. static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
  1411. {
  1412. bPoseChannel *pchan = BKE_pose_channel_verify(pose, bone->name); /* verify checks and/or adds */
  1413. pchan->bone = bone;
  1414. pchan->parent = parchan;
  1415. counter++;
  1416. for (bone = bone->childbase.first; bone; bone = bone->next) {
  1417. counter = rebuild_pose_bone(pose, bone, pchan, counter);
  1418. /* for quick detecting of next bone in chain, only b-bone uses it now */
  1419. if (bone->flag & BONE_CONNECTED)
  1420. pchan->child = BKE_pose_channel_find_name(pose, bone->name);
  1421. }
  1422. return counter;
  1423. }
  1424. /* only after leave editmode, duplicating, validating older files, library syncing */
  1425. /* NOTE: pose->flag is set for it */
  1426. void BKE_pose_rebuild(Object *ob, bArmature *arm)
  1427. {
  1428. Bone *bone;
  1429. bPose *pose;
  1430. bPoseChannel *pchan, *next;
  1431. int counter = 0;
  1432. /* only done here */
  1433. if (ob->pose == NULL) {
  1434. /* create new pose */
  1435. ob->pose = MEM_callocN(size

Large files files are truncated, but you can click here to view the full file