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

Revision 490, 18.5 KB checked in by mattausch, 19 years ago (diff)

added loading and storing rays capability

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