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