Fixed Camera Ortho scale animation import
[blender-staging.git] / source / blender / collada / MeshImporter.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/MeshImporter.cpp
26  *  \ingroup collada
27  */
28
29
30 #include <algorithm>
31
32 #if !defined(WIN32) || defined(FREE_WINDOWS)
33 #include <iostream>
34 #endif
35
36 /* COLLADABU_ASSERT, may be able to remove later */
37 #include "COLLADABUPlatform.h"
38
39 #include "COLLADAFWMeshPrimitive.h"
40 #include "COLLADAFWMeshVertexData.h"
41 #include "COLLADAFWPolygons.h"
42
43 extern "C" {
44 #include "BKE_blender.h"
45 #include "BKE_customdata.h"
46 #include "BKE_displist.h"
47 #include "BKE_global.h"
48 #include "BKE_library.h"
49 #include "BKE_main.h"
50 #include "BKE_material.h"
51 #include "BKE_mesh.h"
52 #include "BKE_object.h"
53
54 #include "BLI_listbase.h"
55 #include "BLI_math.h"
56 #include "BLI_string.h"
57
58 #include "MEM_guardedalloc.h"
59 }
60
61 #include "ArmatureImporter.h"
62 #include "MeshImporter.h"
63 #include "collada_utils.h"
64
65 // get node name, or fall back to original id if not present (name is optional)
66 template<class T>
67 static const char *bc_get_dae_name(T *node)
68 {
69         const std::string& name = node->getName();
70         return name.size() ? name.c_str() : node->getOriginalId().c_str();
71 }
72
73 static const char *bc_primTypeToStr(COLLADAFW::MeshPrimitive::PrimitiveType type)
74 {
75         switch (type) {
76         case COLLADAFW::MeshPrimitive::LINES:
77                 return "LINES";
78         case COLLADAFW::MeshPrimitive::LINE_STRIPS:
79                 return "LINESTRIPS";
80         case COLLADAFW::MeshPrimitive::POLYGONS:
81                 return "POLYGONS";
82         case COLLADAFW::MeshPrimitive::POLYLIST:
83                 return "POLYLIST";
84         case COLLADAFW::MeshPrimitive::TRIANGLES:
85                 return "TRIANGLES";
86         case COLLADAFW::MeshPrimitive::TRIANGLE_FANS:
87                 return "TRIANGLE_FANS";
88         case COLLADAFW::MeshPrimitive::TRIANGLE_STRIPS:
89                 return "TRIANGLE_FANS";
90         case COLLADAFW::MeshPrimitive::POINTS:
91                 return "POINTS";
92         case COLLADAFW::MeshPrimitive::UNDEFINED_PRIMITIVE_TYPE:
93                 return "UNDEFINED_PRIMITIVE_TYPE";
94         }
95         return "UNKNOWN";
96 }
97
98 static const char *bc_geomTypeToStr(COLLADAFW::Geometry::GeometryType type)
99 {
100         switch (type) {
101         case COLLADAFW::Geometry::GEO_TYPE_MESH:
102                 return "MESH";
103         case COLLADAFW::Geometry::GEO_TYPE_SPLINE:
104                 return "SPLINE";
105         case COLLADAFW::Geometry::GEO_TYPE_CONVEX_MESH:
106                 return "CONVEX_MESH";
107         case COLLADAFW::Geometry::GEO_TYPE_UNKNOWN:
108         default:
109                 return "UNKNOWN";
110         }
111 }
112
113
114 UVDataWrapper::UVDataWrapper(COLLADAFW::MeshVertexData& vdata) : mVData(&vdata)
115 {}
116
117 #ifdef COLLADA_DEBUG
118 void WVDataWrapper::print()
119 {
120         fprintf(stderr, "UVs:\n");
121         switch(mVData->getType()) {
122         case COLLADAFW::MeshVertexData::DATA_TYPE_FLOAT:
123                 {
124                         COLLADAFW::ArrayPrimitiveType<float>* values = mVData->getFloatValues();
125                         if (values->getCount()) {
126                                 for (int i = 0; i < values->getCount(); i += 2) {
127                                         fprintf(stderr, "%.1f, %.1f\n", (*values)[i], (*values)[i+1]);
128                                 }
129                         }
130                 }
131                 break;
132         case COLLADAFW::MeshVertexData::DATA_TYPE_DOUBLE:
133                 {
134                         COLLADAFW::ArrayPrimitiveType<double>* values = mVData->getDoubleValues();
135                         if (values->getCount()) {
136                                 for (int i = 0; i < values->getCount(); i += 2) {
137                                         fprintf(stderr, "%.1f, %.1f\n", (float)(*values)[i], (float)(*values)[i+1]);
138                                 }
139                         }
140                 }
141                 break;
142         }
143         fprintf(stderr, "\n");
144 }
145 #endif
146
147 void UVDataWrapper::getUV(int uv_index, float *uv)
148 {
149         int stride = mVData->getStride(0);
150         if(stride==0) stride = 2;
151
152         switch(mVData->getType()) {
153         case COLLADAFW::MeshVertexData::DATA_TYPE_FLOAT:
154                 {
155                         COLLADAFW::ArrayPrimitiveType<float>* values = mVData->getFloatValues();
156                         if (values->empty()) return;
157                         uv[0] = (*values)[uv_index*stride];
158                         uv[1] = (*values)[uv_index*stride + 1];
159                         
160                 }
161                 break;
162         case COLLADAFW::MeshVertexData::DATA_TYPE_DOUBLE:
163                 {
164                         COLLADAFW::ArrayPrimitiveType<double>* values = mVData->getDoubleValues();
165                         if (values->empty()) return;
166                         uv[0] = (float)(*values)[uv_index*stride];
167                         uv[1] = (float)(*values)[uv_index*stride + 1];
168                         
169                 }
170                 break;
171         case COLLADAFW::MeshVertexData::DATA_TYPE_UNKNOWN:
172         default:
173                 fprintf(stderr, "MeshImporter.getUV(): unknown data type\n");
174         }
175 }
176
177 void MeshImporter::set_face_indices(MFace *mface, unsigned int *indices, bool quad)
178 {
179         mface->v1 = indices[0];
180         mface->v2 = indices[1];
181         mface->v3 = indices[2];
182         if (quad) mface->v4 = indices[3];
183         else mface->v4 = 0;
184 #ifdef COLLADA_DEBUG
185         // fprintf(stderr, "%u, %u, %u \n", indices[0], indices[1], indices[2]);
186 #endif
187 }
188
189 // not used anymore, test_index_face from blenkernel is better
190 #if 0
191 // change face indices order so that v4 is not 0
192 void MeshImporter::rotate_face_indices(MFace *mface) {
193         mface->v4 = mface->v1;
194         mface->v1 = mface->v2;
195         mface->v2 = mface->v3;
196         mface->v3 = 0;
197 }
198 #endif
199
200 void MeshImporter::set_face_uv(MTFace *mtface, UVDataWrapper &uvs,
201                                  COLLADAFW::IndexList& index_list, unsigned int *tris_indices)
202 {
203         // per face vertex indices, this means for quad we have 4 indices, not 8
204         COLLADAFW::UIntValuesArray& indices = index_list.getIndices();
205
206         uvs.getUV(indices[tris_indices[0]], mtface->uv[0]);
207         uvs.getUV(indices[tris_indices[1]], mtface->uv[1]);
208         uvs.getUV(indices[tris_indices[2]], mtface->uv[2]);
209 }
210
211 void MeshImporter::set_face_uv(MTFace *mtface, UVDataWrapper &uvs,
212                                 COLLADAFW::IndexList& index_list, int index, bool quad)
213 {
214         // per face vertex indices, this means for quad we have 4 indices, not 8
215         COLLADAFW::UIntValuesArray& indices = index_list.getIndices();
216
217         uvs.getUV(indices[index + 0], mtface->uv[0]);
218         uvs.getUV(indices[index + 1], mtface->uv[1]);
219         uvs.getUV(indices[index + 2], mtface->uv[2]);
220
221         if (quad) uvs.getUV(indices[index + 3], mtface->uv[3]);
222
223 #ifdef COLLADA_DEBUG
224         /*if (quad) {
225                 fprintf(stderr, "face uv:\n"
226                                 "((%d, %d, %d, %d))\n"
227                                 "((%.1f, %.1f), (%.1f, %.1f), (%.1f, %.1f), (%.1f, %.1f))\n",
228
229                                 indices[index + 0],
230                                 indices[index + 1],
231                                 indices[index + 2],
232                                 indices[index + 3],
233
234                                 mtface->uv[0][0], mtface->uv[0][1],
235                                 mtface->uv[1][0], mtface->uv[1][1],
236                                 mtface->uv[2][0], mtface->uv[2][1],
237                                 mtface->uv[3][0], mtface->uv[3][1]);
238         }
239         else {
240                 fprintf(stderr, "face uv:\n"
241                                 "((%d, %d, %d))\n"
242                                 "((%.1f, %.1f), (%.1f, %.1f), (%.1f, %.1f))\n",
243
244                                 indices[index + 0],
245                                 indices[index + 1],
246                                 indices[index + 2],
247
248                                 mtface->uv[0][0], mtface->uv[0][1],
249                                 mtface->uv[1][0], mtface->uv[1][1],
250                                 mtface->uv[2][0], mtface->uv[2][1]);
251         }*/
252 #endif
253 }
254
255 #ifdef COLLADA_DEBUG
256 void MeshImporter::print_index_list(COLLADAFW::IndexList& index_list)
257 {
258         fprintf(stderr, "Index list for \"%s\":\n", index_list.getName().c_str());
259         for (int i = 0; i < index_list.getIndicesCount(); i += 2) {
260                 fprintf(stderr, "%u, %u\n", index_list.getIndex(i), index_list.getIndex(i + 1));
261         }
262         fprintf(stderr, "\n");
263 }
264 #endif
265
266 bool MeshImporter::is_nice_mesh(COLLADAFW::Mesh *mesh)  // checks if mesh has supported primitive types: polylist, triangles, triangle_fans
267 {
268         COLLADAFW::MeshPrimitiveArray& prim_arr = mesh->getMeshPrimitives();
269
270         const char *name = bc_get_dae_name(mesh);
271         
272         for (unsigned i = 0; i < prim_arr.getCount(); i++) {
273                 
274                 COLLADAFW::MeshPrimitive *mp = prim_arr[i];
275                 COLLADAFW::MeshPrimitive::PrimitiveType type = mp->getPrimitiveType();
276
277                 const char *type_str = bc_primTypeToStr(type);
278                 
279                 // OpenCollada passes POLYGONS type for <polylist>
280                 if (type == COLLADAFW::MeshPrimitive::POLYLIST || type == COLLADAFW::MeshPrimitive::POLYGONS) {
281
282                         COLLADAFW::Polygons *mpvc = (COLLADAFW::Polygons*)mp;
283                         COLLADAFW::Polygons::VertexCountArray& vca = mpvc->getGroupedVerticesVertexCountArray();
284                         
285                         for(unsigned int j = 0; j < vca.getCount(); j++){
286                                 int count = vca[j];
287                                 if (count < 3) {
288                                         fprintf(stderr, "Primitive %s in %s has at least one face with vertex count < 3\n",
289                                                         type_str, name);
290                                         return false;
291                                 }
292                         }
293                                 
294                 }
295                 else if(type != COLLADAFW::MeshPrimitive::TRIANGLES && type!= COLLADAFW::MeshPrimitive::TRIANGLE_FANS) {
296                         fprintf(stderr, "Primitive type %s is not supported.\n", type_str);
297                         return false;
298                 }
299         }
300         
301         if (mesh->getPositions().empty()) {
302                 fprintf(stderr, "Mesh %s has no vertices.\n", name);
303                 return false;
304         }
305
306         return true;
307 }
308
309 void MeshImporter::read_vertices(COLLADAFW::Mesh *mesh, Mesh *me)
310 {
311         // vertices
312         COLLADAFW::MeshVertexData& pos = mesh->getPositions();
313         int stride = pos.getStride(0);
314         if(stride==0) stride = 3;
315         
316         me->totvert = mesh->getPositions().getFloatValues()->getCount() / stride;
317         me->mvert = (MVert*)CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, me->totvert);
318
319         MVert *mvert;
320         int i;
321
322         for (i = 0, mvert = me->mvert; i < me->totvert; i++, mvert++) {
323                 get_vector(mvert->co, pos, i, stride);
324         }
325 }
326
327 int MeshImporter::triangulate_poly(unsigned int *indices, int totvert, MVert *verts, std::vector<unsigned int>& tri)
328 {
329         ListBase dispbase;
330         DispList *dl;
331         float *vert;
332         int i = 0;
333         
334         dispbase.first = dispbase.last = NULL;
335         
336         dl = (DispList*)MEM_callocN(sizeof(DispList), "poly disp");
337         dl->nr = totvert;
338         dl->type = DL_POLY;
339         dl->parts = 1;
340         dl->verts = vert = (float*)MEM_callocN(totvert * 3 * sizeof(float), "poly verts");
341         dl->index = (int*)MEM_callocN(sizeof(int) * 3 * totvert, "dl index");
342
343         BLI_addtail(&dispbase, dl);
344         
345         for (i = 0; i < totvert; i++) {
346                 copy_v3_v3(vert, verts[indices[i]].co);
347                 vert += 3;
348         }
349         
350         filldisplist(&dispbase, &dispbase, 0);
351
352         int tottri = 0;
353         dl= (DispList*)dispbase.first;
354
355         if (dl->type == DL_INDEX3) {
356                 tottri = dl->parts;
357
358                 int *index = dl->index;
359                 for (i= 0; i < tottri; i++) {
360                         int t[3]= {*index, *(index + 1), *(index + 2)};
361
362                         std::sort(t, t + 3);
363
364                         tri.push_back(t[0]);
365                         tri.push_back(t[1]);
366                         tri.push_back(t[2]);
367
368                         index += 3;
369                 }
370         }
371
372         freedisplist(&dispbase);
373
374         return tottri;
375 }
376
377 int MeshImporter::count_new_tris(COLLADAFW::Mesh *mesh, Mesh *me)
378 {
379         COLLADAFW::MeshPrimitiveArray& prim_arr = mesh->getMeshPrimitives();
380         unsigned int i;
381         int tottri = 0;
382         
383         for (i = 0; i < prim_arr.getCount(); i++) {
384                 
385                 COLLADAFW::MeshPrimitive *mp = prim_arr[i];
386                 int type = mp->getPrimitiveType();
387                 size_t prim_totface = mp->getFaceCount();
388                 unsigned int *indices = mp->getPositionIndices().getData();
389                 
390                 if (type == COLLADAFW::MeshPrimitive::POLYLIST ||
391                         type == COLLADAFW::MeshPrimitive::POLYGONS) {
392                         
393                         COLLADAFW::Polygons *mpvc =     (COLLADAFW::Polygons*)mp;
394                         COLLADAFW::Polygons::VertexCountArray& vcounta = mpvc->getGroupedVerticesVertexCountArray();
395                         
396                         for (unsigned int j = 0; j < prim_totface; j++) {
397                                 int vcount = vcounta[j];
398                                 
399                                 if (vcount > 4) {
400                                         std::vector<unsigned int> tri;
401                                         
402                                         // tottri += triangulate_poly(indices, vcount, me->mvert, tri) - 1; // XXX why - 1?!
403                                         tottri += triangulate_poly(indices, vcount, me->mvert, tri);
404                                 }
405
406                                 indices += vcount;
407                         }
408                 }
409         }
410         return tottri;
411 }
412
413 // TODO: import uv set names
414 void MeshImporter::read_faces(COLLADAFW::Mesh *mesh, Mesh *me, int new_tris)        //TODO:: Refactor. Possibly replace by iterators
415 {
416         unsigned int i;
417         
418         // allocate faces
419         me->totface = mesh->getFacesCount() + new_tris;
420         me->mface = (MFace*)CustomData_add_layer(&me->fdata, CD_MFACE, CD_CALLOC, NULL, me->totface);
421         
422         // allocate UV layers
423         unsigned int totuvset = mesh->getUVCoords().getInputInfosArray().getCount();
424
425         for (i = 0; i < totuvset; i++) {
426                 if (mesh->getUVCoords().getLength(i) == 0) {
427                         totuvset = 0;
428                         break;
429                 }
430         }
431
432         for (i = 0; i < totuvset; i++) {
433                 COLLADAFW::MeshVertexData::InputInfos *info = mesh->getUVCoords().getInputInfosArray()[i];
434                 CustomData_add_layer_named(&me->fdata, CD_MTFACE, CD_CALLOC, NULL, me->totface, info->mName.c_str());
435                 //this->set_layername_map[i] = CustomData_get_layer_name(&me->fdata, CD_MTFACE, i);
436         }
437
438         // activate the first uv layer
439         if (totuvset) me->mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, 0);
440
441         UVDataWrapper uvs(mesh->getUVCoords());
442
443 #ifdef COLLADA_DEBUG
444         // uvs.print();
445 #endif
446
447         MFace *mface = me->mface;
448
449         MaterialIdPrimitiveArrayMap mat_prim_map;
450
451         int face_index = 0;
452
453         COLLADAFW::MeshPrimitiveArray& prim_arr = mesh->getMeshPrimitives();
454
455         bool has_normals = mesh->hasNormals();
456         COLLADAFW::MeshVertexData& nor = mesh->getNormals();
457
458         for (i = 0; i < prim_arr.getCount(); i++) {
459                 
460                 COLLADAFW::MeshPrimitive *mp = prim_arr[i];
461
462                 // faces
463                 size_t prim_totface = mp->getFaceCount();
464                 unsigned int *indices = mp->getPositionIndices().getData();
465                 unsigned int *nind = mp->getNormalIndices().getData();
466
467                 if (has_normals && mp->getPositionIndices().getCount() != mp->getNormalIndices().getCount()) {
468                         fprintf(stderr, "Warning: Number of normals is different from the number of vertcies, skipping normals\n");
469                         has_normals = false;
470                 }
471
472                 unsigned int j, k;
473                 int type = mp->getPrimitiveType();
474                 int index = 0;
475                 
476                 // since we cannot set mface->mat_nr here, we store a portion of me->mface in Primitive
477                 Primitive prim = {mface, 0};
478                 COLLADAFW::IndexListArray& index_list_array = mp->getUVCoordIndicesArray();
479
480 #ifdef COLLADA_DEBUG
481                 /*
482                 fprintf(stderr, "Primitive %d:\n", i);
483                 for (int j = 0; j < totuvset; j++) {
484                         print_index_list(*index_list_array[j]);
485                 }
486                 */
487 #endif
488                 
489                 if (type == COLLADAFW::MeshPrimitive::TRIANGLES) {
490                         for (j = 0; j < prim_totface; j++){
491                                 
492                                 set_face_indices(mface, indices, false);
493                                 indices += 3;
494
495 #if 0
496                                 for (k = 0; k < totuvset; k++) {
497                                         if (!index_list_array.empty() && index_list_array[k]) {
498                                                 // get mtface by face index and uv set index
499                                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, k);
500                                                 set_face_uv(&mtface[face_index], uvs, k, *index_list_array[k], index, false);
501                                         }
502                                 }
503 #else
504                                 for (k = 0; k < index_list_array.getCount(); k++) {
505                                         // get mtface by face index and uv set index
506                                         MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, k);
507                                         set_face_uv(&mtface[face_index], uvs, *index_list_array[k], index, false);
508                                 }
509 #endif
510
511                                 test_index_face(mface, &me->fdata, face_index, 3);
512
513                                 if (has_normals) {
514                                         if (!flat_face(nind, nor, 3))
515                                                 mface->flag |= ME_SMOOTH;
516
517                                         nind += 3;
518                                 }
519                                 
520                                 index += 3;
521                                 mface++;
522                                 face_index++;
523                                 prim.totface++;
524                         }
525                 }
526
527                 // If MeshPrimitive is TRIANGLE_FANS we split it into triangles
528                 // The first trifan vertex will be the first vertex in every triangle
529                 if (type == COLLADAFW::MeshPrimitive::TRIANGLE_FANS) {
530                         unsigned grouped_vertex_count = mp->getGroupedVertexElementsCount();
531                         for (unsigned int group_index = 0; group_index < grouped_vertex_count; group_index++){
532                                 unsigned int first_vertex = indices[0]; // Store first trifan vertex
533                                 unsigned int first_normal = nind[0]; // Store first trifan vertex normal
534                                 unsigned int vertex_count = mp->getGroupedVerticesVertexCount(group_index);
535
536                                 for (unsigned int vertex_index = 0; vertex_index < vertex_count - 2; vertex_index++){
537                                         // For each triangle store indeces of its 3 vertices
538                                         unsigned int triangle_vertex_indices[3]={first_vertex, indices[1], indices[2]};
539                                         set_face_indices(mface, triangle_vertex_indices, false);
540                                         test_index_face(mface, &me->fdata, face_index, 3);
541
542                                         if (has_normals) {  // vertex normals, same inplementation as for the triangles
543                                                 // the same for vertces normals
544                                                 unsigned int vertex_normal_indices[3]={first_normal, nind[1], nind[2]};
545                                                 if (!flat_face(vertex_normal_indices, nor, 3))
546                                                         mface->flag |= ME_SMOOTH;
547                                                         nind++;
548                                                 }
549
550                                                 mface++;        // same inplementation as for the triangles
551                                                 indices++;
552                                                 face_index++;
553                                                 prim.totface++;
554                                         }
555                                 
556                                 // Moving cursor  to the next triangle fan.
557                                 if (has_normals)
558                                         nind += 2;
559
560                                 indices +=  2;
561                         }
562                 }
563                 else if (type == COLLADAFW::MeshPrimitive::POLYLIST || type == COLLADAFW::MeshPrimitive::POLYGONS) {
564                         COLLADAFW::Polygons *mpvc =     (COLLADAFW::Polygons*)mp;
565                         COLLADAFW::Polygons::VertexCountArray& vcounta = mpvc->getGroupedVerticesVertexCountArray();
566                         
567                         for (j = 0; j < prim_totface; j++) {
568                                 
569                                 // face
570                                 int vcount = vcounta[j];
571                                 if (vcount == 3 || vcount == 4) {
572                                         
573                                         set_face_indices(mface, indices, vcount == 4);
574                                         
575                                         // set mtface for each uv set
576                                         // it is assumed that all primitives have equal number of UV sets
577                                         
578 #if 0
579                                         for (k = 0; k < totuvset; k++) {
580                                                 if (!index_list_array.empty() && index_list_array[k]) {
581                                                         // get mtface by face index and uv set index
582                                                         MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, k);
583                                                         set_face_uv(&mtface[face_index], uvs, k, *index_list_array[k], index, mface->v4 != 0);
584                                                 }
585                                         }
586 #else
587                                         for (k = 0; k < index_list_array.getCount(); k++) {
588                                                 // get mtface by face index and uv set index
589                                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, k);
590                                                 set_face_uv(&mtface[face_index], uvs, *index_list_array[k], index, mface->v4 != 0);
591                                         }
592 #endif
593
594                                         test_index_face(mface, &me->fdata, face_index, vcount);
595
596                                         if (has_normals) {
597                                                 if (!flat_face(nind, nor, vcount))
598                                                         mface->flag |= ME_SMOOTH;
599
600                                                 nind += vcount;
601                                         }
602                                         
603                                         mface++;
604                                         face_index++;
605                                         prim.totface++;
606                                         
607                                 }
608                                 else {
609                                         std::vector<unsigned int> tri;
610                                         
611                                         triangulate_poly(indices, vcount, me->mvert, tri);
612                                         
613                                         for (k = 0; k < tri.size() / 3; k++) {
614                                                 int v = k * 3;
615                                                 unsigned int uv_indices[3] = {
616                                                         index + tri[v],
617                                                         index + tri[v + 1],
618                                                         index + tri[v + 2]
619                                                 };
620                                                 unsigned int tri_indices[3] = {
621                                                         indices[tri[v]],
622                                                         indices[tri[v + 1]],
623                                                         indices[tri[v + 2]]
624                                                 };
625
626                                                 set_face_indices(mface, tri_indices, false);
627                                                 
628 #if 0
629                                                 for (unsigned int l = 0; l < totuvset; l++) {
630                                                         if (!index_list_array.empty() && index_list_array[l]) {
631                                                                 // get mtface by face index and uv set index
632                                                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, l);
633                                                                 set_face_uv(&mtface[face_index], uvs, l, *index_list_array[l], uv_indices);
634                                                         }
635                                                 }
636 #else
637                                                 for (unsigned int l = 0; l < index_list_array.getCount(); l++) {
638                                                         int uvset_index = index_list_array[l]->getSetIndex();
639
640                                                         // get mtface by face index and uv set index
641                                                         MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, uvset_index);
642                                                         set_face_uv(&mtface[face_index], uvs, *index_list_array[l], uv_indices);
643                                                 }
644 #endif
645
646
647                                                 test_index_face(mface, &me->fdata, face_index, 3);
648
649                                                 if (has_normals) {
650                                                         unsigned int ntri[3] = {nind[tri[v]], nind[tri[v + 1]], nind[tri[v + 2]]};
651
652                                                         if (!flat_face(ntri, nor, 3))
653                                                                 mface->flag |= ME_SMOOTH;
654                                                 }
655                                                 
656                                                 mface++;
657                                                 face_index++;
658                                                 prim.totface++;
659                                         }
660
661                                         if (has_normals)
662                                                 nind += vcount;
663                                 }
664
665                                 index += vcount;
666                                 indices += vcount;
667                         }
668                 }
669                 
670                 mat_prim_map[mp->getMaterialId()].push_back(prim);
671         }
672
673         geom_uid_mat_mapping_map[mesh->getUniqueId()] = mat_prim_map;
674 }
675
676 void MeshImporter::get_vector(float v[3], COLLADAFW::MeshVertexData& arr, int i, int stride)
677 {
678         i *= stride;
679         
680         switch(arr.getType()) {
681         case COLLADAFW::MeshVertexData::DATA_TYPE_FLOAT:
682                 {
683                         COLLADAFW::ArrayPrimitiveType<float>* values = arr.getFloatValues();
684                         if (values->empty()) return;
685
686                         v[0] = (*values)[i++];
687                         v[1] = (*values)[i++];
688                         v[2] = (*values)[i];
689
690                 }
691                 break;
692         case COLLADAFW::MeshVertexData::DATA_TYPE_DOUBLE:
693                 {
694                         COLLADAFW::ArrayPrimitiveType<double>* values = arr.getDoubleValues();
695                         if (values->empty()) return;
696
697                         v[0] = (float)(*values)[i++];
698                         v[1] = (float)(*values)[i++];
699                         v[2] = (float)(*values)[i];
700                 }
701                 break;
702         default:
703                 break;
704         }
705 }
706
707 bool MeshImporter::flat_face(unsigned int *nind, COLLADAFW::MeshVertexData& nor, int count)
708 {
709         float a[3], b[3];
710
711         get_vector(a, nor, *nind, 3);
712         normalize_v3(a);
713
714         nind++;
715
716         for (int i = 1; i < count; i++, nind++) {
717                 get_vector(b, nor, *nind, 3);
718                 normalize_v3(b);
719
720                 float dp = dot_v3v3(a, b);
721
722                 if (dp < 0.99999f || dp > 1.00001f)
723                         return false;
724         }
725
726         return true;
727 }
728
729 MeshImporter::MeshImporter(UnitConverter *unitconv, ArmatureImporter *arm, Scene *sce) : unitconverter(unitconv), scene(sce), armature_importer(arm) {}
730
731 Object *MeshImporter::get_object_by_geom_uid(const COLLADAFW::UniqueId& geom_uid)
732 {
733         if (uid_object_map.find(geom_uid) != uid_object_map.end())
734                 return uid_object_map[geom_uid];
735         return NULL;
736 }
737
738 MTex *MeshImporter::assign_textures_to_uvlayer(COLLADAFW::TextureCoordinateBinding &ctexture,
739                                                                  Mesh *me, TexIndexTextureArrayMap& texindex_texarray_map,
740                                                                  MTex *color_texture)
741 {
742         const COLLADAFW::TextureMapId texture_index = ctexture.getTextureMapId();
743         size_t setindex = ctexture.getSetIndex();
744         std::string uvname = ctexture.getSemantic();
745         
746         if(setindex==-1) return NULL;
747         
748         const CustomData *data = &me->fdata;
749         int layer_index = CustomData_get_layer_index(data, CD_MTFACE);
750         CustomDataLayer *cdl = &data->layers[layer_index+setindex];
751         
752         /* set uvname to bind_vertex_input semantic */
753         BLI_strncpy(cdl->name, uvname.c_str(), sizeof(cdl->name));
754
755         if (texindex_texarray_map.find(texture_index) == texindex_texarray_map.end()) {
756                 
757                 fprintf(stderr, "Cannot find texture array by texture index.\n");
758                 return color_texture;
759         }
760         
761         std::vector<MTex*> textures = texindex_texarray_map[texture_index];
762         
763         std::vector<MTex*>::iterator it;
764         
765         for (it = textures.begin(); it != textures.end(); it++) {
766                 
767                 MTex *texture = *it;
768                 
769                 if (texture) {
770                         BLI_strncpy(texture->uvname, uvname.c_str(), sizeof(texture->uvname));
771                         if (texture->mapto == MAP_COL) color_texture = texture;
772                 }
773         }
774         return color_texture;
775 }
776
777 MTFace *MeshImporter::assign_material_to_geom(COLLADAFW::MaterialBinding cmaterial,
778                                                                 std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
779                                                                 Object *ob, const COLLADAFW::UniqueId *geom_uid, 
780                                                                 MTex **color_texture, char *layername, MTFace *texture_face,
781                                                                 std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map, int mat_index)
782 {
783         Mesh *me = (Mesh*)ob->data;
784         const COLLADAFW::UniqueId& ma_uid = cmaterial.getReferencedMaterial();
785         
786         // do we know this material?
787         if (uid_material_map.find(ma_uid) == uid_material_map.end()) {
788                 
789                 fprintf(stderr, "Cannot find material by UID.\n");
790                 return NULL;
791         }
792         
793         // different nodes can point to same geometry, but still also specify the same materials
794         // again. Make sure we don't overwrite them on the next occurrences, so keep list of
795         // what we already have handled.
796         std::multimap<COLLADAFW::UniqueId, COLLADAFW::UniqueId>::iterator it;
797         it=materials_mapped_to_geom.find(*geom_uid);
798         while(it!=materials_mapped_to_geom.end()) {
799                 if(it->second == ma_uid) return NULL; // do nothing if already found
800                 it++;
801         }
802         // first time we get geom_uid, ma_uid pair. Save for later check.
803         materials_mapped_to_geom.insert(std::pair<COLLADAFW::UniqueId, COLLADAFW::UniqueId>(*geom_uid, ma_uid));
804         
805         Material *ma = uid_material_map[ma_uid];
806         assign_material(ob, ma, ob->totcol + 1);
807         
808         COLLADAFW::TextureCoordinateBindingArray& tex_array = 
809                 cmaterial.getTextureCoordinateBindingArray();
810         TexIndexTextureArrayMap texindex_texarray_map = material_texture_mapping_map[ma];
811         unsigned int i;
812         // loop through <bind_vertex_inputs>
813         for (i = 0; i < tex_array.getCount(); i++) {
814                 
815                 *color_texture = assign_textures_to_uvlayer(tex_array[i], me, texindex_texarray_map,
816                                                                                                         *color_texture);
817         }
818         
819         // set texture face
820         if (*color_texture &&
821                 strlen((*color_texture)->uvname) &&
822                 strcmp(layername, (*color_texture)->uvname) != 0) {
823                 texture_face = (MTFace*)CustomData_get_layer_named(&me->fdata, CD_MTFACE,
824                                                                                                                    (*color_texture)->uvname);
825                 strcpy(layername, (*color_texture)->uvname);
826         }
827         
828         MaterialIdPrimitiveArrayMap& mat_prim_map = geom_uid_mat_mapping_map[*geom_uid];
829         COLLADAFW::MaterialId mat_id = cmaterial.getMaterialId();
830         
831         // assign material indices to mesh faces
832         if (mat_prim_map.find(mat_id) != mat_prim_map.end()) {
833                 
834                 std::vector<Primitive>& prims = mat_prim_map[mat_id];
835                 
836                 std::vector<Primitive>::iterator it;
837                 
838                 for (it = prims.begin(); it != prims.end(); it++) {
839                         Primitive& prim = *it;
840                         i = 0;
841                         while (i++ < prim.totface) {
842                                 prim.mface->mat_nr = mat_index;
843                                 prim.mface++;
844                                 // bind texture images to faces
845                                 if (texture_face && (*color_texture)) {
846                                         texture_face->mode = TF_TEX;
847                                         texture_face->tpage = (Image*)(*color_texture)->tex->ima;
848                                         texture_face++;
849                                 }
850                         }
851                 }
852         }
853         
854         return texture_face;
855 }
856
857
858 Object *MeshImporter::create_mesh_object(COLLADAFW::Node *node, COLLADAFW::InstanceGeometry *geom,
859                                                    bool isController,
860                                                    std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
861                                                    std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map)
862 {
863         const COLLADAFW::UniqueId *geom_uid = &geom->getInstanciatedObjectId();
864         
865         // check if node instanciates controller or geometry
866         if (isController) {
867                 
868                 geom_uid = armature_importer->get_geometry_uid(*geom_uid);
869                 
870                 if (!geom_uid) {
871                         fprintf(stderr, "Couldn't find a mesh UID by controller's UID.\n");
872                         return NULL;
873                 }
874         }
875         else {
876                 
877                 if (uid_mesh_map.find(*geom_uid) == uid_mesh_map.end()) {
878                         // this could happen if a mesh was not created
879                         // (e.g. if it contains unsupported geometry)
880                         fprintf(stderr, "Couldn't find a mesh by UID.\n");
881                         return NULL;
882                 }
883         }
884         if (!uid_mesh_map[*geom_uid]) return NULL;
885         
886         Object *ob = add_object(scene, OB_MESH);
887
888         // store object pointer for ArmatureImporter
889         uid_object_map[*geom_uid] = ob;
890         
891         // name Object
892         const std::string& id = node->getName().size() ? node->getName() : node->getOriginalId();
893         if (id.length())
894                 rename_id(&ob->id, (char*)id.c_str());
895         
896         // replace ob->data freeing the old one
897         Mesh *old_mesh = (Mesh*)ob->data;
898
899         set_mesh(ob, uid_mesh_map[*geom_uid]);
900         
901         if (old_mesh->id.us == 0) free_libblock(&G.main->mesh, old_mesh);
902         
903         char layername[100];
904         layername[0] = '\0';
905         MTFace *texture_face = NULL;
906         MTex *color_texture = NULL;
907         
908         COLLADAFW::MaterialBindingArray& mat_array =
909                 geom->getMaterialBindings();
910         
911         // loop through geom's materials
912         for (unsigned int i = 0; i < mat_array.getCount(); i++) {
913                 
914                 if(mat_array[i].getReferencedMaterial().isValid()) {
915                         texture_face = assign_material_to_geom(mat_array[i], uid_material_map, ob, geom_uid,
916                                                                                                    &color_texture, layername, texture_face,
917                                                                                                    material_texture_mapping_map, i);
918                 } else {
919                         fprintf(stderr, "invalid referenced material for %s\n", mat_array[i].getName().c_str());
920                 }
921         }
922                 
923         return ob;
924 }
925
926 // create a mesh storing a pointer in a map so it can be retrieved later by geometry UID
927 bool MeshImporter::write_geometry(const COLLADAFW::Geometry* geom) 
928 {
929         // TODO: import also uvs, normals
930         // XXX what to do with normal indices?
931         // XXX num_normals may be != num verts, then what to do?
932
933         // check geometry->getType() first
934         if (geom->getType() != COLLADAFW::Geometry::GEO_TYPE_MESH) {
935                 // TODO: report warning
936                 fprintf(stderr, "Mesh type %s is not supported\n", bc_geomTypeToStr(geom->getType()));
937                 return true;
938         }
939         
940         COLLADAFW::Mesh *mesh = (COLLADAFW::Mesh*)geom;
941         
942         if (!is_nice_mesh(mesh)) {
943                 fprintf(stderr, "Ignoring mesh %s\n", bc_get_dae_name(mesh));
944                 return true;
945         }
946         
947         const std::string& str_geom_id = mesh->getName().size() ? mesh->getName() : mesh->getOriginalId();
948         Mesh *me = add_mesh((char*)str_geom_id.c_str());
949
950         // store the Mesh pointer to link it later with an Object
951         this->uid_mesh_map[mesh->getUniqueId()] = me;
952         
953         int new_tris = 0;
954         
955         read_vertices(mesh, me);
956
957         new_tris = count_new_tris(mesh, me);
958         
959         read_faces(mesh, me, new_tris);
960
961         make_edges(me, 0);
962         
963         mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
964
965         return true;
966 }