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