source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp @ 863

Revision 863, 17.8 KB checked in by mattausch, 18 years ago (diff)

working on preprocessor integration
added iv stuff

Line 
1// ---------------------------------------------------------------------------
2//  Includes for all the program files to see
3// ---------------------------------------------------------------------------
4#include <string.h>
5#include <stdlib.h>
6#include <iostream>
7using namespace std;
8#include <xercesc/util/PlatformUtils.hpp>
9
10// ---------------------------------------------------------------------------
11//  Includes
12// ---------------------------------------------------------------------------
13#include <xercesc/framework/StdInInputSource.hpp>
14#include <xercesc/parsers/SAXParser.hpp>
15#include <xercesc/util/OutOfMemoryException.hpp>
16
17// ---------------------------------------------------------------------------
18//  Includes
19// ---------------------------------------------------------------------------
20#include <xercesc/sax/AttributeList.hpp>
21#include <xercesc/sax/SAXParseException.hpp>
22#include <xercesc/sax/SAXException.hpp>
23
24#include "ViewCellsParser.h"
25
26#include "ViewCellsParserXerces.h"
27#include "Mesh.h"
28#include "VspBspTree.h"
29#include "ViewCellBsp.h"
30#include "VspKdTree.h"
31#include "ViewCellsManager.h"
32
33namespace GtpVisibilityPreprocessor {
34
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
61
62
63
64// ---------------------------------------------------------------------------
65//  StdInParseHandlers: Constructors and Destructor
66// ---------------------------------------------------------------------------
67ViewCellsParseHandlers::ViewCellsParseHandlers(ObjectContainer *objects):
68  mElementCount(0)
69  , mAttrCount(0)
70  , mCharacterCount(0)
71  , mSpaceCount(0)
72  , mViewCellsManager(NULL)
73  , mVspBspTree(NULL)
74  , mBspTree(NULL)
75  , mViewCellsTree(NULL)
76  , mParseViewCells(true)
77  , mCurrentViewCell(NULL)
78  , mCurrentBspNode(NULL)
79{
80        mObjects = objects;
81}
82
83
84ViewCellsParseHandlers::~ViewCellsParseHandlers()
85{
86}
87
88
89// ---------------------------------------------------------------------------
90//  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
91// ---------------------------------------------------------------------------
92
93
94void ViewCellsParseHandlers::endElement(const XMLCh* const name)
95{
96  StrX lname(name);
97  string element(lname.LocalForm());
98
99  if (element == "ViewCells")
100          EndViewCells();
101
102  if (mParseViewCells)
103  {
104          if (element == "Interior")
105                  EndViewCellInterior();
106  }
107  else
108  {
109        if (element == "Interior")
110                  EndBspInterior();
111  }
112}
113
114
115void ViewCellsParseHandlers::EndBspInterior()
116{
117        // go one up in the tree
118        if (mCurrentBspNode->GetParent())
119        {       cout << "]";
120                mCurrentBspNode = mCurrentBspNode->GetParent();
121        }
122}
123
124
125void ViewCellsParseHandlers::EndViewCellInterior()
126{
127        // go one up in the tree
128        if (mCurrentViewCell->GetParent())
129        {       cout << "]";
130                mCurrentViewCell = mCurrentViewCell->GetParent();
131        }
132}
133
134inline static bool vlt(ViewCell *v1, ViewCell *v2)
135{
136        return v1->mId < v2->mId;
137}
138
139
140void ViewCellsParseHandlers::EndViewCells()
141{
142        // sort view cells to help associating view cells according to their id
143        stable_sort(mViewCells.begin(), mViewCells.end(), vlt);
144}
145
146
147
148void ViewCellsParseHandlers::StartHierarchy(AttributeList&  attributes)
149{
150        int len = attributes.getLength();
151 
152        for (int i = 0; i < len; ++ i)
153        {
154                string attrName(StrX(attributes.getName(i)).LocalForm());
155               
156                if (attrName == "name")
157                {
158                        StrX attrValue(attributes.getValue(i));
159                       
160                        const char *ptr = attrValue.LocalForm();
161                       
162                        CreateViewCellsManager(ptr);
163                }
164        }
165}
166
167
168void ViewCellsParseHandlers::startBspElement(string element,
169                                                                                         AttributeList& attributes)
170{
171        if (element == "Interior")
172        {
173                cout << "[";
174                StartBspInterior(attributes);
175        }
176
177        if (element == "Leaf")
178        {
179                cout << "l";
180                Debug << "leaf" << endl;
181                StartBspLeaf(attributes);
182        }
183}
184
185
186void ViewCellsParseHandlers::startElement(const XMLCh* const name,
187                                                                                  AttributeList& attributes)
188{
189        StrX lname(name);
190        string element(lname.LocalForm());
191
192        // decides the used view cell hierarchy
193        if (element == "ViewCells")
194        {
195                cout << "parsing view cells" << endl;
196                mParseViewCells = true;
197        }
198
199        if (element == "Hierarchy")
200        {
201                cout << "parsing spatial hierarchy" << endl;
202                mParseViewCells = false;
203                StartHierarchy(attributes);
204        }
205       
206        // decides the used view cell hierarchy
207        if (element == "ViewSpaceBox")
208        {
209                cout << "b";
210                StartViewSpaceBox(attributes);
211        }
212
213
214        // use different methods for the given view cell hierarchy types
215        if (!mParseViewCells)
216        {
217                if (mViewCellsManager)
218                {
219                        switch (mViewCellsManager->GetType())
220                        {
221                        case ViewCellsManager::BSP:
222                        case ViewCellsManager::VSP_BSP:
223                                startBspElement(element, attributes);
224                                break;
225       
226                        default:
227                                Debug << "not implemented" << endl;
228                                break;
229                        }
230                }
231        }
232        else
233        {
234                if (element == "Interior")
235                {
236                        cout << "[";
237                        StartViewCellInterior(attributes);
238                }
239
240                if (element == "Leaf")
241                {
242                        cout << "l";
243                        StartViewCellLeaf(attributes);
244                }
245        }
246
247        ++ mElementCount;
248        mAttrCount += attributes.getLength();
249}
250
251
252inline bool ilt(Intersectable *obj1, Intersectable *obj2)
253{
254        return obj1->mId < obj2->mId;
255}
256
257
258void ViewCellsParseHandlers::StartViewCell(ViewCell *viewCell, AttributeList&  attributes)
259{
260        int len = attributes.getLength();
261        vector<int> objIndices;
262
263        for (int i = 0; i < len; ++ i)
264        {
265                string attrName(StrX(attributes.getName(i)).LocalForm());
266               
267                if (attrName == "pvs")
268                {
269                        StrX attrValue(attributes.getValue(i));
270                       
271                        // handle coordIndex
272                        objIndices.clear();
273                        const char *ptr = attrValue.LocalForm();
274                        char *endptr;
275                       
276                        while (1)
277                        {
278                                int index = strtol(ptr, &endptr, 10);
279
280                                if (ptr == endptr)
281                                        break;
282
283                                objIndices.push_back(index);
284
285                                ptr = endptr;
286                        }
287
288                        //TODO: find objects and add them to pvs
289                        // TODO: get view cell with specified id
290                        MeshInstance dummyInst(NULL);
291
292                        vector<int>::const_iterator it, it_end = objIndices.end();
293                        for (it = objIndices.begin(); it != it_end; ++ it)
294                        {
295                                const int objId = *it; 
296                                dummyInst.SetId(objId);
297
298                                ObjectContainer::iterator oit =
299                                  lower_bound(mObjects->begin(), mObjects->end(), (Intersectable *)&dummyInst, ilt);
300                               
301                                Intersectable *obj = *oit;
302                               
303                                if (obj->GetId() == objId)
304                                {
305                                  // $$JB we should store a float a per object which corresponds
306                                  // to sumof pdfs, i.e. its relative visibility
307                                  // temporarily set to 1.0f
308                                        viewCell->GetPvs().AddSample(obj, 1.0f);
309                                }
310                                else
311                                {
312                                        Debug << "error: object does not exist" << endl;
313                                }
314                        }
315                }
316                else if (attrName == "id")
317                {
318                        StrX attrValue(attributes.getValue(i));
319                       
320                        const char *ptr = attrValue.LocalForm();
321                        char *endptr = NULL;
322                        const int id = strtol(ptr, &endptr, 10);
323
324                        viewCell->SetId(id);
325                }
326                else if (attrName == "active")
327                {
328                        StrX attrValue(attributes.getValue(i));
329                       
330                        const char *ptr = attrValue.LocalForm();
331                        char *endptr = NULL;
332                        const bool isActive = (bool)strtol(ptr, &endptr, 10);
333
334                        if (isActive)
335                                viewCell->SetActive();
336                }
337                else if (attrName == "mergecost")
338                {
339                        StrX attrValue(attributes.getValue(i));
340                       
341                        const char *ptr = attrValue.LocalForm();
342                        char *endptr = NULL;
343                        const float cost = (float)strtod(ptr, &endptr);
344
345                        viewCell->SetMergeCost(cost);
346                }
347        }
348}
349
350
351void ViewCellsParseHandlers::StartViewSpaceBox(AttributeList& attributes)
352{
353        int len = attributes.getLength();
354
355        Vector3 bmin, bmax;
356
357        for (int i = 0; i < len; ++ i)
358        {
359                string attrName(StrX(attributes.getName(i)).LocalForm());
360                StrX attrValue(attributes.getValue(i));
361                const char *ptr = attrValue.LocalForm();
362
363                if (attrName == "min")
364                {
365                        sscanf(ptr, "%f %f %f",
366                                   &bmin.x, &bmin.y, &bmin.z);
367                }
368                else if (attrName == "max")
369                {
370                        sscanf(ptr, "%f %f %f",
371                                   &bmax.x, &bmax.y, &bmax.z);
372                }
373        }
374
375        mViewSpaceBox = AxisAlignedBox3(bmin, bmax);
376
377        Debug << "view space box: " << mViewSpaceBox << endl;
378}
379
380
381void ViewCellsParseHandlers::StartBspLeaf(AttributeList& attributes)
382{
383        BspLeaf * leaf =
384                new BspLeaf(dynamic_cast<BspInterior *>(mCurrentBspNode), NULL);
385
386        if (mCurrentBspNode) // replace front or (if not NULL) back child
387        {
388                dynamic_cast<BspInterior *>(mCurrentBspNode)->ReplaceChildLink(NULL, leaf);
389        }
390        else
391        {
392                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
393                {
394                        mBspTree->mRoot = leaf;
395                }
396                else if (mViewCellsManager->GetType() == ViewCellsManager::VSP_BSP)
397                {
398                        mVspBspTree->mRoot = leaf;
399                }
400        }
401
402        //-- find associated view cell
403        int viewCellId;
404       
405        int len = attributes.getLength();
406         
407        for (int i = 0; i < len; ++ i)
408        {
409                string attrName(StrX(attributes.getName(i)).LocalForm());
410                StrX attrValue(attributes.getValue(i));
411
412                const char *ptr = attrValue.LocalForm();
413                char *endptr = NULL;
414
415                if (attrName == "viewCellId")
416                {
417                        viewCellId = strtol(ptr, &endptr, 10);
418                }
419        }
420
421       
422        if (viewCellId >= 0) // valid view cell
423        {
424                // TODO: get view cell with specified id
425                ViewCellInterior dummyVc;
426                dummyVc.SetId(viewCellId);
427
428                ViewCellContainer::iterator vit =
429                        lower_bound(mViewCells.begin(), mViewCells.end(), &dummyVc, vlt);
430                       
431                BspViewCell *viewCell = dynamic_cast<BspViewCell *>(*vit);
432
433       
434                if (viewCell->GetId() == viewCellId)
435                {
436                        leaf->SetViewCell(viewCell);
437                        viewCell->mLeaf = leaf;
438                }
439                else
440                {
441                        Debug << "error: view cell does not exist" << endl;
442                }
443        }
444        else
445        {
446                // add to invalid view space
447                if (mViewCellsManager->GetType() == ViewCellsManager::VSP_BSP)
448                {
449                        leaf->SetViewCell(mVspBspTree->GetOrCreateOutOfBoundsCell());
450                        leaf->SetTreeValid(false);
451                        mVspBspTree->PropagateUpValidity(leaf);
452                }
453        }
454}
455
456
457void ViewCellsParseHandlers::StartBspInterior(AttributeList& attributes)
458{
459        Plane3 plane;
460        int len = attributes.getLength();
461
462        for (int i = 0; i < len; ++ i)
463        {
464                string attrName(StrX(attributes.getName(i)).LocalForm());
465                StrX attrValue(attributes.getValue(i));
466                const char *ptr = attrValue.LocalForm();
467
468                if (attrName == "plane")
469                {
470                        sscanf(ptr, "%f %f %f %f",
471                                   &plane.mNormal.x, &plane.mNormal.y, &plane.mNormal.z, &plane.mD);
472                }
473        }
474
475        BspInterior* interior = new BspInterior(plane);
476       
477        if (mCurrentBspNode) // replace NULL child of parent with current node
478        {
479                BspInterior *current = dynamic_cast<BspInterior *>(mCurrentBspNode);
480
481                current->ReplaceChildLink(NULL, interior);
482                interior->SetParent(current);
483        }
484        else
485        {
486                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
487                {
488                        mBspTree->mRoot = interior;
489                }
490                else
491                {
492                        mVspBspTree->mRoot = interior;
493                }
494        }
495
496        mCurrentBspNode = interior;
497}
498
499
500void ViewCellsParseHandlers::StartViewCellLeaf(AttributeList& attributes)
501{
502        BspViewCell *viewCell = new BspViewCell();
503
504        if (mCurrentViewCell) // replace front or (if not NULL) back child
505        {
506                ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(mCurrentViewCell);
507                interior->SetupChildLink(viewCell);
508        }
509        else // root
510        {
511                mViewCellsTree->SetRoot(viewCell);
512        }
513
514        StartViewCell(viewCell, attributes);
515
516        // collect leaves
517        mViewCells.push_back(viewCell);
518}
519
520
521void ViewCellsParseHandlers::StartViewCellInterior(AttributeList& attributes)
522{
523        ViewCellInterior* interior = new ViewCellInterior();
524       
525        if (mCurrentViewCell) // replace NULL child of parent with current node
526        {
527                ViewCellInterior *current = dynamic_cast<ViewCellInterior *>(mCurrentViewCell);
528
529                current->SetupChildLink(interior);
530        }
531        else
532        {
533                mViewCellsTree->SetRoot(interior);
534        }
535
536        mCurrentViewCell = interior;
537
538        StartViewCell(interior, attributes);
539}
540
541
542
543void ViewCellsParseHandlers::CreateViewCellsManager(const char *name)
544{
545        if (strcmp(name, "bspTree") == 0)
546        {
547                Debug << "view cell type: Bsp" << endl;
548
549                mBspTree = new BspTree();
550                mBspTree->mBox = mViewSpaceBox;
551                //mCurrentBspNode = mBspTree->GetRoot();
552
553                mViewCellsManager = new BspViewCellsManager(mBspTree);
554        }
555        else if (strcmp(name, "vspBspTree") == 0)
556        {
557                Debug << "view cell type: VspBsp" << endl;
558
559                mVspBspTree = new VspBspTree();
560                //mCurrentBspNode = mVspBspTree->GetRoot();
561
562                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree);
563
564                mVspBspTree->mBox = mViewSpaceBox;
565                Debug << "creating vsp bsp view cells manager" << endl;
566        }
567        else if (strcmp(name, "vspKdTree") == 0)
568        {
569                // TODO
570                mVspKdTree = new VspKdTree();   
571                mViewCellsManager = new VspKdViewCellsManager(mVspKdTree);
572        }
573        else
574        {
575                cerr<<"Wrong view cells type " << name << "!!!" << endl;
576                exit(1);
577        }
578
579        mViewCellsTree = mViewCellsManager->GetViewCellsTree();
580        mViewCellsManager->SetViewSpaceBox(mViewSpaceBox);
581}
582
583
584void ViewCellsParseHandlers::characters(const XMLCh* const chars,
585                                                                                const unsigned int length)
586{
587        mCharacterCount += length;
588}
589
590
591void ViewCellsParseHandlers::ignorableWhitespace(const XMLCh* const chars,
592                                                                                                 const unsigned int length)
593{
594        mSpaceCount += length;
595}
596
597
598void ViewCellsParseHandlers::resetDocument()
599{
600        mAttrCount = 0;
601        mCharacterCount = 0;
602        mElementCount = 0;
603        mSpaceCount = 0;
604}
605
606
607// ---------------------------------------------------------------------------
608//  StdInParseHandlers: Overrides of the SAX ErrorHandler interface
609// ---------------------------------------------------------------------------
610void
611ViewCellsParseHandlers::error(const SAXParseException& e)
612{
613  XERCES_STD_QUALIFIER cerr << "\nError at (file " << StrX(e.getSystemId())
614                            << ", line " << e.getLineNumber()
615                            << ", char " << e.getColumnNumber()
616                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
617}
618
619void
620ViewCellsParseHandlers::fatalError(const SAXParseException& e)
621{
622  XERCES_STD_QUALIFIER cerr << "\nFatal Error at (file " << StrX(e.getSystemId())
623                            << ", line " << e.getLineNumber()
624                            << ", char " << e.getColumnNumber()
625                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
626}
627
628void
629ViewCellsParseHandlers::warning(const SAXParseException& e)
630{
631  XERCES_STD_QUALIFIER cerr << "\nWarning at (file " << StrX(e.getSystemId())
632                            << ", line " << e.getLineNumber()
633                            << ", char " << e.getColumnNumber()
634                            << "): " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
635}
636
637
638bool ViewCellsParser::ParseFile(const string filename,
639                                                                ViewCellsManager **viewCells,
640                                                                ObjectContainer *objects)
641{
642  // Initialize the XML4C system
643  try {
644    XMLPlatformUtils::Initialize();
645  }
646 
647  catch (const XMLException& toCatch)
648    {
649      XERCES_STD_QUALIFIER cerr << "Error during initialization! Message:\n"
650                                << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
651      return false;
652    }
653 
654 
655  //
656  //  Create a SAX parser object. Then, according to what we were told on
657  //  the command line, set the options.
658  //
659  SAXParser* parser = new SAXParser;
660  parser->setValidationScheme(valScheme);
661  parser->setDoNamespaces(doNamespaces);
662  parser->setDoSchema(doSchema);
663  parser->setValidationSchemaFullChecking(schemaFullChecking);
664 
665
666  //
667  //  Create our SAX handler object and install it on the parser, as the
668  //  document and error handler. We are responsible for cleaning them
669  //  up, but since its just stack based here, there's nothing special
670  //  to do.
671  //
672  ViewCellsParseHandlers handler(objects);
673  parser->setDocumentHandler(&handler);
674  parser->setErrorHandler(&handler);
675 
676  unsigned long duration;
677  int errorCount = 0;
678  // create a faux scope so that 'src' destructor is called before
679  // XMLPlatformUtils::Terminate
680  {
681    //
682    //  Kick off the parse and catch any exceptions. Create a standard
683    //  input input source and tell the parser to parse from that.
684    //
685    //    StdInInputSource src;
686    try
687      {
688        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
689        parser->parse(filename.c_str());
690        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
691        duration = endMillis - startMillis;
692        errorCount = parser->getErrorCount();
693      }
694    catch (const OutOfMemoryException&)
695      {
696        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
697        errorCount = 2;
698        return false;
699      }
700    catch (const XMLException& e)
701      {
702        XERCES_STD_QUALIFIER cerr << "\nError during parsing: \n"
703                                  << StrX(e.getMessage())
704                                  << "\n" << XERCES_STD_QUALIFIER endl;
705        errorCount = 1;
706        return false;
707      }
708
709   
710    // Print out the stats that we collected and time taken
711    if (!errorCount) {
712      XERCES_STD_QUALIFIER cout << filename << ": " << duration << " ms ("
713                                << handler.GetElementCount() << " elems, "
714                                << handler.GetAttrCount() << " attrs, "
715                                << handler.GetSpaceCount() << " spaces, "
716                                << handler.GetCharacterCount() << " chars)" << XERCES_STD_QUALIFIER endl;
717    }
718  }
719 
720  //
721  //  Delete the parser itself.  Must be done prior to calling Terminate, below.
722  //
723  delete parser;
724 
725  XMLPlatformUtils::Terminate();
726 
727   // assign new view cells manager
728  *viewCells = handler.mViewCellsManager;
729 
730  if (errorCount > 0)
731    return false;
732  else
733    return true;
734}
735
736}
Note: See TracBrowser for help on using the repository browser.