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

Revision 439, 18.3 KB checked in by mattausch, 19 years ago (diff)

added vview cell manager functionality

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)
[162]68{
[176]69  mCurrentNode = root;
[162]70}
71
[170]72X3dParseHandlers::~X3dParseHandlers()
73{
74}
[162]75
[170]76
77// ---------------------------------------------------------------------------
78//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
79// ---------------------------------------------------------------------------
80void X3dParseHandlers::endElement(const XMLCh* const name)
[162]81{
[170]82  StrX lname(name);
[176]83  string element(lname.LocalForm());
[170]84  if (element == "Shape")
85    EndShape();
86}
[162]87
[170]88void
89X3dParseHandlers::EndShape()
90{
[176]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;
[170]101}
[162]102
[170]103void
104X3dParseHandlers::StartIndexedFaceSet(
[439]105                                                                          AttributeList&  attributes)
[170]106{
107  int len = attributes.getLength();
108  int i;
109  VertexIndexContainer vertices;
[162]110 
[170]111  for (i=0; i < len; i++) {
[176]112    string attrName(StrX(attributes.getName(i)).LocalForm());
[170]113    if (attrName == "coordIndex") {
114      StrX attrValue(attributes.getValue(i));
115      // handle coordIndex
116      vertices.clear();
[176]117      const char *ptr = attrValue.LocalForm();
[170]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);
[176]124            mCurrentMesh->mFaces.push_back(face);
[170]125          }
126          vertices.clear();
127          if (ptr == endptr)
128            break;
129        } else {
130          vertices.push_back(index);
131        }
132        ptr = endptr;
133      }
134    }
[162]135  }
136}
137
[170]138void
139X3dParseHandlers::StartMaterial(
140                                AttributeList&  attributes)
[162]141{
[170]142  int len = attributes.getLength();
143  int i;
[176]144  if (!mCurrentMesh->mMaterial)
145    mCurrentMesh->mMaterial = new Material;
[170]146  for (i=0; i < len; i++) {
[176]147    string attrName(StrX(attributes.getName(i)).LocalForm());
[170]148    StrX attrValue(attributes.getValue(i));
[176]149    const char *ptr = attrValue.LocalForm();
[170]150    if (attrName == "diffuseColor") {
151      float r, g, b;
152      if (sscanf(ptr, "%f %f %f", &r, &g, &b) == 3)
[176]153        mCurrentMesh->mMaterial->mDiffuseColor = RgbColor(r, g, b);
[170]154    }
155  }
[162]156}
157
[170]158void
159X3dParseHandlers::StartCoordinate(
160                                  AttributeList&  attributes)
[162]161{
[170]162  int len = attributes.getLength();
163  int i;
164  VertexContainer vertices;
165  for (i=0; i < len; i++) {
[176]166    string attrName(StrX(attributes.getName(i)).LocalForm());
[170]167    if (attrName == "point") {
168      StrX attrValue(attributes.getValue(i));
[176]169      const char *ptr = attrValue.LocalForm();
[170]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      }
[176]189      mCurrentMesh->mVertices = vertices;
[170]190    }
191  }
[162]192}
193
[170]194
195void
196X3dParseHandlers::startElement(const XMLCh* const name,
[439]197                                                           AttributeList&  attributes)
[162]198{
[170]199  StrX lname(name);
[176]200  string element(lname.LocalForm());
[170]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<<"+";
[176]209    mCurrentMesh = new Mesh;
[170]210  }
211 
212  if (element == "Coordinate") {
[176]213    if (mCurrentMesh)
[170]214      StartCoordinate(attributes);
215  }
216 
217  if (element == "Material") {
218    StartMaterial(attributes);
219  }
220
[176]221  mElementCount++;
222  mAttrCount += attributes.getLength();
[162]223}
224
[170]225void
226X3dParseHandlers::characters(const XMLCh* const chars,
227                             const unsigned int length)
[162]228{
[176]229  mCharacterCount += length;
[162]230}
231
[170]232void
233X3dParseHandlers::ignorableWhitespace(const XMLCh* const chars,
234                                      const unsigned int length)
[162]235{
[176]236  mSpaceCount += length;
[162]237}
238
[170]239void
240X3dParseHandlers::resetDocument()
[162]241{
[176]242  mAttrCount = 0;
243  mCharacterCount = 0;
244  mElementCount = 0;
245  mSpaceCount = 0;
[162]246}
247
[170]248
249
250// ---------------------------------------------------------------------------
251//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
252// ---------------------------------------------------------------------------
253void
254X3dParseHandlers::error(const SAXParseException& e)
[162]255{
[170]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}
[162]261
[170]262void
263X3dParseHandlers::fatalError(const SAXParseException& e)
[162]264{
[170]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;
[162]269}
270
[170]271void
272X3dParseHandlers::warning(const SAXParseException& e)
[162]273{
[170]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;
[162]278}
279
[170]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      }
[176]352
[170]353   
354    // Print out the stats that we collected and time taken
355    if (!errorCount) {
356      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
[176]357                                << handler.GetElementCount() << " elems, "
358                                << handler.GetAttrCount() << " attrs, "
359                                << handler.GetSpaceCount() << " spaces, "
360                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
[170]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;
[162]375}
376
[170]377
[260]378
379/***********************************************************
[262]380 *         class X3dViewCellsParseHandlers implemenation   *
[260]381 ***********************************************************/
382
383
384// ---------------------------------------------------------------------------
385//  StdInParseHandlers: Constructors and Destructor
386// ---------------------------------------------------------------------------
[439]387X3dViewCellsParseHandlers::X3dViewCellsParseHandlers(ViewCellsManager *viewCellsManager,
[312]388                                                                                                         float viewCellHeight) :
[260]389  mElementCount(0)
390  , mAttrCount(0)
391  , mCharacterCount(0)
392  , mSpaceCount(0)
[439]393  , mViewCellsManager(viewCellsManager)
[312]394  , mViewCellHeight(viewCellHeight)
[260]395{
396}
397
[261]398X3dViewCellsParseHandlers::~X3dViewCellsParseHandlers()
[260]399{
400}
401
402
403// ---------------------------------------------------------------------------
404//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
405// ---------------------------------------------------------------------------
[261]406void X3dViewCellsParseHandlers::endElement(const XMLCh* const name)
[260]407{
408  StrX lname(name);
409  string element(lname.LocalForm());
410  if (element == "Shape")
411    EndShape();
412}
413
414void
[261]415X3dViewCellsParseHandlers::EndShape()
[260]416{
417}
418
419void
[261]420X3dViewCellsParseHandlers::StartIndexedFaceSet(
[260]421                                      AttributeList&  attributes)
422{
423        int len = attributes.getLength();
424        int i;
[262]425        // clear previous vertex indices
426        mCurrentVertexIndices.clear();
[260]427        for (i=0; i < len; i++)
428        {
429                string attrName(StrX(attributes.getName(i)).LocalForm());
430           
431                if (attrName == "coordIndex")
432                {
433                        StrX attrValue(attributes.getValue(i));
434                       
435                        // handle coordIndex
436                        const char *ptr = attrValue.LocalForm();
437                        char *endptr;
438               
[261]439                        while (1)
[260]440                        {
441                                int index = strtol(ptr, &endptr, 10);
442                               
[261]443                                if (ptr == endptr)
444                                        break;
445
446                                if (index != -1)
[260]447                                {
[261]448                                        mCurrentVertexIndices.push_back(index);
[260]449                                }
450                   
451                                ptr = endptr;
452                        }
453                }
454        }
455}
456
457
458void
[439]459X3dViewCellsParseHandlers::StartCoordinate(AttributeList&  attributes)
[260]460{
461        int len = attributes.getLength();
462       
463        VertexContainer vertices;
[364]464        int i;
465        for (i=0; i < len; i++)
[260]466        {
467                string attrName(StrX(attributes.getName(i)).LocalForm());
468               
469                if (attrName == "point")
470                {
471                        StrX attrValue(attributes.getValue(i));
472                       
473                        const char *ptr = attrValue.LocalForm();
474                       
475                        char *endptr;
476                       
477                        while (1)
478                        {
479                                float x = strtod(ptr, &endptr);
480               
481                                if (ptr == endptr)
482                                        break;
483                                ptr = endptr;
484                               
[318]485                                float y = (float)strtod(ptr, &endptr);
[260]486
487                               
488                                if (ptr == endptr)
489                                        break;
490                                ptr = endptr;
491
[318]492                                float z = (float)strtod(ptr, &endptr);
[260]493
494                                if (ptr == endptr)
495                                        break;
496
497                                ptr = endptr;
498                                if (*ptr == ',')
499                                        ptr++;
500
501                                Vector3 v(x, y, z);
[262]502                                vertices.push_back(v);                         
[260]503                        }
504                }
505        }
[261]506
[333]507        for (i = 0; i < mCurrentVertexIndices.size(); i += 3)
[439]508        {
[312]509                Triangle3 baseTri(vertices[mCurrentVertexIndices[i + 0]],
510                                                  vertices[mCurrentVertexIndices[i + 1]],
511                                                  vertices[mCurrentVertexIndices[i + 2]]);
[261]512
[262]513                // create view cell from base triangle
[439]514                mViewCellsManager->AddViewCell(mViewCellsManager->ExtrudeViewCell(baseTri, mViewCellHeight));
515        }
[260]516}
517
518
519void
[261]520X3dViewCellsParseHandlers::startElement(const XMLCh* const name,
[439]521                                                                                AttributeList&  attributes)
[260]522{
523  StrX lname(name);
524  string element(lname.LocalForm());
525 
526  if (element == "IndexedFaceSet") {
[261]527    // create the viewcells from individual triangles
[260]528    StartIndexedFaceSet(attributes);
529  }
[261]530       
531  // do nothing
532  //if (element == "Shape") {}
[260]533 
534  if (element == "Coordinate") {
[261]535          // add coordinates to the triangles
[260]536      StartCoordinate(attributes);
537  }
[261]538  // ignore material
539  //if (element == "Material") {}
[260]540
541  mElementCount++;
542  mAttrCount += attributes.getLength();
543}
544
545void
[261]546X3dViewCellsParseHandlers::characters(const XMLCh* const chars,
[260]547                             const unsigned int length)
548{
549  mCharacterCount += length;
550}
551
552void
[261]553X3dViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
[260]554                                      const unsigned int length)
555{
556  mSpaceCount += length;
557}
558
559void
[261]560X3dViewCellsParseHandlers::resetDocument()
[260]561{
562  mAttrCount = 0;
563  mCharacterCount = 0;
564  mElementCount = 0;
565  mSpaceCount = 0;
566}
567
568
569
570// ---------------------------------------------------------------------------
571//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
572// ---------------------------------------------------------------------------
573void
[261]574X3dViewCellsParseHandlers::error(const SAXParseException& e)
[260]575{
576  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
577                            << ", line " << e.getLineNumber()
578                            << ", char " << e.getColumnNumber()
579                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
580}
581
582void
[261]583X3dViewCellsParseHandlers::fatalError(const SAXParseException& e)
[260]584{
585  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
586                            << ", line " << e.getLineNumber()
587                            << ", char " << e.getColumnNumber()
588                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
589}
590
591void
[261]592X3dViewCellsParseHandlers::warning(const SAXParseException& e)
[260]593{
594  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
595                            << ", line " << e.getLineNumber()
596                            << ", char " << e.getColumnNumber()
597                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
598}
599
600
601bool
[439]602X3dParser::ParseFile(const string filename, ViewCellsManager &viewCells)
[260]603{
604  // Initialize the XML4C system
605  try {
606    XMLPlatformUtils::Initialize();
607  }
608 
609  catch (const XMLException& toCatch)
610    {
611      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
612                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
613      return false;
614    }
615 
616 
617  //
618  //  Create a SAX parser object. Then, according to what we were told on
619  //  the command line, set the options.
620  //
621  SAXParser* parser = new SAXParser;
622  parser->setValidationScheme(valScheme);
623  parser->setDoNamespaces(doNamespaces);
624  parser->setDoSchema(doSchema);
625  parser->setValidationSchemaFullChecking(schemaFullChecking);
626 
627
628  //
629  //  Create our SAX handler object and install it on the parser, as the
630  //  document and error handler. We are responsible for cleaning them
631  //  up, but since its just stack based here, there's nothing special
632  //  to do.
633  //
[312]634  X3dViewCellsParseHandlers handler(&viewCells, mViewCellHeight);
[260]635  parser->setDocumentHandler(&handler);
636  parser->setErrorHandler(&handler);
637 
638  unsigned long duration;
639  int errorCount = 0;
640  // create a faux scope so that 'src' destructor is called before
641  // XMLPlatformUtils::Terminate
642  {
643    //
644    //  Kick off the parse and catch any exceptions. Create a standard
645    //  input input source and tell the parser to parse from that.
646    //
647    //    StdInInputSource src;
648    try
649      {
650        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
651        parser->parse(filename.c_str());
652        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
653        duration = endMillis - startMillis;
654        errorCount = parser->getErrorCount();
655      }
656    catch (const OutOfMemoryException&)
657      {
658        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
659        errorCount = 2;
660        return false;
661      }
662    catch (const XMLException& e)
663      {
664        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
665                                  << StrX(e.getMessage())
666                                  << "\n" << XERCES_STD_QUALIFIER endl;
667        errorCount = 1;
668        return false;
669      }
670
671   
672    // Print out the stats that we collected and time taken
673    if (!errorCount) {
674      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
675                                << handler.GetElementCount() << " elems, "
676                                << handler.GetAttrCount() << " attrs, "
677                                << handler.GetSpaceCount() << " spaces, "
678                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
679    }
680  }
681 
682  //
683  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
684  //
685  delete parser;
686 
687  XMLPlatformUtils::Terminate();
688 
689  if (errorCount > 0)
690    return false;
691  else
692    return true;
[333]693}
Note: See TracBrowser for help on using the repository browser.