source: trunk/VUT/GtpVisibilityPreprocessor/src/X3dParser.cpp @ 261

Revision 261, 18.1 KB checked in by mattausch, 19 years ago (diff)

added viewcell loader

Line 
1// ---------------------------------------------------------------------------
2//  Includes for all the program files to see
3// ---------------------------------------------------------------------------
4#include <string.h>
5#include <stdlib.h>
6#include <iostream>
7using namespace std;
8#include <xercesc/util/PlatformUtils.hpp>
9
10// ---------------------------------------------------------------------------
11//  Includes
12// ---------------------------------------------------------------------------
13#include <xercesc/framework/StdInInputSource.hpp>
14#include <xercesc/parsers/SAXParser.hpp>
15#include <xercesc/util/OutOfMemoryException.hpp>
16
17// ---------------------------------------------------------------------------
18//  Includes
19// ---------------------------------------------------------------------------
20#include <xercesc/sax/AttributeList.hpp>
21#include <xercesc/sax/SAXParseException.hpp>
22#include <xercesc/sax/SAXException.hpp>
23
24#include "X3dParser.h"
25
26#include "X3dParserXerces.h"
27#include "Mesh.h"
28#include "SceneGraph.h"
29#include "Triangle3.h"
30#include "ViewCell.h"
31
32// ---------------------------------------------------------------------------
33//  Local data
34//
35//  doNamespaces
36//      Indicates whether namespace processing should be enabled or not.
37//      The default is no, but -n overrides that.
38//
39//  doSchema
40//      Indicates whether schema processing should be enabled or not.
41//      The default is no, but -s overrides that.
42//
43//  schemaFullChecking
44//      Indicates whether full schema constraint checking should be enabled or not.
45//      The default is no, but -s overrides that.
46//
47//  valScheme
48//      Indicates what validation scheme to use. It defaults to 'auto', but
49//      can be set via the -v= command.
50// ---------------------------------------------------------------------------
51static bool     doNamespaces       = false;
52static bool     doSchema           = false;
53static bool     schemaFullChecking = false;
54static SAXParser::ValSchemes    valScheme       = SAXParser::Val_Auto;
55
56
57
58
59
60// ---------------------------------------------------------------------------
61//  StdInParseHandlers: Constructors and Destructor
62// ---------------------------------------------------------------------------
63X3dParseHandlers::X3dParseHandlers(SceneGraphNode *root) :
64  mElementCount(0)
65  , mAttrCount(0)
66  , mCharacterCount(0)
67  , mSpaceCount(0)
68{
69  mCurrentNode = root;
70}
71
72X3dParseHandlers::~X3dParseHandlers()
73{
74}
75
76
77// ---------------------------------------------------------------------------
78//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
79// ---------------------------------------------------------------------------
80void X3dParseHandlers::endElement(const XMLCh* const name)
81{
82  StrX lname(name);
83  string element(lname.LocalForm());
84  if (element == "Shape")
85    EndShape();
86}
87
88void
89X3dParseHandlers::EndShape()
90{
91  if (mCurrentMesh->mFaces.size()) {
92    mCurrentMesh->Preprocess();
93    // make an instance of this mesh
94    MeshInstance *mi = new MeshInstance(mCurrentMesh);
95    mCurrentNode->mGeometry.push_back(mi);
96  } else {
97    cout<<"X";
98    delete mCurrentMesh;
99  }
100  mCurrentMesh = NULL;
101}
102
103void
104X3dParseHandlers::StartIndexedFaceSet(
105                                      AttributeList&  attributes)
106{
107  int len = attributes.getLength();
108  int i;
109  VertexIndexContainer vertices;
110 
111  for (i=0; i < len; i++) {
112    string attrName(StrX(attributes.getName(i)).LocalForm());
113    if (attrName == "coordIndex") {
114      StrX attrValue(attributes.getValue(i));
115      // handle coordIndex
116      vertices.clear();
117      const char *ptr = attrValue.LocalForm();
118      char *endptr;
119      while(1) {
120        int index = strtol(ptr, &endptr, 10);
121        if (ptr == endptr || index == -1) {
122          if (vertices.size() > 2) {
123            Face *face = new Face(vertices);
124            mCurrentMesh->mFaces.push_back(face);
125          }
126          vertices.clear();
127          if (ptr == endptr)
128            break;
129        } else {
130          vertices.push_back(index);
131        }
132        ptr = endptr;
133      }
134    }
135  }
136}
137
138void
139X3dParseHandlers::StartMaterial(
140                                AttributeList&  attributes)
141{
142  int len = attributes.getLength();
143  int i;
144  if (!mCurrentMesh->mMaterial)
145    mCurrentMesh->mMaterial = new Material;
146  for (i=0; i < len; i++) {
147    string attrName(StrX(attributes.getName(i)).LocalForm());
148    StrX attrValue(attributes.getValue(i));
149    const char *ptr = attrValue.LocalForm();
150    if (attrName == "diffuseColor") {
151      float r, g, b;
152      if (sscanf(ptr, "%f %f %f", &r, &g, &b) == 3)
153        mCurrentMesh->mMaterial->mDiffuseColor = RgbColor(r, g, b);
154    }
155  }
156}
157
158void
159X3dParseHandlers::StartCoordinate(
160                                  AttributeList&  attributes)
161{
162  int len = attributes.getLength();
163  int i;
164  VertexContainer vertices;
165  for (i=0; i < len; i++) {
166    string attrName(StrX(attributes.getName(i)).LocalForm());
167    if (attrName == "point") {
168      StrX attrValue(attributes.getValue(i));
169      const char *ptr = attrValue.LocalForm();
170      char *endptr;
171      while(1) {
172        float x = strtod(ptr, &endptr);
173        if (ptr == endptr)
174          break;
175        ptr = endptr;
176        float y = strtod(ptr, &endptr);
177        if (ptr == endptr)
178          break;
179        ptr = endptr;
180        float z = strtod(ptr, &endptr);
181        if (ptr == endptr)
182          break;
183        ptr = endptr;
184        if (*ptr == ',')
185          ptr++;
186        Vector3 v(x, y, z);
187        vertices.push_back(v);
188      }
189      mCurrentMesh->mVertices = vertices;
190    }
191  }
192}
193
194
195void
196X3dParseHandlers::startElement(const XMLCh* const name,
197                               AttributeList&  attributes)
198{
199  StrX lname(name);
200  string element(lname.LocalForm());
201 
202  if (element == "IndexedFaceSet") {
203    // create a new mesh node in the scene graph
204    StartIndexedFaceSet(attributes);
205  }
206
207  if (element == "Shape") {
208    cout<<"+";
209    mCurrentMesh = new Mesh;
210  }
211 
212  if (element == "Coordinate") {
213    if (mCurrentMesh)
214      StartCoordinate(attributes);
215  }
216 
217  if (element == "Material") {
218    StartMaterial(attributes);
219  }
220
221  mElementCount++;
222  mAttrCount += attributes.getLength();
223}
224
225void
226X3dParseHandlers::characters(const XMLCh* const chars,
227                             const unsigned int length)
228{
229  mCharacterCount += length;
230}
231
232void
233X3dParseHandlers::ignorableWhitespace(const XMLCh* const chars,
234                                      const unsigned int length)
235{
236  mSpaceCount += length;
237}
238
239void
240X3dParseHandlers::resetDocument()
241{
242  mAttrCount = 0;
243  mCharacterCount = 0;
244  mElementCount = 0;
245  mSpaceCount = 0;
246}
247
248
249
250// ---------------------------------------------------------------------------
251//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
252// ---------------------------------------------------------------------------
253void
254X3dParseHandlers::error(const SAXParseException& e)
255{
256  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
257                            << ", line " << e.getLineNumber()
258                            << ", char " << e.getColumnNumber()
259                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
260}
261
262void
263X3dParseHandlers::fatalError(const SAXParseException& e)
264{
265  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
266                            << ", line " << e.getLineNumber()
267                            << ", char " << e.getColumnNumber()
268                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
269}
270
271void
272X3dParseHandlers::warning(const SAXParseException& e)
273{
274  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
275                            << ", line " << e.getLineNumber()
276                            << ", char " << e.getColumnNumber()
277                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
278}
279
280
281bool
282X3dParser::ParseFile(const string filename,
283                     SceneGraphNode **root)
284{
285  // Initialize the XML4C system
286  try {
287    XMLPlatformUtils::Initialize();
288  }
289 
290  catch (const XMLException& toCatch)
291    {
292      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
293                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
294      return false;
295    }
296 
297 
298  //
299  //  Create a SAX parser object. Then, according to what we were told on
300  //  the command line, set the options.
301  //
302  SAXParser* parser = new SAXParser;
303  parser->setValidationScheme(valScheme);
304  parser->setDoNamespaces(doNamespaces);
305  parser->setDoSchema(doSchema);
306  parser->setValidationSchemaFullChecking(schemaFullChecking);
307 
308
309  //
310  //  Create our SAX handler object and install it on the parser, as the
311  //  document and error handler. We are responsible for cleaning them
312  //  up, but since its just stack based here, there's nothing special
313  //  to do.
314  //
315  *root = new SceneGraphNode;
316  X3dParseHandlers handler(*root);
317  parser->setDocumentHandler(&handler);
318  parser->setErrorHandler(&handler);
319 
320  unsigned long duration;
321  int errorCount = 0;
322  // create a faux scope so that 'src' destructor is called before
323  // XMLPlatformUtils::Terminate
324  {
325    //
326    //  Kick off the parse and catch any exceptions. Create a standard
327    //  input input source and tell the parser to parse from that.
328    //
329    //    StdInInputSource src;
330    try
331      {
332        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
333        parser->parse(filename.c_str());
334        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
335        duration = endMillis - startMillis;
336        errorCount = parser->getErrorCount();
337      }
338    catch (const OutOfMemoryException&)
339      {
340        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
341        errorCount = 2;
342        return false;
343      }
344    catch (const XMLException& e)
345      {
346        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
347                                  << StrX(e.getMessage())
348                                  << "\n" << XERCES_STD_QUALIFIER endl;
349        errorCount = 1;
350        return false;
351      }
352
353   
354    // Print out the stats that we collected and time taken
355    if (!errorCount) {
356      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
357                                << handler.GetElementCount() << " elems, "
358                                << handler.GetAttrCount() << " attrs, "
359                                << handler.GetSpaceCount() << " spaces, "
360                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
361    }
362  }
363 
364  //
365  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
366  //
367  delete parser;
368 
369  XMLPlatformUtils::Terminate();
370 
371  if (errorCount > 0)
372    return false;
373  else
374    return true;
375}
376
377
378
379/***********************************************************
380 *         class X3dViewCellsParseHandlers implemenation          *
381 ***********************************************************/
382
383
384// ---------------------------------------------------------------------------
385//  StdInParseHandlers: Constructors and Destructor
386// ---------------------------------------------------------------------------
387X3dViewCellsParseHandlers::X3dViewCellsParseHandlers(ViewCellContainer *viewCells) :
388  mElementCount(0)
389  , mAttrCount(0)
390  , mCharacterCount(0)
391  , mSpaceCount(0)
392  , mViewCells(viewCells)
393{
394}
395
396X3dViewCellsParseHandlers::~X3dViewCellsParseHandlers()
397{
398}
399
400
401// ---------------------------------------------------------------------------
402//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
403// ---------------------------------------------------------------------------
404void X3dViewCellsParseHandlers::endElement(const XMLCh* const name)
405{
406  StrX lname(name);
407  string element(lname.LocalForm());
408  if (element == "Shape")
409    EndShape();
410}
411
412void
413X3dViewCellsParseHandlers::EndShape()
414{
415}
416
417void
418X3dViewCellsParseHandlers::StartIndexedFaceSet(
419                                      AttributeList&  attributes)
420{
421        int len = attributes.getLength();
422        int i;
423       
424        for (i=0; i < len; i++)
425        {
426                string attrName(StrX(attributes.getName(i)).LocalForm());
427           
428                if (attrName == "coordIndex")
429                {
430                        StrX attrValue(attributes.getValue(i));
431                       
432                        // handle coordIndex
433                        const char *ptr = attrValue.LocalForm();
434                        char *endptr;
435               
436                        while (1)
437                        {
438                                int index = strtol(ptr, &endptr, 10);
439                               
440                                if (ptr == endptr)
441                                        break;
442
443                                if (index != -1)
444                                {
445                                        mCurrentVertexIndices.push_back(index);
446                                }
447                   
448                                ptr = endptr;
449                        }
450                }
451        }
452}
453
454
455void
456X3dViewCellsParseHandlers::StartCoordinate(
457                                  AttributeList&  attributes)
458{
459        int len = attributes.getLength();
460       
461        VertexContainer vertices;
462
463        for (int i=0; i < len; i++)
464        {
465                string attrName(StrX(attributes.getName(i)).LocalForm());
466               
467                if (attrName == "point")
468                {
469                        StrX attrValue(attributes.getValue(i));
470                       
471                        const char *ptr = attrValue.LocalForm();
472                       
473                        char *endptr;
474                       
475                        while (1)
476                        {
477                                float x = strtod(ptr, &endptr);
478               
479                                if (ptr == endptr)
480                                        break;
481                                ptr = endptr;
482                               
483                                float y = strtod(ptr, &endptr);
484
485                               
486                                if (ptr == endptr)
487                                        break;
488                                ptr = endptr;
489
490                                float z = strtod(ptr, &endptr);
491
492                                if (ptr == endptr)
493                                        break;
494
495                                ptr = endptr;
496                                if (*ptr == ',')
497                                        ptr++;
498
499                                Vector3 v(x, y, z);
500                                vertices.push_back(v);
501                        }
502                }
503        }
504
505
506
507    for (int i = 0; i < mCurrentVertexIndices.size(); i+=3)
508        {
509                Triangle3 baseTri(vertices[mCurrentVertexIndices[i]],
510                                                  vertices[mCurrentVertexIndices[i+1]],
511                                                  vertices[mCurrentVertexIndices[i+2]]);
512
513            // create view cell from base triangle
514                const float height = 10;
515                mViewCells->push_back(ViewCell::ExtrudeViewCell(baseTri, height));
516        }
517}
518
519
520void
521X3dViewCellsParseHandlers::startElement(const XMLCh* const name,
522                               AttributeList&  attributes)
523{
524  StrX lname(name);
525  string element(lname.LocalForm());
526 
527  if (element == "IndexedFaceSet") {
528    // create the viewcells from individual triangles
529    StartIndexedFaceSet(attributes);
530  }
531       
532  // do nothing
533  //if (element == "Shape") {}
534 
535  if (element == "Coordinate") {
536          // add coordinates to the triangles
537      StartCoordinate(attributes);
538  }
539  // ignore material
540  //if (element == "Material") {}
541
542  mElementCount++;
543  mAttrCount += attributes.getLength();
544}
545
546void
547X3dViewCellsParseHandlers::characters(const XMLCh* const chars,
548                             const unsigned int length)
549{
550  mCharacterCount += length;
551}
552
553void
554X3dViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
555                                      const unsigned int length)
556{
557  mSpaceCount += length;
558}
559
560void
561X3dViewCellsParseHandlers::resetDocument()
562{
563  mAttrCount = 0;
564  mCharacterCount = 0;
565  mElementCount = 0;
566  mSpaceCount = 0;
567}
568
569
570
571// ---------------------------------------------------------------------------
572//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
573// ---------------------------------------------------------------------------
574void
575X3dViewCellsParseHandlers::error(const SAXParseException& e)
576{
577  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
578                            << ", line " << e.getLineNumber()
579                            << ", char " << e.getColumnNumber()
580                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
581}
582
583void
584X3dViewCellsParseHandlers::fatalError(const SAXParseException& e)
585{
586  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
587                            << ", line " << e.getLineNumber()
588                            << ", char " << e.getColumnNumber()
589                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
590}
591
592void
593X3dViewCellsParseHandlers::warning(const SAXParseException& e)
594{
595  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
596                            << ", line " << e.getLineNumber()
597                            << ", char " << e.getColumnNumber()
598                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
599}
600
601
602bool
603X3dParser::ParseFile(const string filename, ViewCellContainer &viewCells)
604{
605  // Initialize the XML4C system
606  try {
607    XMLPlatformUtils::Initialize();
608  }
609 
610  catch (const XMLException& toCatch)
611    {
612      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
613                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
614      return false;
615    }
616 
617 
618  //
619  //  Create a SAX parser object. Then, according to what we were told on
620  //  the command line, set the options.
621  //
622  SAXParser* parser = new SAXParser;
623  parser->setValidationScheme(valScheme);
624  parser->setDoNamespaces(doNamespaces);
625  parser->setDoSchema(doSchema);
626  parser->setValidationSchemaFullChecking(schemaFullChecking);
627 
628
629  //
630  //  Create our SAX handler object and install it on the parser, as the
631  //  document and error handler. We are responsible for cleaning them
632  //  up, but since its just stack based here, there's nothing special
633  //  to do.
634  //
635  X3dViewCellsParseHandlers handler(&viewCells);
636  parser->setDocumentHandler(&handler);
637  parser->setErrorHandler(&handler);
638 
639  unsigned long duration;
640  int errorCount = 0;
641  // create a faux scope so that 'src' destructor is called before
642  // XMLPlatformUtils::Terminate
643  {
644    //
645    //  Kick off the parse and catch any exceptions. Create a standard
646    //  input input source and tell the parser to parse from that.
647    //
648    //    StdInInputSource src;
649    try
650      {
651        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
652        parser->parse(filename.c_str());
653        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
654        duration = endMillis - startMillis;
655        errorCount = parser->getErrorCount();
656      }
657    catch (const OutOfMemoryException&)
658      {
659        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
660        errorCount = 2;
661        return false;
662      }
663    catch (const XMLException& e)
664      {
665        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
666                                  << StrX(e.getMessage())
667                                  << "\n" << XERCES_STD_QUALIFIER endl;
668        errorCount = 1;
669        return false;
670      }
671
672   
673    // Print out the stats that we collected and time taken
674    if (!errorCount) {
675      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
676                                << handler.GetElementCount() << " elems, "
677                                << handler.GetAttrCount() << " attrs, "
678                                << handler.GetSpaceCount() << " spaces, "
679                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
680    }
681  }
682 
683  //
684  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
685  //
686  delete parser;
687 
688  XMLPlatformUtils::Terminate();
689 
690  if (errorCount > 0)
691    return false;
692  else
693    return true;
694}
Note: See TracBrowser for help on using the repository browser.