Merging trunk up to r39145.
[blender-staging.git] / source / blender / collada / ArmatureExporter.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Jan Diederich, Tod Liverseed,
21  *                 Nathan Letwory
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/collada/ArmatureExporter.cpp
27  *  \ingroup collada
28  */
29
30
31 #include "COLLADASWBaseInputElement.h"
32 #include "COLLADASWInstanceController.h"
33 #include "COLLADASWPrimitves.h"
34 #include "COLLADASWSource.h"
35
36 #include "DNA_action_types.h"
37 #include "DNA_meshdata_types.h"
38 #include "DNA_modifier_types.h"
39
40 #include "BKE_action.h"
41 #include "BKE_armature.h"
42
43 #include "BLI_listbase.h"
44
45 #include "GeometryExporter.h"
46 #include "ArmatureExporter.h"
47
48 // XXX exporter writes wrong data for shared armatures.  A separate
49 // controller should be written for each armature-mesh binding how do
50 // we make controller ids then?
51 ArmatureExporter::ArmatureExporter(COLLADASW::StreamWriter *sw) : COLLADASW::LibraryControllers(sw) {}
52
53 // write bone nodes
54 void ArmatureExporter::add_armature_bones(Object *ob_arm, Scene *sce)
55 {
56         // write bone nodes
57         bArmature *arm = (bArmature*)ob_arm->data;
58         for (Bone *bone = (Bone*)arm->bonebase.first; bone; bone = bone->next) {
59                 // start from root bones
60                 if (!bone->parent)
61                         add_bone_node(bone, ob_arm);
62         }
63 }
64
65 bool ArmatureExporter::is_skinned_mesh(Object *ob)
66 {
67         return get_assigned_armature(ob) != NULL;
68 }
69
70 void ArmatureExporter::add_instance_controller(Object *ob)
71 {
72         Object *ob_arm = get_assigned_armature(ob);
73         bArmature *arm = (bArmature*)ob_arm->data;
74
75         const std::string& controller_id = get_controller_id(ob_arm, ob);
76
77         COLLADASW::InstanceController ins(mSW);
78         ins.setUrl(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, controller_id));
79
80         // write root bone URLs
81         Bone *bone;
82         for (bone = (Bone*)arm->bonebase.first; bone; bone = bone->next) {
83                 if (!bone->parent)
84                         ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(bone, ob_arm)));
85         }
86
87         InstanceWriter::add_material_bindings(ins.getBindMaterial(), ob);
88                 
89         ins.add();
90 }
91
92 void ArmatureExporter::export_controllers(Scene *sce, bool export_selected)
93 {
94         scene = sce;
95
96         openLibrary();
97
98         GeometryFunctor gf;
99         gf.forEachMeshObjectInScene<ArmatureExporter>(sce, *this, export_selected);
100
101         closeLibrary();
102 }
103
104 void ArmatureExporter::operator()(Object *ob)
105 {
106         Object *ob_arm = get_assigned_armature(ob);
107
108         if (ob_arm /*&& !already_written(ob_arm)*/)
109                 export_controller(ob, ob_arm);
110 }
111 #if 0
112
113 bool ArmatureExporter::already_written(Object *ob_arm)
114 {
115         return std::find(written_armatures.begin(), written_armatures.end(), ob_arm) != written_armatures.end();
116 }
117
118 void ArmatureExporter::wrote(Object *ob_arm)
119 {
120         written_armatures.push_back(ob_arm);
121 }
122
123 void ArmatureExporter::find_objects_using_armature(Object *ob_arm, std::vector<Object *>& objects, Scene *sce)
124 {
125         objects.clear();
126
127         Base *base= (Base*) sce->base.first;
128         while(base) {
129                 Object *ob = base->object;
130                 
131                 if (ob->type == OB_MESH && get_assigned_armature(ob) == ob_arm) {
132                         objects.push_back(ob);
133                 }
134
135                 base= base->next;
136         }
137 }
138 #endif
139
140 Object *ArmatureExporter::get_assigned_armature(Object *ob)
141 {
142         Object *ob_arm = NULL;
143
144         if (ob->parent && ob->partype == PARSKEL && ob->parent->type == OB_ARMATURE) {
145                 ob_arm = ob->parent;
146         }
147         else {
148                 ModifierData *mod = (ModifierData*)ob->modifiers.first;
149                 while (mod) {
150                         if (mod->type == eModifierType_Armature) {
151                                 ob_arm = ((ArmatureModifierData*)mod)->object;
152                         }
153
154                         mod = mod->next;
155                 }
156         }
157
158         return ob_arm;
159 }
160
161 std::string ArmatureExporter::get_joint_sid(Bone *bone, Object *ob_arm)
162 {
163         return get_joint_id(bone, ob_arm);
164 }
165
166 // parent_mat is armature-space
167 void ArmatureExporter::add_bone_node(Bone *bone, Object *ob_arm)
168 {
169         std::string node_id = get_joint_id(bone, ob_arm);
170         std::string node_name = std::string(bone->name);
171         std::string node_sid = get_joint_sid(bone, ob_arm);
172
173         COLLADASW::Node node(mSW);
174
175         node.setType(COLLADASW::Node::JOINT);
176         node.setNodeId(node_id);
177         node.setNodeName(node_name);
178         node.setNodeSid(node_sid);
179
180         if ( bone->childbase.first == NULL )
181                 add_blender_leaf_bone( bone, ob_arm , node );
182         else{
183         node.start();
184
185         add_bone_transform(ob_arm, bone, node);
186
187         for (Bone *child = (Bone*)bone->childbase.first; child; child = child->next) {
188                 add_bone_node(child, ob_arm);
189         }
190
191         node.end();
192         }
193 }
194
195 void ArmatureExporter::add_blender_leaf_bone(Bone *bone, Object *ob_arm, COLLADASW::Node& node)
196 {
197         node.start();
198     
199         add_bone_transform(ob_arm, bone, node);
200     
201         node.addExtraTechniqueParameter("blender", "tip_x", bone->tail[0] );
202         node.addExtraTechniqueParameter("blender", "tip_y", bone->tail[1] );
203         node.addExtraTechniqueParameter("blender", "tip_z", bone->tail[2] );
204         
205         node.end();
206         
207 }
208 void ArmatureExporter::add_bone_transform(Object *ob_arm, Bone *bone, COLLADASW::Node& node)
209 {
210         bPoseChannel *pchan = get_pose_channel(ob_arm->pose, bone->name);
211
212         float mat[4][4];
213
214         if (bone->parent) {
215                 // get bone-space matrix from armature-space
216                 bPoseChannel *parchan = get_pose_channel(ob_arm->pose, bone->parent->name);
217
218                 float invpar[4][4];
219                 invert_m4_m4(invpar, parchan->pose_mat);
220                 mul_m4_m4m4(mat, pchan->pose_mat, invpar);
221         }
222         else {
223                 // get world-space from armature-space
224                 mul_m4_m4m4(mat, pchan->pose_mat, ob_arm->obmat);
225         }
226
227         TransformWriter::add_node_transform(node, mat, NULL);
228 }
229
230 std::string ArmatureExporter::get_controller_id(Object *ob_arm, Object *ob)
231 {
232         return translate_id(id_name(ob_arm)) + "_" + translate_id(id_name(ob)) + SKIN_CONTROLLER_ID_SUFFIX;
233 }
234
235 // ob should be of type OB_MESH
236 // both args are required
237 void ArmatureExporter::export_controller(Object* ob, Object *ob_arm)
238 {
239         // joint names
240         // joint inverse bind matrices
241         // vertex weights
242
243         // input:
244         // joint names: ob -> vertex group names
245         // vertex group weights: me->dvert -> groups -> index, weight
246
247         /*
248         me->dvert:
249
250         typedef struct MDeformVert {
251                 struct MDeformWeight *dw;
252                 int totweight;
253                 int flag;       // flag only in use for weightpaint now
254         } MDeformVert;
255
256         typedef struct MDeformWeight {
257                 int                             def_nr;
258                 float                   weight;
259         } MDeformWeight;
260         */
261
262         Mesh *me = (Mesh*)ob->data;
263         if (!me->dvert) return;
264
265         std::string controller_name = id_name(ob_arm);
266         std::string controller_id = get_controller_id(ob_arm, ob);
267
268         openSkin(controller_id, controller_name,
269                          COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob)));
270
271         add_bind_shape_mat(ob);
272
273         std::string joints_source_id = add_joints_source(ob_arm, &ob->defbase, controller_id);
274         std::string inv_bind_mat_source_id = add_inv_bind_mats_source(ob_arm, &ob->defbase, controller_id);
275         std::string weights_source_id = add_weights_source(me, controller_id);
276
277         add_joints_element(&ob->defbase, joints_source_id, inv_bind_mat_source_id);
278         add_vertex_weights_element(weights_source_id, joints_source_id, me, ob_arm, &ob->defbase);
279
280         closeSkin();
281         closeController();
282 }
283
284 void ArmatureExporter::add_joints_element(ListBase *defbase,
285                                                 const std::string& joints_source_id, const std::string& inv_bind_mat_source_id)
286 {
287         COLLADASW::JointsElement joints(mSW);
288         COLLADASW::InputList &input = joints.getInputList();
289
290         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
291                                                            COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id)));
292         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::BINDMATRIX,
293                                                            COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, inv_bind_mat_source_id)));
294         joints.add();
295 }
296
297 void ArmatureExporter::add_bind_shape_mat(Object *ob)
298 {
299         double bind_mat[4][4];
300
301         converter.mat4_to_dae_double(bind_mat, ob->obmat);
302
303         addBindShapeTransform(bind_mat);
304 }
305
306 std::string ArmatureExporter::add_joints_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
307 {
308         std::string source_id = controller_id + JOINTS_SOURCE_ID_SUFFIX;
309
310         int totjoint = 0;
311         bDeformGroup *def;
312         for (def = (bDeformGroup*)defbase->first; def; def = def->next) {
313                 if (is_bone_defgroup(ob_arm, def))
314                         totjoint++;
315         }
316
317         COLLADASW::NameSource source(mSW);
318         source.setId(source_id);
319         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
320         source.setAccessorCount(totjoint);
321         source.setAccessorStride(1);
322         
323         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
324         param.push_back("JOINT");
325
326         source.prepareToAppendValues();
327
328         for (def = (bDeformGroup*)defbase->first; def; def = def->next) {
329                 Bone *bone = get_bone_from_defgroup(ob_arm, def);
330                 if (bone)
331                         source.appendValues(get_joint_sid(bone, ob_arm));
332         }
333
334         source.finish();
335
336         return source_id;
337 }
338
339 std::string ArmatureExporter::add_inv_bind_mats_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
340 {
341         std::string source_id = controller_id + BIND_POSES_SOURCE_ID_SUFFIX;
342
343         COLLADASW::FloatSourceF source(mSW);
344         source.setId(source_id);
345         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
346         source.setAccessorCount(BLI_countlist(defbase));
347         source.setAccessorStride(16);
348         
349         source.setParameterTypeName(&COLLADASW::CSWC::CSW_VALUE_TYPE_FLOAT4x4);
350         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
351         param.push_back("TRANSFORM");
352
353         source.prepareToAppendValues();
354
355         bPose *pose = ob_arm->pose;
356         bArmature *arm = (bArmature*)ob_arm->data;
357
358         int flag = arm->flag;
359
360         // put armature in rest position
361         if (!(arm->flag & ARM_RESTPOS)) {
362                 arm->flag |= ARM_RESTPOS;
363                 where_is_pose(scene, ob_arm);
364         }
365
366         for (bDeformGroup *def = (bDeformGroup*)defbase->first; def; def = def->next) {
367                 if (is_bone_defgroup(ob_arm, def)) {
368
369                         bPoseChannel *pchan = get_pose_channel(pose, def->name);
370
371                         float pose_mat[4][4];
372                         float mat[4][4];
373                         float world[4][4];
374                         float inv_bind_mat[4][4];
375
376                         // pose_mat is the same as pchan->pose_mat, but without the rotation
377                         unit_m4(pose_mat);
378                         translate_m4(pose_mat, pchan->pose_head[0], pchan->pose_head[1], pchan->pose_head[2]);
379
380                         // make world-space matrix, pose_mat is armature-space
381                         mul_m4_m4m4(world, pose_mat, ob_arm->obmat);
382                         
383                         invert_m4_m4(mat, world);
384                         converter.mat4_to_dae(inv_bind_mat, mat);
385
386                         source.appendValues(inv_bind_mat);
387                 }
388         }
389
390         // back from rest positon
391         if (!(flag & ARM_RESTPOS)) {
392                 arm->flag = flag;
393                 where_is_pose(scene, ob_arm);
394         }
395
396         source.finish();
397
398         return source_id;
399 }
400
401 Bone *ArmatureExporter::get_bone_from_defgroup(Object *ob_arm, bDeformGroup* def)
402 {
403         bPoseChannel *pchan = get_pose_channel(ob_arm->pose, def->name);
404         return pchan ? pchan->bone : NULL;
405 }
406
407 bool ArmatureExporter::is_bone_defgroup(Object *ob_arm, bDeformGroup* def)
408 {
409         return get_bone_from_defgroup(ob_arm, def) != NULL;
410 }
411
412 std::string ArmatureExporter::add_weights_source(Mesh *me, const std::string& controller_id)
413 {
414         std::string source_id = controller_id + WEIGHTS_SOURCE_ID_SUFFIX;
415
416         int i;
417         int totweight = 0;
418
419         for (i = 0; i < me->totvert; i++) {
420                 totweight += me->dvert[i].totweight;
421         }
422
423         COLLADASW::FloatSourceF source(mSW);
424         source.setId(source_id);
425         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
426         source.setAccessorCount(totweight);
427         source.setAccessorStride(1);
428         
429         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
430         param.push_back("WEIGHT");
431
432         source.prepareToAppendValues();
433
434         // NOTE: COLLADA spec says weights should be normalized
435
436         for (i = 0; i < me->totvert; i++) {
437                 MDeformVert *vert = &me->dvert[i];
438                 for (int j = 0; j < vert->totweight; j++) {
439                         source.appendValues(vert->dw[j].weight);
440                 }
441         }
442
443         source.finish();
444
445         return source_id;
446 }
447
448 void ArmatureExporter::add_vertex_weights_element(const std::string& weights_source_id, const std::string& joints_source_id, Mesh *me,
449                                                                 Object *ob_arm, ListBase *defbase)
450 {
451         COLLADASW::VertexWeightsElement weights(mSW);
452         COLLADASW::InputList &input = weights.getInputList();
453
454         int offset = 0;
455         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
456                                                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id), offset++));
457         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::WEIGHT,
458                                                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, weights_source_id), offset++));
459
460         weights.setCount(me->totvert);
461
462         // write number of deformers per vertex
463         COLLADASW::PrimitivesBase::VCountList vcount;
464         int i;
465         for (i = 0; i < me->totvert; i++) {
466                 vcount.push_back(me->dvert[i].totweight);
467         }
468
469         weights.prepareToAppendVCountValues();
470         weights.appendVertexCount(vcount);
471
472         // def group index -> joint index
473         std::map<int, int> joint_index_by_def_index;
474         bDeformGroup *def;
475         int j;
476         for (def = (bDeformGroup*)defbase->first, i = 0, j = 0; def; def = def->next, i++) {
477                 if (is_bone_defgroup(ob_arm, def))
478                         joint_index_by_def_index[i] = j++;
479                 else
480                         joint_index_by_def_index[i] = -1;
481         }
482
483         weights.CloseVCountAndOpenVElement();
484
485         // write deformer index - weight index pairs
486         int weight_index = 0;
487         for (i = 0; i < me->totvert; i++) {
488                 MDeformVert *dvert = &me->dvert[i];
489                 for (int j = 0; j < dvert->totweight; j++) {
490                         weights.appendValues(joint_index_by_def_index[dvert->dw[j].def_nr]);
491                         weights.appendValues(weight_index++);
492                 }
493         }
494
495         weights.finish();
496 }