source: GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp @ 971

Revision 971, 24.4 KB checked in by mattausch, 18 years ago (diff)

added stuff for view cell ziping (not working yet!)

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#include <xercesc/util/BinFileInputStream.hpp>
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 "ViewCellsManager.h"
31
32namespace GtpVisibilityPreprocessor {
33
34float X3dParser::DEFAULT_VIEWCELL_HEIGHT = 5.0f;
35
36// ---------------------------------------------------------------------------
37//  Local data
38//
39//  doNamespaces
40//      Indicates whether namespace processing should be enabled or not.
41//      The default is no, but -n overrides that.
42//
43//  doSchema
44//      Indicates whether schema processing should be enabled or not.
45//      The default is no, but -s overrides that.
46//
47//  schemaFullChecking
48//      Indicates whether full schema constraint checking should be enabled or not.
49//      The default is no, but -s overrides that.
50//
51//  valScheme
52//      Indicates what validation scheme to use. It defaults to 'auto', but
53//      can be set via the -v= command.
54// ---------------------------------------------------------------------------
55static bool     doNamespaces       = false;
56static bool     doSchema           = false;
57static bool     schemaFullChecking = false;
58static SAXParser::ValSchemes    valScheme       = SAXParser::Val_Auto;
59
60#define ROTATE_SCENE 0
61
62
63static void RotateMesh(Mesh *mesh)
64{
65        VertexContainer::iterator it, it_end = mesh->mVertices.end();
66
67        const float angle = 30.0f * PI / 180.0f;
68        const Matrix4x4 rot = RotationYMatrix(angle);
69
70        for (it = mesh->mVertices.begin(); it != it_end; ++ it)
71        {
72                (*it) = rot * (*it);       
73        }
74}
75
76// ---------------------------------------------------------------------------
77//  StdInParseHandlers: Constructors and Destructor
78// ---------------------------------------------------------------------------
79X3dParseHandlers::X3dParseHandlers(SceneGraphNode *root, const bool loadPolygonsAsMeshes):
80  mElementCount(0)
81  , mAttrCount(0)
82  , mCharacterCount(0)
83  , mSpaceCount(0)
84  , mLoadPolygonsAsMeshes(loadPolygonsAsMeshes)
85{
86  mCurrentNode = root;
87  // this matrix should never be removed from stack
88  //mTransformations.push(IdentityMatrix());
89}
90
91X3dParseHandlers::~X3dParseHandlers()
92{
93        if (!mTransformations.empty())
94                cout << "error: transformation stack size: " << (int)mTransformations.size() << endl;
95}
96
97
98// ---------------------------------------------------------------------------
99//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
100// ---------------------------------------------------------------------------
101void X3dParseHandlers::endElement(const XMLCh* const name)
102{
103  StrX lname(name);
104  string element(lname.LocalForm());
105 
106  // only create new mesh instance if define mechanism was not used
107  if (element == "Shape")
108    EndShape();
109
110  if (element == "Transform")
111          EndTransform();
112}
113
114
115
116
117void X3dParseHandlers::ApplyTransformation(Mesh *mesh,
118                                                                                   const Matrix4x4 &m) const
119{
120        VertexContainer::iterator it, it_end = mesh->mVertices.end();
121
122        for (it = mesh->mVertices.begin(); it != it_end; ++ it)
123        {
124                (*it) = m * (*it);       
125        }
126}
127
128
129void X3dParseHandlers::ApplyTransformations(TrafoStack trafos, Mesh *mesh) const
130{
131        while (!trafos.empty())
132        {
133                const Matrix4x4 m = trafos.top();
134                trafos.pop();
135
136                ApplyTransformation(mesh, m);
137        }
138}
139
140void X3dParseHandlers::StartTransform(AttributeList&  attributes)
141{
142        Matrix4x4 currentTransform = IdentityMatrix();
143
144        const int len = attributes.getLength();
145    Matrix4x4 *rotm = NULL;
146        Matrix4x4 *scalem = NULL;
147        Matrix4x4 *translm = NULL;
148   
149        for (int i = 0; i < len; ++ i)
150        {
151                string attrName(StrX(attributes.getName(i)).LocalForm());
152                       
153                StrX attrValue(attributes.getValue(i));
154                const char *ptr = attrValue.LocalForm();
155                       
156                if (attrName == "rotation")
157                {
158                        Vector3 axis;
159                        float angle;
160                               
161                        if (sscanf(ptr, "%f %f %f %f", &axis.x, &axis.y, &axis.z, &angle) == 4)
162                        {
163                                rotm = new Matrix4x4(RotationAxisMatrix(axis, angle));
164                        }
165                }
166                else if (attrName == "translation")
167                {
168                        Vector3 transl;
169                                                       
170                        if (sscanf(ptr, "%f %f %f %f", &transl.x, &transl.y, &transl.z) == 3)
171                        {
172                                translm = new Matrix4x4(TranslationMatrix(transl));
173                        }
174                }
175                else if (attrName == "scale")
176                {
177                        Vector3 scale;
178
179                        if (sscanf(ptr, "%f %f %f %f", &scale.x, &scale.y, &scale.z) == 3)
180                        {
181                                scalem = new Matrix4x4(ScaleMatrix(scale.x, scale.y, scale.z));
182                        }
183                }
184                // todo: scale orientation
185        }
186       
187        if (scalem)
188                currentTransform *= (*scalem);
189        if (rotm)
190                currentTransform *= (*rotm);
191        if (translm)
192                currentTransform *= (*translm);
193
194        DEL_PTR(scalem);
195        DEL_PTR(rotm);
196        DEL_PTR(translm);
197
198        mTransformations.push(currentTransform);
199}
200
201
202void X3dParseHandlers::EndTransform()
203{
204        mTransformations.pop();
205}
206
207
208void X3dParseHandlers::EndShape()
209{
210        // this shape is a definition => don't create mesh instance
211        if (mIsMeshDefinition)
212{
213                mMeshDefinitions[mCurrentMeshName.c_str()] = mCurrentMesh;
214                //cout << "new definition: " << mCurrentMeshName << endl;
215               
216                return;
217        }
218
219        // each polygon is one single mesh
220        if (mLoadPolygonsAsMeshes)
221        {
222                //if (mCurrentMesh->mFaces.empty())     cout << "error!" << endl;
223
224                FaceContainer::const_iterator fit, fit_end = mCurrentMesh->mFaces.end();
225
226                cout << "m";
227                //cout << "m: " << mCurrentMesh->mFaces.size() << endl;
228                for (fit = mCurrentMesh->mFaces.begin(); fit != fit_end; ++ fit)
229                {
230                        cout << "f";
231
232                        Face *face = *fit;
233                        // only one face per mesh
234                        Mesh *mesh = new Mesh();
235                        VertexIndexContainer vc;
236                                       
237                        VertexIndexContainer::const_iterator vit, vit_end = face->mVertexIndices.end();
238                       
239                        int i = 0;
240                        for (vit = face->mVertexIndices.begin(); vit != vit_end; ++ vit, ++ i)
241                        {
242                                cout << "i";
243                                int index = (*vit);
244                                // add vertices
245                                mesh->mVertices.push_back(mCurrentMesh->mVertices[index]);
246                                vc.push_back(i);
247                        }
248
249                        mesh->mFaces.push_back(new Face(vc));
250
251                        // NOTE: should rather be written into trafo of mesh instance
252                        ApplyTransformations(mTransformations, mesh);
253
254                        mesh->Preprocess();
255                               
256                        // make an instance of this mesh
257                        MeshInstance *mi = new MeshInstance(mesh);
258                        mCurrentNode->mGeometry.push_back(mi);
259                }
260
261                // LEAK!! TODO: delete if not defd
262                if (!mUsingMeshDefinition)
263                        delete mCurrentMesh;
264
265                //mCurrentVertices.clear();
266                //mCurrentVertexIndices.clear();
267        }
268        else
269        {
270                if (!mCurrentMesh->mFaces.empty())
271                {
272                        // should rather be written into the transformation
273                        // of a mesh instance
274                        ApplyTransformations(mTransformations, mCurrentMesh);
275
276                        mCurrentMesh->Preprocess();
277                        // make an instance of this mesh
278                        MeshInstance *mi = new MeshInstance(mCurrentMesh);
279
280                        mCurrentNode->mGeometry.push_back(mi);
281                        // set the object id to a unique value
282                        //mi->SetId(mCurrentObjectId ++);
283                }
284                else
285                {
286                        // empty mesh => discard
287                        cout<<"X";
288
289                        delete mCurrentMesh;
290                }
291
292                mCurrentMesh = NULL;
293        }
294}
295
296
297void X3dParseHandlers::StartIndexedFaceSet(AttributeList&  attributes)
298{
299  int len = attributes.getLength();
300
301  int i;
302  VertexIndexContainer vertices;
303 
304        mIsMeshDefinition = false;
305        mUsingMeshDefinition = false;
306        for (i = 0; i < len; ++ i)
307        {
308                string attrName(StrX(attributes.getName(i)).LocalForm());
309         
310                // this is a definition of a mesh
311                if (attrName == "DEF")
312                {
313                        mIsMeshDefinition = true;
314                        StrX attrValue(attributes.getValue(i));
315                        const char *ptr = attrValue.LocalForm();
316                        mCurrentMeshName = ptr;
317
318                        cout << "d";
319                }
320               
321                // we use an already defined mesh
322                if (attrName == "USE")
323                {
324                        StrX attrValue(attributes.getValue(i));
325
326                        // discard new mesh and assign defined mesh
327                        DEL_PTR(mCurrentMesh);
328                        const char *ptr = attrValue.LocalForm();
329
330                        mCurrentMesh = mMeshDefinitions[ptr];
331                        mUsingMeshDefinition = true;
332                        cout << "u";
333                }
334               
335                if (attrName == "coordIndex")
336                {
337                        StrX attrValue(attributes.getValue(i));
338                        // handle coordIndex
339                        vertices.clear();
340                        const char *ptr = attrValue.LocalForm();
341                 
342                        char *endptr;
343         
344                        while (1)
345                        {
346                                int index = strtol(ptr, &endptr, 10);
347                                 
348                                if (ptr == endptr || index == -1)
349                                {
350                                        if (vertices.size() > 2)
351                                        {
352                                                Face *face = new Face(vertices);                 
353                                                mCurrentMesh->mFaces.push_back(face);
354                                        }
355                         
356                                        vertices.clear();
357                 
358                                        if (ptr == endptr)
359                                                break;
360                         
361                                  }
362                                  else
363                                  {
364                                          vertices.push_back(index);
365                                  }
366                                  ptr = endptr;
367                        }
368                }
369        }
370}
371
372
373void
374X3dParseHandlers::StartMaterial(
375                                AttributeList&  attributes)
376{
377  int len = attributes.getLength();
378  int i;
379  if (!mCurrentMesh->mMaterial)
380    mCurrentMesh->mMaterial = new Material;
381  for (i=0; i < len; i++) {
382    string attrName(StrX(attributes.getName(i)).LocalForm());
383    StrX attrValue(attributes.getValue(i));
384    const char *ptr = attrValue.LocalForm();
385    if (attrName == "diffuseColor") {
386      float r, g, b;
387      if (sscanf(ptr, "%f %f %f", &r, &g, &b) == 3)
388        mCurrentMesh->mMaterial->mDiffuseColor = RgbColor(r, g, b);
389    }
390  }
391}
392
393void
394X3dParseHandlers::StartCoordinate(
395                                  AttributeList&  attributes)
396{
397        int len = attributes.getLength();
398       
399        int i;
400        VertexContainer vertices;
401       
402        for (i=0; i < len; i++)
403        {
404                string attrName(StrX(attributes.getName(i)).LocalForm());
405         
406                if (attrName == "point")
407                {
408                        StrX attrValue(attributes.getValue(i));
409                 
410
411                        const char *ptr = attrValue.LocalForm();
412                        char *endptr;
413
414
415                        while (1)
416                        {
417                                float x = (float)strtod(ptr, &endptr);
418               
419                                if (ptr == endptr)
420                                  break;
421                         
422                                ptr = endptr;
423                               
424                                float y = (float)strtod(ptr, &endptr);
425                         
426                                if (ptr == endptr)
427                                        break;
428
429                                ptr = endptr;
430                         
431                                float z = (float)strtod(ptr, &endptr);
432                                if (ptr == endptr)
433                                        break;
434                         
435                                ptr = endptr;
436                         
437                                if (*ptr == ',')
438                                        ptr ++;
439
440                                Vector3 v(x, y, z);
441                                vertices.push_back(v);
442                        }
443                       
444                        mCurrentMesh->mVertices = vertices;
445                }
446        }
447}
448
449
450void
451X3dParseHandlers::startElement(const XMLCh* const name,
452                                                           AttributeList&  attributes)
453{
454  StrX lname(name);
455  string element(lname.LocalForm());
456 
457  if (element == "IndexedFaceSet") {
458    // create a new mesh node in the scene graph
459    StartIndexedFaceSet(attributes);
460  }
461 
462  if (element == "Shape") {
463    cout << "+";
464        mCurrentMesh = new Mesh;
465  }
466 
467  if (element == "Coordinate")
468  {
469    if (mCurrentMesh)
470      StartCoordinate(attributes);
471  }
472 
473  if (element == "Material") {
474    StartMaterial(attributes);
475  }
476 
477  if (element == "Transform") {
478          StartTransform(attributes);
479  }
480
481  mElementCount++;
482  mAttrCount += attributes.getLength();
483}
484
485void
486X3dParseHandlers::characters(const XMLCh* const chars,
487                             const unsigned int length)
488{
489  mCharacterCount += length;
490}
491
492void
493X3dParseHandlers::ignorableWhitespace(const XMLCh* const chars,
494                                      const unsigned int length)
495{
496  mSpaceCount += length;
497}
498
499void
500X3dParseHandlers::resetDocument()
501{
502  mAttrCount = 0;
503  mCharacterCount = 0;
504  mElementCount = 0;
505  mSpaceCount = 0;
506}
507
508
509
510// ---------------------------------------------------------------------------
511//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
512// ---------------------------------------------------------------------------
513void
514X3dParseHandlers::error(const SAXParseException& e)
515{
516  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
517                            << ", line " << e.getLineNumber()
518                            << ", char " << e.getColumnNumber()
519                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
520}
521
522void
523X3dParseHandlers::fatalError(const SAXParseException& e)
524{
525  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
526                            << ", line " << e.getLineNumber()
527                            << ", char " << e.getColumnNumber()
528                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
529}
530
531void
532X3dParseHandlers::warning(const SAXParseException& e)
533{
534  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
535                            << ", line " << e.getLineNumber()
536                            << ", char " << e.getColumnNumber()
537                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
538}
539
540/*************************************************************************/
541/*                     X3dParser implementation                          */
542/*******************+*****************************************************/
543
544X3dParser::X3dParser():
545mViewCellHeight(DEFAULT_VIEWCELL_HEIGHT)
546{}
547
548bool
549X3dParser::ParseFile(const string filename,
550                                         SceneGraphNode **root,
551                                         const bool loadPolygonsAsMeshes)
552{
553  // Initialize the XML4C system
554  try {
555    XMLPlatformUtils::Initialize();
556  }
557 
558  catch (const XMLException& toCatch)
559    {
560      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
561                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
562      return false;
563    }
564 
565 
566  //
567  //  Create a SAX parser object. Then, according to what we were told on
568  //  the command line, set the options.
569  //
570  SAXParser* parser = new SAXParser;
571  parser->setValidationScheme(valScheme);
572  parser->setDoNamespaces(doNamespaces);
573  parser->setDoSchema(doSchema);
574  parser->setValidationSchemaFullChecking(schemaFullChecking);
575 
576
577  //
578  //  Create our SAX handler object and install it on the parser, as the
579  //  document and error handler. We are responsible for cleaning them
580  //  up, but since its just stack based here, there's nothing special
581  //  to do.
582  //
583  *root = new SceneGraphNode;
584  X3dParseHandlers handler(*root, loadPolygonsAsMeshes);
585  parser->setDocumentHandler(&handler);
586  parser->setErrorHandler(&handler);
587 
588  unsigned long duration;
589  int errorCount = 0;
590  // create a faux scope so that 'src' destructor is called before
591  // XMLPlatformUtils::Terminate
592  {
593    //
594    //  Kick off the parse and catch any exceptions. Create a standard
595    //  input input source and tell the parser to parse from that.
596    //
597    //    StdInInputSource src;
598    try
599      {
600        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
601        parser->parse(filename.c_str());
602        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
603        duration = endMillis - startMillis;
604        errorCount = parser->getErrorCount();
605      }
606    catch (const OutOfMemoryException&)
607      {
608        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
609        errorCount = 2;
610        return false;
611      }
612    catch (const XMLException& e)
613      {
614        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
615                                  << StrX(e.getMessage())
616                                  << "\n" << XERCES_STD_QUALIFIER endl;
617        errorCount = 1;
618        return false;
619      }
620
621   
622    // Print out the stats that we collected and time taken
623    if (!errorCount) {
624      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
625                                << handler.GetElementCount() << " elems, "
626                                << handler.GetAttrCount() << " attrs, "
627                                << handler.GetSpaceCount() << " spaces, "
628                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
629    }
630  }
631 
632  //
633  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
634  //
635  delete parser;
636 
637  XMLPlatformUtils::Terminate();
638 
639  if (errorCount > 0)
640    return false;
641  else
642    return true;
643}
644
645
646
647/************************************************************************/
648/*             class X3dViewCellsParseHandlers implementation           */
649/************************************************************************/
650
651
652// ---------------------------------------------------------------------------
653//  StdInParseHandlers: Constructors and Destructor
654// ---------------------------------------------------------------------------
655X3dViewCellsParseHandlers::X3dViewCellsParseHandlers(ViewCellsManager *viewCellsManager,
656                                                                                                         const float viewCellHeight):
657mElementCount(0),
658mAttrCount(0),
659mCharacterCount(0),
660mSpaceCount(0),
661mViewCellsManager(viewCellsManager),
662mViewCellHeight(viewCellHeight)
663{
664}
665
666X3dViewCellsParseHandlers::~X3dViewCellsParseHandlers()
667{
668}
669
670
671// ---------------------------------------------------------------------------
672//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
673// ---------------------------------------------------------------------------
674void X3dViewCellsParseHandlers::endElement(const XMLCh* const name)
675{
676  StrX lname(name);
677  string element(lname.LocalForm());
678 
679  if (element == "Shape")
680    EndShape();
681}
682
683void
684X3dViewCellsParseHandlers::EndShape()
685{
686        // currently processing no shape
687}
688
689void
690X3dViewCellsParseHandlers::StartIndexedFaceSet(
691                                      AttributeList&  attributes)
692{
693        int len = attributes.getLength();
694        int i;
695       
696        // clear previous vertex indices
697        mCurrentVertexIndices.clear();
698
699
700        for (i=0; i < len; i++)
701        {
702                string attrName(StrX(attributes.getName(i)).LocalForm());
703           
704
705                if (attrName == "coordIndex")
706                {
707                        StrX attrValue(attributes.getValue(i));
708                       
709                        // handle coordIndex
710                        const char *ptr = attrValue.LocalForm();
711                        char *endptr;
712               
713                        while (1)
714                        {
715                                int index = strtol(ptr, &endptr, 10);
716                               
717                                if (ptr == endptr)
718                                        break;
719
720                                if (index != -1)
721                                {
722                                        mCurrentVertexIndices.push_back(index);
723                                }
724                   
725                                ptr = endptr;
726                        }
727                }
728        }
729}
730
731
732void
733X3dViewCellsParseHandlers::StartCoordinate(AttributeList&  attributes)
734{
735        int len = attributes.getLength();
736       
737        VertexContainer vertices;
738        int i;
739        for (i=0; i < len; i++)
740        {
741                string attrName(StrX(attributes.getName(i)).LocalForm());
742               
743                if (attrName == "point")
744                {
745                        StrX attrValue(attributes.getValue(i));
746                       
747                        const char *ptr = attrValue.LocalForm();
748                       
749                        char *endptr;
750                       
751                        while (1)
752                        {
753                                float x = (float)strtod(ptr, &endptr);
754               
755                                if (ptr == endptr)
756                                        break;
757                                ptr = endptr;
758                               
759                                float y = (float)(float)strtod(ptr, &endptr);
760
761                               
762                                if (ptr == endptr)
763                                        break;
764                                ptr = endptr;
765
766                                float z = (float)(float)strtod(ptr, &endptr);
767
768                                if (ptr == endptr)
769                                        break;
770
771                                ptr = endptr;
772                                if (*ptr == ',')
773                                        ptr++;
774
775                                Vector3 v(x, y, z);
776                                vertices.push_back(v);                         
777                        }
778                }
779        }
780
781        for (i = 0; i < mCurrentVertexIndices.size(); i += 3)
782        {
783                Triangle3 baseTri(vertices[mCurrentVertexIndices[i + 0]],
784                                                  vertices[mCurrentVertexIndices[i + 1]],
785                                                  vertices[mCurrentVertexIndices[i + 2]]);
786
787                // create view cell from base triangle
788                mViewCellsManager->AddViewCell(
789                        mViewCellsManager->ExtrudeViewCell(baseTri,
790                        mViewCellHeight));
791        }
792}
793
794
795void
796X3dViewCellsParseHandlers::startElement(const XMLCh* const name,
797                                                                                AttributeList&  attributes)
798{
799  StrX lname(name);
800  string element(lname.LocalForm());
801 
802  if (element == "IndexedFaceSet") {
803    // create the viewcells from individual triangles
804    StartIndexedFaceSet(attributes);
805  }
806       
807  if (element == "Coordinate") {
808          // add coordinates to the triangles
809      StartCoordinate(attributes);
810  }
811  // do nothing
812  //if (element == "Shape") {}
813  // ignore material
814  //if (element == "Material") {}
815
816  ++ mElementCount;
817  mAttrCount += attributes.getLength();
818}
819
820void
821X3dViewCellsParseHandlers::characters(const XMLCh* const chars,
822                             const unsigned int length)
823{
824  mCharacterCount += length;
825}
826
827void
828X3dViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
829                                      const unsigned int length)
830{
831  mSpaceCount += length;
832}
833
834void
835X3dViewCellsParseHandlers::resetDocument()
836{
837  mAttrCount = 0;
838  mCharacterCount = 0;
839  mElementCount = 0;
840  mSpaceCount = 0;
841}
842
843
844
845// ---------------------------------------------------------------------------
846//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
847// ---------------------------------------------------------------------------
848void
849X3dViewCellsParseHandlers::error(const SAXParseException& e)
850{
851  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
852                            << ", line " << e.getLineNumber()
853                            << ", char " << e.getColumnNumber()
854                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
855}
856
857void
858X3dViewCellsParseHandlers::fatalError(const SAXParseException& e)
859{
860  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
861                            << ", line " << e.getLineNumber()
862                            << ", char " << e.getColumnNumber()
863                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
864}
865
866void
867X3dViewCellsParseHandlers::warning(const SAXParseException& e)
868{
869  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
870                            << ", line " << e.getLineNumber()
871                            << ", char " << e.getColumnNumber()
872                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
873}
874
875
876bool
877X3dParser::ParseFile(const string filename, ViewCellsManager &viewCells)
878{
879  // Initialize the XML4C system
880  try {
881    XMLPlatformUtils::Initialize();
882  }
883 
884  catch (const XMLException& toCatch)
885    {
886      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
887                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
888      return false;
889    }
890 
891 
892  //
893  //  Create a SAX parser object. Then, according to what we were told on
894  //  the command line, set the options.
895  //
896  SAXParser* parser = new SAXParser;
897  parser->setValidationScheme(valScheme);
898  parser->setDoNamespaces(doNamespaces);
899  parser->setDoSchema(doSchema);
900  parser->setValidationSchemaFullChecking(schemaFullChecking);
901 
902
903  //
904  //  Create our SAX handler object and install it on the parser, as the
905  //  document and error handler. We are responsible for cleaning them
906  //  up, but since its just stack based here, there's nothing special
907  //  to do.
908  //
909  X3dViewCellsParseHandlers handler(&viewCells, mViewCellHeight);
910  parser->setDocumentHandler(&handler);
911  parser->setErrorHandler(&handler);
912 
913  unsigned long duration;
914  int errorCount = 0;
915  // create a faux scope so that 'src' destructor is called before
916  // XMLPlatformUtils::Terminate
917  {
918    //
919    //  Kick off the parse and catch any exceptions. Create a standard
920    //  input input source and tell the parser to parse from that.
921    //
922    //    StdInInputSource src;
923    try
924      {
925        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
926        //GzBinFileInputStream str(filename.c_str());
927       
928        parser->parse(filename.c_str());
929        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
930        duration = endMillis - startMillis;
931        errorCount = parser->getErrorCount();
932      }
933    catch (const OutOfMemoryException&)
934      {
935        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
936        errorCount = 2;
937        return false;
938      }
939    catch (const XMLException& e)
940      {
941        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
942                                  << StrX(e.getMessage())
943                                  << "\n" << XERCES_STD_QUALIFIER endl;
944        errorCount = 1;
945        return false;
946      }
947
948   
949    // Print out the stats that we collected and time taken
950    if (!errorCount) {
951      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
952                                << handler.GetElementCount() << " elems, "
953                                << handler.GetAttrCount() << " attrs, "
954                                << handler.GetSpaceCount() << " spaces, "
955                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
956    }
957  }
958 
959  //
960  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
961  //
962  delete parser;
963 
964  XMLPlatformUtils::Terminate();
965 
966  if (errorCount > 0)
967    return false;
968  else
969    return true;
970}
971
972
973
974
975}
Note: See TracBrowser for help on using the repository browser.