remove BLI_utildefines from BKE_DerivedMesh.h header
[blender.git] / source / blender / collada / GeometryExporter.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Jan Diederich, Tod Liverseed,
19  *                 Nathan Letwory
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/collada/GeometryExporter.cpp
25  *  \ingroup collada
26  */
27
28
29 #include <sstream>
30
31 #include "COLLADASWPrimitves.h"
32 #include "COLLADASWSource.h"
33 #include "COLLADASWVertices.h"
34 #include "COLLADABUUtils.h"
35
36 #include "GeometryExporter.h"
37
38 #include "DNA_meshdata_types.h"
39
40 extern "C" {
41         #include "BLI_utildefines.h"
42
43         #include "BKE_DerivedMesh.h"
44         #include "BKE_main.h"
45         #include "BKE_global.h"
46         #include "BKE_library.h"
47         #include "BKE_customdata.h"
48         #include "BKE_material.h"
49         #include "BKE_mesh.h"
50 }
51
52 #include "collada_internal.h"
53 #include "collada_utils.h"
54
55 // TODO: optimize UV sets by making indexed list with duplicates removed
56 GeometryExporter::GeometryExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings) : COLLADASW::LibraryGeometries(sw), export_settings(export_settings) {
57 }
58
59
60 void GeometryExporter::exportGeom(Scene *sce)
61 {
62         openLibrary();
63
64         mScene = sce;
65         GeometryFunctor gf;
66         gf.forEachMeshObjectInExportSet<GeometryExporter>(sce, *this, this->export_settings->export_set);
67
68         closeLibrary();
69 }
70
71 void GeometryExporter::operator()(Object *ob)
72 {
73         // XXX don't use DerivedMesh, Mesh instead?
74
75 #if 0           
76         DerivedMesh *dm = mesh_get_derived_final(mScene, ob, CD_MASK_BAREMESH);
77 #endif
78
79         bool use_instantiation = this->export_settings->use_object_instantiation;
80         Mesh *me;
81         if (this->export_settings->apply_modifiers) {
82                 me = bc_to_mesh_apply_modifiers(mScene, ob, this->export_settings->export_mesh_type);
83         }
84         else {
85                 me = (Mesh *)ob->data;
86         }
87         BKE_mesh_tessface_ensure(me);
88
89         std::string geom_id = get_geometry_id(ob, use_instantiation);
90         std::vector<Normal> nor;
91         std::vector<Face> norind;
92
93         // Skip if linked geometry was already exported from another reference
94         if (use_instantiation && 
95             exportedGeometry.find(geom_id) != exportedGeometry.end())
96         {
97                 return;
98         }
99
100         std::string geom_name = (use_instantiation) ? id_name(ob->data) : id_name(ob);
101
102         exportedGeometry.insert(geom_id);
103
104         bool has_color = (bool)CustomData_has_layer(&me->fdata, CD_MCOL);
105
106         create_normals(nor, norind, me);
107
108         // openMesh(geoId, geoName, meshId)
109         openMesh(geom_id, geom_name);
110         
111         // writes <source> for vertex coords
112         createVertsSource(geom_id, me);
113         
114         // writes <source> for normal coords
115         createNormalsSource(geom_id, me, nor);
116
117         bool has_uvs = (bool)CustomData_has_layer(&me->fdata, CD_MTFACE);
118         
119         // writes <source> for uv coords if mesh has uv coords
120         if (has_uvs)
121                 createTexcoordsSource(geom_id, me);
122
123         if (has_color)
124                 createVertexColorSource(geom_id, me);
125
126         // <vertices>
127
128         COLLADASW::Vertices verts(mSW);
129         verts.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX));
130         COLLADASW::InputList &input_list = verts.getInputList();
131         COLLADASW::Input input(COLLADASW::InputSemantic::POSITION, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::POSITION));
132         input_list.push_back(input);
133         verts.add();
134
135         createLooseEdgeList(ob, me, geom_id, norind);
136
137         // Only create Polylists if number of faces > 0
138         if (me->totface > 0) {
139                 // XXX slow
140                 if (ob->totcol) {
141                         for (int a = 0; a < ob->totcol; a++) {
142                                 createPolylist(a, has_uvs, has_color, ob, me, geom_id, norind);
143                         }
144                 }
145                 else {
146                         createPolylist(0, has_uvs, has_color, ob, me, geom_id, norind);
147                 }
148         }
149         
150         closeMesh();
151         
152         if (me->flag & ME_TWOSIDED) {
153                 mSW->appendTextBlock("<extra><technique profile=\"MAYA\"><double_sided>1</double_sided></technique></extra>");
154         }
155
156         closeGeometry();
157
158         if (this->export_settings->apply_modifiers)
159         {
160                 BKE_libblock_free_us(&(G.main->mesh), me);
161         }
162
163
164 #if 0
165         dm->release(dm);
166 #endif
167 }
168
169
170 void GeometryExporter::createLooseEdgeList(Object *ob,
171                                            Mesh   *me,
172                                            std::string& geom_id,
173                                            std::vector<Face>& norind)
174 {
175
176         MEdge *medges = me->medge;
177         int totedges  = me->totedge;
178         int edges_in_linelist = 0;
179         std::vector<unsigned int> edge_list;
180         int index;
181
182         // Find all loose edges in Mesh 
183         // and save vertex indices in edge_list
184         for (index = 0; index < totedges; index++) 
185         {
186                 MEdge *edge = &medges[index];
187
188                 if (edge->flag & ME_LOOSEEDGE)
189                 {
190                         edges_in_linelist += 1;
191                         edge_list.push_back(edge->v1);
192                         edge_list.push_back(edge->v2);
193                 }
194         }
195
196         if (edges_in_linelist > 0)
197         {
198                 // Create the list of loose edges
199                 COLLADASW::Lines lines(mSW);
200
201                 lines.setCount(edges_in_linelist);
202
203
204                 COLLADASW::InputList &til = lines.getInputList();
205                         
206                 // creates <input> in <lines> for vertices 
207                 COLLADASW::Input input1(COLLADASW::InputSemantic::VERTEX, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX), 0);
208                 til.push_back(input1);
209
210                 lines.prepareToAppendValues();
211
212                 for (index = 0; index < edges_in_linelist; index++) 
213                 {
214                         lines.appendValues(edge_list[2 * index + 1]);
215                         lines.appendValues(edge_list[2 * index]);
216                 }
217                 lines.finish();
218         }
219
220 }
221
222 // powerful because it handles both cases when there is material and when there's not
223 void GeometryExporter::createPolylist(short material_index,
224                                       bool has_uvs,
225                                       bool has_color,
226                                       Object *ob,
227                                       Mesh *me,
228                                       std::string& geom_id,
229                                       std::vector<Face>& norind)
230 {
231         MFace *mfaces = me->mface;
232         int totfaces = me->totface;
233
234         // <vcount>
235         int i;
236         int faces_in_polylist = 0;
237         std::vector<unsigned long> vcount_list;
238
239         // count faces with this material
240         for (i = 0; i < totfaces; i++) {
241                 MFace *f = &mfaces[i];
242                 
243                 if (f->mat_nr == material_index) {
244                         faces_in_polylist++;
245                         if (f->v4 == 0) {
246                                 vcount_list.push_back(3);
247                         }
248                         else {
249                                 vcount_list.push_back(4);
250                         }
251                 }
252         }
253
254         // no faces using this material
255         if (faces_in_polylist == 0) {
256                 fprintf(stderr, "%s: material with index %d is not used.\n", id_name(ob).c_str(), material_index);
257                 return;
258         }
259                 
260         Material *ma = ob->totcol ? give_current_material(ob, material_index + 1) : NULL;
261         COLLADASW::Polylist polylist(mSW);
262                 
263         // sets count attribute in <polylist>
264         polylist.setCount(faces_in_polylist);
265                 
266         // sets material name
267         if (ma) {
268                 std::string material_id = get_material_id(ma);
269                 std::ostringstream ostr;
270                 ostr << translate_id(material_id);
271                 polylist.setMaterial(ostr.str());
272         }
273                         
274         COLLADASW::InputList &til = polylist.getInputList();
275                 
276         // creates <input> in <polylist> for vertices 
277         COLLADASW::Input input1(COLLADASW::InputSemantic::VERTEX, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX), 0);
278                 
279         // creates <input> in <polylist> for normals
280         COLLADASW::Input input2(COLLADASW::InputSemantic::NORMAL, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL), 1);
281                 
282         til.push_back(input1);
283         til.push_back(input2);
284                 
285         // if mesh has uv coords writes <input> for TEXCOORD
286         int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
287         int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE)-1;
288         for (i = 0; i < num_layers; i++) {
289                 if (!this->export_settings->active_uv_only || i == active_uv_index) {
290
291                         // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, i);
292                         COLLADASW::Input input3(COLLADASW::InputSemantic::TEXCOORD,
293                                                                         makeUrl(makeTexcoordSourceId(geom_id, i)),
294                                                                         2, // offset always 2, this is only until we have optimized UV sets
295                                                                         i  // set number equals UV map index
296                                                                         );
297                         til.push_back(input3);
298                 }
299         }
300
301         if (has_color) {
302                 COLLADASW::Input input4(COLLADASW::InputSemantic::COLOR, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::COLOR), has_uvs ? 3 : 2);
303                 til.push_back(input4);
304         }
305                 
306         // sets <vcount>
307         polylist.setVCountList(vcount_list);
308                 
309         // performs the actual writing
310         polylist.prepareToAppendValues();
311         
312
313                 
314         // <p>
315         int texindex = 0;
316         for (i = 0; i < totfaces; i++) {
317                 MFace *f = &mfaces[i];
318
319                 if (f->mat_nr == material_index) {
320
321                         unsigned int *v = &f->v1;
322                         unsigned int *n = &norind[i].v1;
323                         for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) {
324                                 polylist.appendValues(v[j]);
325                                 polylist.appendValues(n[j]);
326
327                                 if (has_uvs)
328                                         polylist.appendValues(texindex + j);
329
330                                 if (has_color)
331                                         polylist.appendValues(texindex + j);
332                         }
333                 }
334
335                 texindex += 3;
336                 if (f->v4 != 0)
337                         texindex++;
338         }
339                 
340         polylist.finish();
341 }
342
343 // creates <source> for positions
344 void GeometryExporter::createVertsSource(std::string geom_id, Mesh *me)
345 {
346 #if 0
347         int totverts = dm->getNumVerts(dm);
348         MVert *verts = dm->getVertArray(dm);
349 #endif
350         int totverts = me->totvert;
351         MVert *verts = me->mvert;
352         
353         COLLADASW::FloatSourceF source(mSW);
354         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION));
355         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION) +
356                           ARRAY_ID_SUFFIX);
357         source.setAccessorCount(totverts);
358         source.setAccessorStride(3);
359         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
360         param.push_back("X");
361         param.push_back("Y");
362         param.push_back("Z");
363         /* main function, it creates <source id = "">, <float_array id = ""
364          * count = ""> */
365         source.prepareToAppendValues();
366         //appends data to <float_array>
367         int i = 0;
368         for (i = 0; i < totverts; i++) {
369                 source.appendValues(verts[i].co[0], verts[i].co[1], verts[i].co[2]);
370         }
371         
372         source.finish();
373
374 }
375
376 void GeometryExporter::createVertexColorSource(std::string geom_id, Mesh *me)
377 {
378         if (!CustomData_has_layer(&me->fdata, CD_MCOL))
379                 return;
380
381         MFace *f;
382         int totcolor = 0, i, j;
383
384         for (i = 0, f = me->mface; i < me->totface; i++, f++)
385                 totcolor += f->v4 ? 4 : 3;
386
387         COLLADASW::FloatSourceF source(mSW);
388         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR));
389         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR) + ARRAY_ID_SUFFIX);
390         source.setAccessorCount(totcolor);
391         source.setAccessorStride(3);
392
393         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
394         param.push_back("R");
395         param.push_back("G");
396         param.push_back("B");
397
398         source.prepareToAppendValues();
399
400         int index = CustomData_get_active_layer_index(&me->fdata, CD_MCOL);
401
402         MCol *mcol = (MCol *)me->fdata.layers[index].data;
403         MCol *c = mcol;
404
405         for (i = 0, f = me->mface; i < me->totface; i++, c += 4, f++)
406                 for (j = 0; j < (f->v4 ? 4 : 3); j++)
407                         source.appendValues(c[j].b / 255.0f, c[j].g / 255.0f, c[j].r / 255.0f);
408         
409         source.finish();
410 }
411
412 std::string GeometryExporter::makeTexcoordSourceId(std::string& geom_id, int layer_index)
413 {
414         char suffix[20];
415         sprintf(suffix, "-%d", layer_index);
416         return getIdBySemantics(geom_id, COLLADASW::InputSemantic::TEXCOORD) + suffix;
417 }
418
419 //creates <source> for texcoords
420 void GeometryExporter::createTexcoordsSource(std::string geom_id, Mesh *me)
421 {
422 #if 0
423         int totfaces = dm->getNumTessFaces(dm);
424         MFace *mfaces = dm->getTessFaceArray(dm);
425 #endif
426         int totfaces = me->totface;
427         MFace *mfaces = me->mface;
428
429         int totuv = 0;
430         int i;
431
432         // count totuv
433         for (i = 0; i < totfaces; i++) {
434                 MFace *f = &mfaces[i];
435                 if (f->v4 == 0) {
436                         totuv += 3;
437                 }
438                 else {
439                         totuv += 4;
440                 }
441         }
442
443         int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
444
445         // write <source> for each layer
446         // each <source> will get id like meshName + "map-channel-1"
447         int map_index = 0;
448         int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE)-1;
449         for (int a = 0; a < num_layers; a++) {
450
451                 if (!this->export_settings->active_uv_only || a == active_uv_index) {
452                         MTFace *tface = (MTFace *)CustomData_get_layer_n(&me->fdata, CD_MTFACE, a);
453                         // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, a);
454                         
455                         COLLADASW::FloatSourceF source(mSW);
456                         std::string layer_id = makeTexcoordSourceId(geom_id, map_index++);
457                         source.setId(layer_id);
458                         source.setArrayId(layer_id + ARRAY_ID_SUFFIX);
459                         
460                         source.setAccessorCount(totuv);
461                         source.setAccessorStride(2);
462                         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
463                         param.push_back("S");
464                         param.push_back("T");
465                         
466                         source.prepareToAppendValues();
467                         
468                         for (i = 0; i < totfaces; i++) {
469                                 MFace *f = &mfaces[i];
470                                 
471                                 for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) {
472                                         source.appendValues(tface[i].uv[j][0],
473                                                                                 tface[i].uv[j][1]);
474                                 }
475                         }
476                         
477                         source.finish();
478                 }
479         }
480 }
481
482
483 //creates <source> for normals
484 void GeometryExporter::createNormalsSource(std::string geom_id, Mesh *me, std::vector<Normal>& nor)
485 {
486 #if 0
487         int totverts = dm->getNumVerts(dm);
488         MVert *verts = dm->getVertArray(dm);
489 #endif
490
491         COLLADASW::FloatSourceF source(mSW);
492         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL));
493         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL) +
494                           ARRAY_ID_SUFFIX);
495         source.setAccessorCount((unsigned long)nor.size());
496         source.setAccessorStride(3);
497         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
498         param.push_back("X");
499         param.push_back("Y");
500         param.push_back("Z");
501         
502         source.prepareToAppendValues();
503
504         std::vector<Normal>::iterator it;
505         for (it = nor.begin(); it != nor.end(); it++) {
506                 Normal& n = *it;
507                 source.appendValues(n.x, n.y, n.z);
508         }
509
510         source.finish();
511 }
512
513 void GeometryExporter::create_normals(std::vector<Normal> &nor, std::vector<Face> &ind, Mesh *me)
514 {
515         int i, j, v;
516         MVert *vert = me->mvert;
517         std::map<unsigned int, unsigned int> nshar;
518
519         for (i = 0; i < me->totface; i++) {
520                 MFace *fa = &me->mface[i];
521                 Face f;
522                 unsigned int *nn = &f.v1;
523                 unsigned int *vv = &fa->v1;
524
525                 memset(&f, 0, sizeof(f));
526                 v = fa->v4 == 0 ? 3 : 4;
527
528                 if (!(fa->flag & ME_SMOOTH)) {
529                         Normal n;
530                         if (v == 4)
531                                 normal_quad_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co, vert[fa->v4].co);
532                         else
533                                 normal_tri_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co);
534                         nor.push_back(n);
535                 }
536
537                 for (j = 0; j < v; j++) {
538                         if (fa->flag & ME_SMOOTH) {
539                                 if (nshar.find(*vv) != nshar.end())
540                                         *nn = nshar[*vv];
541                                 else {
542                                         Normal n = {
543                                                 (float)vert[*vv].no[0] / 32767.0f,
544                                                 (float)vert[*vv].no[1] / 32767.0f,
545                                                 (float)vert[*vv].no[2] / 32767.0f
546                                         };
547                                         nor.push_back(n);
548                                         *nn = (unsigned int)nor.size() - 1;
549                                         nshar[*vv] = *nn;
550                                 }
551                                 vv++;
552                         }
553                         else {
554                                 *nn = (unsigned int)nor.size() - 1;
555                         }
556                         nn++;
557                 }
558
559                 ind.push_back(f);
560         }
561 }
562
563 std::string GeometryExporter::getIdBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix)
564 {
565         return geom_id + getSuffixBySemantic(type) + other_suffix;
566 }
567
568
569 COLLADASW::URI GeometryExporter::getUrlBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix)
570 {
571         
572         std::string id(getIdBySemantics(geom_id, type, other_suffix));
573         return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id);
574         
575 }
576
577 COLLADASW::URI GeometryExporter::makeUrl(std::string id)
578 {
579         return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id);
580 }
581
582 #if 0
583 int GeometryExporter::getTriCount(MFace *faces, int totface)
584 {
585         int i;
586         int tris = 0;
587         for (i = 0; i < totface; i++) {
588                 // if quad
589                 if (faces[i].v4 != 0)
590                         tris += 2;
591                 else
592                         tris++;
593         }
594
595         return tris;
596 }
597 #endif