style cleanup: comment blocks
[blender.git] / source / blender / collada / DocumentImporter.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, Nathan Letwory.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/collada/DocumentImporter.cpp
24  *  \ingroup collada
25  */
26
27 // TODO:
28 // * name imported objects
29 // * import object rotation as euler
30
31 #include <string>
32 #include <map>
33 #include <algorithm> // sort()
34
35 #include "COLLADAFWRoot.h"
36 #include "COLLADAFWStableHeaders.h"
37 #include "COLLADAFWColorOrTexture.h"
38 #include "COLLADAFWIndexList.h"
39 #include "COLLADAFWMeshPrimitiveWithFaceVertexCount.h"
40 #include "COLLADAFWPolygons.h"
41 #include "COLLADAFWSampler.h"
42 #include "COLLADAFWTypes.h"
43 #include "COLLADAFWVisualScene.h"
44 #include "COLLADAFWArrayPrimitiveType.h"
45 #include "COLLADAFWLibraryNodes.h"
46 #include "COLLADAFWCamera.h"
47 #include "COLLADAFWLight.h"
48
49 #include "COLLADASaxFWLLoader.h"
50 #include "COLLADASaxFWLIExtraDataCallbackHandler.h"
51
52 extern "C" {
53 #include "BLI_listbase.h"
54 #include "BLI_math.h"
55 #include "BLI_string.h"
56 #include "BLI_utildefines.h"
57
58 #include "BKE_camera.h"
59 #include "BKE_main.h"
60 #include "BKE_lamp.h"
61 #include "BKE_library.h"
62 #include "BKE_texture.h"
63 #include "BKE_fcurve.h"
64 #include "BKE_depsgraph.h"
65 #include "BKE_scene.h"
66 #include "BKE_global.h"
67 #include "BKE_material.h"
68 #include "BKE_image.h"
69
70 #include "BLI_path_util.h"
71
72 #include "DNA_camera_types.h"
73 #include "DNA_lamp_types.h"
74
75 #include "RNA_access.h"
76
77 #include "MEM_guardedalloc.h"
78
79 }
80
81 #include "ExtraHandler.h"
82 #include "ErrorHandler.h"
83 #include "DocumentImporter.h"
84 #include "TransformReader.h"
85
86 #include "collada_internal.h"
87 #include "collada_utils.h"
88
89
90 /*
91  * COLLADA Importer limitations:
92  * - no multiple scene import, all objects are added to active scene
93  */
94
95 // #define COLLADA_DEBUG
96 // creates empties for each imported bone on layer 2, for debugging
97 // #define ARMATURE_TEST
98
99 DocumentImporter::DocumentImporter(bContext *C, const char *filename) :
100         mImportStage(General),
101         mFilename(filename),
102         mContext(C),
103         armature_importer(&unit_converter, &mesh_importer, &anim_importer, CTX_data_scene(C)),
104         mesh_importer(&unit_converter, &armature_importer, CTX_data_scene(C)),
105         anim_importer(&unit_converter, &armature_importer, CTX_data_scene(C))
106 {
107 }
108
109 DocumentImporter::~DocumentImporter()
110 {
111         TagsMap::iterator etit;
112         etit = uid_tags_map.begin();
113         while (etit != uid_tags_map.end()) {
114                 delete etit->second;
115                 etit++;
116         }
117 }
118
119 bool DocumentImporter::import()
120 {
121         ErrorHandler errorHandler;
122         COLLADASaxFWL::Loader loader(&errorHandler);
123         COLLADAFW::Root root(&loader, this);
124         ExtraHandler *ehandler = new ExtraHandler(this, &(this->anim_importer));
125         
126         loader.registerExtraDataCallbackHandler(ehandler);
127
128         // deselect all to select new objects
129         BKE_scene_base_deselect_all(CTX_data_scene(mContext));
130
131         if (!root.loadDocument(mFilename)) {
132                 fprintf(stderr, "COLLADAFW::Root::loadDocument() returned false on 1st pass\n");
133                 return false;
134         }
135         
136         if (errorHandler.hasError())
137                 return false;
138         
139         /** TODO set up scene graph and such here */
140         
141         mImportStage = Controller;
142         
143         COLLADASaxFWL::Loader loader2;
144         COLLADAFW::Root root2(&loader2, this);
145         
146         if (!root2.loadDocument(mFilename)) {
147                 fprintf(stderr, "COLLADAFW::Root::loadDocument() returned false on 2nd pass\n");
148                 return false;
149         }
150         
151         
152         delete ehandler;
153
154         mesh_importer.bmeshConversion();
155
156         return true;
157 }
158
159 void DocumentImporter::cancel(const COLLADAFW::String& errorMessage)
160 {
161         // TODO: if possible show error info
162         //
163         // Should we get rid of invisible Meshes that were created so far
164         // or maybe create objects at coordinate space origin?
165         //
166         // The latter sounds better.
167 }
168
169 void DocumentImporter::start()
170 {
171 }
172
173 void DocumentImporter::finish()
174 {
175         if (mImportStage != General)
176                 return;
177                 
178         /** TODO Break up and put into 2-pass parsing of DAE */
179         std::vector<const COLLADAFW::VisualScene *>::iterator it;
180         for (it = vscenes.begin(); it != vscenes.end(); it++) {
181                 PointerRNA sceneptr, unit_settings;
182                 PropertyRNA *system, *scale;
183                 // TODO: create a new scene except the selected <visual_scene> - use current blender scene for it
184                 Scene *sce = CTX_data_scene(mContext);
185                 
186                 // for scene unit settings: system, scale_length
187                 RNA_id_pointer_create(&sce->id, &sceneptr);
188                 unit_settings = RNA_pointer_get(&sceneptr, "unit_settings");
189                 system = RNA_struct_find_property(&unit_settings, "system");
190                 scale = RNA_struct_find_property(&unit_settings, "scale_length");
191                 
192                 switch (unit_converter.isMetricSystem()) {
193                         case UnitConverter::Metric:
194                                 RNA_property_enum_set(&unit_settings, system, USER_UNIT_METRIC);
195                                 break;
196                         case UnitConverter::Imperial:
197                                 RNA_property_enum_set(&unit_settings, system, USER_UNIT_IMPERIAL);
198                                 break;
199                         default:
200                                 RNA_property_enum_set(&unit_settings, system, USER_UNIT_NONE);
201                                 break;
202                 }
203                 RNA_property_float_set(&unit_settings, scale, unit_converter.getLinearMeter());
204                 
205                 const COLLADAFW::NodePointerArray& roots = (*it)->getRootNodes();
206
207                 for (unsigned int i = 0; i < roots.getCount(); i++) {
208                         write_node(roots[i], NULL, sce, NULL, false);
209                 }
210         }
211
212
213         mesh_importer.optimize_material_assignments();
214
215         armature_importer.set_tags_map(this->uid_tags_map);
216         armature_importer.make_armatures(mContext);
217
218 #if 0
219         armature_importer.fix_animation();
220 #endif
221
222         for (std::vector<const COLLADAFW::VisualScene *>::iterator it = vscenes.begin(); it != vscenes.end(); it++) {
223                 const COLLADAFW::NodePointerArray& roots = (*it)->getRootNodes();
224
225                 for (unsigned int i = 0; i < roots.getCount(); i++)
226                         translate_anim_recursive(roots[i], NULL, NULL);
227         }
228
229         if (libnode_ob.size()) {
230                 Scene *sce = CTX_data_scene(mContext);
231
232                 fprintf(stderr, "got %d library nodes to free\n", (int)libnode_ob.size());
233                 // free all library_nodes
234                 std::vector<Object *>::iterator it;
235                 for (it = libnode_ob.begin(); it != libnode_ob.end(); it++) {
236                         Object *ob = *it;
237
238                         Base *base = BKE_scene_base_find(sce, ob);
239                         if (base) {
240                                 BLI_remlink(&sce->base, base);
241                                 BKE_libblock_free_us(&G.main->object, base->object);
242                                 if (sce->basact == base)
243                                         sce->basact = NULL;
244                                 MEM_freeN(base);
245                         }
246                 }
247                 libnode_ob.clear();
248
249                 DAG_scene_sort(CTX_data_main(mContext), sce);
250                 DAG_ids_flush_update(CTX_data_main(mContext), 0);
251         }
252 }
253
254
255 void DocumentImporter::translate_anim_recursive(COLLADAFW::Node *node, COLLADAFW::Node *par = NULL, Object *parob = NULL)
256 {
257
258         // The split in #29246, rootmap must point at actual root when
259         // calculating bones in apply_curves_as_matrix.
260         // This has to do with inverse bind poses being world space
261         // (the sources for skinned bones' restposes) and the way
262         // non-skinning nodes have their "restpose" recursively calculated.
263         // XXX TODO: design issue, how to support unrelated joints taking
264         // part in skinning.
265         if (par) { // && par->getType() == COLLADAFW::Node::JOINT) {
266                 // par is root if there's no corresp. key in root_map
267                 if (root_map.find(par->getUniqueId()) == root_map.end())
268                         root_map[node->getUniqueId()] = par;
269                 else
270                         root_map[node->getUniqueId()] = root_map[par->getUniqueId()];
271         }
272
273 #if 0
274         COLLADAFW::Transformation::TransformationType types[] = {
275                 COLLADAFW::Transformation::ROTATE,
276                 COLLADAFW::Transformation::SCALE,
277                 COLLADAFW::Transformation::TRANSLATE,
278                 COLLADAFW::Transformation::MATRIX
279         };
280
281         Object *ob;
282 #endif
283         unsigned int i;
284
285         //for (i = 0; i < 4; i++)
286         //    ob =
287         anim_importer.translate_Animations(node, root_map, object_map, FW_object_map);
288
289         COLLADAFW::NodePointerArray &children = node->getChildNodes();
290         for (i = 0; i < children.getCount(); i++) {
291                 translate_anim_recursive(children[i], node, NULL);
292         }
293 }
294
295 /** When this method is called, the writer must write the global document asset.
296  * \return The writer should return true, if writing succeeded, false otherwise.*/
297 bool DocumentImporter::writeGlobalAsset(const COLLADAFW::FileInfo *asset)
298 {
299         unit_converter.read_asset(asset);
300
301         return true;
302 }
303
304 /** When this method is called, the writer must write the scene.
305  * \return The writer should return true, if writing succeeded, false otherwise.*/
306 bool DocumentImporter::writeScene(const COLLADAFW::Scene *scene)
307 {
308         // XXX could store the scene id, but do nothing for now
309         return true;
310 }
311 Object *DocumentImporter::create_camera_object(COLLADAFW::InstanceCamera *camera, Scene *sce)
312 {
313         const COLLADAFW::UniqueId& cam_uid = camera->getInstanciatedObjectId();
314         if (uid_camera_map.find(cam_uid) == uid_camera_map.end()) {     
315                 // fprintf(stderr, "Couldn't find camera by UID.\n");
316                 return NULL;
317         }
318
319         Object *ob = bc_add_object(sce, OB_CAMERA, NULL);
320         Camera *cam = uid_camera_map[cam_uid];
321         Camera *old_cam = (Camera *)ob->data;
322         ob->data = cam;
323         old_cam->id.us--;
324         if (old_cam->id.us == 0)
325                 BKE_libblock_free(&G.main->camera, old_cam);
326         return ob;
327 }
328
329 Object *DocumentImporter::create_lamp_object(COLLADAFW::InstanceLight *lamp, Scene *sce)
330 {
331         const COLLADAFW::UniqueId& lamp_uid = lamp->getInstanciatedObjectId();
332         if (uid_lamp_map.find(lamp_uid) == uid_lamp_map.end()) {        
333                 fprintf(stderr, "Couldn't find lamp by UID.\n");
334                 return NULL;
335         }
336
337         Object *ob = bc_add_object(sce, OB_LAMP, NULL);
338         Lamp *la = uid_lamp_map[lamp_uid];
339         Lamp *old_lamp = (Lamp *)ob->data;
340         ob->data = la;
341         old_lamp->id.us--;
342         if (old_lamp->id.us == 0)
343                 BKE_libblock_free(&G.main->lamp, old_lamp);
344         return ob;
345 }
346
347 Object *DocumentImporter::create_instance_node(Object *source_ob, COLLADAFW::Node *source_node, COLLADAFW::Node *instance_node, Scene *sce, bool is_library_node)
348 {
349         fprintf(stderr, "create <instance_node> under node id=%s from node id=%s\n", instance_node ? instance_node->getOriginalId().c_str() : NULL, source_node ? source_node->getOriginalId().c_str() : NULL);
350
351         Object *obn = BKE_object_copy(source_ob);
352         obn->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
353         BKE_scene_base_add(sce, obn);
354
355         if (instance_node) {
356                 anim_importer.read_node_transform(instance_node, obn);
357                 // if we also have a source_node (always ;), take its
358                 // transformation matrix and apply it to the newly instantiated
359                 // object to account for node hierarchy transforms in
360                 // .dae
361                 if (source_node) {
362                         COLLADABU::Math::Matrix4 mat4 = source_node->getTransformationMatrix();
363                         COLLADABU::Math::Matrix4 bmat4 = mat4.transpose(); // transpose to get blender row-major order
364                         float mat[4][4];
365                         for (int i = 0; i < 4; i++) {
366                                 for (int j = 0; j < 4; j++) {
367                                         mat[i][j] = bmat4[i][j];
368                                 }
369                         }
370                         // calc new matrix and apply
371                         mult_m4_m4m4(obn->obmat, obn->obmat, mat);
372                         BKE_object_apply_mat4(obn, obn->obmat, 0, 0);
373                 }
374         }
375         else {
376                 anim_importer.read_node_transform(source_node, obn);
377         }
378
379         DAG_scene_sort(CTX_data_main(mContext), sce);
380         DAG_ids_flush_update(CTX_data_main(mContext), 0);
381
382         COLLADAFW::NodePointerArray &children = source_node->getChildNodes();
383         if (children.getCount()) {
384                 for (unsigned int i = 0; i < children.getCount(); i++) {
385                         COLLADAFW::Node *child_node = children[i];
386                         const COLLADAFW::UniqueId& child_id = child_node->getUniqueId();
387                         if (object_map.find(child_id) == object_map.end())
388                                 continue;
389                         COLLADAFW::InstanceNodePointerArray &inodes = child_node->getInstanceNodes();
390                         Object *new_child = NULL;
391                         if (inodes.getCount()) { // \todo loop through instance nodes
392                                 const COLLADAFW::UniqueId& id = inodes[0]->getInstanciatedObjectId();
393                                 fprintf(stderr, "Doing %d child nodes\n", (int)node_map.count(id));
394                                 new_child = create_instance_node(object_map.find(id)->second, node_map[id], child_node, sce, is_library_node);
395                         }
396                         else {
397                                 new_child = create_instance_node(object_map.find(child_id)->second, child_node, NULL, sce, is_library_node);
398                         }
399                         bc_set_parent(new_child, obn, mContext, true);
400
401                         if (is_library_node)
402                                 libnode_ob.push_back(new_child);
403                 }
404         }
405
406         return obn;
407 }
408
409 void DocumentImporter::write_node(COLLADAFW::Node *node, COLLADAFW::Node *parent_node, Scene *sce, Object *par, bool is_library_node)
410 {
411         Object *ob = NULL;
412         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
413         bool read_transform = true;
414
415         std::vector<Object *> *objects_done = new std::vector<Object *>();
416
417         if (is_joint) {
418                 if (par) {
419                         Object *empty = par;
420                         par = bc_add_object(sce, OB_ARMATURE, NULL);
421                         bc_set_parent(par, empty->parent, mContext);
422                         //remove empty : todo
423                         object_map.insert(std::make_pair<COLLADAFW::UniqueId, Object *>(parent_node->getUniqueId(), par));
424                 }
425                 armature_importer.add_joint(node, parent_node == NULL || parent_node->getType() != COLLADAFW::Node::JOINT, par, sce);
426         }
427         else {
428                 COLLADAFW::InstanceGeometryPointerArray &geom = node->getInstanceGeometries();
429                 COLLADAFW::InstanceCameraPointerArray &camera = node->getInstanceCameras();
430                 COLLADAFW::InstanceLightPointerArray &lamp = node->getInstanceLights();
431                 COLLADAFW::InstanceControllerPointerArray &controller = node->getInstanceControllers();
432                 COLLADAFW::InstanceNodePointerArray &inst_node = node->getInstanceNodes();
433                 size_t geom_done = 0;
434                 size_t camera_done = 0;
435                 size_t lamp_done = 0;
436                 size_t controller_done = 0;
437                 size_t inst_done = 0;
438
439                 // XXX linking object with the first <instance_geometry>, though a node may have more of them...
440                 // maybe join multiple <instance_...> meshes into 1, and link object with it? not sure...
441                 // <instance_geometry>
442                 while (geom_done < geom.getCount()) {
443                         ob = mesh_importer.create_mesh_object(node, geom[geom_done], false, uid_material_map,
444                                                               material_texture_mapping_map);
445                         objects_done->push_back(ob);
446                         ++geom_done;
447                 }
448                 while (camera_done < camera.getCount()) {
449                         ob = create_camera_object(camera[camera_done], sce);
450                         if (ob == NULL) {
451                                 std::string id = node->getOriginalId();
452                                 std::string name = node->getName();
453                                 fprintf(stderr, "<node id=\"%s\", name=\"%s\" >...contains a reference to an unknown instance_camera.\n", id.c_str(), name.c_str());
454                         }
455                         else
456                                 objects_done->push_back(ob);
457                         ++camera_done;
458                 }
459                 while (lamp_done < lamp.getCount()) {
460                         ob = create_lamp_object(lamp[lamp_done], sce);
461                         objects_done->push_back(ob);
462                         ++lamp_done;
463                 }
464                 while (controller_done < controller.getCount()) {
465                         COLLADAFW::InstanceGeometry *geom = (COLLADAFW::InstanceGeometry *)controller[controller_done];
466                         ob = mesh_importer.create_mesh_object(node, geom, true, uid_material_map, material_texture_mapping_map);
467                         objects_done->push_back(ob);
468                         ++controller_done;
469                 }
470                 // XXX instance_node is not supported yet
471                 while (inst_done < inst_node.getCount()) {
472                         const COLLADAFW::UniqueId& node_id = inst_node[inst_done]->getInstanciatedObjectId();
473                         if (object_map.find(node_id) == object_map.end()) {
474                                 fprintf(stderr, "Cannot find object for node referenced by <instance_node name=\"%s\">.\n", inst_node[inst_done]->getName().c_str());
475                                 ob = NULL;
476                         }
477                         else {
478                                 std::pair<std::multimap<COLLADAFW::UniqueId, Object *>::iterator, std::multimap<COLLADAFW::UniqueId, Object *>::iterator> pair_iter = object_map.equal_range(node_id);
479                                 for (std::multimap<COLLADAFW::UniqueId, Object *>::iterator it2 = pair_iter.first; it2 != pair_iter.second; it2++) {
480                                         Object *source_ob = (Object *)it2->second;
481                                         COLLADAFW::Node *source_node = node_map[node_id];
482                                         ob = create_instance_node(source_ob, source_node, node, sce, is_library_node);
483                                 }
484                         }
485                         if (ob != NULL) objects_done->push_back(ob);
486                         ++inst_done;
487
488                         read_transform = false;
489                 }
490                 // if node is empty - create empty object
491                 // XXX empty node may not mean it is empty object, not sure about this
492                 if ( (geom_done + camera_done + lamp_done + controller_done + inst_done) < 1) {
493                         ob = bc_add_object(sce, OB_EMPTY, NULL);
494                         objects_done->push_back(ob);
495                 }
496                 
497                 // XXX: if there're multiple instances, only one is stored
498
499                 if (!ob) return;
500                 for (std::vector<Object *>::iterator it = objects_done->begin(); it != objects_done->end(); ++it) {
501                         ob = *it;
502                         std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
503                         rename_id(&ob->id, (char *)nodename.c_str());
504                         object_map.insert(std::make_pair<COLLADAFW::UniqueId, Object *>(node->getUniqueId(), ob));
505                         node_map[node->getUniqueId()] = node;
506
507                         if (is_library_node)
508                                 libnode_ob.push_back(ob);
509                 }
510
511         }
512
513         for (std::vector<Object *>::iterator it = objects_done->begin(); it != objects_done->end(); ++it) {
514                 ob = *it;
515
516                 if (read_transform)
517                         anim_importer.read_node_transform(node, ob);  // overwrites location set earlier
518
519                 if (!is_joint) {
520                         // if par was given make this object child of the previous
521                         if (par && ob)
522                                 bc_set_parent(ob, par, mContext);
523                 }
524         }
525         // if node has child nodes write them
526         COLLADAFW::NodePointerArray &child_nodes = node->getChildNodes();
527         for (unsigned int i = 0; i < child_nodes.getCount(); i++) {     
528                 write_node(child_nodes[i], node, sce, ob, is_library_node);
529         }
530 }
531
532 /** When this method is called, the writer must write the entire visual scene.
533  * \return The writer should return true, if writing succeeded, false otherwise.*/
534 bool DocumentImporter::writeVisualScene(const COLLADAFW::VisualScene *visualScene)
535 {
536         if (mImportStage != General)
537                 return true;
538                 
539         // this method called on post process after writeGeometry, writeMaterial, etc.
540
541         // for each <node> in <visual_scene>:
542         // create an Object
543         // if Mesh (previously created in writeGeometry) to which <node> corresponds exists, link Object with that mesh
544
545         // update: since we cannot link a Mesh with Object in
546         // writeGeometry because <geometry> does not reference <node>,
547         // we link Objects with Meshes here
548
549         vscenes.push_back(visualScene);
550         
551         return true;
552 }
553
554 /** When this method is called, the writer must handle all nodes contained in the 
555 * library nodes.
556 * \return The writer should return true, if writing succeeded, false otherwise.*/
557 bool DocumentImporter::writeLibraryNodes(const COLLADAFW::LibraryNodes *libraryNodes)
558 {
559         if (mImportStage != General)
560                 return true;
561                 
562         Scene *sce = CTX_data_scene(mContext);
563
564         const COLLADAFW::NodePointerArray& nodes = libraryNodes->getNodes();
565
566         for (unsigned int i = 0; i < nodes.getCount(); i++) {
567                 write_node(nodes[i], NULL, sce, NULL, true);
568         }
569
570         return true;
571 }
572
573 /** When this method is called, the writer must write the geometry.
574  * \return The writer should return true, if writing succeeded, false otherwise.*/
575 bool DocumentImporter::writeGeometry(const COLLADAFW::Geometry *geom)
576 {
577         if (mImportStage != General)
578                 return true;
579                 
580         return mesh_importer.write_geometry(geom);
581 }
582
583 /** When this method is called, the writer must write the material.
584  * \return The writer should return true, if writing succeeded, false otherwise.*/
585 bool DocumentImporter::writeMaterial(const COLLADAFW::Material *cmat)
586 {
587         if (mImportStage != General)
588                 return true;
589                 
590         const std::string& str_mat_id = cmat->getName().size() ? cmat->getName() : cmat->getOriginalId();
591         Material *ma = BKE_material_add((char *)str_mat_id.c_str());
592         
593         this->uid_effect_map[cmat->getInstantiatedEffect()] = ma;
594         this->uid_material_map[cmat->getUniqueId()] = ma;
595         
596         return true;
597 }
598
599 // create mtex, create texture, set texture image
600 MTex *DocumentImporter::create_texture(COLLADAFW::EffectCommon *ef, COLLADAFW::Texture &ctex, Material *ma,
601                                        int i, TexIndexTextureArrayMap &texindex_texarray_map)
602 {
603         COLLADAFW::SamplerPointerArray& samp_array = ef->getSamplerPointerArray();
604         COLLADAFW::Sampler *sampler = samp_array[ctex.getSamplerId()];
605                 
606         const COLLADAFW::UniqueId& ima_uid = sampler->getSourceImage();
607         
608         if (uid_image_map.find(ima_uid) == uid_image_map.end()) {
609                 fprintf(stderr, "Couldn't find an image by UID.\n");
610                 return NULL;
611         }
612         
613         ma->mtex[i] = add_mtex();
614         ma->mtex[i]->texco = TEXCO_UV;
615         ma->mtex[i]->tex = add_texture("Texture");
616         ma->mtex[i]->tex->type = TEX_IMAGE;
617         ma->mtex[i]->tex->imaflag &= ~TEX_USEALPHA;
618         ma->mtex[i]->tex->ima = uid_image_map[ima_uid];
619         
620         texindex_texarray_map[ctex.getTextureMapId()].push_back(ma->mtex[i]);
621         
622         return ma->mtex[i];
623 }
624
625 void DocumentImporter::write_profile_COMMON(COLLADAFW::EffectCommon *ef, Material *ma)
626 {
627         COLLADAFW::EffectCommon::ShaderType shader = ef->getShaderType();
628         
629         // blinn
630         if (shader == COLLADAFW::EffectCommon::SHADER_BLINN) {
631                 ma->spec_shader = MA_SPEC_BLINN;
632                 ma->spec = ef->getShininess().getFloatValue();
633         }
634         // phong
635         else if (shader == COLLADAFW::EffectCommon::SHADER_PHONG) {
636                 ma->spec_shader = MA_SPEC_PHONG;
637                 ma->har = ef->getShininess().getFloatValue();
638         }
639         // lambert
640         else if (shader == COLLADAFW::EffectCommon::SHADER_LAMBERT) {
641                 ma->diff_shader = MA_DIFF_LAMBERT;
642         }
643         // default - lambert
644         else {
645                 ma->diff_shader = MA_DIFF_LAMBERT;
646                 fprintf(stderr, "Current shader type is not supported, default to lambert.\n");
647         }
648         // reflectivity
649         ma->ray_mirror = ef->getReflectivity().getFloatValue();
650         // index of refraction
651         ma->ang = ef->getIndexOfRefraction().getFloatValue();
652         
653         int i = 0;
654         COLLADAFW::Color col;
655         MTex *mtex = NULL;
656         TexIndexTextureArrayMap texindex_texarray_map;
657         
658         // DIFFUSE
659         // color
660         if (ef->getDiffuse().isColor()) {
661                 col = ef->getDiffuse().getColor();
662                 ma->r = col.getRed();
663                 ma->g = col.getGreen();
664                 ma->b = col.getBlue();
665         }
666         // texture
667         else if (ef->getDiffuse().isTexture()) {
668                 COLLADAFW::Texture ctex = ef->getDiffuse().getTexture(); 
669                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
670                 if (mtex != NULL) {
671                         mtex->mapto = MAP_COL;
672                         ma->texact = (int)i;
673                         i++;
674                 }
675         }
676         // AMBIENT
677         // color
678         if (ef->getAmbient().isColor()) {
679                 col = ef->getAmbient().getColor();
680                 ma->ambr = col.getRed();
681                 ma->ambg = col.getGreen();
682                 ma->ambb = col.getBlue();
683         }
684         // texture
685         else if (ef->getAmbient().isTexture()) {
686                 COLLADAFW::Texture ctex = ef->getAmbient().getTexture(); 
687                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
688                 if (mtex != NULL) {
689                         mtex->mapto = MAP_AMB; 
690                         i++;
691                 }
692         }
693         // SPECULAR
694         // color
695         if (ef->getSpecular().isColor()) {
696                 col = ef->getSpecular().getColor();
697                 ma->specr = col.getRed();
698                 ma->specg = col.getGreen();
699                 ma->specb = col.getBlue();
700         }
701         // texture
702         else if (ef->getSpecular().isTexture()) {
703                 COLLADAFW::Texture ctex = ef->getSpecular().getTexture(); 
704                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
705                 if (mtex != NULL) {
706                         mtex->mapto = MAP_SPEC; 
707                         i++;
708                 }
709         }
710         // REFLECTIVE
711         // color
712         if (ef->getReflective().isColor()) {
713                 col = ef->getReflective().getColor();
714                 ma->mirr = col.getRed();
715                 ma->mirg = col.getGreen();
716                 ma->mirb = col.getBlue();
717         }
718         // texture
719         else if (ef->getReflective().isTexture()) {
720                 COLLADAFW::Texture ctex = ef->getReflective().getTexture(); 
721                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
722                 if (mtex != NULL) {
723                         mtex->mapto = MAP_REF; 
724                         i++;
725                 }
726         }
727         // EMISSION
728         // color
729         if (ef->getEmission().isColor()) {
730                 // XXX there is no emission color in blender
731                 // but I am not sure
732         }
733         // texture
734         else if (ef->getEmission().isTexture()) {
735                 COLLADAFW::Texture ctex = ef->getEmission().getTexture(); 
736                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
737                 if (mtex != NULL) {
738                         mtex->mapto = MAP_EMIT; 
739                         i++;
740                 }
741         }
742         
743         if (ef->getOpacity().isTexture()) {
744                 COLLADAFW::Texture ctex = ef->getOpacity().getTexture();
745                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
746                 if (mtex != NULL) {
747                         mtex->mapto = MAP_ALPHA;
748                         mtex->tex->imaflag |= TEX_USEALPHA;
749                         i++;
750                         ma->spectra = ma->alpha = 0;
751                         ma->mode |= MA_ZTRANSP | MA_TRANSP;
752                 }
753         }
754         // TRANSPARENT
755         // color
756 #if 0
757         if (ef->getOpacity().isColor()) {
758                 // XXX don't know what to do here
759         }
760         // texture
761         else if (ef->getOpacity().isTexture()) {
762                 ctex = ef->getOpacity().getTexture();
763                 if (mtex != NULL) mtex->mapto &= MAP_ALPHA;
764                 else {
765                         mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
766                         if (mtex != NULL) mtex->mapto = MAP_ALPHA;
767                 }
768         }
769 #endif
770         material_texture_mapping_map[ma] = texindex_texarray_map;
771 }
772
773 /** When this method is called, the writer must write the effect.
774  * \return The writer should return true, if writing succeeded, false otherwise.*/
775
776 bool DocumentImporter::writeEffect(const COLLADAFW::Effect *effect)
777 {
778         if (mImportStage != General)
779                 return true;
780         
781         const COLLADAFW::UniqueId& uid = effect->getUniqueId();
782         
783         if (uid_effect_map.find(uid) == uid_effect_map.end()) {
784                 fprintf(stderr, "Couldn't find a material by UID.\n");
785                 return true;
786         }
787         
788         Material *ma = uid_effect_map[uid];
789         std::map<COLLADAFW::UniqueId, Material *>::iterator iter;
790         for (iter = uid_material_map.begin(); iter != uid_material_map.end(); iter++) {
791                 if (iter->second == ma) {
792                         this->FW_object_map[iter->first] = effect;
793                         break;
794                 }
795         }
796         COLLADAFW::CommonEffectPointerArray common_efs = effect->getCommonEffects();
797         if (common_efs.getCount() < 1) {
798                 fprintf(stderr, "Couldn't find <profile_COMMON>.\n");
799                 return true;
800         }
801         // XXX TODO: Take all <profile_common>s
802         // Currently only first <profile_common> is supported
803         COLLADAFW::EffectCommon *ef = common_efs[0];
804         write_profile_COMMON(ef, ma);
805         this->FW_object_map[effect->getUniqueId()] = effect;
806                 
807         return true;
808 }
809
810
811 /** When this method is called, the writer must write the camera.
812  * \return The writer should return true, if writing succeeded, false otherwise.*/
813 bool DocumentImporter::writeCamera(const COLLADAFW::Camera *camera)
814 {
815         if (mImportStage != General)
816                 return true;
817                 
818         Camera *cam = NULL;
819         std::string cam_id, cam_name;
820         
821         cam_id = camera->getOriginalId();
822         cam_name = camera->getName();
823         if (cam_name.size()) cam = (Camera *)BKE_camera_add((char *)cam_name.c_str());
824         else cam = (Camera *)BKE_camera_add((char *)cam_id.c_str());
825         
826         if (!cam) {
827                 fprintf(stderr, "Cannot create camera.\n");
828                 return true;
829         }
830         cam->clipsta = camera->getNearClippingPlane().getValue();
831         cam->clipend = camera->getFarClippingPlane().getValue();
832         
833         COLLADAFW::Camera::CameraType type = camera->getCameraType();
834         switch (type) {
835                 case COLLADAFW::Camera::ORTHOGRAPHIC:
836                 {
837                         cam->type = CAM_ORTHO;
838                 }
839                 break;
840                 case COLLADAFW::Camera::PERSPECTIVE:
841                 {
842                         cam->type = CAM_PERSP;
843                 }
844                 break;
845                 case COLLADAFW::Camera::UNDEFINED_CAMERATYPE:
846                 {
847                         fprintf(stderr, "Current camera type is not supported.\n");
848                         cam->type = CAM_PERSP;
849                 }
850                 break;
851         }
852         
853         switch (camera->getDescriptionType()) {
854                 case COLLADAFW::Camera::ASPECTRATIO_AND_Y:
855                 {
856                         switch (cam->type) {
857                                 case CAM_ORTHO:
858                                 {
859                                         double ymag = 2 * camera->getYMag().getValue();
860                                         double aspect = camera->getAspectRatio().getValue();
861                                         double xmag = aspect * ymag;
862                                         cam->ortho_scale = (float)xmag;
863                                 }
864                                 break;
865                                 case CAM_PERSP:
866                                 default:
867                                 {
868                                         double yfov = camera->getYFov().getValue();
869                                         double aspect = camera->getAspectRatio().getValue();
870
871                                         // NOTE: Needs more testing (As we curretnly have no official test data for this)
872
873                                         double xfov = 2.0f * atanf(aspect * tanf(DEG2RADF(yfov) * 0.5f));
874                                         cam->lens = fov_to_focallength(xfov, cam->sensor_x);
875                                 }
876                                 break;
877                         }
878                 }
879                 break;
880                 /* XXX correct way to do following four is probably to get also render
881                  * size and determine proper settings from that somehow */
882                 case COLLADAFW::Camera::ASPECTRATIO_AND_X:
883                 case COLLADAFW::Camera::SINGLE_X:
884                 case COLLADAFW::Camera::X_AND_Y:
885                 {
886                         switch (cam->type) {
887                                 case CAM_ORTHO:
888                                         cam->ortho_scale = (float)camera->getXMag().getValue() * 2;
889                                         break;
890                                 case CAM_PERSP:
891                                 default:
892                                 {
893                                         double x = camera->getXFov().getValue();
894                                         // x is in degrees, cam->lens is in millimiters
895                                         cam->lens = fov_to_focallength(DEG2RADF(x), cam->sensor_x);
896                                 }
897                                 break;
898                         }
899                 }
900                 break;
901                 case COLLADAFW::Camera::SINGLE_Y:
902                 {
903                         switch (cam->type) {
904                                 case CAM_ORTHO:
905                                         cam->ortho_scale = (float)camera->getYMag().getValue();
906                                         break;
907                                 case CAM_PERSP:
908                                 default:
909                                 {
910                                         double yfov = camera->getYFov().getValue();
911                                         // yfov is in degrees, cam->lens is in millimiters
912                                         cam->lens = fov_to_focallength(DEG2RADF(yfov), cam->sensor_x);
913                                 }
914                                 break;
915                         }
916                 }
917                 break;
918                 case COLLADAFW::Camera::UNDEFINED:
919                         // read nothing, use blender defaults.
920                         break;
921         }
922         
923         this->uid_camera_map[camera->getUniqueId()] = cam;
924         this->FW_object_map[camera->getUniqueId()] = camera;
925         // XXX import camera options
926         return true;
927 }
928
929 /** When this method is called, the writer must write the image.
930  * \return The writer should return true, if writing succeeded, false otherwise.*/
931 bool DocumentImporter::writeImage(const COLLADAFW::Image *image)
932 {
933         if (mImportStage != General)
934                 return true;
935                 
936         // XXX maybe it is necessary to check if the path is absolute or relative
937         const std::string& filepath = image->getImageURI().toNativePath();
938         const char *filename = (const char *)mFilename.c_str();
939         char dir[FILE_MAX];
940         char full_path[FILE_MAX];
941         
942         BLI_split_dir_part(filename, dir, sizeof(dir));
943         BLI_join_dirfile(full_path, sizeof(full_path), dir, filepath.c_str());
944         Image *ima = BKE_image_load_exists(full_path);
945         if (!ima) {
946                 fprintf(stderr, "Cannot create image.\n");
947                 return true;
948         }
949         this->uid_image_map[image->getUniqueId()] = ima;
950         
951         return true;
952 }
953
954 /** When this method is called, the writer must write the light.
955  * \return The writer should return true, if writing succeeded, false otherwise.*/
956 bool DocumentImporter::writeLight(const COLLADAFW::Light *light)
957 {
958         if (mImportStage != General)
959                 return true;
960
961         Lamp *lamp = NULL;
962         std::string la_id, la_name;
963
964         TagsMap::iterator etit;
965         ExtraTags *et = 0;
966         etit = uid_tags_map.find(light->getUniqueId().toAscii());
967         if (etit != uid_tags_map.end())
968                 et = etit->second;
969
970         la_id = light->getOriginalId();
971         la_name = light->getName();
972         if (la_name.size()) lamp = (Lamp *)BKE_lamp_add((char *)la_name.c_str());
973         else lamp = (Lamp *)BKE_lamp_add((char *)la_id.c_str());
974
975         if (!lamp) {
976                 fprintf(stderr, "Cannot create lamp.\n");
977                 return true;
978         }
979
980         // if we find an ExtraTags for this, use that instead.
981         if (et && et->isProfile("blender")) {
982                 et->setData("type", &(lamp->type));
983                 et->setData("flag", &(lamp->flag));
984                 et->setData("mode", &(lamp->mode));
985                 et->setData("gamma", &(lamp->k));
986                 et->setData("red", &(lamp->r));
987                 et->setData("green", &(lamp->g));
988                 et->setData("blue", &(lamp->b));
989                 et->setData("shadow_r", &(lamp->shdwr));
990                 et->setData("shadow_g", &(lamp->shdwg));
991                 et->setData("shadow_b", &(lamp->shdwb));
992                 et->setData("energy", &(lamp->energy));
993                 et->setData("dist", &(lamp->dist));
994                 et->setData("spotsize", &(lamp->spotsize));
995                 et->setData("spotblend", &(lamp->spotblend));
996                 et->setData("halo_intensity", &(lamp->haint));
997                 et->setData("att1", &(lamp->att1));
998                 et->setData("att2", &(lamp->att2));
999                 et->setData("falloff_type", &(lamp->falloff_type));
1000                 et->setData("clipsta", &(lamp->clipsta));
1001                 et->setData("clipend", &(lamp->clipend));
1002                 et->setData("shadspotsize", &(lamp->shadspotsize));
1003                 et->setData("bias", &(lamp->bias));
1004                 et->setData("soft", &(lamp->soft));
1005                 et->setData("compressthresh", &(lamp->compressthresh));
1006                 et->setData("bufsize", &(lamp->bufsize));
1007                 et->setData("samp", &(lamp->samp));
1008                 et->setData("buffers", &(lamp->buffers));
1009                 et->setData("filtertype", &(lamp->filtertype));
1010                 et->setData("bufflag", &(lamp->bufflag));
1011                 et->setData("buftype", &(lamp->buftype));
1012                 et->setData("ray_samp", &(lamp->ray_samp));
1013                 et->setData("ray_sampy", &(lamp->ray_sampy));
1014                 et->setData("ray_sampz", &(lamp->ray_sampz));
1015                 et->setData("ray_samp_type", &(lamp->ray_samp_type));
1016                 et->setData("area_shape", &(lamp->area_shape));
1017                 et->setData("area_size", &(lamp->area_size));
1018                 et->setData("area_sizey", &(lamp->area_sizey));
1019                 et->setData("area_sizez", &(lamp->area_sizez));
1020                 et->setData("adapt_thresh", &(lamp->adapt_thresh));
1021                 et->setData("ray_samp_method", &(lamp->ray_samp_method));
1022                 et->setData("shadhalostep", &(lamp->shadhalostep));
1023                 et->setData("sun_effect_type", &(lamp->shadhalostep));
1024                 et->setData("skyblendtype", &(lamp->skyblendtype));
1025                 et->setData("horizon_brightness", &(lamp->horizon_brightness));
1026                 et->setData("spread", &(lamp->spread));
1027                 et->setData("sun_brightness", &(lamp->sun_brightness));
1028                 et->setData("sun_size", &(lamp->sun_size));
1029                 et->setData("backscattered_light", &(lamp->backscattered_light));
1030                 et->setData("sun_intensity", &(lamp->sun_intensity));
1031                 et->setData("atm_turbidity", &(lamp->atm_turbidity));
1032                 et->setData("atm_extinction_factor", &(lamp->atm_extinction_factor));
1033                 et->setData("atm_distance_factor", &(lamp->atm_distance_factor));
1034                 et->setData("skyblendfac", &(lamp->skyblendfac));
1035                 et->setData("sky_exposure", &(lamp->sky_exposure));
1036                 et->setData("sky_colorspace", &(lamp->sky_colorspace));
1037         }
1038         else {
1039                 float constatt = light->getConstantAttenuation().getValue();
1040                 float linatt = light->getLinearAttenuation().getValue();
1041                 float quadatt = light->getQuadraticAttenuation().getValue();
1042                 float d = 25.0f;
1043                 float att1 = 0.0f;
1044                 float att2 = 0.0f;
1045                 float e = 1.0f;
1046
1047                 if (light->getColor().isValid()) {
1048                         COLLADAFW::Color col = light->getColor();
1049                         lamp->r = col.getRed();
1050                         lamp->g = col.getGreen();
1051                         lamp->b = col.getBlue();
1052                 }
1053
1054                 if (IS_EQ(linatt, 0.0f) && quadatt > 0.0f) {
1055                         att2 = quadatt;
1056                         d = sqrt(1.0f / quadatt);
1057                 }
1058                 // linear light
1059                 else if (IS_EQ(quadatt, 0.0f) && linatt > 0.0f) {
1060                         att1 = linatt;
1061                         d = (1.0f / linatt);
1062                 }
1063                 else if (IS_EQ(constatt, 1.0f)) {
1064                         att1 = 1.0f;
1065                 }
1066                 else {
1067                         // assuming point light (const att = 1.0);
1068                         att1 = 1.0f;
1069                 }
1070                 
1071                 d *= (1.0f / unit_converter.getLinearMeter());
1072
1073                 lamp->energy = e;
1074                 lamp->dist = d;
1075
1076                 COLLADAFW::Light::LightType type = light->getLightType();
1077                 switch (type) {
1078                         case COLLADAFW::Light::AMBIENT_LIGHT:
1079                         {
1080                                 lamp->type = LA_HEMI;
1081                         }
1082                         break;
1083                         case COLLADAFW::Light::SPOT_LIGHT:
1084                         {
1085                                 lamp->type = LA_SPOT;
1086                                 lamp->att1 = att1;
1087                                 lamp->att2 = att2;
1088                                 if (IS_EQ(att1, 0.0f) && att2 > 0)
1089                                         lamp->falloff_type = LA_FALLOFF_INVSQUARE;
1090                                 if (IS_EQ(att2, 0.0f) && att1 > 0)
1091                                         lamp->falloff_type = LA_FALLOFF_INVLINEAR;
1092                                 lamp->spotsize = light->getFallOffAngle().getValue();
1093                                 lamp->spotblend = light->getFallOffExponent().getValue();
1094                         }
1095                         break;
1096                         case COLLADAFW::Light::DIRECTIONAL_LIGHT:
1097                         {
1098                                 /* our sun is very strong, so pick a smaller energy level */
1099                                 lamp->type = LA_SUN;
1100                                 lamp->mode |= LA_NO_SPEC;
1101                         }
1102                         break;
1103                         case COLLADAFW::Light::POINT_LIGHT:
1104                         {
1105                                 lamp->type = LA_LOCAL;
1106                                 lamp->att1 = att1;
1107                                 lamp->att2 = att2;
1108                                 if (IS_EQ(att1, 0.0f) && att2 > 0)
1109                                         lamp->falloff_type = LA_FALLOFF_INVSQUARE;
1110                                 if (IS_EQ(att2, 0.0f) && att1 > 0)
1111                                         lamp->falloff_type = LA_FALLOFF_INVLINEAR;
1112                         }
1113                         break;
1114                         case COLLADAFW::Light::UNDEFINED:
1115                         {
1116                                 fprintf(stderr, "Current lamp type is not supported.\n");
1117                                 lamp->type = LA_LOCAL;
1118                         }
1119                         break;
1120                 }
1121         }
1122
1123         this->uid_lamp_map[light->getUniqueId()] = lamp;
1124         this->FW_object_map[light->getUniqueId()] = light;
1125         return true;
1126 }
1127
1128 // this function is called only for animations that pass COLLADAFW::validate
1129 bool DocumentImporter::writeAnimation(const COLLADAFW::Animation *anim)
1130 {
1131         if (mImportStage != General)
1132                 return true;
1133                 
1134         // return true;
1135         return anim_importer.write_animation(anim);
1136 }
1137
1138 // called on post-process stage after writeVisualScenes
1139 bool DocumentImporter::writeAnimationList(const COLLADAFW::AnimationList *animationList)
1140 {
1141         if (mImportStage != General)
1142                 return true;
1143                 
1144         // return true;
1145         return anim_importer.write_animation_list(animationList);
1146 }
1147
1148 /** When this method is called, the writer must write the skin controller data.
1149  * \return The writer should return true, if writing succeeded, false otherwise.*/
1150 bool DocumentImporter::writeSkinControllerData(const COLLADAFW::SkinControllerData *skin)
1151 {
1152         return armature_importer.write_skin_controller_data(skin);
1153 }
1154
1155 // this is called on postprocess, before writeVisualScenes
1156 bool DocumentImporter::writeController(const COLLADAFW::Controller *controller)
1157 {
1158         if (mImportStage != General)
1159                 return true;
1160                 
1161         return armature_importer.write_controller(controller);
1162 }
1163
1164 bool DocumentImporter::writeFormulas(const COLLADAFW::Formulas *formulas)
1165 {
1166         return true;
1167 }
1168
1169 bool DocumentImporter::writeKinematicsScene(const COLLADAFW::KinematicsScene *kinematicsScene)
1170 {
1171         return true;
1172 }
1173
1174 ExtraTags *DocumentImporter::getExtraTags(const COLLADAFW::UniqueId &uid)
1175 {
1176         if (uid_tags_map.find(uid.toAscii()) == uid_tags_map.end()) {
1177                 return NULL;
1178         }
1179         return uid_tags_map[uid.toAscii()];
1180 }
1181
1182 bool DocumentImporter::addExtraTags(const COLLADAFW::UniqueId &uid, ExtraTags *extra_tags)
1183 {
1184         uid_tags_map[uid.toAscii()] = extra_tags;
1185         return true;
1186 }
1187