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

Revision 260, 18.0 KB checked in by mattausch, 19 years ago (diff)

added viewcell stuff

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