source: GTP/trunk/App/Demos/Vis/FriendlyCulling/Converter/ObjConverter.cpp @ 3358

Revision 3358, 15.4 KB checked in by mattausch, 15 years ago (diff)
Line 
1#include "ObjConverter.h"
2#include "SimpleTri.h"
3#include "SimpleVec.h"
4#include "gzstream.h"
5#include <iostream>
6
7
8using namespace std;
9
10//#define USE_TEXTURE
11
12
13static void LoadIndices(char *str,
14                                                const VertexArray &vertices,
15                                                const VertexArray &normals,
16                                                const TexcoordArray &texcoords,
17                                                VertexArray &faceVertices,
18                                                VertexArray &faceNormals,
19                                                TexcoordArray &faceTexcoords
20                                                )
21{
22        vector<string> triples;
23
24        char *next_token;
25
26        // extract the triples of the form v/t/n v/t/n ...
27        char *pch = strtok_s(str + 1, " ", &next_token);
28
29        while (pch)
30        {
31                string s(pch);
32                triples.push_back(s);
33               
34                pch = strtok_s(NULL, " ", &next_token);   
35        }
36
37        // throw away last symbol (\n)
38        triples.back().resize(triples.back().size() - 1);
39
40        vector<int> indices;
41        vector<int> nIndices;
42        vector<int> tIndices;
43
44        char seps[] = " ";
45        char seps2[] = "/";
46
47        for (size_t i = 0; i < triples.size(); ++ i)
48        {
49                //cout << "triple " << i << " " << triples[i] << endl;
50                size_t found;
51                found = triples[i].find_first_of(seps2);
52                size_t prevfound = 0;
53
54                // extract vertex, normal, texture indices
55                string str = triples[i].substr(prevfound, found);
56
57                int index = (int)strtol(str.c_str(), NULL, 10) - 1;
58                int tIndex = index;
59                int nIndex = index;     
60               
61                // try to extract texture and normal indices
62                prevfound = found + 1;
63                found = triples[i].find_first_of(seps2, prevfound); 
64
65                if (found != string::npos)
66                {
67                        str = triples[i].substr(prevfound, found);
68
69                        int idx = (int)strtol(str.c_str(), NULL, 10) - 1;
70                        if (idx > 0) tIndex = idx;
71                }
72               
73                if (found != string::npos)
74                {
75                        str = triples[i].substr(found + 1);
76
77                        int idx = (int)strtol(str.c_str(), NULL, 10) - 1;
78                        if (idx > 0) nIndex = idx;
79                }
80
81                // store indices
82                if (index >= 0)
83                {
84                        indices.push_back(index);
85                        nIndices.push_back(nIndex);
86                        tIndices.push_back(tIndex);
87
88                        //cout << index << " " << tIndex << " " << nIndex << endl;
89                }
90
91                // new triangle found
92                if (indices.size() > 2)
93                {
94                        // change orientation of faces?
95#if 1
96                        int idx1 = 0;
97                        int idx2 = (int)indices.size() - 2;
98                        int idx3 = (int)indices.size() - 1;
99#else
100                        int idx3 = 0;
101                        int idx2 = (int)indices.size() - 2;
102                        int idx1 = (int)indices.size() - 1;
103#endif
104                        faceVertices.push_back(vertices[indices[idx1]]);
105                        faceVertices.push_back(vertices[indices[idx2]]);
106                        faceVertices.push_back(vertices[indices[idx3]]);
107
108
109                        if (!normals.empty())
110                        {
111                                faceNormals.push_back(normals[nIndices[idx1]]);
112                                faceNormals.push_back(normals[nIndices[idx2]]);
113                                faceNormals.push_back(normals[nIndices[idx3]]);
114                        }
115                        else
116                        {
117                                // no face normals? => create normals
118                                const SimpleTri tri(vertices[indices[idx1]],
119                                                        vertices[indices[idx2]],
120                                                                        vertices[indices[idx3]]);
121                                const SimpleVec n = tri.GetNormal();
122
123                                faceNormals.push_back(n);
124                                faceNormals.push_back(n);
125                                faceNormals.push_back(n);
126                        }
127
128                        if (!texcoords.empty())
129                        {
130                                faceTexcoords.push_back(texcoords[tIndices[idx1]]);
131                                faceTexcoords.push_back(texcoords[tIndices[idx2]]);
132                                faceTexcoords.push_back(texcoords[tIndices[idx3]]);
133                        }
134                }
135        }
136}
137
138
139ObjConverter::ObjConverter()
140{}
141
142
143ObjConverter::~ObjConverter()
144{
145        for (size_t i = 0; i < mGeometry.size(); ++ i)
146                delete mGeometry[i];
147       
148        mGeometry.clear();
149}
150
151
152void ObjConverter::LoadShape(const VertexArray &faceVertices,
153                                                         const VertexArray &faceNormals,
154                                                         const vector<Texcoord> &faceTexcoords,
155                                                         Material *mat)
156{
157        int numElements = (int)faceVertices.size();
158        Geometry *geom = new Geometry();
159
160        // convert the triangles to geometry
161        geom->mVertices = new SimpleVec[numElements];
162        geom->mNormals = new SimpleVec[numElements];
163        geom->mTexcoords = new Texcoord[numElements];
164
165        geom->mVertexCount = numElements;
166        geom->mTexcoordCount = (int)faceTexcoords.size();
167
168        geom->mMaterial = mat;
169
170        cout << "creating new geometry with " << numElements << " vertices" << endl;
171
172        for (int i = 0; i < numElements; ++ i)
173        {
174#if 0
175                // convert to our camera system: change y and z
176                geom->mVertices[i].x = faceVertices[i].x;
177                geom->mVertices[i].y = -faceVertices[i].z;
178                geom->mVertices[i].z = faceVertices[i].y;
179       
180                geom->mNormals[i].x = faceNormals[i].x;
181                geom->mNormals[i].y = -faceNormals[i].z;
182                geom->mNormals[i].z = faceNormals[i].y;
183
184#else
185                geom->mVertices[i].x = faceVertices[i].x;
186                geom->mVertices[i].y = faceVertices[i].y;
187                geom->mVertices[i].z = faceVertices[i].z;
188       
189                geom->mNormals[i].x = faceNormals[i].x;
190                geom->mNormals[i].y = faceNormals[i].y;
191                geom->mNormals[i].z = faceNormals[i].z;
192
193#endif
194
195                if (i < geom->mTexcoordCount)
196                {
197                        geom->mTexcoords[i].first = faceTexcoords[i].first;
198                        geom->mTexcoords[i].second = faceTexcoords[i].second;
199                }
200        }
201
202        mGeometry.push_back(geom);
203}
204
205
206bool ObjConverter::Convert(const string &filename, const std::string &outputFilename)
207{
208        mNumShapes = 0;
209       
210        for (size_t i = 0; i < mGeometry.size(); ++ i)
211                delete mGeometry[i];
212       
213        mGeometry.clear();
214
215        if (!ReadFile(filename))
216        {
217                cerr << "could not read file" << endl;
218                return false;
219        }
220
221        if (!WriteFile(outputFilename))
222        {
223                cerr << "could not write file" << endl;
224                return false;
225        }
226
227
228        return true;
229}
230
231
232bool ObjConverter::ReadFile(const string &filename)
233{
234        FILE *file;
235
236        if ((file = fopen(filename.c_str(), "r")) == NULL)
237        {       
238                return false;
239        }
240       
241        Material *currentMat = NULL;
242        VertexArray faceVertices;
243        VertexArray faceNormals;
244        vector<Texcoord> faceTexcoords;
245
246        VertexArray vertices;
247        VertexArray normals;
248        vector<Texcoord> texcoords;
249
250        vector<int> indices;
251
252        int line = 0;
253        const int len = 10000;
254        char str[len];
255
256        while (fgets(str, len, file) != NULL)
257        {
258                switch (str[0])
259                {
260                case 'v': // vertex or normal
261                        {
262                                float x, y, z;
263
264                                switch (str[1])
265                                {
266                                case 'n' :
267                                        sscanf(str + 2, "%f %f %f", &x, &y, &z);
268                                        normals.push_back(SimpleVec(x, y, z));
269                                        break;
270                                case 't':
271                                        sscanf(str + 2, "%f %f", &x, &y);
272                                        texcoords.push_back(pair<float, float>(x, y));
273                                        break;
274                                default:
275                                        sscanf(str + 1, "%f %f %f", &x, &y, &z);
276                                        //const float scale = 5e-3f;
277                                        const float scale = 5.0f;
278                                        vertices.push_back(SimpleVec(x * scale, y * scale, z* scale));
279                                        //cout <<"v " << x << " " << y << " "<< z << " ";
280                                }
281                                break;
282                        }
283                case 'f':
284                        {
285                                //////////
286                                //-- indices in the current line
287
288                                LoadIndices(str,
289                                                vertices, normals, texcoords,
290                                                faceVertices, faceNormals, faceTexcoords);
291
292                                break;
293                        }   // end face
294                case 'g': // load a new shape
295                        {
296                                if (!faceVertices.empty())
297                                {
298                                        ++ mNumShapes;
299
300                                        LoadShape(faceVertices, faceNormals, faceTexcoords, currentMat);
301
302                                        faceVertices.clear();
303                                        faceNormals.clear();
304                                        faceTexcoords.clear();
305
306                                        currentMat = NULL;
307                                }
308                        }
309                        break;
310                case 'u': // usemtl => material
311                        {
312                                string matName(str + 7);
313                                // throw away linebreak character
314                                matName.resize(matName.size() - 1);
315
316                                currentMat = mMaterialTable[matName];
317                                //cout << "matname: " << matName << endl;
318                        }
319
320                        break;
321                default:
322                        // throw away line
323                        break;
324                }
325
326                ++ line;
327        }
328
329        if (!faceVertices.empty())
330        {
331                ++ mNumShapes;
332
333                LoadShape(faceVertices, faceNormals, faceTexcoords, currentMat);
334
335                faceVertices.clear();
336                faceNormals.clear();
337                faceTexcoords.clear();
338        }
339
340        fclose(file);
341       
342        return true;
343}
344
345
346void ObjConverter::WriteGeometry(ogzstream &str, Geometry *geom)
347{
348        int vertexCount = geom->mVertexCount;
349        str.write(reinterpret_cast<char *>(&vertexCount), sizeof(int));
350 
351        str.write(reinterpret_cast<char *>(geom->mVertices), sizeof(SimpleVec) * vertexCount);
352        str.write(reinterpret_cast<char *>(geom->mNormals), sizeof(SimpleVec) * vertexCount);
353
354        int texCoordCount = geom->mTexcoordCount;
355        str.write(reinterpret_cast<char *>(&texCoordCount), sizeof(int));
356
357        if (texCoordCount)
358                str.write(reinterpret_cast<char *>(geom->mTexcoords), sizeof(float) * texCoordCount * 2);
359       
360
361        ///////
362        //-- texture
363/*
364#ifdef USE_TEXTURE
365        int texId = 0;
366#else
367        int texId = -1;
368#endif
369
370        str.write(reinterpret_cast<char *>(&texId), sizeof(int));
371
372        bool alphaTestEnabled = false;
373        //bool cullFaceEnabled = false;
374        bool cullFaceEnabled = true;
375
376        str.write(reinterpret_cast<char *>(&alphaTestEnabled), sizeof(bool));
377        str.write(reinterpret_cast<char *>(&cullFaceEnabled), sizeof(bool));
378
379        // material
380        bool hasMaterial = true;
381        //bool hasMaterial = false;
382        str.write(reinterpret_cast<char *>(&hasMaterial), sizeof(bool));
383       
384        if (hasMaterial)
385        {
386                SimpleVec ambient, diffuse, spec, emm;
387
388                ambient.x = ambient.y = ambient.z = 0.2f;
389                //diffuse.x = diffuse.y = diffuse.z = 1.0f;
390                diffuse.x = 0.7f; diffuse.y = 0.5f; diffuse.z = 0.2f;
391                spec.x    = spec.y    = spec.z    =  .0f;
392                emm = spec;
393
394                // only write rgb part of the material
395                str.write(reinterpret_cast<char *>(&ambient), sizeof(SimpleVec));
396                str.write(reinterpret_cast<char *>(&diffuse), sizeof(SimpleVec));
397                str.write(reinterpret_cast<char *>(&spec), sizeof(SimpleVec));
398                str.write(reinterpret_cast<char *>(&emm), sizeof(SimpleVec));
399        }
400*/
401}
402
403#if 0
404
405bool ObjConverter::WriteFile(const string &filename)
406{
407        ogzstream ofile(filename.c_str());
408
409        if (!ofile.is_open())
410                return false;
411       
412
413        /////////
414        //-- write textures
415
416#ifdef USE_TEXTURE
417        int textureCount = 1;
418#else
419        int textureCount = 0;
420#endif
421        ofile.write(reinterpret_cast<char *>(&textureCount), sizeof(int));
422
423        if (textureCount > 0)
424        {
425                // hack
426                const string texName("wood.jpg");
427
428                int texnameSize = (int)texName.length() + 1;
429                ofile.write(reinterpret_cast<char *>(&texnameSize), sizeof(int));
430
431                ofile.write(texName.c_str(), sizeof(char) * texnameSize);
432
433                int boundS = 1, boundT = 1;
434
435                ofile.write(reinterpret_cast<char *>(&boundS), sizeof(int));
436                ofile.write(reinterpret_cast<char *>(&boundT), sizeof(int));
437        }
438
439
440        ///////////
441        //-- write shapes
442
443        ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
444
445        vector<Geometry *>::const_iterator it, it_end = mGeometry.end();
446
447        for (it = mGeometry.begin(); it != it_end; ++ it)
448        {
449                WriteGeometry(ofile, *it);
450        }
451
452
453        int entityCount = 1;
454        ofile.write(reinterpret_cast<char *>(&entityCount), sizeof(int));
455
456
457        //////////
458        //-- write single scene entity
459
460        // no transformation
461        bool hasTrafo = false;
462        ofile.write(reinterpret_cast<char *>(&hasTrafo), sizeof(bool));
463
464        // a dummy lod
465        int numLODs = 1;
466        ofile.write(reinterpret_cast<char *>(&numLODs), sizeof(int));
467
468        float dist = 0;
469        ofile.write(reinterpret_cast<char *>(&dist), sizeof(float));
470
471        ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
472
473        // all shapes belong to this scene entity
474        for (int i = 0; i < mNumShapes; ++ i)
475        {
476                int shapeId = i;
477                ofile.write(reinterpret_cast<char *>(&shapeId), sizeof(int));
478        }
479
480        return true;
481}
482
483#else
484
485bool ObjConverter::WriteFile(const string &filename)
486{
487        ogzstream ofile(filename.c_str());
488
489        if (!ofile.is_open())
490                return false;
491       
492
493        /////////
494        //-- write textures
495
496        int textureCount = (int)mTextures.size();
497
498        ofile.write(reinterpret_cast<char *>(&textureCount), sizeof(int));
499
500        TextureArray::const_iterator tit, tit_end = mTextures.end();
501       
502        for (tit = mTextures.begin(); tit != tit_end; ++ tit)
503        {
504                const string texName = (*tit);
505
506                int texnameSize = (int)texName.length() + 1;
507                ofile.write(reinterpret_cast<char *>(&texnameSize), sizeof(int));
508
509                ofile.write(texName.c_str(), sizeof(char) * texnameSize);
510
511                int boundS = 1, boundT = 1;
512
513                ofile.write(reinterpret_cast<char *>(&boundS), sizeof(int));
514                ofile.write(reinterpret_cast<char *>(&boundT), sizeof(int));
515        }
516
517
518        ///////////
519        //-- write shapes
520
521        ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
522
523        vector<Geometry *>::const_iterator it, it_end = mGeometry.end();
524
525        for (it = mGeometry.begin(); it != it_end; ++ it)
526        {
527                WriteGeometry(ofile, *it);
528
529               
530                /////////
531                //-- material
532
533                Material *mat = (*it)->mMaterial;
534
535                if (!mat) cerr << "error: no material specified!!" << endl;
536
537                ofile.write(reinterpret_cast<char *>(&mat->texture), sizeof(int));
538
539                bool alphaTestEnabled = false;
540                //bool cullFaceEnabled = false;
541                bool cullFaceEnabled = true;
542               
543                ofile.write(reinterpret_cast<char *>(&alphaTestEnabled), sizeof(bool));
544                ofile.write(reinterpret_cast<char *>(&cullFaceEnabled), sizeof(bool));
545
546                // material
547                bool hasMaterial = true;
548                ofile.write(reinterpret_cast<char *>(&hasMaterial), sizeof(bool));
549       
550                SimpleVec ambient, diffuse, spec, emm;
551
552                ambient.x = ambient.y = ambient.z = 0.2f;
553                //diffuse.x = diffuse.y = diffuse.z = 1.0f;
554                diffuse.x = mat->rgb[0]; diffuse.y =mat->rgb[1]; diffuse.z = mat->rgb[2];
555                spec.x = spec.y = spec.z = .0f;
556                emm = spec;
557
558                // only write rgb part of the material
559                ofile.write(reinterpret_cast<char *>(&ambient), sizeof(SimpleVec));
560                ofile.write(reinterpret_cast<char *>(&diffuse), sizeof(SimpleVec));
561                ofile.write(reinterpret_cast<char *>(&spec), sizeof(SimpleVec));
562                ofile.write(reinterpret_cast<char *>(&emm), sizeof(SimpleVec));
563        }
564
565
566        //int entityCount = 1;
567        int entityCount = mNumShapes;
568        ofile.write(reinterpret_cast<char *>(&entityCount), sizeof(int));
569
570
571        //////////
572        //-- q: write single scene entity with all shapes or many entities with one shape
573
574        // all shapes belong to this scene entity
575        for (int i = 0; i < mNumShapes; ++ i)
576        {
577                // no transformation
578                bool hasTrafo = false;
579                ofile.write(reinterpret_cast<char *>(&hasTrafo), sizeof(bool));
580
581                // a dummy lod
582                int numLODs = 1;
583                ofile.write(reinterpret_cast<char *>(&numLODs), sizeof(int));
584
585                float dist = 0;
586                ofile.write(reinterpret_cast<char *>(&dist), sizeof(float));
587
588                //ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
589                int one = 1;
590                ofile.write(reinterpret_cast<char *>(&one), sizeof(int));
591
592                int shapeId = i;
593                ofile.write(reinterpret_cast<char *>(&shapeId), sizeof(int));
594        }
595
596        return true;
597}
598#endif
599
600
601bool ObjConverter::LoadMaterials(const std::string &matFileName)
602{
603        FILE *file;
604
605        if ((file = fopen(matFileName.c_str(), "r")) == NULL)
606        {       
607                return false;
608        }
609       
610        int line = 0;
611        const int len = 10000;
612        char str[len];
613
614        Material *currentMat = NULL;
615
616
617        while (fgets(str, len, file) != NULL)
618        {
619                //sscanf(str + 1, "%f %f %f", &x, &y, &z);
620                vector<string> strings;
621
622                char *next_token;
623
624                // extract the triples of the form v/t/n v/t/n ...
625                char *pch = strtok_s(str, " \n", &next_token);
626
627                while (pch)
628                {
629                        string s(pch);
630                        strings.push_back(s);
631
632                        pch = strtok_s(NULL, " \n", &next_token);       
633                }
634
635                if ((strings.size() == 2) && (strcmp(strings[0].c_str(), "newmtl") == 0))
636                {
637                        currentMat = new Material();
638                        mMaterialTable[strings[1].c_str()] = currentMat;
639                }
640
641                if ((strings.size() == 2) && (strcmp(strings[0].c_str(), "map_Kd") == 0))
642                {
643                        TextureTable::const_iterator it = mTextureTable.find(strings[1]);
644
645                        int id;
646
647                        if (it == mTextureTable.end()) // parameter not found
648                        {
649                                mTextures.push_back(strings[1]);
650                                id = (int)mTextures.size();
651                                mTextureTable[strings[1]] = id;
652                        }
653                        else
654                        {
655                                id = (*it).second;
656                        }
657
658                        currentMat->texture = id;
659                }
660
661                if ((strings.size() == 4) && (strcmp(strings[0].c_str(),"Kd") == 0))
662                {
663                        currentMat->rgb[0] = (float)atof(strings[1].c_str());
664                        currentMat->rgb[1] = (float)atof(strings[2].c_str());
665                        currentMat->rgb[2] = (float)atof(strings[3].c_str());
666                }
667
668                ++ line;
669        }
670
671        return true;
672}
Note: See TracBrowser for help on using the repository browser.