style cleanup
[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         }
126         if (key) {
127                 export_morph_controller(ob, key);
128         }
129 }
130 #if 0
131
132 bool ArmatureExporter::already_written(Object *ob_arm)
133 {
134         return std::find(written_armatures.begin(), written_armatures.end(), ob_arm) != written_armatures.end();
135 }
136
137 void ArmatureExporter::wrote(Object *ob_arm)
138 {
139         written_armatures.push_back(ob_arm);
140 }
141
142 void ArmatureExporter::find_objects_using_armature(Object *ob_arm, std::vector<Object *>& objects, Scene *sce)
143 {
144         objects.clear();
145
146         Base *base = (Base *) sce->base.first;
147         while (base) {
148                 Object *ob = base->object;
149                 
150                 if (ob->type == OB_MESH && get_assigned_armature(ob) == ob_arm) {
151                         objects.push_back(ob);
152                 }
153
154                 base = base->next;
155         }
156 }
157 #endif
158
159 std::string ControllerExporter::get_joint_sid(Bone *bone, Object *ob_arm)
160 {
161         return get_joint_id(bone, ob_arm);
162 }
163
164 std::string ControllerExporter::get_controller_id(Object *ob_arm, Object *ob)
165 {
166         return translate_id(id_name(ob_arm)) + "_" + translate_id(id_name(ob)) + SKIN_CONTROLLER_ID_SUFFIX;
167 }
168
169 std::string ControllerExporter::get_controller_id(Key *key, Object *ob)
170 {
171         return translate_id(id_name(ob)) + MORPH_CONTROLLER_ID_SUFFIX;
172 }
173
174 // ob should be of type OB_MESH
175 // both args are required
176 void ControllerExporter::export_skin_controller(Object *ob, Object *ob_arm)
177 {
178         // joint names
179         // joint inverse bind matrices
180         // vertex weights
181
182         // input:
183         // joint names: ob -> vertex group names
184         // vertex group weights: me->dvert -> groups -> index, weight
185
186 #if 0
187         me->dvert :
188
189         typedef struct MDeformVert {
190                 struct MDeformWeight *dw;
191                 int totweight;
192                 int flag;   // flag only in use for weightpaint now
193         } MDeformVert;
194
195         typedef struct MDeformWeight {
196                 int def_nr;
197                 float weight;
198         } MDeformWeight;
199 #endif
200
201         bool use_instantiation = this->export_settings->use_object_instantiation;
202         Mesh *me;
203
204         if (this->export_settings->apply_modifiers) 
205                 me = bc_to_mesh_apply_modifiers(scene, ob, this->export_settings->export_mesh_type);
206         else 
207                 me = (Mesh *)ob->data;
208         
209         BKE_mesh_tessface_ensure(me);
210
211         if (!me->dvert) return;
212
213         std::string controller_name = id_name(ob_arm);
214         std::string controller_id = get_controller_id(ob_arm, ob);
215
216         openSkin(controller_id, controller_name,
217                  COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
218
219         add_bind_shape_mat(ob);
220
221         std::string joints_source_id = add_joints_source(ob_arm, &ob->defbase, controller_id);
222         std::string inv_bind_mat_source_id = add_inv_bind_mats_source(ob_arm, &ob->defbase, controller_id);
223
224         std::list<int> vcounts;
225         std::list<int> joints;
226         std::list<float> weights;
227
228         {
229                 int i, j;
230
231                 // def group index -> joint index
232                 std::vector<int> joint_index_by_def_index;
233                 bDeformGroup *def;
234
235                 for (def = (bDeformGroup *)ob->defbase.first, i = 0, j = 0; def; def = def->next, i++) {
236                         if (is_bone_defgroup(ob_arm, def))
237                                 joint_index_by_def_index.push_back(j++);
238                         else
239                                 joint_index_by_def_index.push_back(-1);
240                 }
241
242                 for (i = 0; i < me->totvert; i++) {
243                         MDeformVert *vert = &me->dvert[i];
244                         std::map<int, float> jw;
245
246                         // We're normalizing the weights later
247                         float sumw = 0.0f;
248
249                         for (j = 0; j < vert->totweight; j++) {
250                                 int idx = vert->dw[j].def_nr;
251                                 if (idx >= 0) {
252                                         int joint_index = joint_index_by_def_index[idx];
253                                         if (joint_index != -1 && vert->dw[j].weight > 0.0f) {
254                                                 jw[joint_index] += vert->dw[j].weight;
255                                                 sumw += vert->dw[j].weight;
256                                         }
257                                 }
258                         }
259
260                         if (sumw > 0.0f) {
261                                 float invsumw = 1.0f / sumw;
262                                 vcounts.push_back(jw.size());
263                                 for (std::map<int, float>::iterator m = jw.begin(); m != jw.end(); ++m) {
264                                         joints.push_back((*m).first);
265                                         weights.push_back(invsumw * (*m).second);
266                                 }
267                         }
268                         else {
269                                 vcounts.push_back(0);
270 #if 0
271                                 vcounts.push_back(1);
272                                 joints.push_back(-1);
273                                 weights.push_back(1.0f);
274 #endif
275                         }
276                 }
277         }
278
279         std::string weights_source_id = add_weights_source(me, controller_id, weights);
280         add_joints_element(&ob->defbase, joints_source_id, inv_bind_mat_source_id);
281         add_vertex_weights_element(weights_source_id, joints_source_id, vcounts, joints);
282
283         if (this->export_settings->apply_modifiers)
284         {
285                 BKE_libblock_free_us(&(G.main->mesh), me);
286         }
287         closeSkin();
288         closeController();
289 }
290
291 void ControllerExporter::export_morph_controller(Object *ob, Key *key)
292 {
293         bool use_instantiation = this->export_settings->use_object_instantiation;
294         Mesh *me;
295
296         if (this->export_settings->apply_modifiers) {
297                 me = bc_to_mesh_apply_modifiers(scene, ob, this->export_settings->export_mesh_type);
298         } 
299         else {
300                 me = (Mesh *)ob->data;
301         }
302         BKE_mesh_tessface_ensure(me);
303
304         std::string controller_name = id_name(ob) + "-morph";
305         std::string controller_id = get_controller_id(key, ob);
306
307         openMorph(controller_id, controller_name,
308                  COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
309
310         std::string targets_id = add_morph_targets(key, ob);
311         std::string morph_weights_id = add_morph_weights(key, ob);
312         
313         COLLADASW::TargetsElement targets(mSW);
314
315         COLLADASW::InputList &input = targets.getInputList();
316
317         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::MORPH_TARGET, // constant declared in COLLADASWInputList.h
318                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, targets_id)));
319         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::MORPH_WEIGHT,
320                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, morph_weights_id)));
321         targets.add();
322
323         if (this->export_settings->apply_modifiers)
324         {
325                 BKE_libblock_free_us(&(G.main->mesh), me);
326         }
327
328         //support for animations
329         //can also try the base element and param alternative
330         add_weight_extras(key);
331         closeMorph();
332         closeController();
333 }
334
335 std::string ControllerExporter::add_morph_targets(Key *key, Object *ob)
336 {
337         std::string source_id = translate_id(id_name(ob)) + TARGETS_SOURCE_ID_SUFFIX;
338
339         COLLADASW::IdRefSource source(mSW);
340         source.setId(source_id);
341         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
342         source.setAccessorCount(key->totkey - 1);
343         source.setAccessorStride(1);
344
345         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
346         param.push_back("IDREF");
347
348         source.prepareToAppendValues();
349
350         KeyBlock * kb = (KeyBlock*)key->block.first;
351         //skip the basis
352         kb = kb->next;
353         for (; kb; kb = kb->next) {
354                 std::string geom_id = get_geometry_id(ob, false) + "_morph_" + translate_id(kb->name);
355                 source.appendValues(geom_id);
356
357         }
358
359         source.finish();
360
361         return source_id;
362 }
363
364 std::string ControllerExporter::add_morph_weights(Key *key, Object *ob)
365 {
366         std::string source_id = translate_id(id_name(ob)) + WEIGHTS_SOURCE_ID_SUFFIX;
367
368         COLLADASW::FloatSourceF source(mSW);
369         source.setId(source_id);
370         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
371         source.setAccessorCount(key->totkey - 1);
372         source.setAccessorStride(1);
373
374         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
375         param.push_back("MORPH_WEIGHT");
376         
377         source.prepareToAppendValues();
378
379         KeyBlock * kb = (KeyBlock*)key->block.first;
380         //skip the basis
381         kb = kb->next;
382         for (; kb; kb = kb->next) {
383                 float weight = kb->curval;
384                 source.appendValues(weight);
385         }
386         source.finish();
387
388         return source_id;
389 }
390
391 //Added to implemente support for animations.
392 void ControllerExporter::add_weight_extras(Key *key)
393 {
394         // can also try the base element and param alternative
395         COLLADASW::BaseExtraTechnique extra;
396         
397         KeyBlock * kb = (KeyBlock*)key->block.first;
398         //skip the basis
399         kb = kb->next;
400         for (; kb; kb = kb->next) {
401                 // XXX why is the weight not used here and set to 0.0?
402                 float weight = kb->curval;
403                 extra.addExtraTechniqueParameter ("KHR", "morph_weights" , 0.000, "MORPH_WEIGHT_TO_TARGET");
404         }
405 }
406
407
408
409 void ControllerExporter::add_joints_element(ListBase *defbase,
410                                           const std::string& joints_source_id, const std::string& inv_bind_mat_source_id)
411 {
412         COLLADASW::JointsElement joints(mSW);
413         COLLADASW::InputList &input = joints.getInputList();
414
415         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
416                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id)));
417         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::BINDMATRIX,
418                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, inv_bind_mat_source_id)));
419         joints.add();
420 }
421
422 void ControllerExporter::add_bind_shape_mat(Object *ob)
423 {
424         double bind_mat[4][4];
425
426         converter.mat4_to_dae_double(bind_mat, ob->obmat);
427
428         addBindShapeTransform(bind_mat);
429 }
430
431 std::string ControllerExporter::add_joints_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
432 {
433         std::string source_id = controller_id + JOINTS_SOURCE_ID_SUFFIX;
434
435         int totjoint = 0;
436         bDeformGroup *def;
437         for (def = (bDeformGroup *)defbase->first; def; def = def->next) {
438                 if (is_bone_defgroup(ob_arm, def))
439                         totjoint++;
440         }
441
442         COLLADASW::NameSource source(mSW);
443         source.setId(source_id);
444         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
445         source.setAccessorCount(totjoint);
446         source.setAccessorStride(1);
447         
448         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
449         param.push_back("JOINT");
450
451         source.prepareToAppendValues();
452
453         for (def = (bDeformGroup *)defbase->first; def; def = def->next) {
454                 Bone *bone = get_bone_from_defgroup(ob_arm, def);
455                 if (bone)
456                         source.appendValues(get_joint_sid(bone, ob_arm));
457         }
458
459         source.finish();
460
461         return source_id;
462 }
463
464 std::string ControllerExporter::add_inv_bind_mats_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
465 {
466         std::string source_id = controller_id + BIND_POSES_SOURCE_ID_SUFFIX;
467
468         int totjoint = 0;
469         for (bDeformGroup *def = (bDeformGroup *)defbase->first; def; def = def->next) {
470                 if (is_bone_defgroup(ob_arm, def))
471                         totjoint++;
472         }
473
474         COLLADASW::FloatSourceF source(mSW);
475         source.setId(source_id);
476         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
477         source.setAccessorCount(totjoint); //BLI_countlist(defbase));
478         source.setAccessorStride(16);
479         
480         source.setParameterTypeName(&COLLADASW::CSWC::CSW_VALUE_TYPE_FLOAT4x4);
481         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
482         param.push_back("TRANSFORM");
483
484         source.prepareToAppendValues();
485
486         bPose *pose = ob_arm->pose;
487         bArmature *arm = (bArmature *)ob_arm->data;
488
489         int flag = arm->flag;
490
491         // put armature in rest position
492         if (!(arm->flag & ARM_RESTPOS)) {
493                 arm->flag |= ARM_RESTPOS;
494                 BKE_pose_where_is(scene, ob_arm);
495         }
496
497         for (bDeformGroup *def = (bDeformGroup *)defbase->first; def; def = def->next) {
498                 if (is_bone_defgroup(ob_arm, def)) {
499                         bPoseChannel *pchan = BKE_pose_channel_find_name(pose, def->name);
500
501                         float mat[4][4];
502                         float world[4][4];
503                         float inv_bind_mat[4][4];
504
505                         // SECOND_LIFE_COMPATIBILITY
506                         if (export_settings->second_life) {
507                                 // Only translations, no rotation vs armature
508                                 float temp[4][4];
509                                 unit_m4(temp);
510                                 copy_v3_v3(temp[3], pchan->bone->arm_mat[3]);
511                                 mult_m4_m4m4(world, ob_arm->obmat, temp);
512                         }
513                         else {
514                                 // make world-space matrix, arm_mat is armature-space
515                                 mult_m4_m4m4(world, ob_arm->obmat, pchan->bone->arm_mat);
516                         }
517
518                         invert_m4_m4(mat, world);
519                         converter.mat4_to_dae(inv_bind_mat, mat);
520
521                         source.appendValues(inv_bind_mat);
522                 }
523         }
524
525         // back from rest positon
526         if (!(flag & ARM_RESTPOS)) {
527                 arm->flag = flag;
528                 BKE_pose_where_is(scene, ob_arm);
529         }
530
531         source.finish();
532
533         return source_id;
534 }
535
536 Bone *ControllerExporter::get_bone_from_defgroup(Object *ob_arm, bDeformGroup *def)
537 {
538         bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, def->name);
539         return pchan ? pchan->bone : NULL;
540 }
541
542 bool ControllerExporter::is_bone_defgroup(Object *ob_arm, bDeformGroup *def)
543 {
544         return get_bone_from_defgroup(ob_arm, def) != NULL;
545 }
546
547 std::string ControllerExporter::add_weights_source(Mesh *me, const std::string& controller_id, const std::list<float>& weights)
548 {
549         std::string source_id = controller_id + WEIGHTS_SOURCE_ID_SUFFIX;
550
551         COLLADASW::FloatSourceF source(mSW);
552         source.setId(source_id);
553         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
554         source.setAccessorCount(weights.size());
555         source.setAccessorStride(1);
556         
557         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
558         param.push_back("WEIGHT");
559
560         source.prepareToAppendValues();
561
562         for (std::list<float>::const_iterator i = weights.begin(); i != weights.end(); ++i) {
563                 source.appendValues(*i);
564         }
565
566         source.finish();
567
568         return source_id;
569 }
570
571 void ControllerExporter::add_vertex_weights_element(const std::string& weights_source_id, const std::string& joints_source_id,
572                                                   const std::list<int>& vcounts,
573                                                   const std::list<int>& joints)
574 {
575         COLLADASW::VertexWeightsElement weightselem(mSW);
576         COLLADASW::InputList &input = weightselem.getInputList();
577
578         int offset = 0;
579         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
580                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id), offset++));
581         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::WEIGHT,
582                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, weights_source_id), offset++));
583
584         weightselem.setCount(vcounts.size());
585
586         // write number of deformers per vertex
587         COLLADASW::PrimitivesBase::VCountList vcountlist;
588
589         vcountlist.resize(vcounts.size());
590         std::copy(vcounts.begin(), vcounts.end(), vcountlist.begin());
591
592         weightselem.prepareToAppendVCountValues();
593         weightselem.appendVertexCount(vcountlist);
594
595         weightselem.CloseVCountAndOpenVElement();
596
597         // write deformer index - weight index pairs
598         int weight_index = 0;
599         for (std::list<int>::const_iterator i = joints.begin(); i != joints.end(); ++i) {
600                 weightselem.appendValues(*i, weight_index++);
601         }
602
603         weightselem.finish();
604 }