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

Revision 3319, 15.5 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 vector<pair<float, float> > &texcoords,
17                                                VertexArray &faceVertices,
18                                                VertexArray &faceNormals,
19                                                vector<Texcoord> &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 (0)//!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        //-- hack: a default material
363        ///////
364        //-- texture
365
366#ifdef USE_TEXTURE
367        int texId = 0;
368#else
369        int texId = -1;
370#endif
371
372        str.write(reinterpret_cast<char *>(&texId), sizeof(int));
373
374        bool alphaTestEnabled = false;
375        //bool cullFaceEnabled = false;
376        bool cullFaceEnabled = true;
377
378        str.write(reinterpret_cast<char *>(&alphaTestEnabled), sizeof(bool));
379        str.write(reinterpret_cast<char *>(&cullFaceEnabled), sizeof(bool));
380
381        // material
382        bool hasMaterial = true;
383        //bool hasMaterial = false;
384        str.write(reinterpret_cast<char *>(&hasMaterial), sizeof(bool));
385       
386        if (hasMaterial)
387        {
388                SimpleVec ambient, diffuse, spec, emm;
389
390                ambient.x = ambient.y = ambient.z = 0.2f;
391                //diffuse.x = diffuse.y = diffuse.z = 1.0f;
392                diffuse.x = 0.7f; diffuse.y = 0.5f; diffuse.z = 0.2f;
393                spec.x    = spec.y    = spec.z    =  .0f;
394                emm = spec;
395
396                // only write rgb part of the material
397                str.write(reinterpret_cast<char *>(&ambient), sizeof(SimpleVec));
398                str.write(reinterpret_cast<char *>(&diffuse), sizeof(SimpleVec));
399                str.write(reinterpret_cast<char *>(&spec), sizeof(SimpleVec));
400                str.write(reinterpret_cast<char *>(&emm), sizeof(SimpleVec));
401        }
402*/
403}
404
405#if 0
406
407bool ObjConverter::WriteFile(const string &filename)
408{
409        ogzstream ofile(filename.c_str());
410
411        if (!ofile.is_open())
412                return false;
413       
414
415        /////////
416        //-- write textures
417
418#ifdef USE_TEXTURE
419        int textureCount = 1;
420#else
421        int textureCount = 0;
422#endif
423        ofile.write(reinterpret_cast<char *>(&textureCount), sizeof(int));
424
425        if (textureCount > 0)
426        {
427                // hack
428                const string texName("wood.jpg");
429
430                int texnameSize = (int)texName.length() + 1;
431                ofile.write(reinterpret_cast<char *>(&texnameSize), sizeof(int));
432
433                ofile.write(texName.c_str(), sizeof(char) * texnameSize);
434
435                int boundS = 1, boundT = 1;
436
437                ofile.write(reinterpret_cast<char *>(&boundS), sizeof(int));
438                ofile.write(reinterpret_cast<char *>(&boundT), sizeof(int));
439        }
440
441
442        ///////////
443        //-- write shapes
444
445        ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
446
447        vector<Geometry *>::const_iterator it, it_end = mGeometry.end();
448
449        for (it = mGeometry.begin(); it != it_end; ++ it)
450        {
451                WriteGeometry(ofile, *it);
452        }
453
454
455        int entityCount = 1;
456        ofile.write(reinterpret_cast<char *>(&entityCount), sizeof(int));
457
458
459        //////////
460        //-- write single scene entity
461
462        // no transformation
463        bool hasTrafo = false;
464        ofile.write(reinterpret_cast<char *>(&hasTrafo), sizeof(bool));
465
466        // a dummy lod
467        int numLODs = 1;
468        ofile.write(reinterpret_cast<char *>(&numLODs), sizeof(int));
469
470        float dist = 0;
471        ofile.write(reinterpret_cast<char *>(&dist), sizeof(float));
472
473        ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
474
475        // all shapes belong to this scene entity
476        for (int i = 0; i < mNumShapes; ++ i)
477        {
478                int shapeId = i;
479                ofile.write(reinterpret_cast<char *>(&shapeId), sizeof(int));
480        }
481
482        return true;
483}
484
485#else
486
487bool ObjConverter::WriteFile(const string &filename)
488{
489        ogzstream ofile(filename.c_str());
490
491        if (!ofile.is_open())
492                return false;
493       
494
495        /////////
496        //-- write textures
497
498        int textureCount = (int)mTextures.size();
499
500        ofile.write(reinterpret_cast<char *>(&textureCount), sizeof(int));
501
502        TextureArray::const_iterator tit, tit_end = mTextures.end();
503       
504        for (tit = mTextures.begin(); tit != tit_end; ++ tit)
505        {
506                const string texName = (*tit);
507
508                int texnameSize = (int)texName.length() + 1;
509                ofile.write(reinterpret_cast<char *>(&texnameSize), sizeof(int));
510
511                ofile.write(texName.c_str(), sizeof(char) * texnameSize);
512
513                int boundS = 1, boundT = 1;
514
515                ofile.write(reinterpret_cast<char *>(&boundS), sizeof(int));
516                ofile.write(reinterpret_cast<char *>(&boundT), sizeof(int));
517        }
518
519
520        ///////////
521        //-- write shapes
522
523        ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
524
525        vector<Geometry *>::const_iterator it, it_end = mGeometry.end();
526
527        for (it = mGeometry.begin(); it != it_end; ++ it)
528        {
529                WriteGeometry(ofile, *it);
530
531               
532                /////////
533                //-- material
534
535                Material *mat = (*it)->mMaterial;
536
537                if (!mat) cerr << "error: no material specified!!" << endl;
538
539                ofile.write(reinterpret_cast<char *>(&mat->texture), sizeof(int));
540
541                bool alphaTestEnabled = false;
542                //bool cullFaceEnabled = false;
543                bool cullFaceEnabled = true;
544               
545                ofile.write(reinterpret_cast<char *>(&alphaTestEnabled), sizeof(bool));
546                ofile.write(reinterpret_cast<char *>(&cullFaceEnabled), sizeof(bool));
547
548                // material
549                bool hasMaterial = true;
550                ofile.write(reinterpret_cast<char *>(&hasMaterial), sizeof(bool));
551       
552                SimpleVec ambient, diffuse, spec, emm;
553
554                ambient.x = ambient.y = ambient.z = 0.2f;
555                //diffuse.x = diffuse.y = diffuse.z = 1.0f;
556                diffuse.x = mat->rgb[0]; diffuse.y =mat->rgb[1]; diffuse.z = mat->rgb[2];
557                spec.x = spec.y = spec.z = .0f;
558                emm = spec;
559
560                // only write rgb part of the material
561                ofile.write(reinterpret_cast<char *>(&ambient), sizeof(SimpleVec));
562                ofile.write(reinterpret_cast<char *>(&diffuse), sizeof(SimpleVec));
563                ofile.write(reinterpret_cast<char *>(&spec), sizeof(SimpleVec));
564                ofile.write(reinterpret_cast<char *>(&emm), sizeof(SimpleVec));
565        }
566
567
568        //int entityCount = 1;
569        int entityCount = mNumShapes;
570        ofile.write(reinterpret_cast<char *>(&entityCount), sizeof(int));
571
572
573        //////////
574        //-- q: write single scene entity with all shapes or many entities with one shape
575
576        // all shapes belong to this scene entity
577        for (int i = 0; i < mNumShapes; ++ i)
578        {
579                // no transformation
580                bool hasTrafo = false;
581                ofile.write(reinterpret_cast<char *>(&hasTrafo), sizeof(bool));
582
583                // a dummy lod
584                int numLODs = 1;
585                ofile.write(reinterpret_cast<char *>(&numLODs), sizeof(int));
586
587                float dist = 0;
588                ofile.write(reinterpret_cast<char *>(&dist), sizeof(float));
589
590                //ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
591                int one = 1;
592                ofile.write(reinterpret_cast<char *>(&one), sizeof(int));
593
594                int shapeId = i;
595                ofile.write(reinterpret_cast<char *>(&shapeId), sizeof(int));
596        }
597
598        return true;
599}
600#endif
601
602
603bool ObjConverter::LoadMaterials(const std::string &matFileName)
604{
605        FILE *file;
606
607        if ((file = fopen(matFileName.c_str(), "r")) == NULL)
608        {       
609                return false;
610        }
611       
612        int line = 0;
613        const int len = 10000;
614        char str[len];
615
616        Material *currentMat = NULL;
617
618
619        while (fgets(str, len, file) != NULL)
620        {
621                //sscanf(str + 1, "%f %f %f", &x, &y, &z);
622                vector<string> strings;
623
624                char *next_token;
625
626                // extract the triples of the form v/t/n v/t/n ...
627                char *pch = strtok_s(str, " \n", &next_token);
628
629                while (pch)
630                {
631                        string s(pch);
632                        strings.push_back(s);
633
634                        pch = strtok_s(NULL, " \n", &next_token);       
635                }
636
637                if ((strings.size() == 2) && (strcmp(strings[0].c_str(), "newmtl") == 0))
638                {
639                        currentMat = new Material();
640                        mMaterialTable[strings[1].c_str()] = currentMat;
641                }
642
643                if ((strings.size() == 2) && (strcmp(strings[0].c_str(), "map_Kd") == 0))
644                {
645                        TextureTable::const_iterator it = mTextureTable.find(strings[1]);
646
647                        int id;
648
649                        if (it == mTextureTable.end()) // parameter not found
650                        {
651                                mTextures.push_back(strings[1]);
652                                id = (int)mTextures.size();
653                                mTextureTable[strings[1]] = id;
654                        }
655                        else
656                        {
657                                id = (*it).second;
658                        }
659
660                        currentMat->texture = id;
661                }
662
663                if ((strings.size() == 4) && (strcmp(strings[0].c_str(),"Kd") == 0))
664                {
665                        currentMat->rgb[0] = (float)atof(strings[1].c_str());
666                        currentMat->rgb[1] = (float)atof(strings[2].c_str());
667                        currentMat->rgb[2] = (float)atof(strings[3].c_str());
668                }
669
670                ++ line;
671        }
672
673        return true;
674}
Note: See TracBrowser for help on using the repository browser.