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

Revision 752, 24.6 KB checked in by mattausch, 18 years ago (diff)

after rendering workshop submissioin
x3dparser can use def - use constructs
implemented improved evaluation (samples are only stored in leaves, only propagate pvs size)

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