source: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsParser.cpp @ 580

Revision 580, 15.3 KB checked in by mattausch, 18 years ago (diff)

implemented variance
started implementing merge history

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