Added gsoc-2012 collada improvements from bratwurst branch
[blender.git] / source / blender / collada / ControllerExporter.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, Sukhitha Jayathilake
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/collada/ControllerExporter.cpp
25  *  \ingroup collada
26  */
27
28 #include "COLLADASWBaseInputElement.h"
29 #include "COLLADASWInstanceController.h"
30 #include "COLLADASWPrimitves.h"
31 #include "COLLADASWSource.h"
32
33 #include "DNA_action_types.h"
34 #include "DNA_meshdata_types.h"
35 #include "DNA_modifier_types.h"
36
37 #include "BKE_action.h"
38 #include "BKE_armature.h"
39
40 extern "C" {
41 #include "BKE_main.h"
42 #include "BKE_mesh.h"
43 #include "BKE_global.h"
44 #include "BKE_library.h"
45 }
46
47 #include "ED_armature.h"
48
49 #include "BLI_listbase.h"
50
51 #include "GeometryExporter.h"
52 #include "ArmatureExporter.h"
53 #include "ControllerExporter.h"
54 #include "SceneExporter.h"
55
56 #include "collada_utils.h"
57
58 // XXX exporter writes wrong data for shared armatures.  A separate
59 // controller should be written for each armature-mesh binding how do
60 // we make controller ids then?
61 ControllerExporter::ControllerExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings) : COLLADASW::LibraryControllers(sw), export_settings(export_settings) {
62 }
63
64 bool ControllerExporter::is_skinned_mesh(Object *ob)
65 {
66         return bc_get_assigned_armature(ob) != NULL;
67 }
68
69
70 void ControllerExporter::write_bone_URLs(COLLADASW::InstanceController &ins, Object *ob_arm, Bone *bone)
71 {
72         if (bc_is_root_bone(bone, this->export_settings->deform_bones_only))
73                 ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(bone, ob_arm)));
74         else {
75                 for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
76                         write_bone_URLs(ins, ob_arm, child);
77                 }
78         }
79 }
80
81 bool ControllerExporter::add_instance_controller(Object *ob)
82 {
83         Object *ob_arm = bc_get_assigned_armature(ob);
84         bArmature *arm = (bArmature *)ob_arm->data;
85
86         const std::string& controller_id = get_controller_id(ob_arm, ob);
87
88         COLLADASW::InstanceController ins(mSW);
89         ins.setUrl(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, controller_id));
90
91         Mesh *me = (Mesh *)ob->data;
92         if (!me->dvert) return false;
93
94         // write root bone URLs
95         Bone *bone;
96         for (bone = (Bone *)arm->bonebase.first; bone; bone = bone->next) {
97                 write_bone_URLs(ins, ob_arm, bone);
98         }
99     
100         InstanceWriter::add_material_bindings(ins.getBindMaterial(), ob, this->export_settings->active_uv_only);
101                 
102         ins.add();
103         return true;
104 }
105
106 void ControllerExporter::export_controllers(Scene *sce)
107 {
108         scene = sce;
109
110         openLibrary();
111
112         GeometryFunctor gf;
113         gf.forEachMeshObjectInExportSet<ControllerExporter>(sce, *this, this->export_settings->export_set);
114
115         closeLibrary();
116 }
117
118 void ControllerExporter::operator()(Object *ob)
119 {
120         Object *ob_arm = bc_get_assigned_armature(ob);
121         Key *key = BKE_key_from_object(ob);
122
123         if (ob_arm)
124                 export_skin_controller(ob, ob_arm);
125         if(key){
126                 export_morph_controller(ob, key);
127         }
128 }
129 #if 0
130
131 bool ArmatureExporter::already_written(Object *ob_arm)
132 {
133         return std::find(written_armatures.begin(), written_armatures.end(), ob_arm) != written_armatures.end();
134 }
135
136 void ArmatureExporter::wrote(Object *ob_arm)
137 {
138         written_armatures.push_back(ob_arm);
139 }
140
141 void ArmatureExporter::find_objects_using_armature(Object *ob_arm, std::vector<Object *>& objects, Scene *sce)
142 {
143         objects.clear();
144
145         Base *base = (Base *) sce->base.first;
146         while (base) {
147                 Object *ob = base->object;
148                 
149                 if (ob->type == OB_MESH && get_assigned_armature(ob) == ob_arm) {
150                         objects.push_back(ob);
151                 }
152
153                 base = base->next;
154         }
155 }
156 #endif
157
158 std::string ControllerExporter::get_joint_sid(Bone *bone, Object *ob_arm)
159 {
160         return get_joint_id(bone, ob_arm);
161 }
162
163 std::string ControllerExporter::get_controller_id(Object *ob_arm, Object *ob)
164 {
165         return translate_id(id_name(ob_arm)) + "_" + translate_id(id_name(ob)) + SKIN_CONTROLLER_ID_SUFFIX;
166 }
167
168 std::string ControllerExporter::get_controller_id(Key *key, Object *ob)
169 {
170         return translate_id(id_name(ob)) + MORPH_CONTROLLER_ID_SUFFIX;
171 }
172
173 // ob should be of type OB_MESH
174 // both args are required
175 void ControllerExporter::export_skin_controller(Object *ob, Object *ob_arm)
176 {
177         // joint names
178         // joint inverse bind matrices
179         // vertex weights
180
181         // input:
182         // joint names: ob -> vertex group names
183         // vertex group weights: me->dvert -> groups -> index, weight
184
185 #if 0
186         me->dvert :
187
188         typedef struct MDeformVert {
189                 struct MDeformWeight *dw;
190                 int totweight;
191                 int flag;   // flag only in use for weightpaint now
192         } MDeformVert;
193
194         typedef struct MDeformWeight {
195                 int def_nr;
196                 float weight;
197         } MDeformWeight;
198 #endif
199
200         bool use_instantiation = this->export_settings->use_object_instantiation;
201         Mesh *me;
202
203         if (this->export_settings->apply_modifiers) 
204                 me = bc_to_mesh_apply_modifiers(scene, ob, this->export_settings->export_mesh_type);
205         else 
206                 me = (Mesh *)ob->data;
207         
208         BKE_mesh_tessface_ensure(me);
209
210         if (!me->dvert) return;
211
212         std::string controller_name = id_name(ob_arm);
213         std::string controller_id = get_controller_id(ob_arm, ob);
214
215         openSkin(controller_id, controller_name,
216                  COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
217
218         add_bind_shape_mat(ob);
219
220         std::string joints_source_id = add_joints_source(ob_arm, &ob->defbase, controller_id);
221         std::string inv_bind_mat_source_id = add_inv_bind_mats_source(ob_arm, &ob->defbase, controller_id);
222
223         std::list<int> vcounts;
224         std::list<int> joints;
225         std::list<float> weights;
226
227         {
228                 int i, j;
229
230                 // def group index -> joint index
231                 std::vector<int> joint_index_by_def_index;
232                 bDeformGroup *def;
233
234                 for (def = (bDeformGroup *)ob->defbase.first, i = 0, j = 0; def; def = def->next, i++) {
235                         if (is_bone_defgroup(ob_arm, def))
236                                 joint_index_by_def_index.push_back(j++);
237                         else
238                                 joint_index_by_def_index.push_back(-1);
239                 }
240
241                 for (i = 0; i < me->totvert; i++) {
242                         MDeformVert *vert = &me->dvert[i];
243                         std::map<int, float> jw;
244
245                         // We're normalizing the weights later
246                         float sumw = 0.0f;
247
248                         for (j = 0; j < vert->totweight; j++) {
249                                 int joint_index = joint_index_by_def_index[vert->dw[j].def_nr];
250                                 if (joint_index != -1 && vert->dw[j].weight > 0.0f) {
251                                         jw[joint_index] += vert->dw[j].weight;
252                                         sumw += vert->dw[j].weight;
253                                 }
254                         }
255
256                         if (sumw > 0.0f) {
257                                 float invsumw = 1.0f / sumw;
258                                 vcounts.push_back(jw.size());
259                                 for (std::map<int, float>::iterator m = jw.begin(); m != jw.end(); ++m) {
260                                         joints.push_back((*m).first);
261                                         weights.push_back(invsumw * (*m).second);
262                                 }
263                         }
264                         else {
265                                 vcounts.push_back(0);
266 #if 0
267                                 vcounts.push_back(1);
268                                 joints.push_back(-1);
269                                 weights.push_back(1.0f);
270 #endif
271                         }
272                 }
273         }
274
275         std::string weights_source_id = add_weights_source(me, controller_id, weights);
276         add_joints_element(&ob->defbase, joints_source_id, inv_bind_mat_source_id);
277         add_vertex_weights_element(weights_source_id, joints_source_id, vcounts, joints);
278
279         if (this->export_settings->apply_modifiers)
280         {
281                 BKE_libblock_free_us(&(G.main->mesh), me);
282         }
283         closeSkin();
284         closeController();
285 }
286
287 void ControllerExporter::export_morph_controller(Object *ob, Key *key)
288 {
289         bool use_instantiation = this->export_settings->use_object_instantiation;
290         Mesh *me;
291
292         if (this->export_settings->apply_modifiers) {
293                 me = bc_to_mesh_apply_modifiers(scene, ob, this->export_settings->export_mesh_type);
294         } 
295         else {
296                 me = (Mesh *)ob->data;
297         }
298         BKE_mesh_tessface_ensure(me);
299
300         std::string controller_name = id_name(ob) + "-morph";
301         std::string controller_id = get_controller_id(key, ob);
302
303         openMorph(controller_id, controller_name,
304                  COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
305     
306         std::string targets_id = add_morph_targets(key, ob);
307         std::string morph_weights_id = add_morph_weights(key, ob);
308         
309         COLLADASW::TargetsElement targets(mSW);
310
311         COLLADASW::InputList &input = targets.getInputList();
312
313         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::MORPH_TARGET, // constant declared in COLLADASWInputList.h
314                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, targets_id)));
315         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::MORPH_WEIGHT,
316                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, morph_weights_id)));
317         targets.add();
318
319         if (this->export_settings->apply_modifiers)
320         {
321                 BKE_libblock_free_us(&(G.main->mesh), me);
322         }
323     
324         //support for animations
325         //can also try the base element and param alternative
326         add_weight_extras(key);
327         closeMorph();
328         closeController();
329 }
330
331 std::string ControllerExporter::add_morph_targets(Key *key, Object *ob)
332 {
333         std::string source_id = translate_id(id_name(ob)) + TARGETS_SOURCE_ID_SUFFIX;
334
335         COLLADASW::IdRefSource source(mSW);
336         source.setId(source_id);
337         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
338         source.setAccessorCount(key->totkey - 1);
339         source.setAccessorStride(1);
340     
341         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
342         param.push_back("IDREF");
343
344         source.prepareToAppendValues();
345
346         KeyBlock * kb = (KeyBlock*)key->block.first;
347         //skip the basis
348         kb = kb->next;
349         for (; kb; kb = kb->next) {
350                 std::string geom_id = get_geometry_id(ob, false) + "_morph_" + translate_id(kb->name);
351                 source.appendValues(geom_id);
352
353         }
354
355         source.finish();
356
357         return source_id;
358 }
359
360 std::string ControllerExporter::add_morph_weights(Key *key, Object *ob)
361 {
362         std::string source_id = translate_id(id_name(ob)) + WEIGHTS_SOURCE_ID_SUFFIX;
363
364         COLLADASW::FloatSourceF source(mSW);
365         source.setId(source_id);
366         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
367         source.setAccessorCount(key->totkey - 1);
368         source.setAccessorStride(1);
369     
370         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
371         param.push_back("MORPH_WEIGHT");
372         
373         source.prepareToAppendValues();
374
375         KeyBlock * kb = (KeyBlock*)key->block.first;
376         //skip the basis
377         kb = kb->next;
378         for (; kb; kb = kb->next) {
379                 float weight = kb->curval;
380                 source.appendValues(weight);
381         }
382         source.finish();
383
384         return source_id;
385 }
386
387 //Added to implemente support for animations.
388 void ControllerExporter::add_weight_extras(Key *key){
389         // can also try the base element and param alternative
390         COLLADASW::BaseExtraTechnique extra;
391         
392         KeyBlock * kb = (KeyBlock*)key->block.first;
393         //skip the basis
394         kb = kb->next;
395         for (; kb; kb = kb->next) {
396                 float weight = kb->curval;
397                 extra.addExtraTechniqueParameter ("KHR", "morph_weights" , 0.000, "MORPH_WEIGHT_TO_TARGET");
398         }
399 }
400
401
402
403 void ControllerExporter::add_joints_element(ListBase *defbase,
404                                           const std::string& joints_source_id, const std::string& inv_bind_mat_source_id)
405 {
406         COLLADASW::JointsElement joints(mSW);
407         COLLADASW::InputList &input = joints.getInputList();
408
409         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
410                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id)));
411         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::BINDMATRIX,
412                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, inv_bind_mat_source_id)));
413         joints.add();
414 }
415
416 void ControllerExporter::add_bind_shape_mat(Object *ob)
417 {
418         double bind_mat[4][4];
419
420         converter.mat4_to_dae_double(bind_mat, ob->obmat);
421
422         addBindShapeTransform(bind_mat);
423 }
424
425 std::string ControllerExporter::add_joints_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
426 {
427         std::string source_id = controller_id + JOINTS_SOURCE_ID_SUFFIX;
428
429         int totjoint = 0;
430         bDeformGroup *def;
431         for (def = (bDeformGroup *)defbase->first; def; def = def->next) {
432                 if (is_bone_defgroup(ob_arm, def))
433                         totjoint++;
434         }
435
436         COLLADASW::NameSource source(mSW);
437         source.setId(source_id);
438         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
439         source.setAccessorCount(totjoint);
440         source.setAccessorStride(1);
441         
442         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
443         param.push_back("JOINT");
444
445         source.prepareToAppendValues();
446
447         for (def = (bDeformGroup *)defbase->first; def; def = def->next) {
448                 Bone *bone = get_bone_from_defgroup(ob_arm, def);
449                 if (bone)
450                         source.appendValues(get_joint_sid(bone, ob_arm));
451         }
452
453         source.finish();
454
455         return source_id;
456 }
457
458 std::string ControllerExporter::add_inv_bind_mats_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
459 {
460         std::string source_id = controller_id + BIND_POSES_SOURCE_ID_SUFFIX;
461
462         int totjoint = 0;
463         for (bDeformGroup *def = (bDeformGroup *)defbase->first; def; def = def->next) {
464                 if (is_bone_defgroup(ob_arm, def))
465                         totjoint++;
466         }
467
468         COLLADASW::FloatSourceF source(mSW);
469         source.setId(source_id);
470         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
471         source.setAccessorCount(totjoint); //BLI_countlist(defbase));
472         source.setAccessorStride(16);
473         
474         source.setParameterTypeName(&COLLADASW::CSWC::CSW_VALUE_TYPE_FLOAT4x4);
475         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
476         param.push_back("TRANSFORM");
477
478         source.prepareToAppendValues();
479
480         bPose *pose = ob_arm->pose;
481         bArmature *arm = (bArmature *)ob_arm->data;
482
483         int flag = arm->flag;
484
485         // put armature in rest position
486         if (!(arm->flag & ARM_RESTPOS)) {
487                 arm->flag |= ARM_RESTPOS;
488                 BKE_pose_where_is(scene, ob_arm);
489         }
490
491         for (bDeformGroup *def = (bDeformGroup *)defbase->first; def; def = def->next) {
492                 if (is_bone_defgroup(ob_arm, def)) {
493                         bPoseChannel *pchan = BKE_pose_channel_find_name(pose, def->name);
494
495                         float mat[4][4];
496                         float world[4][4];
497                         float inv_bind_mat[4][4];
498
499                         // SECOND_LIFE_COMPATIBILITY
500                         if (export_settings->second_life) {
501                                 // Only translations, no rotation vs armature
502                                 float temp[4][4];
503                                 unit_m4(temp);
504                                 copy_v3_v3(temp[3], pchan->bone->arm_mat[3]);
505                                 mult_m4_m4m4(world, ob_arm->obmat, temp);
506                         }
507                         else {
508                                 // make world-space matrix, arm_mat is armature-space
509                                 mult_m4_m4m4(world, ob_arm->obmat, pchan->bone->arm_mat);
510                         }
511
512                         invert_m4_m4(mat, world);
513                         converter.mat4_to_dae(inv_bind_mat, mat);
514
515                         source.appendValues(inv_bind_mat);
516                 }
517         }
518
519         // back from rest positon
520         if (!(flag & ARM_RESTPOS)) {
521                 arm->flag = flag;
522                 BKE_pose_where_is(scene, ob_arm);
523         }
524
525         source.finish();
526
527         return source_id;
528 }
529
530 Bone *ControllerExporter::get_bone_from_defgroup(Object *ob_arm, bDeformGroup *def)
531 {
532         bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, def->name);
533         return pchan ? pchan->bone : NULL;
534 }
535
536 bool ControllerExporter::is_bone_defgroup(Object *ob_arm, bDeformGroup *def)
537 {
538         return get_bone_from_defgroup(ob_arm, def) != NULL;
539 }
540
541 std::string ControllerExporter::add_weights_source(Mesh *me, const std::string& controller_id, const std::list<float>& weights)
542 {
543         std::string source_id = controller_id + WEIGHTS_SOURCE_ID_SUFFIX;
544
545         COLLADASW::FloatSourceF source(mSW);
546         source.setId(source_id);
547         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
548         source.setAccessorCount(weights.size());
549         source.setAccessorStride(1);
550         
551         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
552         param.push_back("WEIGHT");
553
554         source.prepareToAppendValues();
555
556         for (std::list<float>::const_iterator i = weights.begin(); i != weights.end(); ++i) {
557                 source.appendValues(*i);
558         }
559
560         source.finish();
561
562         return source_id;
563 }
564
565 void ControllerExporter::add_vertex_weights_element(const std::string& weights_source_id, const std::string& joints_source_id,
566                                                   const std::list<int>& vcounts,
567                                                   const std::list<int>& joints)
568 {
569         COLLADASW::VertexWeightsElement weightselem(mSW);
570         COLLADASW::InputList &input = weightselem.getInputList();
571
572         int offset = 0;
573         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
574                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id), offset++));
575         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::WEIGHT,
576                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, weights_source_id), offset++));
577
578         weightselem.setCount(vcounts.size());
579
580         // write number of deformers per vertex
581         COLLADASW::PrimitivesBase::VCountList vcountlist;
582
583         vcountlist.resize(vcounts.size());
584         std::copy(vcounts.begin(), vcounts.end(), vcountlist.begin());
585
586         weightselem.prepareToAppendVCountValues();
587         weightselem.appendVertexCount(vcountlist);
588
589         weightselem.CloseVCountAndOpenVElement();
590
591         // write deformer index - weight index pairs
592         int weight_index = 0;
593         for (std::list<int>::const_iterator i = joints.begin(); i != joints.end(); ++i) {
594                 weightselem.appendValues(*i, weight_index++);
595         }
596
597         weightselem.finish();
598 }