diff --git a/JPSvis.pro b/JPSvis.pro index 6e1453b8d8d8b0f69961acafe6f948fb55368710..f9a4f320ee98d9162818a5c105c2b88e74990fa6 100644 --- a/JPSvis.pro +++ b/JPSvis.pro @@ -11,6 +11,8 @@ QT += xml network #QMAKE_CXXFLAGS += -static #QMAKE_LFLAGS_RELEASE += -static-libgcc +QMAKE_CXXFLAGS += -Wno-deprecated -Wno-unused-parameter -Wno-unused-variable + greaterThan(QT_MAJOR_VERSION, 4):QT += widgets #Dynamic linking diff --git a/forms/Settings.cpp b/forms/Settings.cpp index fdadc40816ba3c51ee53b8e9e2133b8714b90282..d945e7c1dfda62d1b6c02dfb42fed6a08d935124 100644 --- a/forms/Settings.cpp +++ b/forms/Settings.cpp @@ -32,6 +32,7 @@ #include <iostream> #include <QFileDialog> #include <QMessageBox> +#include <QCloseEvent> #include <QColorDialog> #include "Settings.h" @@ -42,19 +43,19 @@ using namespace std; QColor Settings::tmpCaptionColor=QColor(); Settings::Settings(QWidget *parent) -: QWidget(parent) + : QWidget(parent) { - ui.setupUi(this); + ui.setupUi(this); - // initialize the output directory - QString dir; - SystemSettings::getOutputDirectory(dir); - ui.LEditOutputDir->setText(dir); + // initialize the output directory + QString dir; + SystemSettings::getOutputDirectory(dir); + ui.LEditOutputDir->setText(dir); - //restore the caption color parameter - char bgcolor[50]; - sprintf(bgcolor,"background-color: rgb(%d, %d, %d);",tmpCaptionColor.red(),tmpCaptionColor.green(),tmpCaptionColor.blue()); - ui.frameCaptionColorPreview->setStyleSheet(bgcolor); + //restore the caption color parameter + char bgcolor[50]; + sprintf(bgcolor,"background-color: rgb(%d, %d, %d);",tmpCaptionColor.red(),tmpCaptionColor.green(),tmpCaptionColor.blue()); + ui.frameCaptionColorPreview->setStyleSheet(bgcolor); } @@ -65,207 +66,220 @@ Settings::~Settings() void Settings::slotChangePedestrianShape() { - int resolution=ui.CbEllipseResolution->currentText().toInt(); - SystemSettings::setEllipseResolution(resolution); - extern_force_system_update=true; + int resolution=ui.CbEllipseResolution->currentText().toInt(); + SystemSettings::setEllipseResolution(resolution); + extern_force_system_update=true; } -void Settings::slotUpdateTrailSettings(){ +void Settings::slotUpdateTrailSettings() +{ - bool ok=false; - int count=ui.CbTrailPointsCount->currentText().toInt(&ok); - if(ok==false){ - //FIXME: + bool ok=false; + int count=ui.CbTrailPointsCount->currentText().toInt(&ok); + if(ok==false) { + //FIXME: // ui.CbTrailPointsCount->removeItem(ui.CbEllipseRadiusA->currentIndex()); - return; - } - int type=ui.CbTrailType->currentIndex(); - int form=ui.CbTrailGeometry->currentIndex(); - - if(form==1) - ui.CbTrailPolygoneWidth->setEnabled(true); - else - ui.CbTrailPolygoneWidth->setEnabled(false); - SystemSettings::setTrailsInfo(count,type,form); + return; + } + int type=ui.CbTrailType->currentIndex(); + int form=ui.CbTrailGeometry->currentIndex(); + + if(form==1) + ui.CbTrailPolygoneWidth->setEnabled(true); + else + ui.CbTrailPolygoneWidth->setEnabled(false); + SystemSettings::setTrailsInfo(count,type,form); } /// @todo use the QColorDialog instead /// @todo make the whole thing live by connecting signal -void Settings::slotPickPedestrianColor(){ +void Settings::slotPickPedestrianColor() +{ - QColorDialog* colorDialog = new QColorDialog(this); - QColor col=colorDialog->getColor("choose the new pedestrian color"); + QColorDialog* colorDialog = new QColorDialog(this); + QColor col=colorDialog->getColor("choose the new pedestrian color"); - // the user may have cancelled the process - if(col.isValid()==false) return; - slotChangePedestrianColor(col); + // the user may have cancelled the process + if(col.isValid()==false) return; + slotChangePedestrianColor(col); - delete colorDialog; + delete colorDialog; } -void Settings::slotChangePedestrianColor(const QColor & color){ - int r=0.0,g=0.0,b=0.0; - color.getRgb(&r,&g,&b); - int bkcolor[3]={r ,g,b}; +void Settings::slotChangePedestrianColor(const QColor & color) +{ + int r=0.0,g=0.0,b=0.0; + color.getRgb(&r,&g,&b); + int bkcolor[3]= {r ,g,b}; - SystemSettings::setPedestrianColor(ui.CbPedestrianGroup->currentIndex(),bkcolor); - extern_force_system_update=true; + SystemSettings::setPedestrianColor(ui.CbPedestrianGroup->currentIndex(),bkcolor); + extern_force_system_update=true; } -void Settings::slotChangeVerticesWidth(){ - bool ok=false; - - double width=ui.CbTrailPolygoneWidth->currentText().toDouble(&ok); - if(ok==false){ - //fixme: - //ui.CbEllipseRadiusA->removeItem(ui.CbTrailPolygoneWidth->currentIndex()); - return; - } - LinePlotter::setLineWidth((int)width); +void Settings::slotChangeVerticesWidth() +{ + bool ok=false; + + double width=ui.CbTrailPolygoneWidth->currentText().toDouble(&ok); + if(ok==false) { + //fixme: + //ui.CbEllipseRadiusA->removeItem(ui.CbTrailPolygoneWidth->currentIndex()); + return; + } + LinePlotter::setLineWidth((int)width); } /// choose a new directory -void Settings::slotChangeOutputDir(){ - - QString dir = QFileDialog::getExistingDirectory(this, tr("Select a Directory for saving your files (screenshots, video,...)"), - "", - QFileDialog::ShowDirsOnly - | QFileDialog::DontResolveSymlinks); - - // in the case the selection was aborted - if(!QFileInfo(dir).isWritable()) { - slotErrorOutput("I cant write to that directory"); - dir=""; - } - if(dir.isEmpty()){ - SystemSettings::getOutputDirectory(dir); - ui.LEditOutputDir->setText(dir); - }else{ - ui.LEditOutputDir->setText(dir); - SystemSettings::setOutputDirectory(dir); - } +void Settings::slotChangeOutputDir() +{ + + QString dir = QFileDialog::getExistingDirectory(this, tr("Select a Directory for saving your files (screenshots, video,...)"), + "", + QFileDialog::ShowDirsOnly + | QFileDialog::DontResolveSymlinks); + + // in the case the selection was aborted + if(!QFileInfo(dir).isWritable()) { + slotErrorOutput("I cant write to that directory"); + dir=""; + } + if(dir.isEmpty()) { + SystemSettings::getOutputDirectory(dir); + ui.LEditOutputDir->setText(dir); + } else { + ui.LEditOutputDir->setText(dir); + SystemSettings::setOutputDirectory(dir); + } } -void Settings::slotErrorOutput(QString err) { - QMessageBox msgBox; - msgBox.setText("Error"); - msgBox.setInformativeText(err); - msgBox.setStandardButtons(QMessageBox::Ok); - msgBox.setIcon(QMessageBox::Critical); - msgBox.exec(); +void Settings::slotErrorOutput(QString err) +{ + QMessageBox msgBox; + msgBox.setText("Error"); + msgBox.setInformativeText(err); + msgBox.setStandardButtons(QMessageBox::Ok); + msgBox.setIcon(QMessageBox::Critical); + msgBox.exec(); } -void Settings::slotChangePedestrianColorProfile(){ - - if(!ui.chBpedestrianDefaultColor->isChecked()){ - ui.CbPedestrianGroup->setEnabled(true); - ui.pushButtonChangePedestrianColor->setEnabled(true); - SystemSettings::setPedestrianColorProfileFromFile(false); - }else{ - ui.CbPedestrianGroup->setEnabled(false); - ui.pushButtonChangePedestrianColor->setEnabled(false); - SystemSettings::setPedestrianColorProfileFromFile(true); - } +void Settings::slotChangePedestrianColorProfile() +{ + + if(!ui.chBpedestrianDefaultColor->isChecked()) { + ui.CbPedestrianGroup->setEnabled(true); + ui.pushButtonChangePedestrianColor->setEnabled(true); + SystemSettings::setPedestrianColorProfileFromFile(false); + } else { + ui.CbPedestrianGroup->setEnabled(false); + ui.pushButtonChangePedestrianColor->setEnabled(false); + SystemSettings::setPedestrianColorProfileFromFile(true); + } } -void Settings::slotChangeCaptionSize(){ - bool ok=false; +void Settings::slotChangeCaptionSize() +{ + bool ok=false; - int size =ui.CbCaptionSize->currentText().toInt(&ok); - if( (ok==false)|| (size >=200)){ - ui.CbCaptionSize->removeItem(ui.CbCaptionSize->currentIndex()); - return; - } + int size =ui.CbCaptionSize->currentText().toInt(&ok); + if( (ok==false)|| (size >=200)) { + ui.CbCaptionSize->removeItem(ui.CbCaptionSize->currentIndex()); + return; + } - int orientation= ui.ComboCaptionOrientation->currentIndex(); - bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); + int orientation= ui.ComboCaptionOrientation->currentIndex(); + bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); - SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); + SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); - extern_force_system_update=true; + extern_force_system_update=true; } -void Settings::slotPickCaptionColor(){ +void Settings::slotPickCaptionColor() +{ - QColorDialog* colorDialog = new QColorDialog(this); + QColorDialog* colorDialog = new QColorDialog(this); - tmpCaptionColor=colorDialog->getColor(); + tmpCaptionColor=colorDialog->getColor(); - // the user may have cancelled the process - if(tmpCaptionColor.isValid()==false) return; + // the user may have cancelled the process + if(tmpCaptionColor.isValid()==false) return; - int size =ui.CbCaptionSize->currentText().toInt(); - int orientation= ui.ComboCaptionOrientation->currentText().toInt(); - bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); + int size =ui.CbCaptionSize->currentText().toInt(); + int orientation= ui.ComboCaptionOrientation->currentText().toInt(); + bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); - SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); + SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); - //update the color marker defined by a frame - char bgcolor[50]; - sprintf(bgcolor,"background-color: rgb(%d, %d, %d);",tmpCaptionColor.red(),tmpCaptionColor.green(),tmpCaptionColor.blue()); - ui.frameCaptionColorPreview->setStyleSheet(bgcolor); + //update the color marker defined by a frame + char bgcolor[50]; + sprintf(bgcolor,"background-color: rgb(%d, %d, %d);",tmpCaptionColor.red(),tmpCaptionColor.green(),tmpCaptionColor.blue()); + ui.frameCaptionColorPreview->setStyleSheet(bgcolor); - extern_force_system_update=true; + extern_force_system_update=true; - delete colorDialog; + delete colorDialog; } -void Settings::slotChangeCaptionOrientation(){ - int size =ui.CbCaptionSize->currentText().toInt(); - int orientation= ui.ComboCaptionOrientation->currentIndex(); - bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); +void Settings::slotChangeCaptionOrientation() +{ + int size =ui.CbCaptionSize->currentText().toInt(); + int orientation= ui.ComboCaptionOrientation->currentIndex(); + bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); - SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); - extern_force_system_update=true; + SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); + extern_force_system_update=true; } -void Settings::slotChangeCaptionAutoRotation(){ - int size =ui.CbCaptionSize->currentText().toInt(); - int orientation= ui.ComboCaptionOrientation->currentText().toInt(); - bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); +void Settings::slotChangeCaptionAutoRotation() +{ + int size =ui.CbCaptionSize->currentText().toInt(); + int orientation= ui.ComboCaptionOrientation->currentText().toInt(); + bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); - SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); - extern_force_system_update=true; + SystemSettings::setCaptionsParameters(size, tmpCaptionColor,orientation, automaticRotation); + extern_force_system_update=true; } -void Settings::slotChangeCaptionColorMode(){ +void Settings::slotChangeCaptionColorMode() +{ - if(ui.comboCaptionColorMode->currentText().compare("Auto")==0){ - int size =ui.CbCaptionSize->currentText().toInt(); - int orientation= ui.ComboCaptionOrientation->currentText().toInt(); - bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); + if(ui.comboCaptionColorMode->currentText().compare("Auto")==0) { + int size =ui.CbCaptionSize->currentText().toInt(); + int orientation= ui.ComboCaptionOrientation->currentText().toInt(); + bool automaticRotation=ui.checkBoxCaptionAutoRotate->isChecked(); - SystemSettings::setCaptionsParameters(size, QColor() ,orientation, automaticRotation); - extern_force_system_update=true; + SystemSettings::setCaptionsParameters(size, QColor() ,orientation, automaticRotation); + extern_force_system_update=true; - }else if(ui.comboCaptionColorMode->currentText().compare("Custom")==0){ - slotPickCaptionColor(); - } + } else if(ui.comboCaptionColorMode->currentText().compare("Custom")==0) { + slotPickCaptionColor(); + } } //ugly, I had no choice :) -void Settings::closeEvent(QCloseEvent* event){ - hide(); - ///@FIXME -// event->ignore(); +void Settings::closeEvent(QCloseEvent* event) +{ + hide(); + ///@FIXME + event->ignore(); } -void Settings::slotControlSequence(QString msg){ +void Settings::slotControlSequence(QString msg) +{ - if(msg.compare("CAPTION_AUTO")==0){ - ui.comboCaptionColorMode->setCurrentIndex(0); //should be auto - }else - if (msg.compare("CAPTION_CUSTOM")==0){ - ui.comboCaptionColorMode->setCurrentIndex(1); //should be custom - } - slotChangeCaptionColorMode(); + if(msg.compare("CAPTION_AUTO")==0) { + ui.comboCaptionColorMode->setCurrentIndex(0); //should be auto + } else if (msg.compare("CAPTION_CUSTOM")==0) { + ui.comboCaptionColorMode->setCurrentIndex(1); //should be custom + } + slotChangeCaptionColorMode(); } diff --git a/forms/Settings.h b/forms/Settings.h index f8825ca5755a27aa64eb4a8285a16cf9f77fbda7..2acf60396321a174055e9318ad626a2079970007 100644 --- a/forms/Settings.h +++ b/forms/Settings.h @@ -38,66 +38,65 @@ extern bool extern_force_system_update; -class Settings : public QWidget -{ - Q_OBJECT +class Settings : public QWidget { + Q_OBJECT public: - enum Shape {DEFAULT=1,ELLIPSE,PINGUINS}; - Settings(QWidget *parent = 0); - virtual ~Settings(); + enum Shape {DEFAULT=1,ELLIPSE,PINGUINS}; + Settings(QWidget *parent = 0); + virtual ~Settings(); - public Q_SLOTS: +public Q_SLOTS: - /// change the resolution of the ellipse representing the pedestrian - void slotChangePedestrianShape(); + /// change the resolution of the ellipse representing the pedestrian + void slotChangePedestrianShape(); - /// change the trails settings - void slotUpdateTrailSettings(); + /// change the trails settings + void slotUpdateTrailSettings(); - /// customize pedestrian color - void slotPickPedestrianColor(); + /// customize pedestrian color + void slotPickPedestrianColor(); - void slotChangePedestrianColor(const QColor& color); + void slotChangePedestrianColor(const QColor& color); - /// set the width of the lines defining the vertices - void slotChangeVerticesWidth(); + /// set the width of the lines defining the vertices + void slotChangeVerticesWidth(); - /// change the output directory - void slotChangeOutputDir(); + /// change the output directory + void slotChangeOutputDir(); - /// change the size of the pedestrian caption - /// The maximal size is limited to 200 - void slotChangeCaptionSize(); + /// change the size of the pedestrian caption + /// The maximal size is limited to 200 + void slotChangeCaptionSize(); - ///change the caption orientation - void slotChangeCaptionOrientation(); + ///change the caption orientation + void slotChangeCaptionOrientation(); - ///change the caption auto rotation policy - void slotChangeCaptionAutoRotation(); + ///change the caption auto rotation policy + void slotChangeCaptionAutoRotation(); - /// change pedestrian color profile - void slotChangePedestrianColorProfile(); + /// change pedestrian color profile + void slotChangePedestrianColorProfile(); - /// choose a new caption color - void slotPickCaptionColor(); + /// choose a new caption color + void slotPickCaptionColor(); - ///change the caption color mode, auto or custom - void slotChangeCaptionColorMode(); + ///change the caption color mode, auto or custom + void slotChangeCaptionColorMode(); - /// execute a control sequence - void slotControlSequence(QString msg); + /// execute a control sequence + void slotControlSequence(QString msg); protected: - virtual void closeEvent(QCloseEvent* event); + virtual void closeEvent(QCloseEvent* event); private: - void updateCaptionSetting(); - Ui::SettingsClass ui; - static QColor tmpCaptionColor; - void slotErrorOutput(QString err); + void updateCaptionSetting(); + Ui::SettingsClass ui; + static QColor tmpCaptionColor; + void slotErrorOutput(QString err); }; #endif // PEDESTRIANSHAPE_H diff --git a/src/Debug.cpp b/src/Debug.cpp index 5c49c7c68caf321158b46314a1cc0e376d4a2075..a1da19b309ffcfac63a4aab1c1df20a54c5c250d 100644 --- a/src/Debug.cpp +++ b/src/Debug.cpp @@ -47,95 +47,99 @@ int Debug::MSG_Count=0; int Debug::ERR_Count=0; int Debug::WAR_Count=0; -Debug::Debug() { +Debug::Debug() +{ } -Debug::~Debug() { +Debug::~Debug() +{ } -void Debug::setOutputStream(std::ostream &osl ){ - os.rdbuf(osl.rdbuf()); +void Debug::setOutputStream(std::ostream &osl ) +{ + os.rdbuf(osl.rdbuf()); } -void Debug::setDebugLevel(Debug::LEVEL level){ - debugLevel=level; +void Debug::setDebugLevel(Debug::LEVEL level) +{ + debugLevel=level; } -void Debug::Messages(const char *format, ...){ +void Debug::Messages(const char *format, ...) +{ - switch (debugLevel){ + switch (debugLevel) { - case ALL: - case INFO: - { - MSG_Count++; - char msg[256]; - va_list ap; - va_start (ap, format); - vsprintf (msg,format ,ap); - va_end (ap); + case ALL: + case INFO: { + MSG_Count++; + char msg[256]; + va_list ap; + va_start (ap, format); + vsprintf (msg,format ,ap); + va_end (ap); - os<<"Info["<<MSG_Count<<"]"<<msg<<endl; - } - break; + os<<"Info["<<MSG_Count<<"]"<<msg<<endl; + } + break; - case ERROR: - case WARNING: - case NONE: - break; - } + case ERROR: + case WARNING: + case NONE: + break; + } } -void Debug::Warning(const char *format, ...){ - - switch (debugLevel){ - - case WARNING: - case ALL: - { - WAR_Count++; - char msg[256]; - va_list ap; - va_start (ap, format); - vsprintf (msg,format ,ap); - va_end (ap); - os<<"Warning["<<WAR_Count<<"]"<<msg<<endl; - } - break; - - case ERROR: - case INFO: - case NONE: - break; - } +void Debug::Warning(const char *format, ...) +{ + + switch (debugLevel) { + + case WARNING: + case ALL: { + WAR_Count++; + char msg[256]; + va_list ap; + va_start (ap, format); + vsprintf (msg,format ,ap); + va_end (ap); + os<<"Warning["<<WAR_Count<<"]"<<msg<<endl; + } + break; + + case ERROR: + case INFO: + case NONE: + break; + } } -void Debug::Error(const char *format, ...){ - - switch (debugLevel){ - - case WARNING: - case ERROR : - case ALL: - { - ERR_Count++; - char msg[256]; - va_list ap; - va_start (ap, format); - vsprintf (msg,format ,ap); - va_end (ap); - os<<"Error["<<ERR_Count<<"]"<<msg<<endl; - } - break; - - case INFO: - case NONE: - break; - } +void Debug::Error(const char *format, ...) +{ + + switch (debugLevel) { + + case WARNING: + case ERROR : + case ALL: { + ERR_Count++; + char msg[256]; + va_list ap; + va_start (ap, format); + vsprintf (msg,format ,ap); + va_end (ap); + os<<"Error["<<ERR_Count<<"]"<<msg<<endl; + } + break; + + case INFO: + case NONE: + break; + } } diff --git a/src/Debug.h b/src/Debug.h index 1c647c18920ad90dca955b398f31cacfd4430ec5..953e3fd1d5f1d4203d1ae37c96d1b69b79d8ed67 100644 --- a/src/Debug.h +++ b/src/Debug.h @@ -38,74 +38,74 @@ class Debug { public: - /** - * different debug levels - */ - enum LEVEL{ - NONE, //!< NONE The logger is switched off - INFO, //!< INFO debug messages only are output - WARNING, //!< WARNING warning and Errors are output - //CRITICAL,//!< CRITICAL - ERROR, //!< ERROR Only errors are output - ALL //!< ALL Performs a full logging - }; + /** + * different debug levels + */ + enum LEVEL { + NONE, //!< NONE The logger is switched off + INFO, //!< INFO debug messages only are output + WARNING, //!< WARNING warning and Errors are output + //CRITICAL,//!< CRITICAL + ERROR, //!< ERROR Only errors are output + ALL //!< ALL Performs a full logging + }; - /** - * Constructor - */ - Debug(); + /** + * Constructor + */ + Debug(); - /** - * Destructor - */ - virtual ~Debug(); + /** + * Destructor + */ + virtual ~Debug(); - /** - * set the debug output stream. can be a file as well - * as one of the cout, cerr, clog, ... - * Default output stream if std::cout. - * - * @param os, the output stream - */ - static void setOutputStream(std::ostream &os ); + /** + * set the debug output stream. can be a file as well + * as one of the cout, cerr, clog, ... + * Default output stream if std::cout. + * + * @param os, the output stream + */ + static void setOutputStream(std::ostream &os ); - /** - * set the desired debug level. - * - * @see LEVEL - * - * @param level, the desired debug level - */ - static void setDebugLevel(Debug::LEVEL level); + /** + * set the desired debug level. + * + * @see LEVEL + * + * @param level, the desired debug level + */ + static void setDebugLevel(Debug::LEVEL level); - /** - * send a message (information) to the output stream - * - * @param string, the message - */ - static void Messages(const char *string, ...); + /** + * send a message (information) to the output stream + * + * @param string, the message + */ + static void Messages(const char *string, ...); - /** - * add a warning to the output stream - * - * @param string, the warning message - */ - static void Warning(const char *string, ...); + /** + * add a warning to the output stream + * + * @param string, the warning message + */ + static void Warning(const char *string, ...); - /** - * add an error message to the output stream - * - * @param string, the error message - */ - static void Error(const char *string, ...); + /** + * add an error message to the output stream + * + * @param string, the error message + */ + static void Error(const char *string, ...); private: - static std::ostream &os; - static Debug::LEVEL debugLevel; - static int MSG_Count; - static int ERR_Count; - static int WAR_Count; + static std::ostream &os; + static Debug::LEVEL debugLevel; + static int MSG_Count; + static int ERR_Count; + static int WAR_Count; }; #endif /* DEBUG_H_ */ diff --git a/src/Frame.cpp b/src/Frame.cpp index c62f6132c7d2215a119ad64de5e9710e168cd6d5..d98756b4834799baef205e61fba7bf838ce4355c 100644 --- a/src/Frame.cpp +++ b/src/Frame.cpp @@ -57,7 +57,7 @@ Frame::Frame() Frame::~Frame() { - while (!_framePoints.empty()){ + while (!_framePoints.empty()) { delete _framePoints.back(); _framePoints.pop_back(); } @@ -79,7 +79,7 @@ void Frame::addElement(FrameElement* point) void Frame::clear() { - while (!_framePoints.empty()){ + while (!_framePoints.empty()) { delete _framePoints.back(); _framePoints.pop_back(); } @@ -93,7 +93,7 @@ FrameElement* Frame::getNextElement() if(_elementCursor>=_framePoints.size()) { return NULL; - }else{ + } else { return _framePoints.at(_elementCursor++); } //next test @@ -227,10 +227,9 @@ void Frame::ComputePolyData2D() labels->SetName("labels"); labels->SetNumberOfComponents(1); - for (unsigned int i=0;i<_framePoints.size();i++) - { - double pos[3]={0,0,0}; - double rad[3]={1.0,1.0,1.0}; + for (unsigned int i=0; i<_framePoints.size(); i++) { + double pos[3]= {0,0,0}; + double rad[3]= {1.0,1.0,1.0}; double rot[3]; double color; _framePoints[i]->GetPos(pos); //pos[2]=90; @@ -239,30 +238,36 @@ void Frame::ComputePolyData2D() _framePoints[i]->GetRadius(rad); labels->InsertNextValue(_framePoints[i]->GetId()+1); - rad[0]/=30;rad[1]/=30;rad[2]/=120; + rad[0]/=30; + rad[1]/=30; + rad[2]/=120; points->InsertNextPoint(pos); rot[2]=vtkMath::RadiansFromDegrees(rot[2]); //scaling matrix double sc[3][3] = {{rad[0],0,0}, - {0,rad[1],0}, - {0,0,rad[2]}}; + {0,rad[1],0}, + {0,0,rad[2]} + }; //rotation matrix around x-axis double roX[3][3] = {{1, 0, 0}, - {0, cos(rot[0]),-sin(rot[0])}, - {0, sin(rot[0]), cos(rot[0])}}; + {0, cos(rot[0]),-sin(rot[0])}, + {0, sin(rot[0]), cos(rot[0])} + }; //rotation matrix around y-axis double roY[3][3] = {{cos(rot[1]), 0,sin(rot[1])}, - {0, 1, 0}, - {-sin(rot[1]),0,cos(rot[1])}}; + {0, 1, 0}, + {-sin(rot[1]),0,cos(rot[1])} + }; //rotation matrix around z-axis double roZ[3][3] = {{cos(rot[2]),sin(rot[2]),0.0}, - {-sin(rot[2]),cos(rot[2]),0.0}, - {0.0,0.0,1.0}}; + {-sin(rot[2]),cos(rot[2]),0.0}, + {0.0,0.0,1.0} + }; //final rotation matrix @@ -275,14 +280,13 @@ void Frame::ComputePolyData2D() vtkMath::Multiply3x3(sc,ro,rs); tensors->InsertNextTuple9(rs[0][0],rs[0][1],rs[0][2], - rs[1][0],rs[1][1],rs[1][2], - rs[2][0],rs[2][1],rs[2][2]); + rs[1][0],rs[1][1],rs[1][2], + rs[2][0],rs[2][1],rs[2][2]); - if(color==-1){ + if(color==-1) { colors->InsertNextValue(NAN); - } - else{ + } else { colors->InsertNextValue(color/255.0); } } @@ -312,9 +316,9 @@ void Frame::ComputePolyData3D() tensors->SetName("tensors"); tensors->SetNumberOfComponents(9); - for (unsigned int i=0;i<_framePoints.size();i++){ - double pos[3]={0,0,0}; - double rad[3]={1.0,1.0,1.0}; + for (unsigned int i=0; i<_framePoints.size(); i++) { + double pos[3]= {0,0,0}; + double rad[3]= {1.0,1.0,1.0}; double rot[3]; double color; _framePoints[i]->GetPos(pos); //pos[2]=90; @@ -338,8 +342,10 @@ void Frame::ComputePolyData3D() pos[2]+=height_i/2.0; // slightly above ground - rad[0]/=20; rad[0]=1; - rad[2]/=20; rad[2]=1; + rad[0]/=20; + rad[0]=1; + rad[2]/=20; + rad[2]=1; //?height default to 30 in SaxParser and 160 in Renderingengine //rad[1]=height_i/160.0; rad[1]=height_i/max_height; @@ -350,24 +356,28 @@ void Frame::ComputePolyData3D() //scaling matrix double sc[3][3] = {{rad[0],0,0}, - {0,rad[1],0}, - {0,0,rad[2]}}; + {0,rad[1],0}, + {0,0,rad[2]} + }; //rotation matrix around x-axis double roX[3][3] = {{1, 0, 0}, - {0, cos(rot[0]),-sin(rot[0])}, - {0, sin(rot[0]), cos(rot[0])}}; + {0, cos(rot[0]),-sin(rot[0])}, + {0, sin(rot[0]), cos(rot[0])} + }; //rotation matrix around y-axis double roY[3][3] = {{cos(rot[1]), 0,sin(rot[1])}, - {0, 1, 0}, - {-sin(rot[1]),0,cos(rot[1])}}; + {0, 1, 0}, + {-sin(rot[1]),0,cos(rot[1])} + }; //rotation matrix around z-axis double roZ[3][3] = {{cos(rot[2]),sin(rot[2]),0.0}, - {-sin(rot[2]),cos(rot[2]),0.0}, - {0.0,0.0,1.0}}; + {-sin(rot[2]),cos(rot[2]),0.0}, + {0.0,0.0,1.0} + }; //final rotation matrix @@ -380,14 +390,13 @@ void Frame::ComputePolyData3D() vtkMath::Multiply3x3(sc,ro,rs); tensors->InsertNextTuple9(rs[0][0],rs[0][1],rs[0][2], - rs[1][0],rs[1][1],rs[1][2], - rs[2][0],rs[2][1],rs[2][2]); + rs[1][0],rs[1][1],rs[1][2], + rs[2][0],rs[2][1],rs[2][2]); - if(color==-1){ + if(color==-1) { colors->InsertNextValue(NAN); - } - else{ + } else { colors->InsertNextValue(color/255.0); } } diff --git a/src/Frame.h b/src/Frame.h index 1dd955e3d9476213ff582d8747b1d5ff818e33ae..19b34dbb0e0c3a1826bb0f149c27cdc5b52cc187 100644 --- a/src/Frame.h +++ b/src/Frame.h @@ -35,21 +35,20 @@ class FrameElement; class vtkPolyData; -class Frame -{ +class Frame { public: /// constructor Frame(); /// destructor - virtual ~Frame(); + virtual ~Frame(); - /// add an element to the Frame - void addElement(FrameElement* point); + /// add an element to the Frame + void addElement(FrameElement* point); - ///clear all Points in the frame - void clear(); + ///clear all Points in the frame + void clear(); - ///return the next object in the frame + ///return the next object in the frame FrameElement *getNextElement(); ///compute the polydata. @@ -81,7 +80,7 @@ private: /// compute the 3D polydata void ComputePolyData3D(); - unsigned int getElementCursor(); + unsigned int getElementCursor(); private: @@ -90,7 +89,7 @@ private: vtkPolyData * _polydata2D; vtkPolyData * _polydata3D; - /// points to the actual element in the frame + /// points to the actual element in the frame unsigned int _elementCursor; }; diff --git a/src/FrameElement.cpp b/src/FrameElement.cpp index 9bd235dbea3ca2310b49751899e1db2edb8d5555..82223a94d29b28f365f1f81dba737f8d8442914d 100644 --- a/src/FrameElement.cpp +++ b/src/FrameElement.cpp @@ -49,11 +49,13 @@ FrameElement::FrameElement(int id) _radius[2] = std::numeric_limits<double>::quiet_NaN(); } -FrameElement::~FrameElement() { +FrameElement::~FrameElement() +{ } -void FrameElement::SetId(int index) { +void FrameElement::SetId(int index) +{ _id = index; } @@ -87,9 +89,9 @@ void FrameElement::GetPos(double pos[3]) void FrameElement::SetOrientation(double angle[]) { - _orientation[0]=angle[0]; - _orientation[1]=angle[1]; - _orientation[2]=angle[2]; + _orientation[0]=angle[0]; + _orientation[1]=angle[1]; + _orientation[2]=angle[2]; } void FrameElement::GetOrientation(double angle[]) diff --git a/src/FrameElement.h b/src/FrameElement.h index 58e4ac9fc195a6ae6809e74078292210de3b57d1..e59262b3326aa2ddd5c69242a60f25618dacca65 100644 --- a/src/FrameElement.h +++ b/src/FrameElement.h @@ -37,14 +37,14 @@ public: FrameElement(int _id); virtual ~FrameElement(); - /// set/get the point ID + /// set/get the point ID void SetId(int _id); - /// set/get the point ID + /// set/get the point ID int GetId(); - /// set/get the position of the point/agent + /// set/get the position of the point/agent void GetPos(double pos[3]); - /// set/get the position of the point/agent + /// set/get the position of the point/agent void SetPos(double pos[3]); ///Set/Get the agent scaling, semi axes of the ellipses diff --git a/src/IO/OutputHandler.cpp b/src/IO/OutputHandler.cpp index 1fb1428f9382d8d2e986b63c7c37927322656921..8f57384657cbd5be79eb6ca0c3b7a300fadd073a 100644 --- a/src/IO/OutputHandler.cpp +++ b/src/IO/OutputHandler.cpp @@ -34,39 +34,42 @@ using namespace std; -void OutputHandler::Write(string str) { - if (this != NULL) - cout << str << endl; +void OutputHandler::Write(string str) +{ + if (this != NULL) + cout << str << endl; } -void OutputHandler::Write(const char* message,...) { - char msg[CLENGTH]; - va_list ap; - va_start (ap, message); - vsprintf (msg,message ,ap); - va_end (ap); - - string str(msg); - if(str.find("ERROR")==string::npos) { - cout<<msg<<endl; - cout.flush(); - } - else { - cerr<<msg<<endl; - cerr.flush(); - } - - //cout << "\033[1;30mbold red text\033[0m\n"; - //cout << "\033[1;31"<<msg<<"\033[0m\n"; - //cout << "\033[1;31 bla bla \033[0m\n"; +void OutputHandler::Write(const char* message,...) +{ + char msg[CLENGTH]; + va_list ap; + va_start (ap, message); + vsprintf (msg,message ,ap); + va_end (ap); + + string str(msg); + if(str.find("ERROR")==string::npos) { + cout<<msg<<endl; + cout.flush(); + } else { + cerr<<msg<<endl; + cerr.flush(); + } + + //cout << "\033[1;30mbold red text\033[0m\n"; + //cout << "\033[1;31"<<msg<<"\033[0m\n"; + //cout << "\033[1;31 bla bla \033[0m\n"; } -void STDIOHandler::Write(string str) { - if (this != NULL) - cout << str << endl; +void STDIOHandler::Write(string str) +{ + if (this != NULL) + cout << str << endl; } -FileHandler::FileHandler(const char *fn) { +FileHandler::FileHandler(const char *fn) +{ pfp.open(fn); if (!fn) { char tmp[CLENGTH]; @@ -76,39 +79,45 @@ FileHandler::FileHandler(const char *fn) { } } -FileHandler::~FileHandler() { +FileHandler::~FileHandler() +{ pfp.close(); } -void FileHandler::Write(string str) { +void FileHandler::Write(string str) +{ if (this != NULL) { pfp << str << endl; pfp.flush(); } } -void FileHandler::Write(const char* string,...) { - char msg[CLENGTH]; - va_list ap; - va_start (ap, string); - vsprintf (msg,string ,ap); - va_end (ap); - pfp<<msg<<endl; - pfp.flush(); +void FileHandler::Write(const char* string,...) +{ + char msg[CLENGTH]; + va_list ap; + va_start (ap, string); + vsprintf (msg,string ,ap); + va_end (ap); + pfp<<msg<<endl; + pfp.flush(); } -TraVisToHandler::TraVisToHandler(string host, int port) { +TraVisToHandler::TraVisToHandler(string host, int port) +{ client = new TraVisToClient(host, port); brokentags.push_back("<trajectoriesDataset>"); brokentags.push_back("</trajectoriesDataset>"); brokentags.push_back("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); } -TraVisToHandler::~TraVisToHandler(){ - delete client; +TraVisToHandler::~TraVisToHandler() +{ + delete client; } -void TraVisToHandler::Write(string str) { +void TraVisToHandler::Write(string str) +{ vector<string>::iterator str_it; diff --git a/src/IO/OutputHandler.h b/src/IO/OutputHandler.h index 855d85ad4b6f72f53d0b82e510767cf822fff2b6..1a2841bbf5ecf0bc9c91accda0df3898ab051c88 100644 --- a/src/IO/OutputHandler.h +++ b/src/IO/OutputHandler.h @@ -39,8 +39,8 @@ class OutputHandler { public: virtual void Write(std::string str); - virtual void Write(const char *string, ...); - virtual ~OutputHandler(){}; + virtual void Write(const char *string, ...); + virtual ~OutputHandler() {}; }; class STDIOHandler : public OutputHandler { diff --git a/src/IO/TraVisToClient.cpp b/src/IO/TraVisToClient.cpp index d095a4bbfb0281858ed271f4fe717725547b819c..70614c3161791925d2afa591b97f84b9d8ee0ff7 100644 --- a/src/IO/TraVisToClient.cpp +++ b/src/IO/TraVisToClient.cpp @@ -38,7 +38,8 @@ using namespace std; -TraVisToClient::TraVisToClient(string hostname, unsigned short port) { +TraVisToClient::TraVisToClient(string hostname, unsigned short port) +{ _hostname=hostname; _port = port; _isConnected = false; @@ -47,14 +48,16 @@ TraVisToClient::TraVisToClient(string hostname, unsigned short port) { } -TraVisToClient::~TraVisToClient() { +TraVisToClient::~TraVisToClient() +{ if (_isConnected) close(); } /// send datablock to the server -void TraVisToClient::sendData(const char* data) { +void TraVisToClient::sendData(const char* data) +{ // first create a new connection, in the case the last one was lost/close @@ -103,7 +106,8 @@ void TraVisToClient::sendData(const char* data) { /// close the client (end the connection) -void TraVisToClient::close() { +void TraVisToClient::close() +{ if (_isConnected) { /* all things are done, so shutdown the connection */ if (!shutdownAndCloseSocket(_tcpSocket)) { @@ -119,7 +123,8 @@ void TraVisToClient::close() { } -void TraVisToClient::createConnection() { +void TraVisToClient::createConnection() +{ /* start the socket session */ if (!startSocketSession()) { @@ -151,7 +156,8 @@ void TraVisToClient::createConnection() { * @c INADDR_NONE. */ unsigned long -TraVisToClient::lookupHostAddress(const char *hostName) { +TraVisToClient::lookupHostAddress(const char *hostName) +{ unsigned long addr; /* inet address of hostname */ struct hostent *host; /* host structure for DNS request */ @@ -192,7 +198,8 @@ TraVisToClient::lookupHostAddress(const char *hostName) { * returns @c INVALID_SOCKET. */ socket_t -TraVisToClient::createClientSocket(const char *serverName, unsigned short portNumber) { +TraVisToClient::createClientSocket(const char *serverName, unsigned short portNumber) +{ unsigned long ipAddress; /* internet address */ struct sockaddr_in srvAddr; /* server's internet socket address */ socket_t sock; /* file descriptor for client socket */ @@ -244,7 +251,8 @@ TraVisToClient::createClientSocket(const char *serverName, unsigned short portNu * If an error occurs, the function returns @c INVALID_SOCKET. */ socket_t -TraVisToClient::createServerSocket(unsigned short portNumber) { +TraVisToClient::createServerSocket(unsigned short portNumber) +{ struct sockaddr_in srvAddr; /* server's internet socket address */ socket_t sock; /* file descriptor for server socket */ @@ -299,7 +307,8 @@ TraVisToClient::createServerSocket(unsigned short portNumber) { * otherwise the function returns @c false. */ bool -TraVisToClient::sendMessage(socket_t sock, const void *msg, int msgSize) { +TraVisToClient::sendMessage(socket_t sock, const void *msg, int msgSize) +{ dtrace("entering sendMessage()"); /* check if parameters are valid */ @@ -343,7 +352,8 @@ TraVisToClient::sendMessage(socket_t sock, const void *msg, int msgSize) { * the function returns @c false. */ bool -TraVisToClient::receiveMessage(socket_t sock, void *msg, int msgSize) { +TraVisToClient::receiveMessage(socket_t sock, void *msg, int msgSize) +{ char *msgPart; /* pointer to the memory for receiving the message */ int toReceive; /* number of bytes to receive */ int received; /* number of bytes totally received */ @@ -374,19 +384,19 @@ TraVisToClient::receiveMessage(socket_t sock, void *msg, int msgSize) { toReceive = msgSize - received; nBytes = recv(sock, msgPart, toReceive, 0); switch (nBytes) { - case SOCKET_ERROR: /* error occurred */ - derror("error during message receipt"); - dtrace("leaving receiveMessage()"); - return (false); - case 0: /* connection has been closed */ - derror("remote host has closed the connection"); - dtrace("leaving receiveMessage()"); - return (false); - default: /* some bytes have been received */ - dtrace("received %d bytes of message", nBytes); - received += nBytes; - msgPart += nBytes; - break; + case SOCKET_ERROR: /* error occurred */ + derror("error during message receipt"); + dtrace("leaving receiveMessage()"); + return (false); + case 0: /* connection has been closed */ + derror("remote host has closed the connection"); + dtrace("leaving receiveMessage()"); + return (false); + default: /* some bytes have been received */ + dtrace("received %d bytes of message", nBytes); + received += nBytes; + msgPart += nBytes; + break; } } while (received != msgSize); @@ -406,7 +416,8 @@ TraVisToClient::receiveMessage(socket_t sock, void *msg, int msgSize) { * @c false */ bool -TraVisToClient::shutdownAndCloseSocket(socket_t sock) { +TraVisToClient::shutdownAndCloseSocket(socket_t sock) +{ bool status = true; dtrace("entering shutdownAndCloseSocket()"); @@ -429,7 +440,8 @@ TraVisToClient::shutdownAndCloseSocket(socket_t sock) { /******** end of function shutdownAndCloseSocket *********************/ void -TraVisToClient::_printErrorMessage(void) { +TraVisToClient::_printErrorMessage(void) +{ } @@ -442,7 +454,8 @@ TraVisToClient::_printErrorMessage(void) { * @c false */ bool -TraVisToClient::_startWin32SocketSession(void) { +TraVisToClient::_startWin32SocketSession(void) +{ WORD requestedVersion; WSADATA wsaData; @@ -482,7 +495,8 @@ TraVisToClient::_startWin32SocketSession(void) { * No future API calls are allowed. */ void -TraVisToClient::_stopWin32SocketSession(void) { +TraVisToClient::_stopWin32SocketSession(void) +{ dtrace("entering _stopWin32SocketSession()"); if (SOCKET_ERROR == WSACleanup()) { diff --git a/src/IO/TraVisToClient.h b/src/IO/TraVisToClient.h index 9b37e54ebfc18bad87eff0ea5c2261350bec36eb..12d375cc1722ad8f7fcc63dec41a4ce129096854 100644 --- a/src/IO/TraVisToClient.h +++ b/src/IO/TraVisToClient.h @@ -132,7 +132,7 @@ private: bool _startWin32SocketSession(void); void _stopWin32SocketSession(void); #else - #define closesocket close +#define closesocket close #endif diff --git a/src/InteractorStyle.cpp b/src/InteractorStyle.cpp index f7b615fdff82b7a61dc343c56e15676aef9e9b45..594e1cf92ac9b157ab3dab079d5180356bf35a89 100644 --- a/src/InteractorStyle.cpp +++ b/src/InteractorStyle.cpp @@ -48,237 +48,245 @@ using namespace std; #define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() -InteractorStyle::InteractorStyle() { +InteractorStyle::InteractorStyle() +{ } -InteractorStyle::~InteractorStyle() { +InteractorStyle::~InteractorStyle() +{ } ///static constructor -InteractorStyle* InteractorStyle::New() { - return new InteractorStyle(); +InteractorStyle* InteractorStyle::New() +{ + return new InteractorStyle(); } -void InteractorStyle::SetActor() { +void InteractorStyle::SetActor() +{ } ; -void InteractorStyle::SetSource() { +void InteractorStyle::SetSource() +{ } ; //forward the event only if not in 2d mode -void InteractorStyle::Rotate() { - //if(!SystemSettings::get2D()) - vtkInteractorStyleTrackballCamera::Rotate(); +void InteractorStyle::Rotate() +{ + //if(!SystemSettings::get2D()) + vtkInteractorStyleTrackballCamera::Rotate(); } -void InteractorStyle::Spin() { - vtkInteractorStyleTrackballCamera::Spin(); +void InteractorStyle::Spin() +{ + vtkInteractorStyleTrackballCamera::Spin(); } -void InteractorStyle::Pan() { - vtkInteractorStyleTrackballCamera::Pan(); +void InteractorStyle::Pan() +{ + vtkInteractorStyleTrackballCamera::Pan(); } -void InteractorStyle::Dolly() { - vtkInteractorStyleTrackballCamera::Dolly(); +void InteractorStyle::Dolly() +{ + vtkInteractorStyleTrackballCamera::Dolly(); } -void InteractorStyle::OnChar() { - - vtkRenderWindowInteractor *rwi = this->Interactor; - //this->Interactor->GetRenderWindow()->GetScreenSize(); - //rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Print(std::cout); - - char ch = rwi->GetKeyCode(); - - - switch (ch) { - - case '+': - case '-': - rwi->Render(); // render - update the screen - break; - - //escape - case 27: - extern_fullscreen_enable = false; - extern_force_system_update = true; - break; - - case 'a': { - double para[3]; - vtkCamera - * cam = - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); - cam->GetPosition(para); - //std::cout<<endl<<; - //cam->Roll(90-cam->GetRoll()); - //cam->Yaw(0); - //cam->Pitch(0); - //cam->Roll(-90); - //cam->Elevation(0); - //cam->Azimuth(0); - //std::cout <<"roll [ "<< cam->GetRoll()<<" ]"<<std::endl; - //std::cout <<"azimuth [ "<< cam->GetRoll()<<" ]"<<std::endl; - //std::cout <<"elevation [ "<< cam->GetRoll()<<" ]"<<std::endl; - //std::cout <<"roll [ "<<para[0]<<" " <<para[1] <<" "<<para[2]<<" ]"<<std::endl; - } - break; - - //zoom in - case 'n': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); - break; - //zoom out - case 'N': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(0.95); - break; - - //pan - case 'b': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Roll(5.0); - //Pan(); - break; - case 'B': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Roll(-5.0); - break; - - //rotate - case 'v': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Pitch(5); - break; - case 'V': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Pitch(-5); - break; - - //dolly - case 'c': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Yaw(5); - break; - case 'C': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Yaw(-5); - break; - - //Spin - case 'x': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Elevation(5); - rwi->GetRenderWindow()->Modified(); - rwi->Render(); - break; - case 'X': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Elevation(-5); - rwi->GetRenderWindow()->Modified(); - rwi->Render(); - break; - - //Spin - case 'm': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Azimuth(5); - rwi->GetRenderWindow()->Modified(); - break; - case 'M': - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Azimuth(-5); - rwi->GetRenderWindow()->Modified(); - break; - - - case 'h': // display camera settings - { - double para[3]; - vtkCamera - * cam = - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); - cam->GetPosition(para); - std::cout << endl << endl; - std::cout << "position [ " << para[0] << " " << para[1] << " " - << para[2] << " ]" << std::endl; - cam->GetFocalPoint(para); - std::cout << "focal point [ " << para[0] << " " << para[1] << " " - << para[2] << " ]" << std::endl; - cam->GetClippingRange(para); - std::cout << "clipping range [ " << para[0] << " " << para[1] << " " - << para[2] << " ]" << std::endl; - cam->GetViewPlaneNormal(para); - std::cout << "viewplan norm [ " << para[0] << " " << para[1] << " " - << para[2] << " ]" << std::endl; - - } - break; - - default: - { - std::string key = rwi->GetKeySym(); - int sensitivity=2; - double pos[3]; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->GetPosition(pos); +void InteractorStyle::OnChar() +{ + + vtkRenderWindowInteractor *rwi = this->Interactor; + //this->Interactor->GetRenderWindow()->GetScreenSize(); + //rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Print(std::cout); + + char ch = rwi->GetKeyCode(); + + + switch (ch) { + + case '+': + case '-': + rwi->Render(); // render - update the screen + break; + + //escape + case 27: + extern_fullscreen_enable = false; + extern_force_system_update = true; + break; + + case 'a': { + double para[3]; + vtkCamera + * cam = + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); + cam->GetPosition(para); + //std::cout<<endl<<; + //cam->Roll(90-cam->GetRoll()); + //cam->Yaw(0); + //cam->Pitch(0); + //cam->Roll(-90); + //cam->Elevation(0); + //cam->Azimuth(0); + //std::cout <<"roll [ "<< cam->GetRoll()<<" ]"<<std::endl; + //std::cout <<"azimuth [ "<< cam->GetRoll()<<" ]"<<std::endl; + //std::cout <<"elevation [ "<< cam->GetRoll()<<" ]"<<std::endl; + //std::cout <<"roll [ "<<para[0]<<" " <<para[1] <<" "<<para[2]<<" ]"<<std::endl; + } + break; + + //zoom in + case 'n': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(1.05); + break; + //zoom out + case 'N': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Zoom(0.95); + break; + + //pan + case 'b': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Roll(5.0); + //Pan(); + break; + case 'B': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Roll(-5.0); + break; + + //rotate + case 'v': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Pitch(5); + break; + case 'V': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Pitch(-5); + break; + + //dolly + case 'c': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Yaw(5); + break; + case 'C': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Yaw(-5); + break; + + //Spin + case 'x': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Elevation(5); + rwi->GetRenderWindow()->Modified(); + rwi->Render(); + break; + case 'X': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Elevation(-5); + rwi->GetRenderWindow()->Modified(); + rwi->Render(); + break; + + //Spin + case 'm': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Azimuth(5); + rwi->GetRenderWindow()->Modified(); + break; + case 'M': + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->Azimuth(-5); + rwi->GetRenderWindow()->Modified(); + break; + + + case 'h': { // display camera settings + double para[3]; + vtkCamera + * cam = + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); + cam->GetPosition(para); + std::cout << endl << endl; + std::cout << "position [ " << para[0] << " " << para[1] << " " + << para[2] << " ]" << std::endl; + cam->GetFocalPoint(para); + std::cout << "focal point [ " << para[0] << " " << para[1] << " " + << para[2] << " ]" << std::endl; + cam->GetClippingRange(para); + std::cout << "clipping range [ " << para[0] << " " << para[1] << " " + << para[2] << " ]" << std::endl; + cam->GetViewPlaneNormal(para); + std::cout << "viewplan norm [ " << para[0] << " " << para[1] << " " + << para[2] << " ]" << std::endl; + + } + break; + + default: { + std::string key = rwi->GetKeySym(); + int sensitivity=2; + double pos[3]; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->GetPosition(pos); // printf("[%f,%f,%f]\n",pos[0],pos[1],pos[2]); - if(key=="Up"){ - pos[1]=pos[1]-sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],1); - - } - else if(key=="Down"){ - pos[1]=pos[1]+sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],1); - - }else if(key=="Left"){ - pos[0]=pos[0]+sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); - - }else if(key=="Right"){ - pos[0]=pos[0]-sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); - - }else if(key=="k"){ - pos[0]=pos[0]-sensitivity*10; - pos[1]=pos[1]-sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); - - }else if(key=="K"){ - pos[0]=pos[0]+sensitivity*10; - pos[1]=pos[1]+sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); - - }else if(key=="l"){ - pos[0]=pos[0]-sensitivity*10; - pos[1]=pos[1]+sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); - - }else if(key=="L"){ - pos[0]=pos[0]+sensitivity*10; - pos[1]=pos[1]-sensitivity*10; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; - rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); - } - } - break; - - } - - // forward events - vtkInteractorStyleTrackballCamera::OnChar(); + if(key=="Up") { + pos[1]=pos[1]-sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],1); + + } else if(key=="Down") { + pos[1]=pos[1]+sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],1); + + } else if(key=="Left") { + pos[0]=pos[0]+sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); + + } else if(key=="Right") { + pos[0]=pos[0]-sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); + + } else if(key=="k") { + pos[0]=pos[0]-sensitivity*10; + pos[1]=pos[1]-sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); + + } else if(key=="K") { + pos[0]=pos[0]+sensitivity*10; + pos[1]=pos[1]+sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); + + } else if(key=="l") { + pos[0]=pos[0]-sensitivity*10; + pos[1]=pos[1]+sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); + + } else if(key=="L") { + pos[0]=pos[0]+sensitivity*10; + pos[1]=pos[1]-sensitivity*10; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetPosition(pos);; + rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera()->SetFocalPoint(pos[0],pos[1],10); + } + } + break; + + } + + // forward events + vtkInteractorStyleTrackballCamera::OnChar(); } //http://vtk.1045678.n5.nabble.com/Coordinate-conversions-World-Display-td2808312.html -void InteractorStyle::OnLeftButtonUp(){ +void InteractorStyle::OnLeftButtonUp() +{ vtkRenderWindowInteractor *rwi = this->Interactor; diff --git a/src/InteractorStyle.h b/src/InteractorStyle.h index 34cb7ca5b44c36398646329d6d9ce15015bb29a3..7171fb466ad30b7955ca3d0b0a74c9e03b02758a 100644 --- a/src/InteractorStyle.h +++ b/src/InteractorStyle.h @@ -41,31 +41,31 @@ extern bool extern_force_system_update; class InteractorStyle: public vtkInteractorStyleTrackballCamera { public: - InteractorStyle(); - virtual ~InteractorStyle(); + InteractorStyle(); + virtual ~InteractorStyle(); - /// static constructor - static InteractorStyle* New(); + /// static constructor + static InteractorStyle* New(); - ///set the actor - void SetActor(/*vtkActor* actor*/); - ///set the source - void SetSource(/*some source*/); + ///set the actor + void SetActor(/*vtkActor* actor*/); + ///set the source + void SetSource(/*some source*/); - ///override - virtual void OnChar(); - virtual void Rotate(); - virtual void Spin(); - virtual void Pan(); - virtual void Dolly(); - virtual void OnLeftButtonUp(); + ///override + virtual void OnChar(); + virtual void Rotate(); + virtual void Spin(); + virtual void Pan(); + virtual void Dolly(); + virtual void OnLeftButtonUp(); private: - //vtkActor* mActor ; - //vtkSphereSource* mSrc ; + //vtkActor* mActor ; + //vtkSphereSource* mSrc ; }; #endif /* INTERACTORSTYLE_H_ */ diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 7b46263cbc6c8068e9ed9ac8f2f49864f71b21a7..8c2e5d9e11367ed83bd25e155538d99854bfb4ca 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -72,7 +72,8 @@ using namespace std; MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent) { + QMainWindow(parent) +{ ui.setupUi(this); this->setWindowTitle("JPSvis"); @@ -91,25 +92,25 @@ MainWindow::MainWindow(QWidget *parent) : if(!QObject::connect(dataTransferThread, SIGNAL(signal_controlSequence(const char*)), this, - SLOT(slotControlSequence(const char *)))){ + SLOT(slotControlSequence(const char *)))) { Debug::Error("dataTransferThread Thread: control sequence could not be connected"); } if(!QObject::connect(dataTransferThread, SIGNAL(signal_startVisualisationThread(QString,int,float )), this, - SLOT(slotStartVisualisationThread(QString,int,float )))){ + SLOT(slotStartVisualisationThread(QString,int,float )))) { Debug::Error(" signal_startVisualisationThread not connected"); } if(!QObject::connect(dataTransferThread, SIGNAL(signal_stopVisualisationThread(bool )), this, - SLOT(slotShutdownVisualisationThread(bool )))){ + SLOT(slotShutdownVisualisationThread(bool )))) { Debug::Error(" signal_stopVisualisationThread not connected "); } if(!QObject::connect(dataTransferThread, SIGNAL(signal_errorMessage(QString)), this, - SLOT(slotErrorOutput(QString)))){ + SLOT(slotErrorOutput(QString)))) { Debug::Error("signal_errorMessage not connected "); } @@ -121,15 +122,6 @@ MainWindow::MainWindow(QWidget *parent) : SIGNAL(signal_controlSequences(const char*)), this, SLOT(slotControlSequence(const char *))); - QObject::connect(&extern_trajectories_secondSet, - SIGNAL(signal_controlSequences(const char*)), this, - SLOT(slotControlSequence(const char *))); - - QObject::connect(&extern_trajectories_thirdSet, - SIGNAL(signal_controlSequences(const char*)), this, - SLOT(slotControlSequence(const char *))); - - QObject::connect(dataTransferThread, SIGNAL(signal_CurrentAction(QString)), this, SLOT(slotCurrentAction(QString))); @@ -187,44 +179,43 @@ MainWindow::MainWindow(QWidget *parent) : arguments.append("-2D"); // parse arguments list if(arguments.size()>1) - for(int argCount=1;argCount<arguments.size();argCount++){ + for(int argCount=1; argCount<arguments.size(); argCount++) { QString argument=arguments[argCount]; if(argument.compare("help")==0) { Debug::Error("Usage: ./TraVisTo [file1] [file2] [file3] [-2D] [-caption] [-online [port]]"); - } - else if(argument.compare("-2D")==0) { + } else if(argument.compare("-2D")==0) { ui.action2_D->setChecked(true); slotToogle2D(); - }else if(argument.compare("-caption")==0) { + } else if(argument.compare("-caption")==0) { ui.actionShow_Captions->setChecked(true); slotShowPedestrianCaption(); - }else if(argument.compare("-online")==0) { + } else if(argument.compare("-online")==0) { slotSetOnlineMode(true); // checking for other possible options [ port...] - if(argCount!=arguments.size()-1){ + if(argCount!=arguments.size()-1) { bool ok=false; int port = arguments[++argCount].toInt(&ok); Debug:: - Debug::Messages(" listening port: %d",port); + Debug::Messages(" listening port: %d",port); if (ok) { SystemSettings::setListningPort(port); - }else{ // maybe that wasnt the port + } else { // maybe that wasnt the port argCount--; // to ensure that the "option" will be checked } } mayPlay=true; - }else if(argument.startsWith("-")) { + } else if(argument.startsWith("-")) { const char* std=argument.toStdString().c_str(); Debug::Error(" unknown options: %s",std); Debug::Error("Usage: ./TraVisTo [file1] [file2] [file3] [-2D] [-caption] [-online [port] ]"); - }else if(addPedestrianGroup(group,argument)){ + } else if(addPedestrianGroup(group,argument)) { //slotHelpAbout(); group++; mayPlay=true; @@ -235,7 +226,8 @@ MainWindow::MainWindow(QWidget *parent) : if(mayPlay)slotStartPlaying(); } -MainWindow::~MainWindow() { +MainWindow::~MainWindow() +{ extern_shutdown_visual_thread=true; extern_recording_enable=false; @@ -262,19 +254,20 @@ MainWindow::~MainWindow() { } -void MainWindow::slotHelpAbout() { +void MainWindow::slotHelpAbout() +{ QMessageBox::about( - this, - "About JPSVis", - "Version 0.5 built with QT 4.8 and VTK 5.10\n\n" - "JPSVis is part of the Juelich Pedestrian Simulator (JuPdsim)" - "and stands for Trajectories Visualisation Tool. It is a tool for visualizing pedestrians motion\n" - "developped at the Forschungszentrum Juelich GmbH, Germany\n\n" - "Copyright 2009-2014.\n" - "Authors: Ulrich Kemloh\n\n" - "For questions, contact +49-40-246161-4193 \nor mail at \n" - "u.kemloh@fz-juelich.de\n"); + this, + "About JPSVis", + "Version 0.5 built with QT 4.8 and VTK 5.10\n\n" + "JPSVis is part of the Juelich Pedestrian Simulator (JuPdsim)" + "and stands for Trajectories Visualisation Tool. It is a tool for visualizing pedestrians motion\n" + "developped at the Forschungszentrum Juelich GmbH, Germany\n\n" + "Copyright 2009-2014.\n" + "Authors: Ulrich Kemloh\n\n" + "For questions, contact +49-40-246161-4193 \nor mail at \n" + "u.kemloh@fz-juelich.de\n"); } @@ -285,7 +278,8 @@ void MainWindow::slotHelpAbout() { * */ -void MainWindow::slotNetworkSettings() { +void MainWindow::slotNetworkSettings() +{ bool ok; int port = QInputDialog::getInt(this, tr("input a port "), tr( @@ -297,7 +291,8 @@ void MainWindow::slotNetworkSettings() { } -void MainWindow::slotStartPlaying() { +void MainWindow::slotStartPlaying() +{ //first reset this variable. just for the case // the thread was shutdown from the reset option @@ -309,19 +304,17 @@ void MainWindow::slotStartPlaying() { //only start the visualisation thread if in offline modus // otherwise both threads should be started if (extern_offline_mode) { - if(anyDatasetLoaded()){ //at least one dataset was loaded, restarting the playback + if(anyDatasetLoaded()) { //at least one dataset was loaded, restarting the playback // starting the playback from the beginning extern_trajectories_firstSet.resetFrameCursor(); - extern_trajectories_secondSet.resetFrameCursor(); - extern_trajectories_thirdSet.resetFrameCursor(); } else if (!slotAddDataSet()) { //else load a dataset return;//could not read any data } visualisationThread->start(); - } else /*if (extern_online_mode)*/ { //live visualisation + } else { /*if (extern_online_mode)*/ //live visualisation dataTransferThread->start(); //visualisationThread->start(); } @@ -368,7 +361,8 @@ void MainWindow::slotStartPlaying() { } -void MainWindow::slotStopPlaying() { +void MainWindow::slotStopPlaying() +{ if (extern_recording_enable) { int res = QMessageBox::question(this, "action", @@ -406,7 +400,8 @@ void MainWindow::slotStopPlaying() { * and initialize the visualization * */ -bool MainWindow::slotLoadFile() { +bool MainWindow::slotLoadFile() +{ return slotAddDataSet(); @@ -414,7 +409,8 @@ bool MainWindow::slotLoadFile() { // This function is only used in online Mode -FacilityGeometry* MainWindow::parseGeometry(QDomNode geoNode){ +FacilityGeometry* MainWindow::parseGeometry(QDomNode geoNode) +{ cout<<"parsing the geo"<<endl; if(geoNode.isNull()) return NULL; @@ -423,29 +419,25 @@ FacilityGeometry* MainWindow::parseGeometry(QDomNode geoNode){ QString fileName = geoNode.toElement().elementsByTagName("file").item(0).toElement().attribute("location"); FacilityGeometry* geometry = visualisationThread->getGeometry(); - if(!fileName.isEmpty()) - { - if (fileName.endsWith(".xml",Qt::CaseInsensitive)) - { + if(!fileName.isEmpty()) { + if (fileName.endsWith(".xml",Qt::CaseInsensitive)) { //parsing the file SaxParser::parseGeometryJPS(fileName,geometry); - } - else if (fileName.endsWith(".trav",Qt::CaseInsensitive)) - { + } else if (fileName.endsWith(".trav",Qt::CaseInsensitive)) { //must not be a file name SaxParser::parseGeometryTRAV(fileName,geometry); } } // I assume it is a trav format node, //which is the only one which can directly be inserted into a file - else - { + else { //cout<<"online geo: "<<geoNode.toDocument().toString().toStdString()<<endl; exit(0); //geoNode.toText().toComment().toDocument().toString() QDomDocument doc(""); QDomNode geoNode; - if(!geoNode.isNull()){ - cout<<"online geo: "<<geoNode.toElement().toDocument().toString().toStdString()<<endl; exit(0); + if(!geoNode.isNull()) { + cout<<"online geo: "<<geoNode.toElement().toDocument().toString().toStdString()<<endl; + exit(0); } //must not be a file name @@ -481,8 +473,7 @@ FacilityGeometry* MainWindow::parseGeometry(QString geometryString) // } QFile file("_geometry_tmp_file.xml"); - if (file.open(QIODevice::WriteOnly | QIODevice::Text)) - { + if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream(&file); stream << geometryString << endl; } @@ -496,26 +487,20 @@ FacilityGeometry* MainWindow::parseGeometry(QString geometryString) FacilityGeometry* geometry = visualisationThread->getGeometry(); - if(!geofileName.isEmpty()) - { - if (geofileName.endsWith(".xml",Qt::CaseInsensitive)) - { + if(!geofileName.isEmpty()) { + if (geofileName.endsWith(".xml",Qt::CaseInsensitive)) { //parsing the file - if(!SaxParser::parseGeometryJPS(geofileName,geometry)) - { - SaxParser::parseGeometryXMLV04(geofileName,geometry); + if(!SaxParser::parseGeometryJPS(geofileName,geometry)) { + SaxParser::parseGeometryXMLV04(geofileName,geometry); } - } - else if (geofileName.endsWith(".trav",Qt::CaseInsensitive)) - { + } else if (geofileName.endsWith(".trav",Qt::CaseInsensitive)) { //must not be a file name SaxParser::parseGeometryTRAV(geofileName,geometry); } } // I assume it is a trav format node, //which is the only one which can directly be inserted into a file - else - { + else { QDomDocument doc(""); QDomNode geoNode; @@ -529,7 +514,8 @@ FacilityGeometry* MainWindow::parseGeometry(QString geometryString) } // TODO: still used? -bool MainWindow::parsePedestrianShapes(QDomNode shapeNode, int groupID){ +bool MainWindow::parsePedestrianShapes(QDomNode shapeNode, int groupID) +{ if(shapeNode.isNull()) return false; QStringList heights; @@ -549,32 +535,22 @@ bool MainWindow::parsePedestrianShapes(QDomNode shapeNode, int groupID){ if(!ok)color=std::numeric_limits<int>::quiet_NaN(); Debug::Messages("id= %d height= %lf color =%d",id,height,color); - if(!isnan(height)){ + if(!isnan(height)) { heights.append(QString::number(id)); heights.append(QString::number(height)); } - if(!isnan(color)){ + if(!isnan(color)) { colors.append(QString::number(id)); colors.append(QString::number(color)); } } - switch (groupID){ + switch (groupID) { case 1: extern_trajectories_firstSet.setInitialHeights(heights); extern_trajectories_firstSet.setInitialColors(colors); break; - - case 2: - extern_trajectories_secondSet.setInitialHeights(heights); - extern_trajectories_secondSet.setInitialColors(colors); - break; - - case 3: - extern_trajectories_thirdSet.setInitialHeights(heights); - extern_trajectories_thirdSet.setInitialColors(colors); - break; } return true; @@ -583,7 +559,8 @@ bool MainWindow::parsePedestrianShapes(QDomNode shapeNode, int groupID){ /// add a new dataset -bool MainWindow::slotAddDataSet(){ +bool MainWindow::slotAddDataSet() +{ // if (numberOfDatasetLoaded>=3){ // QMessageBox::information(this,"notice","You can load at most 3 datasets.\n In" @@ -602,7 +579,7 @@ bool MainWindow::slotAddDataSet(){ // just continue numberOfDatasetLoaded=1; - if(addPedestrianGroup(numberOfDatasetLoaded)==false){ + if(addPedestrianGroup(numberOfDatasetLoaded)==false) { numberOfDatasetLoaded--; return false; } @@ -618,7 +595,8 @@ bool MainWindow::slotAddDataSet(){ } ///clear all datasets previously entered. -void MainWindow::slotClearAllDataset(){ +void MainWindow::slotClearAllDataset() +{ clearDataSet(1); clearDataSet(2); @@ -655,14 +633,13 @@ bool MainWindow::addPedestrianGroup(int groupID,QString fileName) //cout<<"geometry name: "<<geometry_file.toStdString()<<endl; // if xml is detected, just load and show the geometry then exit - if(geometry_file.endsWith(".xml",Qt::CaseInsensitive)){ + if(geometry_file.endsWith(".xml",Qt::CaseInsensitive)) { //try to parse the correct way // fall back to this if it fails SystemSettings::CreateLogfile(); - if(! SaxParser::parseGeometryJPS(geometry_file,geometry)) - { + if(! SaxParser::parseGeometryJPS(geometry_file,geometry)) { int res = QMessageBox::warning(this, "Errors in Geometry. Continue Parsing?", "JuPedSim has detected an error in the supplied geometry.\n" "The simulation will likely failed using that geometry.\n" @@ -676,9 +653,8 @@ bool MainWindow::addPedestrianGroup(int groupID,QString fileName) return false; } SaxParser::parseGeometryXMLV04(wd+"/"+geometry_file,geometry); - } - else - { //everything was fine. Delete the log file + } else { + //everything was fine. Delete the log file SystemSettings::DeleteLogfile(); } @@ -696,10 +672,8 @@ bool MainWindow::addPedestrianGroup(int groupID,QString fileName) SyncData* dataset=NULL; extern_trajectories_firstSet.clearFrames(); - extern_trajectories_secondSet.clearFrames(); - extern_trajectories_thirdSet.clearFrames(); - switch(groupID){ + switch(groupID) { case 1: Debug::Messages("handling first set"); dataset=&extern_trajectories_firstSet; @@ -710,29 +684,8 @@ bool MainWindow::addPedestrianGroup(int groupID,QString fileName) slotToggleFirstPedestrianGroup(); break; - case 2: - Debug::Messages("handling second set"); - dataset=&extern_trajectories_secondSet; - extern_second_dataset_loaded=true; - extern_second_dataset_visible=true; - ui.actionSecond_Group->setEnabled(true); - ui.actionSecond_Group->setChecked(true); - slotToggleSecondPedestrianGroup(); - break; - - case 3: - Debug::Messages("handling third set"); - dataset=&extern_trajectories_thirdSet; - extern_third_dataset_loaded=true; - extern_third_dataset_visible=true; - ui.actionThird_Group->setEnabled(true); - ui.actionThird_Group->setChecked(true); - slotToggleThirdPedestrianGroup(); - break; - default: Debug::Error("invalid pedestrian group: %d " ,groupID); - Debug::Error("should be 1, 2 or 3"); //return false; break; } @@ -773,7 +726,8 @@ bool MainWindow::addPedestrianGroup(int groupID,QString fileName) } -void MainWindow::slotRecord() { +void MainWindow::slotRecord() +{ if (extern_recording_enable) { int res = QMessageBox::warning(this, "action", @@ -796,14 +750,16 @@ void MainWindow::slotRecord() { QString MainWindow::getTagValueFromElement(QDomNode node, - const char * tagName) { + const char * tagName) +{ if (node.isNull()) return ""; return node.toElement().namedItem(tagName).firstChild().nodeValue(); } -void MainWindow::slotFullScreen(bool status) { +void MainWindow::slotFullScreen(bool status) +{ Debug::Messages("changing full screen status %d",status); extern_fullscreen_enable = true; @@ -811,7 +767,8 @@ void MainWindow::slotFullScreen(bool status) { extern_force_system_update=true; } -void MainWindow::slotSetOfflineMode(bool status) { +void MainWindow::slotSetOfflineMode(bool status) +{ if (status) { ui.actionOnline->setChecked(false); @@ -826,7 +783,8 @@ void MainWindow::slotSetOfflineMode(bool status) { } -void MainWindow::slotSetOnlineMode(bool status) { +void MainWindow::slotSetOnlineMode(bool status) +{ if (status) { ui.actionOffline->setChecked(false); extern_offline_mode = false; @@ -839,7 +797,8 @@ void MainWindow::slotSetOnlineMode(bool status) { } } -void MainWindow::slotReset() { +void MainWindow::slotReset() +{ //stop any recording if (extern_recording_enable) { @@ -849,13 +808,12 @@ void MainWindow::slotReset() { if (res == QMessageBox::Yes) { extern_recording_enable = false; labelCurrentAction->setText(" Playing "); - }else{ + } else { return; } } - if(anyDatasetLoaded()) - { + if(anyDatasetLoaded()) { int res = QMessageBox::question(this, "action", "This will also clear any dataset if loaded.\n" "Do you wish to continue?", QMessageBox::Discard @@ -881,14 +839,16 @@ void MainWindow::slotReset() { } -void MainWindow::slotCurrentAction(QString msg) { +void MainWindow::slotCurrentAction(QString msg) +{ msg = " " + msg + " "; //labelCurrentAction->setText(msg); statusBar()->showMessage(msg); // labelMode->setText(msg); } -void MainWindow::slotFrameNumber(unsigned long actualFrameCount) { +void MainWindow::slotFrameNumber(unsigned long actualFrameCount) +{ QString msg; msg.setNum(actualFrameCount); @@ -896,24 +856,17 @@ void MainWindow::slotFrameNumber(unsigned long actualFrameCount) { //compute the mamixum framenumber int maxFrameCount=1; - if(extern_first_dataset_loaded){ + if(extern_first_dataset_loaded) { maxFrameCount=extern_trajectories_firstSet.getFramesNumber(); } - if(extern_second_dataset_loaded){ - int frameCount=extern_trajectories_secondSet.getFramesNumber(); - if(frameCount>maxFrameCount) maxFrameCount=frameCount; - } - if(extern_third_dataset_loaded){ - int frameCount=extern_trajectories_thirdSet.getFramesNumber(); - if(frameCount>maxFrameCount) maxFrameCount=frameCount; - } if(!frameSliderHold)if(maxFrameCount!=0)//TODO WTF, otherwise an arrymtic exeption arises - ui.framesIndicatorSlider->setValue((ui.framesIndicatorSlider->maximum()*actualFrameCount)/maxFrameCount); + ui.framesIndicatorSlider->setValue((ui.framesIndicatorSlider->maximum()*actualFrameCount)/maxFrameCount); } -void MainWindow::slotRunningTime(unsigned long timems) { +void MainWindow::slotRunningTime(unsigned long timems) +{ // QString msg; // msg.setNum(timems); // msg.append(" milsec"); @@ -928,12 +881,14 @@ void MainWindow::slotRenderingTime(int fps) } -void MainWindow::slotExit() { +void MainWindow::slotExit() +{ cleanUp(); qApp->exit(); } -void MainWindow::closeEvent(QCloseEvent* event) { +void MainWindow::closeEvent(QCloseEvent* event) +{ hide(); cleanUp(); event->accept(); @@ -944,7 +899,8 @@ void MainWindow::closeEvent(QCloseEvent* event) { * closing data * stopping recording */ -void MainWindow::cleanUp() { +void MainWindow::cleanUp() +{ //stop the recording process extern_recording_enable = false; extern_shutdown_visual_thread = true; @@ -959,7 +915,8 @@ void MainWindow::cleanUp() { -void MainWindow::slotControlSequence(const char * sex) { +void MainWindow::slotControlSequence(const char * sex) +{ QString str(sex); @@ -1012,14 +969,12 @@ void MainWindow::slotControlSequence(const char * sex) { //reset the frames cursor extern_trajectories_firstSet.resetFrameCursor(); - extern_trajectories_secondSet.resetFrameCursor(); - extern_trajectories_thirdSet.resetFrameCursor(); resetGraphicalElements(); - } else if (str.compare("STACK_REACHS_BEGINNING")==0){ + } else if (str.compare("STACK_REACHS_BEGINNING")==0) { //return to normal speed - if(extern_update_step<0){ + if(extern_update_step<0) { Debug::Messages("stack reaches beginning, resuming the playback with vel 1"); extern_update_step=1; ui.speedSettingSlider->setValue(1); @@ -1029,7 +984,8 @@ void MainWindow::slotControlSequence(const char * sex) { } -void MainWindow::resetGraphicalElements(){ +void MainWindow::resetGraphicalElements() +{ //restore play button QIcon icon1; @@ -1076,10 +1032,11 @@ void MainWindow::resetGraphicalElements(){ } -void MainWindow::slotToggleFirstPedestrianGroup(){ - if(ui.actionFirst_Group->isChecked()){ +void MainWindow::slotToggleFirstPedestrianGroup() +{ + if(ui.actionFirst_Group->isChecked()) { extern_first_dataset_visible=true; - }else{ + } else { extern_first_dataset_visible=false; } extern_force_system_update=true; @@ -1087,63 +1044,59 @@ void MainWindow::slotToggleFirstPedestrianGroup(){ } /// enable/disable the second pedestrian group -void MainWindow::slotToggleSecondPedestrianGroup(){ - if(ui.actionSecond_Group->isChecked()){ - extern_second_dataset_visible=true; - }else{ - extern_second_dataset_visible=false; - } - extern_force_system_update=true; +void MainWindow::slotToggleSecondPedestrianGroup() +{ +// if(ui.actionSecond_Group->isChecked()){ +// extern_second_dataset_visible=true; +// }else{ +// extern_second_dataset_visible=false; +// } +// extern_force_system_update=true; } /// enable/disable the third pedestrian group -void MainWindow::slotToggleThirdPedestrianGroup(){ - if(ui.actionThird_Group->isChecked()){ - extern_third_dataset_visible=true; - }else{ - extern_third_dataset_visible=false; - } - extern_force_system_update=true; +void MainWindow::slotToggleThirdPedestrianGroup() +{ +// if(ui.actionThird_Group->isChecked()){ +// extern_third_dataset_visible=true; +// }else{ +// extern_third_dataset_visible=false; +// } +// extern_force_system_update=true; } -bool MainWindow::anyDatasetLoaded(){ +bool MainWindow::anyDatasetLoaded() +{ return - (extern_first_dataset_loaded|| - extern_second_dataset_loaded|| - extern_third_dataset_loaded); + extern_first_dataset_loaded; } void MainWindow::slotShowTrajectoryOnly() { - if(ui.actionShow_Trajectories->isChecked()) - { + if(ui.actionShow_Trajectories->isChecked()) { extern_tracking_enable=true; - } - else - { + } else { extern_tracking_enable=false; } - extern_force_system_update=true; + extern_force_system_update=true; } void MainWindow::slotShowPedestrianOnly() { - if(ui.actionShow_Agents->isChecked()) - { + if(ui.actionShow_Agents->isChecked()) { SystemSettings::setShowAgents(true); - } - else - { + } else { SystemSettings::setShowAgents(false); } extern_force_system_update=true; } -void MainWindow::slotShowGeometry(){ +void MainWindow::slotShowGeometry() +{ - if (ui.actionShow_Geometry->isChecked()){ + if (ui.actionShow_Geometry->isChecked()) { visualisationThread->setGeometryVisibility(true); ui.actionShow_Exits->setEnabled(true); ui.actionShow_Walls->setEnabled(true); @@ -1151,45 +1104,43 @@ void MainWindow::slotShowGeometry(){ ui.actionShow_Navigation_Lines->setEnabled(true); ui.actionShow_Floor->setEnabled(true); SystemSettings::setShowGeometry(true); - } - else{ + } else { visualisationThread->setGeometryVisibility(false); ui.actionShow_Exits->setEnabled(false); ui.actionShow_Walls->setEnabled(false); ui.actionShow_Geometry_Captions->setEnabled(false); ui.actionShow_Navigation_Lines->setEnabled(false); - ui.actionShow_Floor->setEnabled(false); + ui.actionShow_Floor->setEnabled(false); SystemSettings::setShowGeometry(false); } extern_force_system_update=true; } /// shows/hide geometry -void MainWindow::slotShowHideExits(){ - if (ui.actionShow_Exits->isChecked()){ +void MainWindow::slotShowHideExits() +{ + if (ui.actionShow_Exits->isChecked()) { visualisationThread->showDoors(true); - } - else{ + } else { visualisationThread->showDoors(false); } } /// shows/hide geometry -void MainWindow::slotShowHideWalls(){ - if (ui.actionShow_Walls->isChecked()){ +void MainWindow::slotShowHideWalls() +{ + if (ui.actionShow_Walls->isChecked()) { visualisationThread->showWalls(true); - } - else{ + } else { visualisationThread->showWalls(false); } } void MainWindow::slotShowHideNavLines() { - if (ui.actionShow_Navigation_Lines->isChecked()){ + if (ui.actionShow_Navigation_Lines->isChecked()) { visualisationThread->showNavLines(true); - } - else{ + } else { visualisationThread->showNavLines(false); } } @@ -1204,7 +1155,8 @@ void MainWindow::slotShowHideFloor() /// update the playing speed -void MainWindow::slotUpdateSpeedSlider(int newValue){ +void MainWindow::slotUpdateSpeedSlider(int newValue) +{ QString msg; msg.setNum(newValue); @@ -1216,48 +1168,30 @@ void MainWindow::slotUpdateSpeedSlider(int newValue){ } /// update the position slider -void MainWindow::slotUpdateFrameSlider(int newValue){ +void MainWindow::slotUpdateFrameSlider(int newValue) +{ // first get the correct position int maxFrameCount=1; - if(extern_first_dataset_loaded){ + if(extern_first_dataset_loaded) { int t=extern_trajectories_firstSet.getFramesNumber(); if(maxFrameCount<t) maxFrameCount=t; } - if(extern_second_dataset_loaded){ - int t=extern_trajectories_secondSet.getFramesNumber(); - if(maxFrameCount<t) maxFrameCount=t; - - } - if(extern_third_dataset_loaded){ - int t=extern_trajectories_thirdSet.getFramesNumber(); - if(maxFrameCount<t) maxFrameCount=t; - } int update = ((maxFrameCount*newValue)/ui.framesIndicatorSlider->maximum()); // then set the correct position - if(extern_first_dataset_loaded){ + if(extern_first_dataset_loaded) { extern_trajectories_firstSet.setFrameCursorTo(update); //Debug::Error( " first dataset frames update to [1] : " <<update<<endl; } - if(extern_second_dataset_loaded){ - extern_trajectories_secondSet.setFrameCursorTo(update); - //Debug::Error( " second dataset frames update to[2] : " <<update<<endl; - - } - if(extern_third_dataset_loaded){ - extern_trajectories_thirdSet.setFrameCursorTo(update); - //Debug::Error( " third dataset frames update to [3] : " <<update<<endl; - } - - } /// update the contrast /// TODO: now known as framePerScond slider -void MainWindow::slotUpdateContrastSlider(int newValue){ +void MainWindow::slotUpdateContrastSlider(int newValue) +{ // extern_screen_contrast=ui.contrastSettingSlider->value(); //extern_screen_contrast=newValue; @@ -1270,9 +1204,10 @@ void MainWindow::slotUpdateContrastSlider(int newValue){ ///clear the corresponding dataset; -void MainWindow::clearDataSet(int ID){ +void MainWindow::clearDataSet(int ID) +{ - switch(ID){ + switch(ID) { case 1: //extern_trajectories_firstSet.clear(); extern_trajectories_firstSet.clearFrames(); @@ -1285,30 +1220,6 @@ void MainWindow::clearDataSet(int ID){ numberOfDatasetLoaded--; break; - case 2: - extern_trajectories_secondSet.clearFrames(); - //extern_trajectories_secondSet.clear(); - extern_trajectories_secondSet.resetFrameCursor(); - extern_second_dataset_visible=false; - extern_second_dataset_loaded=false; - ui.actionSecond_Group->setEnabled(false); - ui.actionSecond_Group->setChecked(false); - slotToggleSecondPedestrianGroup(); - numberOfDatasetLoaded--; - break; - - case 3: - extern_trajectories_thirdSet.clearFrames(); - //extern_trajectories_thirdSet.clear(); - extern_trajectories_thirdSet.resetFrameCursor(); - extern_third_dataset_loaded=false; - extern_third_dataset_visible=false; - ui.actionThird_Group->setEnabled(false); - ui.actionThird_Group->setChecked(false); - slotToggleThirdPedestrianGroup(); - numberOfDatasetLoaded--; - break; - default: break; } @@ -1319,16 +1230,16 @@ void MainWindow::clearDataSet(int ID){ slotClearGeometry(); } -void MainWindow::resetAllFrameCursor(){ - extern_trajectories_thirdSet.resetFrameCursor(); - extern_trajectories_secondSet.resetFrameCursor(); +void MainWindow::resetAllFrameCursor() +{ extern_trajectories_firstSet.resetFrameCursor(); } /// wait for visualisation thread to shutdown ///@todo why two different threads shutdown procedure. -void MainWindow::waitForVisioThread(){ - while(visualisationThread->isRunning()){ +void MainWindow::waitForVisioThread() +{ + while(visualisationThread->isRunning()) { visualisationThread->wait(200); Debug::Messages("waiting for visualisation engine to terminate ..."); #ifdef __linux__ @@ -1344,9 +1255,10 @@ void MainWindow::waitForVisioThread(){ } /// wait for datatransfer thread to be ready -void MainWindow::waitForDataThread(){ +void MainWindow::waitForDataThread() +{ - while(dataTransferThread->isRunning()){ + while(dataTransferThread->isRunning()) { dataTransferThread->shutdown(); Debug::Messages("Waiting for network engine to terminate ..."); dataTransferThread->wait(500); @@ -1356,13 +1268,14 @@ void MainWindow::waitForDataThread(){ /// set visualisation mode to 2D -void MainWindow::slotToogle2D(){ - if(ui.action2_D->isChecked()){ +void MainWindow::slotToogle2D() +{ + if(ui.action2_D->isChecked()) { extern_is_3D=false; ui.action3_D->setChecked(false); SystemSettings::set2D(true); - }else{ + } else { extern_is_3D=true; ui.action3_D->setChecked(true); SystemSettings::set2D(false); @@ -1373,8 +1286,9 @@ void MainWindow::slotToogle2D(){ } /// set visualisation mode to 3D -void MainWindow::slotToogle3D(){ - if(ui.action3_D->isChecked()){ +void MainWindow::slotToogle3D() +{ + if(ui.action3_D->isChecked()) { extern_is_3D=true; ui.action2_D->setChecked(false); SystemSettings::set2D(false); @@ -1389,18 +1303,21 @@ void MainWindow::slotToogle3D(){ extern_force_system_update=true; } -void MainWindow::slotFrameSliderPressed(){ +void MainWindow::slotFrameSliderPressed() +{ frameSliderHold=true; } -void MainWindow::slotFrameSliderReleased(){ +void MainWindow::slotFrameSliderReleased() +{ frameSliderHold=false; } -void MainWindow::slotToogleShowLegend(){ - if(ui.actionShow_Legend->isChecked()){ +void MainWindow::slotToogleShowLegend() +{ + if(ui.actionShow_Legend->isChecked()) { SystemSettings::setShowLegend(true); - }else{ + } else { SystemSettings::setShowLegend(false); } } @@ -1408,7 +1325,8 @@ void MainWindow::slotToogleShowLegend(){ * * @param geodata the geometry data received from the data transfer thread */ -void MainWindow::slotStartVisualisationThread(QString data,int numberOfAgents,float frameRate){ +void MainWindow::slotStartVisualisationThread(QString data,int numberOfAgents,float frameRate) +{ extern_trajectories_firstSet.setNumberOfAgents(numberOfAgents); @@ -1425,7 +1343,7 @@ void MainWindow::slotStartVisualisationThread(QString data,int numberOfAgents,fl QString errorMsg=""; doc.setContent(data,&errorMsg); - if(!errorMsg.isEmpty()){ + if(!errorMsg.isEmpty()) { Debug::Error("%s", (const char *)errorMsg.toStdString().c_str()); return; } @@ -1445,81 +1363,65 @@ void MainWindow::slotStartVisualisationThread(QString data,int numberOfAgents,fl /// this method is called by the data transfer thread /// investigate if you should shutdown the thread -void MainWindow::slotShutdownVisualisationThread( bool clearAndStop){ +void MainWindow::slotShutdownVisualisationThread( bool clearAndStop) +{ //FIXME: it could have some side effects. //you should close this threads - if(clearAndStop){ + if(clearAndStop) { extern_shutdown_visual_thread=true; waitForVisioThread(); } clearDataSet(1); } -void MainWindow::slotFramesByFramesNavigation(){ - if(ui.actionFrames_Navigation->isChecked()){ +void MainWindow::slotFramesByFramesNavigation() +{ + if(ui.actionFrames_Navigation->isChecked()) { ui.BtNextFrame->setVisible(true); ui.BtPreviousFrame->setVisible(true); - } - else{ + } else { ui.BtNextFrame->setVisible(false); ui.BtPreviousFrame->setVisible(false); } } -void MainWindow::slotNextFrame(){ +void MainWindow::slotNextFrame() +{ - if(extern_first_dataset_loaded){ + if(extern_first_dataset_loaded) { int newValue=extern_trajectories_firstSet.getFrameCursor()+1; extern_trajectories_firstSet.setFrameCursorTo(newValue); //Debug::Error( " update to : " <<newValue<<endl; } - if(extern_second_dataset_loaded){ - int newValue=extern_trajectories_secondSet.getFrameCursor()+1; - extern_trajectories_secondSet.setFrameCursorTo(newValue); - //Debug::Error( " update to : " <<newValue<<endl; - } - if(extern_third_dataset_loaded){ - int newValue=extern_trajectories_thirdSet.getFrameCursor()+1; - extern_trajectories_thirdSet.setFrameCursorTo(newValue); - //Debug::Error( " update to : " <<newValue<<endl; - - } } -void MainWindow::slotPreviousFrame(){ - if(extern_first_dataset_loaded){ +void MainWindow::slotPreviousFrame() +{ + if(extern_first_dataset_loaded) { int newValue=extern_trajectories_firstSet.getFrameCursor()-1; extern_trajectories_firstSet.setFrameCursorTo(newValue); //Debug::Error( " update to : " <<newValue<<endl; } - if(extern_second_dataset_loaded){ - int newValue=extern_trajectories_secondSet.getFrameCursor()-1; - extern_trajectories_secondSet.setFrameCursorTo(newValue); - //Debug::Error( " update to : " <<newValue<<endl; - } - if(extern_third_dataset_loaded){ - int newValue=extern_trajectories_thirdSet.getFrameCursor()-1; - extern_trajectories_thirdSet.setFrameCursorTo(newValue); - //Debug::Error( " update to : " <<newValue<<endl; - - } } -void MainWindow::slotShowPedestrianCaption(){ +void MainWindow::slotShowPedestrianCaption() +{ SystemSettings::setShowAgentsCaptions(ui.actionShow_Captions->isChecked()); extern_force_system_update=true; } -void MainWindow::slotToogleShowAxis(){ +void MainWindow::slotToogleShowAxis() +{ visualisationThread->setAxisVisible(ui.actionShow_Axis->isChecked()); } //todo: rename this to slotChangeSettting -void MainWindow::slotChangePedestrianShape(){ +void MainWindow::slotChangePedestrianShape() +{ // Qt::WindowFlags flags = Qt::Window | Qt::WindowCloseButtonHint; // @@ -1532,15 +1434,18 @@ void MainWindow::slotChangePedestrianShape(){ } -void MainWindow::slotCaptionColorAuto(){ +void MainWindow::slotCaptionColorAuto() +{ emit signal_controlSequence("CAPTION_AUTO"); } -void MainWindow::slotCaptionColorCustom(){ +void MainWindow::slotCaptionColorCustom() +{ emit signal_controlSequence("CAPTION_CUSTOM"); } -void MainWindow::slotChangeBackgroundColor(){ +void MainWindow::slotChangeBackgroundColor() +{ QColorDialog* colorDialog = new QColorDialog(this); colorDialog->setToolTip("Choose a new color for the background"); @@ -1549,14 +1454,15 @@ void MainWindow::slotChangeBackgroundColor(){ //the user may have cancelled the process if(col.isValid()==false) return; - double bkcolor[3]={(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; + double bkcolor[3]= {(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; visualisationThread->setBackgroundColor(bkcolor); delete colorDialog; } /// change the wall color -void MainWindow::slotChangeWallsColor(){ +void MainWindow::slotChangeWallsColor() +{ QColorDialog* colorDialog = new QColorDialog(this); colorDialog->setToolTip("Choose a new color for walls"); @@ -1565,7 +1471,7 @@ void MainWindow::slotChangeWallsColor(){ //the user may have cancelled the process if(col.isValid()==false) return; - double bkcolor[3]={(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; + double bkcolor[3]= {(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; visualisationThread->setWallsColor(bkcolor); @@ -1574,7 +1480,8 @@ void MainWindow::slotChangeWallsColor(){ } /// change the exits color -void MainWindow::slotChangeExitsColor(){ +void MainWindow::slotChangeExitsColor() +{ QColorDialog* colorDialog = new QColorDialog(this); colorDialog->setToolTip("Choose a new color for the exits"); QColor col=colorDialog->getColor(Qt::white,this,"Select new exit color"); @@ -1582,7 +1489,7 @@ void MainWindow::slotChangeExitsColor(){ //the user may have cancelled the process if(col.isValid()==false) return; - double color[3]={(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; + double color[3]= {(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; visualisationThread->setExitsColor(color); @@ -1590,7 +1497,8 @@ void MainWindow::slotChangeExitsColor(){ } /// change the navigation lines colors -void MainWindow::slotChangeNavLinesColor(){ +void MainWindow::slotChangeNavLinesColor() +{ QColorDialog* colorDialog = new QColorDialog(this); colorDialog->setToolTip("Choose a new color for walls"); QColor col=colorDialog->getColor(Qt::white,this,"Select new navigation lines color"); @@ -1598,7 +1506,7 @@ void MainWindow::slotChangeNavLinesColor(){ //the user may have cancelled the process if(col.isValid()==false) return; - double color[3]={(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; + double color[3]= {(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; visualisationThread->setNavLinesColor(color); @@ -1614,14 +1522,15 @@ void MainWindow::slotChangeFloorColor() //the user may have cancelled the process if(col.isValid()==false) return; - double color[3]={(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; + double color[3]= {(double)col.red()/255.0 ,(double)col.green()/255.0 ,(double)col.blue()/255.0}; visualisationThread->setFloorColor(color); delete colorDialog; } -void MainWindow::slotSetCameraPerspectiveToTop(){ +void MainWindow::slotSetCameraPerspectiveToTop() +{ int p= 1; //TOP visualisationThread->setCameraPerspective(p); @@ -1630,7 +1539,8 @@ void MainWindow::slotSetCameraPerspectiveToTop(){ //cerr <<"Setting camera view to top"<<endl; } -void MainWindow::slotSetCameraPerspectiveToFront(){ +void MainWindow::slotSetCameraPerspectiveToFront() +{ int p= 2; //FRONT visualisationThread->setCameraPerspective(p); //disable the virtual agent view @@ -1638,7 +1548,8 @@ void MainWindow::slotSetCameraPerspectiveToFront(){ // cerr <<"Setting camera view to FRONT"<<endl; } -void MainWindow::slotSetCameraPerspectiveToSide(){ +void MainWindow::slotSetCameraPerspectiveToSide() +{ int p= 3; //SIDE visualisationThread->setCameraPerspective(p); //disable the virtual agent view @@ -1646,7 +1557,8 @@ void MainWindow::slotSetCameraPerspectiveToSide(){ //cerr <<"Setting camera view to Side"<<endl; } -void MainWindow::slotSetCameraPerspectiveToVirtualAgent(){ +void MainWindow::slotSetCameraPerspectiveToVirtualAgent() +{ bool ok=false; int agent = QInputDialog::getInt(this, tr("choose the agent you want to see the scene through"), tr( @@ -1662,11 +1574,13 @@ void MainWindow::slotSetCameraPerspectiveToVirtualAgent(){ } /// @todo does it work? mem check? -void MainWindow::slotClearGeometry(){ +void MainWindow::slotClearGeometry() +{ visualisationThread->setGeometry(NULL); } -void MainWindow::slotErrorOutput(QString err) { +void MainWindow::slotErrorOutput(QString err) +{ QMessageBox msgBox; msgBox.setText("Error"); msgBox.setInformativeText(err); @@ -1675,30 +1589,33 @@ void MainWindow::slotErrorOutput(QString err) { msgBox.exec(); } -void MainWindow::slotTakeScreenShot(){ +void MainWindow::slotTakeScreenShot() +{ //extern_take_screenshot=true; extern_take_screenshot=!extern_take_screenshot; } /// load settings, parsed from the project file -void MainWindow::loadSettings(){ +void MainWindow::loadSettings() +{ Debug::Error("Not implemented"); } /// start/stop the recording process als png images sequences -void MainWindow::slotRecordPNGsequence(){ - if(!isPlaying){ +void MainWindow::slotRecordPNGsequence() +{ + if(!isPlaying) { slotErrorOutput("Start a video first"); } // get the status from the system settings and toogle it bool status =SystemSettings::getRecordPNGsequence(); - if(status){ + if(status) { ui.actionRecord_PNG_sequences->setText("Record PNG sequence"); - }else{ + } else { ui.actionRecord_PNG_sequences->setText("Stop PNG Recording"); } @@ -1708,17 +1625,20 @@ void MainWindow::slotRecordPNGsequence(){ } /// render a PNG image sequence to an AVI video -void MainWindow::slotRenderPNG2AVI(){ +void MainWindow::slotRenderPNG2AVI() +{ slotErrorOutput("Not Implemented yet, sorry !"); } -void MainWindow::dragEnterEvent(QDragEnterEvent *event){ +void MainWindow::dragEnterEvent(QDragEnterEvent *event) +{ if (event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } -void MainWindow::dropEvent(QDropEvent *event) { +void MainWindow::dropEvent(QDropEvent *event) +{ if (!extern_offline_mode) { slotErrorOutput("online mode, ignoring DnD !"); @@ -1748,14 +1668,16 @@ void MainWindow::dropEvent(QDropEvent *event) { /// show/hide onscreen information /// information include Time and pedestrians left in the facility -void MainWindow::slotShowOnScreenInfos(){ +void MainWindow::slotShowOnScreenInfos() +{ bool value=ui.actionShow_Onscreen_Infos->isChecked(); visualisationThread->setOnscreenInformationVisibility(value); SystemSettings::setOnScreenInfos(value); } /// show/hide the geometry captions -void MainWindow::slotShowHideGeometryCaptions(){ +void MainWindow::slotShowHideGeometryCaptions() +{ bool value=ui.actionShow_Geometry_Captions->isChecked(); visualisationThread->setGeometryLabelsVisibility(value); diff --git a/src/MainWindow.h b/src/MainWindow.h index 2263fbb9cb80c8765643335c6d7a74464722eaf9..41de09d6a5de563e6452bf0920d0fbba2faba628 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -79,9 +79,8 @@ extern bool extern_second_dataset_visible; extern bool extern_third_dataset_visible; -class MainWindow : public QMainWindow -{ - Q_OBJECT +class MainWindow : public QMainWindow { + Q_OBJECT public: MainWindow(QWidget *parent = 0); @@ -90,156 +89,156 @@ public: public Q_SLOTS: - /// display the help modus - void slotHelpAbout(); - - ///quit the program - void slotExit(); - - /// load a file - bool slotLoadFile(); - //void slotLoadProject(); - - /// output an Error - void slotErrorOutput(QString err); - - /// output a warning - //void slotWarningOutput(QString warning); - - /// start the visualisation thread - /// the signal is emitted when the - /// data transfer thread the header and at least one data set - void slotStartVisualisationThread(QString data="",int numberOfAgents=1000,float frameRate=25); - - /// shutdown the visualisation thread - void slotShutdownVisualisationThread(bool); - - /// add a new dataset to the store. - /// note that at most three (3) datasets can be loaded for a visualisation round - bool slotAddDataSet(); - - /// clear all previously added/loaded datasets - void slotClearAllDataset(); - - /// set the camera view angle to TOP/FRONT/SIDE - // TODO: high priority - void slotSetCameraPerspectiveToTop(); - void slotSetCameraPerspectiveToFront(); - void slotSetCameraPerspectiveToSide(); - void slotSetCameraPerspectiveToVirtualAgent(); - - //controls visualisation - void slotStartPlaying(); - void slotStopPlaying(); - void slotRecord(); - void slotFullScreen(bool status); - void slotReset(); - void slotNetworkSettings(); - // void slotToggleVisualisationMode(); - void slotSetOfflineMode(bool status); - void slotSetOnlineMode(bool status); - /// take a screenshot of the rendering window - void slotTakeScreenShot(); - - /// update the status message - void slotCurrentAction(QString msg); - void slotFrameNumber(unsigned long timems); - void slotRunningTime(unsigned long timems); - void slotRenderingTime(int fps); - void slotControlSequence(const char *); - - /// load a geometry file and display it - //void slotLoadGeometry( ); - void slotClearGeometry(); - //void slotLoadParseShowGeometry(QString fileName); - - /// load a geometry sent by the data transfer thread - //void slotLoadGeometryToThread(QString data); - - - /// enable/disable the first pedestrian group - void slotToggleFirstPedestrianGroup(); - /// enable/disable the second pedestrian group - void slotToggleSecondPedestrianGroup(); - /// enable/disable the third pedestrian group - void slotToggleThirdPedestrianGroup(); - - /// show/hides trajectories (leaving a trail) only - void slotShowTrajectoryOnly(); - - /// shows/hide geometry - void slotShowGeometry(); - /// shows/hide geometry - void slotShowHideExits(); - /// shows/hide geometry - void slotShowHideWalls(); + /// display the help modus + void slotHelpAbout(); + + ///quit the program + void slotExit(); + + /// load a file + bool slotLoadFile(); + //void slotLoadProject(); + + /// output an Error + void slotErrorOutput(QString err); + + /// output a warning + //void slotWarningOutput(QString warning); + + /// start the visualisation thread + /// the signal is emitted when the + /// data transfer thread the header and at least one data set + void slotStartVisualisationThread(QString data="",int numberOfAgents=1000,float frameRate=25); + + /// shutdown the visualisation thread + void slotShutdownVisualisationThread(bool); + + /// add a new dataset to the store. + /// note that at most three (3) datasets can be loaded for a visualisation round + bool slotAddDataSet(); + + /// clear all previously added/loaded datasets + void slotClearAllDataset(); + + /// set the camera view angle to TOP/FRONT/SIDE + // TODO: high priority + void slotSetCameraPerspectiveToTop(); + void slotSetCameraPerspectiveToFront(); + void slotSetCameraPerspectiveToSide(); + void slotSetCameraPerspectiveToVirtualAgent(); + + //controls visualisation + void slotStartPlaying(); + void slotStopPlaying(); + void slotRecord(); + void slotFullScreen(bool status); + void slotReset(); + void slotNetworkSettings(); + // void slotToggleVisualisationMode(); + void slotSetOfflineMode(bool status); + void slotSetOnlineMode(bool status); + /// take a screenshot of the rendering window + void slotTakeScreenShot(); + + /// update the status message + void slotCurrentAction(QString msg); + void slotFrameNumber(unsigned long timems); + void slotRunningTime(unsigned long timems); + void slotRenderingTime(int fps); + void slotControlSequence(const char *); + + /// load a geometry file and display it + //void slotLoadGeometry( ); + void slotClearGeometry(); + //void slotLoadParseShowGeometry(QString fileName); + + /// load a geometry sent by the data transfer thread + //void slotLoadGeometryToThread(QString data); + + + /// enable/disable the first pedestrian group + void slotToggleFirstPedestrianGroup(); + /// enable/disable the second pedestrian group + void slotToggleSecondPedestrianGroup(); + /// enable/disable the third pedestrian group + void slotToggleThirdPedestrianGroup(); + + /// show/hides trajectories (leaving a trail) only + void slotShowTrajectoryOnly(); + + /// shows/hide geometry + void slotShowGeometry(); + /// shows/hide geometry + void slotShowHideExits(); + /// shows/hide geometry + void slotShowHideWalls(); /// shows/hide navigation lines void slotShowHideNavLines(); /// shows/hide navigation lines void slotShowHideFloor(); - /// shows/hide geometry captions - void slotShowHideGeometryCaptions(); + /// shows/hide geometry captions + void slotShowHideGeometryCaptions(); - /// show pedestrians only without trail - void slotShowPedestrianOnly(); + /// show pedestrians only without trail + void slotShowPedestrianOnly(); - /// update the playing speed - void slotUpdateSpeedSlider(int newValue); + /// update the playing speed + void slotUpdateSpeedSlider(int newValue); - /// update the position slider - void slotUpdateFrameSlider(int newValue); - void slotFrameSliderPressed(); - void slotFrameSliderReleased(); - //void slotFrameSliderChanged(); + /// update the position slider + void slotUpdateFrameSlider(int newValue); + void slotFrameSliderPressed(); + void slotFrameSliderReleased(); + //void slotFrameSliderChanged(); - /// handle the frame by frame navigation - void slotFramesByFramesNavigation(); - void slotNextFrame(); - void slotPreviousFrame(); + /// handle the frame by frame navigation + void slotFramesByFramesNavigation(); + void slotNextFrame(); + void slotPreviousFrame(); - /// enable/disable the pedestrian captions - void slotShowPedestrianCaption(); + /// enable/disable the pedestrian captions + void slotShowPedestrianCaption(); - /// set the bg color - //void slotPickBackgroundColor(); + /// set the bg color + //void slotPickBackgroundColor(); - /// update the contrast - void slotUpdateContrastSlider(int newValue); + /// update the contrast + void slotUpdateContrastSlider(int newValue); - /// set visualisation mode to 2D - void slotToogle2D(); + /// set visualisation mode to 2D + void slotToogle2D(); - /// set visualisation mode to 3D - void slotToogle3D(); + /// set visualisation mode to 3D + void slotToogle3D(); - /// show / hide the legend - void slotToogleShowLegend(); + /// show / hide the legend + void slotToogleShowLegend(); - void slotToogleShowAxis(); + void slotToogleShowAxis(); - /// change, choose the pedestrian shape - void slotChangePedestrianShape(); + /// change, choose the pedestrian shape + void slotChangePedestrianShape(); - /// start/stop the recording process als png images sequences - void slotRecordPNGsequence(); + /// start/stop the recording process als png images sequences + void slotRecordPNGsequence(); - /// render a PNG image sequence to an AVI video - void slotRenderPNG2AVI(); + /// render a PNG image sequence to an AVI video + void slotRenderPNG2AVI(); - /// adjust the scene background color - void slotChangeBackgroundColor(); + /// adjust the scene background color + void slotChangeBackgroundColor(); - /// change the pedestrian caption mode to automatic - void slotCaptionColorAuto(); + /// change the pedestrian caption mode to automatic + void slotCaptionColorAuto(); - /// change he pedestrian caption color to manual - void slotCaptionColorCustom(); + /// change he pedestrian caption color to manual + void slotCaptionColorCustom(); - /// change the wall color - void slotChangeWallsColor(); + /// change the wall color + void slotChangeWallsColor(); - /// change the exits color - void slotChangeExitsColor(); + /// change the exits color + void slotChangeExitsColor(); /// change the navigation lines color void slotChangeNavLinesColor(); @@ -247,90 +246,90 @@ public Q_SLOTS: /// change the floor color void slotChangeFloorColor(); - /// show/hide onscreen information - /// information include Time and pedestrians left in the facility - void slotShowOnScreenInfos(); + /// show/hide onscreen information + /// information include Time and pedestrians left in the facility + void slotShowOnScreenInfos(); private: - Q_SIGNALS: - void signal_controlSequence(QString); +Q_SIGNALS: + void signal_controlSequence(QString); protected: - virtual void closeEvent(QCloseEvent* event); - void dragEnterEvent(QDragEnterEvent *event); - void dropEvent(QDropEvent *event); + virtual void closeEvent(QCloseEvent* event); + void dragEnterEvent(QDragEnterEvent *event); + void dropEvent(QDropEvent *event); private: - /// load settings, parsed from the project file - /// @todo not implemented - void loadSettings(); + /// load settings, parsed from the project file + /// @todo not implemented + void loadSettings(); - /// performs the necessary cleaning before shutting down the program. - void cleanUp(); + /// performs the necessary cleaning before shutting down the program. + void cleanUp(); - /// reset the system to the very initial state - //void reset(); + /// reset the system to the very initial state + //void reset(); - /// get the value of the tag <tagName> from a QDomNode - QString getTagValueFromElement(QDomNode node, const char * tagName); + /// get the value of the tag <tagName> from a QDomNode + QString getTagValueFromElement(QDomNode node, const char * tagName); - /// parse the geometry Node and return a pointer to geometry object - /// used in online mode only - FacilityGeometry* parseGeometry(QDomNode geoNode); + /// parse the geometry Node and return a pointer to geometry object + /// used in online mode only + FacilityGeometry* parseGeometry(QDomNode geoNode); FacilityGeometry* parseGeometry(QString geometryString); - /** - * parse a shape node and get the initials heights and colors of pedestrians. - * - * @param shapeNode The node to be parsed - * @param groupID 1, 2 or 3 - * @return true if success - */ - bool parsePedestrianShapes(QDomNode shapeNode, int groupID); + /** + * parse a shape node and get the initials heights and colors of pedestrians. + * + * @param shapeNode The node to be parsed + * @param groupID 1, 2 or 3 + * @return true if success + */ + bool parsePedestrianShapes(QDomNode shapeNode, int groupID); - /// reset all graphic element to their initial(default) state - void resetGraphicalElements(); + /// reset all graphic element to their initial(default) state + void resetGraphicalElements(); - /// add a second/third dataset to the visualization data - /// groupID may be 2 or 3 - /// @return false if something went wrong. + /// add a second/third dataset to the visualization data + /// groupID may be 2 or 3 + /// @return false if something went wrong. - bool addPedestrianGroup_old(int groupID, QString fileName=""); - bool addPedestrianGroup(int groupID, QString fileName=""); + bool addPedestrianGroup_old(int groupID, QString fileName=""); + bool addPedestrianGroup(int groupID, QString fileName=""); - ///return true if at least one dataset was loaded - bool anyDatasetLoaded(); + ///return true if at least one dataset was loaded + bool anyDatasetLoaded(); - /// clear the corresponding dataset if it exists - void clearDataSet(int ID); + /// clear the corresponding dataset if it exists + void clearDataSet(int ID); - /// reset all dataset, to the beginning - void resetAllFrameCursor(); + /// reset all dataset, to the beginning + void resetAllFrameCursor(); - /// wait for visualisation thread to terminate - void waitForVisioThread(); + /// wait for visualisation thread to terminate + void waitForVisioThread(); - /// wait for data transfer thread to terminate - void waitForDataThread(); + /// wait for data transfer thread to terminate + void waitForDataThread(); private: Ui::mainwindow ui; - bool isPlaying; - bool isPaused; - bool frameSliderHold; - int numberOfDatasetLoaded; - - Settings* travistoOptions; - ThreadDataTransfer* dataTransferThread; - ThreadVisualisation* visualisationThread; - QLabel *labelCurrentAction; - QLabel *labelFrameNumber; - QLabel *labelRecording; - QLabel *labelMode; + bool isPlaying; + bool isPaused; + bool frameSliderHold; + int numberOfDatasetLoaded; + + Settings* travistoOptions; + ThreadDataTransfer* dataTransferThread; + ThreadVisualisation* visualisationThread; + QLabel *labelCurrentAction; + QLabel *labelFrameNumber; + QLabel *labelRecording; + QLabel *labelMode; }; #endif // TRAVISTO_H diff --git a/src/Message.h b/src/Message.h index ad140935646c1cb9f344dc9237deefd25273f91c..b4e6f8417c3fe63ef53748f9e3811506ce6be150 100644 --- a/src/Message.h +++ b/src/Message.h @@ -35,13 +35,13 @@ class Message { public : - enum message {STACK_EMPTY=1, - STACK_REACHS_BEGINNING, - STACK_REACHS_END, - RESET, - VISUALISATION_TERMINATED + enum message {STACK_EMPTY=1, + STACK_REACHS_BEGINNING, + STACK_REACHS_END, + RESET, + VISUALISATION_TERMINATED - }; + }; }; #endif /* MESSAGE_H_ */ diff --git a/src/Pedestrian.cpp b/src/Pedestrian.cpp index 0ba08551323532bda2ed368e669620cc9f135091..cc719c5b511d107a66437f204693cc4e90448e56 100644 --- a/src/Pedestrian.cpp +++ b/src/Pedestrian.cpp @@ -72,27 +72,28 @@ using namespace std; * @param posY the initial y coordinate * @param posZ the initial z coordinate */ -Pedestrian::Pedestrian(int ID,double posX, double posY, double posZ) { - this->ID = ID; - this->posZ=posZ; - this->posX=posX; - this->posY=posY; - this->pedSize=160; // 160 cm - - this->spaceNeeded=NULL; - //this->assembly=NULL; - this->ellipseActor=NULL; - this->trailActor=NULL; - this->pedestrianAssembly=NULL; - this->assembly3D=NULL; - this->assembly2D=NULL; - this->groupVisibilityStatus=true; - this->trailPlotterLine=NULL; - this->trailPlotterPoint=NULL; - this->caption=NULL; - this->bodyActor=NULL; - this->autoCaptionColorMode=true; - trailPoint.reserve(100); +Pedestrian::Pedestrian(int ID,double posX, double posY, double posZ) +{ + this->ID = ID; + this->posZ=posZ; + this->posX=posX; + this->posY=posY; + this->pedSize=160; // 160 cm + + this->spaceNeeded=NULL; + //this->assembly=NULL; + this->ellipseActor=NULL; + this->trailActor=NULL; + this->pedestrianAssembly=NULL; + this->assembly3D=NULL; + this->assembly2D=NULL; + this->groupVisibilityStatus=true; + this->trailPlotterLine=NULL; + this->trailPlotterPoint=NULL; + this->caption=NULL; + this->bodyActor=NULL; + this->autoCaptionColorMode=true; + trailPoint.reserve(100); } @@ -100,92 +101,99 @@ Pedestrian::Pedestrian(int ID,double posX, double posY, double posZ) { * Parameters less constructor */ -Pedestrian::Pedestrian(int ID){ +Pedestrian::Pedestrian(int ID) +{ - Pedestrian(ID,0,0,0); + Pedestrian(ID,0,0,0); } /** * class Destructor * */ -Pedestrian::~Pedestrian() { +Pedestrian::~Pedestrian() +{ - if(assembly2D) - assembly2D->Delete(); + if(assembly2D) + assembly2D->Delete(); - if(assembly3D) - assembly3D->Delete(); + if(assembly3D) + assembly3D->Delete(); - if(spaceNeeded) - spaceNeeded->Delete(); + if(spaceNeeded) + spaceNeeded->Delete(); - if(ellipseActor) - ellipseActor->Delete(); + if(ellipseActor) + ellipseActor->Delete(); - if(trailActor) - trailActor->Delete(); + if(trailActor) + trailActor->Delete(); - // int i=0; - //free all memory + // int i=0; + //free all memory - //virtualCam->Delete(); - if(bodyActor) - bodyActor->Delete(); - if(caption) - caption->Delete(); + //virtualCam->Delete(); + if(bodyActor) + bodyActor->Delete(); + if(caption) + caption->Delete(); - while(!trailPoint.isEmpty()){ - delete trailPoint.pop(); - } - if(trailPlotterPoint) - delete trailPlotterPoint; - if(trailPlotterLine) - delete trailPlotterLine; + while(!trailPoint.isEmpty()) { + delete trailPoint.pop(); + } + if(trailPlotterPoint) + delete trailPlotterPoint; + if(trailPlotterLine) + delete trailPlotterLine; } /** * * @return the pedestrian ID */ -int Pedestrian::getID() { - return ID; +int Pedestrian::getID() +{ + return ID; } /** * * @return the x-coordinate of the pedestrians */ -double Pedestrian::getX() { - return posX; +double Pedestrian::getX() +{ + return posX; } /** * * @return the y-coordinate of the pedestrian */ -double Pedestrian::getY() { - return posY; +double Pedestrian::getY() +{ + return posY; } /** * * @return the z-coordinate of the pedestrian */ -double Pedestrian::getZ() { - return posZ; +double Pedestrian::getZ() +{ + return posZ; } /*** * create the trail and its actor */ -void Pedestrian::createTrailActor() { - trailPlotterPoint = new PointPlotter(); - trailPlotterLine = new LinePlotter(); - trailActor = vtkAssembly::New(); - //VTK_CREATE(vtkAssembly,trailActor); - trailActor->AddPart(trailPlotterPoint->getActor()); - trailActor->AddPart(trailPlotterLine->getActor()); +void Pedestrian::createTrailActor() +{ + trailPlotterPoint = new PointPlotter(); + trailPlotterLine = new LinePlotter(); + trailActor = vtkAssembly::New(); + //VTK_CREATE(vtkAssembly,trailActor); + trailActor->AddPart(trailPlotterPoint->getActor()); + trailActor->AddPart(trailPlotterLine->getActor()); } /** @@ -193,68 +201,68 @@ void Pedestrian::createTrailActor() { * pedestrian * */ -void Pedestrian::createActor(){ - //createSnowMan(); - //return; - - if(SystemSettings::get2D()){ - CreateActor2D(); - pedestrianAssembly=assembly2D; - } - else - { - CreateActor3D(); - pedestrianAssembly=assembly3D; - } +void Pedestrian::createActor() +{ + //createSnowMan(); + //return; + + if(SystemSettings::get2D()) { + CreateActor2D(); + pedestrianAssembly=assembly2D; + } else { + CreateActor3D(); + pedestrianAssembly=assembly3D; + } } //create the 2D assembly -void Pedestrian::CreateActor2D(){ - double headRadius = 10.0; - double ambient=0.15; - double diffuse=1; - double specular=1; - - assembly2D = vtkAssembly::New(); - - {//private sphere - spaceNeeded = vtkDiskSource::New(); - //spaceNeeded->SetRadialResolution(30); - spaceNeeded->SetCircumferentialResolution(5); - spaceNeeded->SetInnerRadius(0); - //spaceNeeded->SetOuterRadius(bodyRadius); - spaceNeeded->SetOuterRadius(2); - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(spaceNeeded->GetOutputPort()); - //spaceNeeded->Delete(); - ellipseActor = vtkActor::New(); - ellipseActor->SetMapper(mapper); - mapper->Delete(); - // they all start with red color. - ellipseActor->GetProperty()->SetColor(1.0,0.0,0.0); - - //set the ellipse a little bit higher than the ground to - // eliminate interaction with the floor color. - ellipseActor->SetPosition(0,0,7); - // actor->GetProperty()->SetSpecular(specular); - // actor->GetProperty()->SetDiffuse(diffuse); - // actor->GetProperty()->SetAmbient(ambient); - - // this actor belongs to both 2D and 3D - //assembly3D->AddPart(ellipseActor); - assembly2D->AddPart(ellipseActor); - //ellipseActor->Delete(); - - //lookup table - vtkLookupTable* lut = vtkLookupTable::New(); - lut->SetHueRange(0.0,0.470); - //lut->SetSaturationRange(0,0); - lut->SetValueRange(1.0,1.0); - lut->SetNumberOfTableValues(256); - lut->Build(); - mapper->SetLookupTable(lut); - lut->Delete(); - } +void Pedestrian::CreateActor2D() +{ + //double headRadius = 10.0; + //double ambient=0.15; + //double diffuse=1; + //double specular=1; + + assembly2D = vtkAssembly::New(); + + { + //private sphere + spaceNeeded = vtkDiskSource::New(); + //spaceNeeded->SetRadialResolution(30); + spaceNeeded->SetCircumferentialResolution(5); + spaceNeeded->SetInnerRadius(0); + //spaceNeeded->SetOuterRadius(bodyRadius); + spaceNeeded->SetOuterRadius(2); + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(spaceNeeded->GetOutputPort()); + //spaceNeeded->Delete(); + ellipseActor = vtkActor::New(); + ellipseActor->SetMapper(mapper); + mapper->Delete(); + // they all start with red color. + ellipseActor->GetProperty()->SetColor(1.0,0.0,0.0); + //set the ellipse a little bit higher than the ground to + // eliminate interaction with the floor color. + ellipseActor->SetPosition(0,0,7); + // actor->GetProperty()->SetSpecular(specular); + // actor->GetProperty()->SetDiffuse(diffuse); + // actor->GetProperty()->SetAmbient(ambient); + + // this actor belongs to both 2D and 3D + //assembly3D->AddPart(ellipseActor); + assembly2D->AddPart(ellipseActor); + //ellipseActor->Delete(); + + //lookup table + vtkLookupTable* lut = vtkLookupTable::New(); + lut->SetHueRange(0.0,0.470); + //lut->SetSaturationRange(0,0); + lut->SetValueRange(1.0,1.0); + lut->SetNumberOfTableValues(256); + lut->Build(); + mapper->SetLookupTable(lut); + lut->Delete(); + } // {//head // {//face @@ -320,183 +328,190 @@ void Pedestrian::CreateActor2D(){ // //actor->Delete(); // } //} - {//caption - - char txt[10]; - sprintf(txt,"%d",this->ID+1); - caption = vtkTextActor3D ::New(); - caption->SetVisibility(false); - caption->SetInput(txt); - // set the properties of the caption - //FARBE - vtkTextProperty* tprop = caption->GetTextProperty(); - tprop->SetFontFamilyToArial(); - tprop->BoldOn(); - //tprop->ShadowOn(); - tprop->SetLineSpacing(1.0); - tprop->SetFontSize(SystemSettings::getPedestrianCaptionSize()); - - tprop->SetColor(0.0,0.0,0.0); - //tprop->SetShadowOffset(2,2); - - caption->SetPosition( 0, 0,20); //20 cm on the ground - assembly2D->AddPart(caption); - - } - assembly2D->SetPosition( posX, posY, posZ); + { + //caption + + char txt[10]; + sprintf(txt,"%d",this->ID+1); + caption = vtkTextActor3D ::New(); + caption->SetVisibility(false); + caption->SetInput(txt); + // set the properties of the caption + //FARBE + vtkTextProperty* tprop = caption->GetTextProperty(); + tprop->SetFontFamilyToArial(); + tprop->BoldOn(); + //tprop->ShadowOn(); + tprop->SetLineSpacing(1.0); + tprop->SetFontSize(SystemSettings::getPedestrianCaptionSize()); + + tprop->SetColor(0.0,0.0,0.0); + //tprop->SetShadowOffset(2,2); + + caption->SetPosition( 0, 0,20); //20 cm on the ground + assembly2D->AddPart(caption); + + } + assembly2D->SetPosition( posX, posY, posZ); } -void Pedestrian::CreateActor3D(){ - double bodyRadius = 20.0; - double headRadius = 8.0; - double chestThikness=20.0/1.0; - double ambient=0.15; - double diffuse=1; - double specular=1; - - assembly3D = vtkAssembly::New(); - - - { //body - vtkSphereSource* body = vtkSphereSource::New(); - body->SetEndPhi(90.0); - body->SetStartPhi(0); - body->SetThetaResolution(10); - body->SetRadius(bodyRadius); - - // create mapper - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(body->GetOutputPort()); - body->Delete(); - // create actor - double er[]={chestThikness/bodyRadius,1,pedSize/bodyRadius}; - //double er[]={bodyRadius/bodyRadius,pedSize/bodyRadius,chestThikness/bodyRadius}; - - bodyActor = vtkActor::New(); - bodyActor->SetMapper(mapper); - mapper->Delete(); - bodyActor->SetScale(er); - //bodyActor->GetProperty()->SetColor(pedsColors); - bodyActor->GetProperty()->SetColor(pedsColors[0]/255.0,pedsColors[1]/255.0,pedsColors[2]/255.0); - - //actor->GetProperty()->SetLighting(true); - bodyActor->GetProperty()->SetSpecular(specular); - bodyActor->GetProperty()->SetDiffuse(diffuse); - bodyActor->GetProperty()->SetAmbient(ambient); - - //cout << "diffuse: "<<actor->GetProperty()->GetDiffuse()<<" [" << actor->GetProperty()->GetDiffuseMinValue()<<" , "<<actor->GetProperty()->GetDiffuseMaxValue() << " ]"<<endl; - //cout << "ambiant: "<<actor->GetProperty()->GetAmbient()<<" [" << actor->GetProperty()->GetAmbientMinValue()<<" , "<<actor->GetProperty()->GetAmbientMaxValue() << " ]"<<endl; - //cout << "specular:"<<actor->GetProperty()->GetSpecular()<<" [" << actor->GetProperty()->GetSpecularMinValue()<<" , "<<actor->GetProperty()->GetSpecularMaxValue()<< " ]"<<endl; - assembly3D->AddPart(bodyActor); - //bodyActor->Delete(); - } - {//caption - - char txt[10]; - sprintf(txt,"%d",this->ID+1); - caption = vtkTextActor3D ::New(); - caption->SetVisibility(false); - caption->SetInput(txt); - // set the properties of the caption - //FARBE - vtkTextProperty* tprop = caption->GetTextProperty(); - tprop->SetFontFamilyToArial(); - tprop->BoldOn(); - //tprop->ShadowOn(); - tprop->SetLineSpacing(1.0); - tprop->SetFontSize(SystemSettings::getPedestrianCaptionSize()); - - tprop->SetColor(0.0,0.0,0.0); - //tprop->SetShadowOffset(2,2); - - //vtkActor2D* test=vtkActor2D::New(); - //assembly3D->AddPart(test); - //rotate the caption - //caption->RotateX(90); - caption->SetPosition( 0, 0,pedSize+20); - assembly3D->AddPart(caption); - - } - { //head - {//face - vtkSphereSource* head = vtkSphereSource::New(); - head->SetThetaResolution(5); - head->SetStartTheta(270); - head->SetEndTheta(90); - head->SetRadius(headRadius); - //head->SetCenter(0,0,bodyRadius+2); - head->SetCenter(0,0,pedSize+2); - // create mapper - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(head->GetOutputPort()); - head->Delete(); - //mapper->SetColorModeToMapScalars(); - //mapper->SetScalarModeToUsePointData(); - - // create actor - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(.90,.90,1.0); - actor->GetProperty()->SetSpecular(specular); - actor->GetProperty()->SetDiffuse(diffuse); - actor->GetProperty()->SetAmbient(ambient-.10); - - assembly3D->AddPart(actor); - actor->Delete(); - } - //back - { - vtkSphereSource* head = vtkSphereSource::New(); - head->SetThetaResolution(5); - head->SetStartTheta(90); - head->SetEndTheta(270); - head->SetRadius(headRadius); - head->SetCenter(0,0,pedSize+2); - // create mapper - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(head->GetOutputPort()); - head->Delete(); - //mapper->SetColorModeToMapScalars(); - //mapper->SetScalarModeToUsePointData(); - - // create actor - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(0.35,0.35,0.35); - actor->GetProperty()->SetSpecular(specular); - actor->GetProperty()->SetDiffuse(diffuse); - actor->GetProperty()->SetAmbient(ambient-.10); - - assembly3D->AddPart(actor); - actor->Delete(); - } - - } - { //Nose - vtkConeSource* nose = vtkConeSource::New(); - nose->SetCenter((headRadius+nose->GetHeight()/2) ,0,pedSize+2); - nose->SetHeight(2); - nose->SetRadius(.5); - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(nose->GetOutputPort()); - nose->Delete(); - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(1.0,1.0,0.0); - actor->GetProperty()->SetSpecular(specular); - actor->GetProperty()->SetDiffuse(diffuse); - actor->GetProperty()->SetAmbient(ambient); - - assembly3D->AddPart(actor); - actor->Delete(); - } - - //assembly3D->SetScale(2.500); - assembly3D->RotateZ(0.0); - assembly3D->SetPosition( posX, posY, posZ); +void Pedestrian::CreateActor3D() +{ + double bodyRadius = 20.0; + double headRadius = 8.0; + double chestThikness=20.0/1.0; + double ambient=0.15; + double diffuse=1; + double specular=1; + + assembly3D = vtkAssembly::New(); + + + { + //body + vtkSphereSource* body = vtkSphereSource::New(); + body->SetEndPhi(90.0); + body->SetStartPhi(0); + body->SetThetaResolution(10); + body->SetRadius(bodyRadius); + + // create mapper + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(body->GetOutputPort()); + body->Delete(); + // create actor + double er[]= {chestThikness/bodyRadius,1,pedSize/bodyRadius}; + //double er[]={bodyRadius/bodyRadius,pedSize/bodyRadius,chestThikness/bodyRadius}; + + bodyActor = vtkActor::New(); + bodyActor->SetMapper(mapper); + mapper->Delete(); + bodyActor->SetScale(er); + //bodyActor->GetProperty()->SetColor(pedsColors); + bodyActor->GetProperty()->SetColor(pedsColors[0]/255.0,pedsColors[1]/255.0,pedsColors[2]/255.0); + + //actor->GetProperty()->SetLighting(true); + bodyActor->GetProperty()->SetSpecular(specular); + bodyActor->GetProperty()->SetDiffuse(diffuse); + bodyActor->GetProperty()->SetAmbient(ambient); + + //cout << "diffuse: "<<actor->GetProperty()->GetDiffuse()<<" [" << actor->GetProperty()->GetDiffuseMinValue()<<" , "<<actor->GetProperty()->GetDiffuseMaxValue() << " ]"<<endl; + //cout << "ambiant: "<<actor->GetProperty()->GetAmbient()<<" [" << actor->GetProperty()->GetAmbientMinValue()<<" , "<<actor->GetProperty()->GetAmbientMaxValue() << " ]"<<endl; + //cout << "specular:"<<actor->GetProperty()->GetSpecular()<<" [" << actor->GetProperty()->GetSpecularMinValue()<<" , "<<actor->GetProperty()->GetSpecularMaxValue()<< " ]"<<endl; + assembly3D->AddPart(bodyActor); + //bodyActor->Delete(); + } + { + //caption + + char txt[10]; + sprintf(txt,"%d",this->ID+1); + caption = vtkTextActor3D ::New(); + caption->SetVisibility(false); + caption->SetInput(txt); + // set the properties of the caption + //FARBE + vtkTextProperty* tprop = caption->GetTextProperty(); + tprop->SetFontFamilyToArial(); + tprop->BoldOn(); + //tprop->ShadowOn(); + tprop->SetLineSpacing(1.0); + tprop->SetFontSize(SystemSettings::getPedestrianCaptionSize()); + + tprop->SetColor(0.0,0.0,0.0); + //tprop->SetShadowOffset(2,2); + + //vtkActor2D* test=vtkActor2D::New(); + //assembly3D->AddPart(test); + //rotate the caption + //caption->RotateX(90); + caption->SetPosition( 0, 0,pedSize+20); + assembly3D->AddPart(caption); + + } + { + //head + { + //face + vtkSphereSource* head = vtkSphereSource::New(); + head->SetThetaResolution(5); + head->SetStartTheta(270); + head->SetEndTheta(90); + head->SetRadius(headRadius); + //head->SetCenter(0,0,bodyRadius+2); + head->SetCenter(0,0,pedSize+2); + // create mapper + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(head->GetOutputPort()); + head->Delete(); + //mapper->SetColorModeToMapScalars(); + //mapper->SetScalarModeToUsePointData(); + + // create actor + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(.90,.90,1.0); + actor->GetProperty()->SetSpecular(specular); + actor->GetProperty()->SetDiffuse(diffuse); + actor->GetProperty()->SetAmbient(ambient-.10); + + assembly3D->AddPart(actor); + actor->Delete(); + } + //back + { + vtkSphereSource* head = vtkSphereSource::New(); + head->SetThetaResolution(5); + head->SetStartTheta(90); + head->SetEndTheta(270); + head->SetRadius(headRadius); + head->SetCenter(0,0,pedSize+2); + // create mapper + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(head->GetOutputPort()); + head->Delete(); + //mapper->SetColorModeToMapScalars(); + //mapper->SetScalarModeToUsePointData(); + + // create actor + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(0.35,0.35,0.35); + actor->GetProperty()->SetSpecular(specular); + actor->GetProperty()->SetDiffuse(diffuse); + actor->GetProperty()->SetAmbient(ambient-.10); + + assembly3D->AddPart(actor); + actor->Delete(); + } + + } + { + //Nose + vtkConeSource* nose = vtkConeSource::New(); + nose->SetCenter((headRadius+nose->GetHeight()/2) ,0,pedSize+2); + nose->SetHeight(2); + nose->SetRadius(.5); + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(nose->GetOutputPort()); + nose->Delete(); + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(1.0,1.0,0.0); + actor->GetProperty()->SetSpecular(specular); + actor->GetProperty()->SetDiffuse(diffuse); + actor->GetProperty()->SetAmbient(ambient); + + assembly3D->AddPart(actor); + actor->Delete(); + } + + //assembly3D->SetScale(2.500); + assembly3D->RotateZ(0.0); + assembly3D->SetPosition( posX, posY, posZ); } /** @@ -504,727 +519,757 @@ void Pedestrian::CreateActor3D(){ * pedestrian * */ -void Pedestrian::createSnowMan(){ - this->pedSize=100; // very small snowman - double bodyRadius = 30.0; - double headRadius = 10.0; - double headCenter[3]={0,0,pedSize-headRadius+5}; - double chestCenter[3]={0,0,0}; - double bodyCenter[3]={0,0,0}; - double chestRadius= 20.0; - double ambient=0.15; - double diffuse=1; - double specular=1; - - //double eyeColor[3]={217.0/255,110.0/255,163.0/255}; - - double eyeColor[3]={100.0/255,100.0/255,100.0/255}; - - double mouthColor[3]={204.0/255,51.0/255,51.0/255}; - double hatColor[3]={0.8,0.8,0.8}; - - assembly3D = vtkAssembly::New(); - assembly2D = vtkAssembly::New(); - - { // hat - double pos[3]; - { - VTK_CREATE(vtkCylinderSource,src); - src->SetHeight(20); - src->SetRadius(8); - src->SetResolution(20); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->SetPosition(0, 0,pedSize+(src->GetHeight()/2)); - actor->GetProperty()->SetColor(hatColor); - actor->RotateX(90); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - actor->GetPosition(pos); - } - { - VTK_CREATE(vtkCylinderSource,src); - src->SetHeight(2); - src->SetRadius(8.1); - src->SetResolution(20); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->SetPosition(pos); - actor->GetProperty()->SetColor(1,0.1,0.1); - actor->RotateX(90); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - { - VTK_CREATE(vtkCylinderSource,src); - src->SetHeight(1); - src->SetRadius(15); - src->SetResolution(20); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->SetPosition(0, 0, pedSize); - actor->GetProperty()->SetColor(hatColor); - actor->RotateX(90); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - } - - - { //head - {//face - vtkSphereSource* head = vtkSphereSource::New(); - head->SetThetaResolution(5); - head->SetStartTheta(270); - head->SetEndTheta(90); - head->SetRadius(headRadius); - // create mapper - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(head->GetOutputPort()); - head->Delete(); - - // create actor - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(.90,.90,1.0); - actor->SetPosition(headCenter); - //actor->GetProperty()->SetSpecular(specular); - //actor->GetProperty()->SetDiffuse(diffuse); - actor->GetProperty()->SetAmbient(ambient); - - assembly3D->AddPart(actor); - actor->Delete(); - } - //back - { - vtkSphereSource* head = vtkSphereSource::New(); - head->SetThetaResolution(5); - head->SetStartTheta(90); - head->SetEndTheta(270); - head->SetRadius(headRadius); - // create mapper - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(head->GetOutputPort()); - head->Delete(); - - // create actor - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(0.935,0.935,0.935); - //actor->GetProperty()->SetSpecular(specular); - //actor->GetProperty()->SetDiffuse(diffuse); - actor->GetProperty()->SetAmbient(ambient); - actor->SetPosition(headCenter); - - assembly3D->AddPart(actor); - actor->Delete(); - } - - { // eyes - float pi_over_4=0.6; - float radius=headRadius-2; - - {//left eye - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(2); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(eyeColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(radius*cos(pi_over_4),radius*sin(pi_over_4),headCenter[2]); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - - {//right eye - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(2); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(eyeColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - //actor->SetPosition(radius*sin(3*pi_over_4),radius*cos(3*pi_over_4),headCenter[2]); - - actor->SetPosition(radius*cos(-pi_over_4),radius*sin(-pi_over_4),headCenter[2]); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - - } - - { //Nose - vtkConeSource* nose = vtkConeSource::New(); - nose->SetHeight(8); - nose->SetRadius(2); - nose->SetResolution(30); - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(nose->GetOutputPort()); - nose->Delete(); - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(1.0,154.0/255.0,0.0); - //actor->GetProperty()->SetSpecular(specular); - //actor->GetProperty()->SetDiffuse(diffuse); - //actor->GetProperty()->SetAmbient(ambient); - actor->SetPosition((headRadius) ,0,pedSize-headRadius+2); - - assembly3D->AddPart(actor); - actor->Delete(); - } - - {//mouth - - {//first - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(135.0); // 0 to 180 - - pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); - pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); - pos[2]=headCenter[2]+headRadius*cos(theta); - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(1); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(mouthColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {//second - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(10.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(130.0); // 0 to 180 - - pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); - pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); - pos[2]=headCenter[2]+headRadius*cos(theta); - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(1); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(mouthColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {//third - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(-10.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(130.0); // 0 to 180 - - pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); - pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); - pos[2]=headCenter[2]+headRadius*cos(theta); - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(1); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(mouthColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {//fourth - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(20.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(125.0); // 0 to 180 - - pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); - pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); - pos[2]=headCenter[2]+headRadius*cos(theta); - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(1); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(mouthColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {//fifth - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(-20.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(125.0); // 0 to 180 - - pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); - pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); - pos[2]=headCenter[2]+headRadius*cos(theta); - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(1); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(mouthColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {//sixth - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(25.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(115.0); // 0 to 180 - - pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); - pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); - pos[2]=headCenter[2]+headRadius*cos(theta); - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(1); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(mouthColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {//seventh - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(-25.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(115.0); // 0 to 180 - - pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); - pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); - pos[2]=headCenter[2]+headRadius*cos(theta); - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(1); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(mouthColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - - } - } - - {// chest - { - vtkSphereSource* src = vtkSphereSource::New(); - src->SetRadius(chestRadius); - src->SetThetaResolution(10); - src->SetPhiResolution(10); - - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(src->GetOutputPort()); - src->Delete(); - - vtkActor* actor = vtkActor::New(); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(1,1,1); - actor->GetProperty()->SetAmbient(ambient); - //actor->GetProperty()->SetDiffuse(0.0); - float scale=0.90; - actor->SetScale(1,1,scale); - actor->SetPosition(0,0,headCenter[2]-headRadius-chestRadius*scale+2); - actor->GetPosition(chestCenter); - - actor->SetMapper(mapper); - mapper->Delete(); - assembly3D->AddPart(actor); - actor->Delete(); - } - {// first knob 1 - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(30.0); // 0 to 180 - - pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); - pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); - pos[2]=chestCenter[2]+chestRadius*cos(theta)-2; - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(2); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(eyeColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {// first knob 2 - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(60.0); // 0 to 180 - - pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); - pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); - pos[2]=chestCenter[2]+chestRadius*cos(theta)-2; - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(2); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(eyeColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {// first knob 3 - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(90.0); // 0 to 180 - - pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); - pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); - pos[2]=chestCenter[2]+chestRadius*cos(theta)-0; - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(2); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(eyeColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - {// first knob 4 - double pos[3]; - float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 - float theta=vtkMath::RadiansFromDegrees(120.0); // 0 to 180 - - pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); - pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); - pos[2]=chestCenter[2]+chestRadius*cos(theta)-0; - - VTK_CREATE(vtkSphereSource,src); - src->SetRadius(2); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(src->GetOutputPort()); - - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetLighting(true); - actor->GetProperty()->SetColor(eyeColor); - //actor->GetProperty()->SetAmbient(0.2); - //actor->GetProperty()->SetDiffuse(0.8); - actor->SetPosition(pos); - - actor->SetMapper(mapper); - assembly3D->AddPart(actor); - } - - } - { //body - vtkSphereSource* body = vtkSphereSource::New(); - //body->SetEndPhi(90.0); - //body->SetStartPhi(0); - body->SetThetaResolution(10); - body->SetThetaResolution(10); - - body->SetRadius(bodyRadius); - - // create mapper - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(body->GetOutputPort()); - body->Delete(); - // create actor - //double er[]={chestThikness/bodyRadius,1,pedSize/bodyRadius}; - //double er[]={bodyRadius/bodyRadius,pedSize/bodyRadius,chestThikness/bodyRadius}; - - bodyCenter[2]=chestCenter[2]-chestRadius-body->GetRadius()+10; - - bodyActor = vtkActor::New(); - bodyActor->SetMapper(mapper); - mapper->Delete(); - bodyActor->SetScale(1,1,0.90); - // bodyActor->GetProperty()->SetColor(pedsColors[0]/255.0,pedsColors[1]/255.0,pedsColors[2]/255.0); - bodyActor->GetProperty()->SetColor(1,1,1); - - //actor->GetProperty()->SetLighting(true); - //bodyActor->GetProperty()->SetSpecular(specular); - //bodyActor->GetProperty()->SetDiffuse(diffuse); - bodyActor->GetProperty()->SetAmbient(ambient); - bodyActor->SetPosition(0,0,bodyCenter[2]); - - assembly3D->AddPart(bodyActor); - } - - - - assembly3D->SetPosition( posX, posY, posZ); - - //create the 2D assembly - {//private sphere - spaceNeeded = vtkDiskSource::New(); - //spaceNeeded->SetRadialResolution(30); - spaceNeeded->SetCircumferentialResolution(5); - spaceNeeded->SetInnerRadius(0); - //spaceNeeded->SetOuterRadius(bodyRadius); - spaceNeeded->SetOuterRadius(2); - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(spaceNeeded->GetOutputPort()); - //spaceNeeded->Delete(); - ellipseActor = vtkActor::New(); - ellipseActor->SetMapper(mapper); - mapper->Delete(); - // they all start with red color. - ellipseActor->GetProperty()->SetColor(1.0,0.0,0.0); - - //set the ellipse a little bit higher than the ground to - // eliminate interaction with the floor color. - ellipseActor->SetPosition(0,0,47); - - // this actor belongs to both 2D and 3D - //assembly3D->AddPart(ellipseActor); - assembly2D->AddPart(ellipseActor); - //ellipseActor->Delete(); - - //lookup table - vtkLookupTable* lut = vtkLookupTable::New(); - lut->SetHueRange(0.0,0.470); - //lut->SetSaturationRange(0,0); - lut->SetValueRange(1.0,1.0); - lut->SetNumberOfTableValues(256); - lut->Build(); - mapper->SetLookupTable(lut); - lut->Delete(); - } - - {//head - {//face - VTK_CREATE(vtkSphereSource,head); - head->SetThetaResolution(20); - head->SetStartTheta(270); - head->SetEndTheta(90); - head->SetRadius(headRadius); - //head->SetCenter(0,0,bodyRadius+2); - //head->SetCenter(0,0,pedSize+2); - // create mapper - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(head->GetOutputPort()); - - // create actor - VTK_CREATE(vtkActor,actor); - actor->SetMapper(mapper); - //mapper->Delete(); - actor->GetProperty()->SetColor(.90,.90,1.0); - actor->GetProperty()->SetSpecular(specular); - actor->GetProperty()->SetDiffuse(diffuse); - actor->GetProperty()->SetAmbient(ambient-.10); - - //assembly2D->AddPart(actor); - //actor->Delete(); - } - //back - { - VTK_CREATE(vtkSphereSource,head); - head->SetThetaResolution(20); - head->SetStartTheta(90); - head->SetEndTheta(270); - head->SetRadius(headRadius); - //head->SetCenter(0,0,pedSize+2); - // create mapper - VTK_CREATE(vtkPolyDataMapper,mapper); - - mapper->SetInputConnection(head->GetOutputPort()); - - // create actor - VTK_CREATE(vtkActor,actor); - - actor->SetMapper(mapper); - //mapper->Delete(); - actor->GetProperty()->SetColor(0.35,0.35,0.35); - actor->GetProperty()->SetSpecular(specular); - actor->GetProperty()->SetDiffuse(diffuse); - actor->GetProperty()->SetAmbient(ambient-.10); - - //assembly2D->AddPart(actor); - //actor->Delete(); - } - - assembly2D->SetPosition( posX, posY, posZ); - } - - {//caption - - char txt[10]; - sprintf(txt,"%d",this->ID+1); - caption = vtkTextActor3D ::New(); - caption->SetVisibility(false); - caption->SetInput(txt); - // set the properties of the caption - //FARBE - vtkTextProperty* tprop = caption->GetTextProperty(); - tprop->SetFontFamilyToArial(); - tprop->BoldOn(); - //tprop->ShadowOn(); - tprop->SetLineSpacing(1.0); - tprop->SetFontSize(SystemSettings::getPedestrianCaptionSize()); - - tprop->SetColor(0.0,0.0,0.0); - //tprop->SetShadowOffset(2,2); - if(SystemSettings::get2D()){ - caption->SetPosition( 0, 0,20); //20 cm on the ground - //assembly2D->AddPart(caption); - - }else{ - //vtkActor2D* test=vtkActor2D::New(); - //assembly3D->AddPart(test); - - //rotate the caption - //caption->RotateX(90); - caption->SetPosition( 0, 0,pedSize+20); - //assembly3D->AddPart(caption); - } - - } - if(SystemSettings::get2D())pedestrianAssembly=assembly2D; - else pedestrianAssembly=assembly3D; +void Pedestrian::createSnowMan() +{ + this->pedSize=100; // very small snowman + double bodyRadius = 30.0; + double headRadius = 10.0; + double headCenter[3]= {0,0,pedSize-headRadius+5}; + double chestCenter[3]= {0,0,0}; + double bodyCenter[3]= {0,0,0}; + double chestRadius= 20.0; + double ambient=0.15; + double diffuse=1; + double specular=1; + + //double eyeColor[3]={217.0/255,110.0/255,163.0/255}; + + double eyeColor[3]= {100.0/255,100.0/255,100.0/255}; + + double mouthColor[3]= {204.0/255,51.0/255,51.0/255}; + double hatColor[3]= {0.8,0.8,0.8}; + + assembly3D = vtkAssembly::New(); + assembly2D = vtkAssembly::New(); + + { + // hat + double pos[3]; + { + VTK_CREATE(vtkCylinderSource,src); + src->SetHeight(20); + src->SetRadius(8); + src->SetResolution(20); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->SetPosition(0, 0,pedSize+(src->GetHeight()/2)); + actor->GetProperty()->SetColor(hatColor); + actor->RotateX(90); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + actor->GetPosition(pos); + } + { + VTK_CREATE(vtkCylinderSource,src); + src->SetHeight(2); + src->SetRadius(8.1); + src->SetResolution(20); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->SetPosition(pos); + actor->GetProperty()->SetColor(1,0.1,0.1); + actor->RotateX(90); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + VTK_CREATE(vtkCylinderSource,src); + src->SetHeight(1); + src->SetRadius(15); + src->SetResolution(20); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->SetPosition(0, 0, pedSize); + actor->GetProperty()->SetColor(hatColor); + actor->RotateX(90); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + } + + + { + //head + { + //face + vtkSphereSource* head = vtkSphereSource::New(); + head->SetThetaResolution(5); + head->SetStartTheta(270); + head->SetEndTheta(90); + head->SetRadius(headRadius); + // create mapper + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(head->GetOutputPort()); + head->Delete(); + + // create actor + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(.90,.90,1.0); + actor->SetPosition(headCenter); + //actor->GetProperty()->SetSpecular(specular); + //actor->GetProperty()->SetDiffuse(diffuse); + actor->GetProperty()->SetAmbient(ambient); + + assembly3D->AddPart(actor); + actor->Delete(); + } + //back + { + vtkSphereSource* head = vtkSphereSource::New(); + head->SetThetaResolution(5); + head->SetStartTheta(90); + head->SetEndTheta(270); + head->SetRadius(headRadius); + // create mapper + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(head->GetOutputPort()); + head->Delete(); + + // create actor + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(0.935,0.935,0.935); + //actor->GetProperty()->SetSpecular(specular); + //actor->GetProperty()->SetDiffuse(diffuse); + actor->GetProperty()->SetAmbient(ambient); + actor->SetPosition(headCenter); + + assembly3D->AddPart(actor); + actor->Delete(); + } + + { + // eyes + float pi_over_4=0.6; + float radius=headRadius-2; + + { + //left eye + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(2); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(eyeColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(radius*cos(pi_over_4),radius*sin(pi_over_4),headCenter[2]); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + + { + //right eye + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(2); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(eyeColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + //actor->SetPosition(radius*sin(3*pi_over_4),radius*cos(3*pi_over_4),headCenter[2]); + + actor->SetPosition(radius*cos(-pi_over_4),radius*sin(-pi_over_4),headCenter[2]); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + + } + + { + //Nose + vtkConeSource* nose = vtkConeSource::New(); + nose->SetHeight(8); + nose->SetRadius(2); + nose->SetResolution(30); + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(nose->GetOutputPort()); + nose->Delete(); + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(1.0,154.0/255.0,0.0); + //actor->GetProperty()->SetSpecular(specular); + //actor->GetProperty()->SetDiffuse(diffuse); + //actor->GetProperty()->SetAmbient(ambient); + actor->SetPosition((headRadius) ,0,pedSize-headRadius+2); + + assembly3D->AddPart(actor); + actor->Delete(); + } + + { + //mouth + + { + //first + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(135.0); // 0 to 180 + + pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); + pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); + pos[2]=headCenter[2]+headRadius*cos(theta); + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(1); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(mouthColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + //second + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(10.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(130.0); // 0 to 180 + + pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); + pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); + pos[2]=headCenter[2]+headRadius*cos(theta); + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(1); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(mouthColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + //third + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(-10.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(130.0); // 0 to 180 + + pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); + pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); + pos[2]=headCenter[2]+headRadius*cos(theta); + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(1); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(mouthColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + //fourth + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(20.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(125.0); // 0 to 180 + + pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); + pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); + pos[2]=headCenter[2]+headRadius*cos(theta); + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(1); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(mouthColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + //fifth + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(-20.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(125.0); // 0 to 180 + + pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); + pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); + pos[2]=headCenter[2]+headRadius*cos(theta); + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(1); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(mouthColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + //sixth + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(25.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(115.0); // 0 to 180 + + pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); + pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); + pos[2]=headCenter[2]+headRadius*cos(theta); + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(1); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(mouthColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + //seventh + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(-25.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(115.0); // 0 to 180 + + pos[0]=headCenter[0]+headRadius*sin(theta)*cos(phi); + pos[1]=headCenter[1]+headRadius*sin(theta)*sin(phi); + pos[2]=headCenter[2]+headRadius*cos(theta); + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(1); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(mouthColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + + } + } + + { + // chest + { + vtkSphereSource* src = vtkSphereSource::New(); + src->SetRadius(chestRadius); + src->SetThetaResolution(10); + src->SetPhiResolution(10); + + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(src->GetOutputPort()); + src->Delete(); + + vtkActor* actor = vtkActor::New(); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(1,1,1); + actor->GetProperty()->SetAmbient(ambient); + //actor->GetProperty()->SetDiffuse(0.0); + float scale=0.90; + actor->SetScale(1,1,scale); + actor->SetPosition(0,0,headCenter[2]-headRadius-chestRadius*scale+2); + actor->GetPosition(chestCenter); + + actor->SetMapper(mapper); + mapper->Delete(); + assembly3D->AddPart(actor); + actor->Delete(); + } + { + // first knob 1 + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(30.0); // 0 to 180 + + pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); + pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); + pos[2]=chestCenter[2]+chestRadius*cos(theta)-2; + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(2); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(eyeColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + // first knob 2 + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(60.0); // 0 to 180 + + pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); + pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); + pos[2]=chestCenter[2]+chestRadius*cos(theta)-2; + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(2); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(eyeColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + // first knob 3 + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(90.0); // 0 to 180 + + pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); + pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); + pos[2]=chestCenter[2]+chestRadius*cos(theta)-0; + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(2); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(eyeColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + { + // first knob 4 + double pos[3]; + float phi=vtkMath::RadiansFromDegrees(0.0); // 0 to 360 + float theta=vtkMath::RadiansFromDegrees(120.0); // 0 to 180 + + pos[0]=chestCenter[0]+chestRadius*sin(theta)*cos(phi); + pos[1]=chestCenter[1]+chestRadius*sin(theta)*sin(phi); + pos[2]=chestCenter[2]+chestRadius*cos(theta)-0; + + VTK_CREATE(vtkSphereSource,src); + src->SetRadius(2); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(src->GetOutputPort()); + + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetLighting(true); + actor->GetProperty()->SetColor(eyeColor); + //actor->GetProperty()->SetAmbient(0.2); + //actor->GetProperty()->SetDiffuse(0.8); + actor->SetPosition(pos); + + actor->SetMapper(mapper); + assembly3D->AddPart(actor); + } + + } + { + //body + vtkSphereSource* body = vtkSphereSource::New(); + //body->SetEndPhi(90.0); + //body->SetStartPhi(0); + body->SetThetaResolution(10); + body->SetThetaResolution(10); + + body->SetRadius(bodyRadius); + + // create mapper + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(body->GetOutputPort()); + body->Delete(); + // create actor + //double er[]={chestThikness/bodyRadius,1,pedSize/bodyRadius}; + //double er[]={bodyRadius/bodyRadius,pedSize/bodyRadius,chestThikness/bodyRadius}; + + bodyCenter[2]=chestCenter[2]-chestRadius-body->GetRadius()+10; + + bodyActor = vtkActor::New(); + bodyActor->SetMapper(mapper); + mapper->Delete(); + bodyActor->SetScale(1,1,0.90); + // bodyActor->GetProperty()->SetColor(pedsColors[0]/255.0,pedsColors[1]/255.0,pedsColors[2]/255.0); + bodyActor->GetProperty()->SetColor(1,1,1); + + //actor->GetProperty()->SetLighting(true); + //bodyActor->GetProperty()->SetSpecular(specular); + //bodyActor->GetProperty()->SetDiffuse(diffuse); + bodyActor->GetProperty()->SetAmbient(ambient); + bodyActor->SetPosition(0,0,bodyCenter[2]); + + assembly3D->AddPart(bodyActor); + } + + + + assembly3D->SetPosition( posX, posY, posZ); + + //create the 2D assembly + { + //private sphere + spaceNeeded = vtkDiskSource::New(); + //spaceNeeded->SetRadialResolution(30); + spaceNeeded->SetCircumferentialResolution(5); + spaceNeeded->SetInnerRadius(0); + //spaceNeeded->SetOuterRadius(bodyRadius); + spaceNeeded->SetOuterRadius(2); + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(spaceNeeded->GetOutputPort()); + //spaceNeeded->Delete(); + ellipseActor = vtkActor::New(); + ellipseActor->SetMapper(mapper); + mapper->Delete(); + // they all start with red color. + ellipseActor->GetProperty()->SetColor(1.0,0.0,0.0); + + //set the ellipse a little bit higher than the ground to + // eliminate interaction with the floor color. + ellipseActor->SetPosition(0,0,47); + + // this actor belongs to both 2D and 3D + //assembly3D->AddPart(ellipseActor); + assembly2D->AddPart(ellipseActor); + //ellipseActor->Delete(); + + //lookup table + vtkLookupTable* lut = vtkLookupTable::New(); + lut->SetHueRange(0.0,0.470); + //lut->SetSaturationRange(0,0); + lut->SetValueRange(1.0,1.0); + lut->SetNumberOfTableValues(256); + lut->Build(); + mapper->SetLookupTable(lut); + lut->Delete(); + } + + { + //head + { + //face + VTK_CREATE(vtkSphereSource,head); + head->SetThetaResolution(20); + head->SetStartTheta(270); + head->SetEndTheta(90); + head->SetRadius(headRadius); + //head->SetCenter(0,0,bodyRadius+2); + //head->SetCenter(0,0,pedSize+2); + // create mapper + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(head->GetOutputPort()); + + // create actor + VTK_CREATE(vtkActor,actor); + actor->SetMapper(mapper); + //mapper->Delete(); + actor->GetProperty()->SetColor(.90,.90,1.0); + actor->GetProperty()->SetSpecular(specular); + actor->GetProperty()->SetDiffuse(diffuse); + actor->GetProperty()->SetAmbient(ambient-.10); + + //assembly2D->AddPart(actor); + //actor->Delete(); + } + //back + { + VTK_CREATE(vtkSphereSource,head); + head->SetThetaResolution(20); + head->SetStartTheta(90); + head->SetEndTheta(270); + head->SetRadius(headRadius); + //head->SetCenter(0,0,pedSize+2); + // create mapper + VTK_CREATE(vtkPolyDataMapper,mapper); + + mapper->SetInputConnection(head->GetOutputPort()); + + // create actor + VTK_CREATE(vtkActor,actor); + + actor->SetMapper(mapper); + //mapper->Delete(); + actor->GetProperty()->SetColor(0.35,0.35,0.35); + actor->GetProperty()->SetSpecular(specular); + actor->GetProperty()->SetDiffuse(diffuse); + actor->GetProperty()->SetAmbient(ambient-.10); + + //assembly2D->AddPart(actor); + //actor->Delete(); + } + + assembly2D->SetPosition( posX, posY, posZ); + } + + { + //caption + + char txt[10]; + sprintf(txt,"%d",this->ID+1); + caption = vtkTextActor3D ::New(); + caption->SetVisibility(false); + caption->SetInput(txt); + // set the properties of the caption + //FARBE + vtkTextProperty* tprop = caption->GetTextProperty(); + tprop->SetFontFamilyToArial(); + tprop->BoldOn(); + //tprop->ShadowOn(); + tprop->SetLineSpacing(1.0); + tprop->SetFontSize(SystemSettings::getPedestrianCaptionSize()); + + tprop->SetColor(0.0,0.0,0.0); + //tprop->SetShadowOffset(2,2); + if(SystemSettings::get2D()) { + caption->SetPosition( 0, 0,20); //20 cm on the ground + //assembly2D->AddPart(caption); + + } else { + //vtkActor2D* test=vtkActor2D::New(); + //assembly3D->AddPart(test); + + //rotate the caption + //caption->RotateX(90); + caption->SetPosition( 0, 0,pedSize+20); + //assembly3D->AddPart(caption); + } + + } + if(SystemSettings::get2D())pedestrianAssembly=assembly2D; + else pedestrianAssembly=assembly3D; } -void Pedestrian::setColor(int color[3]){ - pedsColors[0]=color[0]; - pedsColors[1]=color[1]; - pedsColors[2]=color[2]; +void Pedestrian::setColor(int color[3]) +{ + pedsColors[0]=color[0]; + pedsColors[1]=color[1]; + pedsColors[2]=color[2]; - if(bodyActor!=NULL) - // bodyActor->GetProperty()->SetColor(pedsColors); - bodyActor->GetProperty()->SetColor(pedsColors[0]/255.0,pedsColors[1]/255.0,pedsColors[2]/255.0); + if(bodyActor!=NULL) + // bodyActor->GetProperty()->SetColor(pedsColors); + bodyActor->GetProperty()->SetColor(pedsColors[0]/255.0,pedsColors[1]/255.0,pedsColors[2]/255.0); } -void Pedestrian::setColor(int color){ - // ich klaue mal die Farbe von der Ellipse - if(bodyActor!=NULL){ - double *col =ellipseActor->GetMapper()->GetLookupTable()->GetColor((double)color/255.0); - bodyActor->GetProperty()->SetColor(col); - }else{ - //lookup table - vtkLookupTable* lut = vtkLookupTable::New(); - lut->SetHueRange(0.0,0.470); - //lut->SetSaturationRange(0,0); - lut->SetValueRange(1.0,1.0); - lut->SetNumberOfTableValues(256); - lut->Build(); - - lut->GetColor((double)color/255.0,pedsColors); - pedsColors[0]*=255; - pedsColors[1]*=255; - pedsColors[2]*=255; - } +void Pedestrian::setColor(int color) +{ + // ich klaue mal die Farbe von der Ellipse + if(bodyActor!=NULL) { + double *col =ellipseActor->GetMapper()->GetLookupTable()->GetColor((double)color/255.0); + bodyActor->GetProperty()->SetColor(col); + } else { + //lookup table + vtkLookupTable* lut = vtkLookupTable::New(); + lut->SetHueRange(0.0,0.470); + //lut->SetSaturationRange(0,0); + lut->SetValueRange(1.0,1.0); + lut->SetNumberOfTableValues(256); + lut->Build(); + + lut->GetColor((double)color/255.0,pedsColors); + pedsColors[0]*=255; + pedsColors[1]*=255; + pedsColors[2]*=255; + } } /// returns the actor to the pedestrians. /// creates one if not existing -vtkAssembly * Pedestrian::getActor(){ - if(pedestrianAssembly==NULL) createActor(); - //if(pedestrianAssembly==NULL) createSnowMan(); - return pedestrianAssembly; +vtkAssembly * Pedestrian::getActor() +{ + if(pedestrianAssembly==NULL) createActor(); + //if(pedestrianAssembly==NULL) createSnowMan(); + return pedestrianAssembly; } /// returns the actor to the pedestrians trail. /// creates one if inexisting -vtkAssembly * Pedestrian::getTrailActor(){ - if(trailActor==NULL) createTrailActor(); - return trailActor; +vtkAssembly * Pedestrian::getTrailActor() +{ + if(trailActor==NULL) createTrailActor(); + return trailActor; } @@ -1233,8 +1278,8 @@ vtkAssembly * Pedestrian::getTrailActor(){ * move the pedestrian to its new position */ -void Pedestrian::moveTo(TrajectoryPoint *point) { - +//void Pedestrian::moveTo(TrajectoryPoint *point) { +/* double xNew ;//= point->getX(); double yNew ;//= point->getY(); double zNew ;//= point->getZ(); @@ -1346,8 +1391,9 @@ void Pedestrian::moveTo(TrajectoryPoint *point) { trailActor->SetVisibility(groupVisibilityStatus & extern_tracking_enable); triggerPlotTrail(); +*/ +//} -} ///** // * // * move the pedestrian to its new position @@ -1474,139 +1520,153 @@ void Pedestrian::moveTo(TrajectoryPoint *point) { // //} -bool Pedestrian::isVisible(){ - return pedestrianAssembly->GetVisibility(); +bool Pedestrian::isVisible() +{ + return pedestrianAssembly->GetVisibility(); } -void Pedestrian::setVisibility(bool status){ - if(pedestrianAssembly==NULL){ - createActor(); - createTrailActor(); - } +void Pedestrian::setVisibility(bool status) +{ + if(pedestrianAssembly==NULL) { + createActor(); + createTrailActor(); + } - pedestrianAssembly->SetVisibility(status); - trailActor->SetVisibility(status); + pedestrianAssembly->SetVisibility(status); + trailActor->SetVisibility(status); } -void Pedestrian::setVisualModeTo2D(bool mode){ - - if(mode){ //2D - pedestrianAssembly=assembly2D; - assembly3D->SetVisibility(false); - } - else{ // 3D - pedestrianAssembly=assembly3D; - assembly2D->SetVisibility(false); - } - pedestrianAssembly->Modified(); +void Pedestrian::setVisualModeTo2D(bool mode) +{ + + if(mode) { //2D + pedestrianAssembly=assembly2D; + assembly3D->SetVisibility(false); + } else { // 3D + pedestrianAssembly=assembly3D; + assembly2D->SetVisibility(false); + } + pedestrianAssembly->Modified(); } /// set the group visibility status -void Pedestrian::setGroupVisibility(bool status){ - groupVisibilityStatus=status; +void Pedestrian::setGroupVisibility(bool status) +{ + groupVisibilityStatus=status; } /// get the group visibility -bool Pedestrian::getGroupVisibility(){ - return groupVisibilityStatus; +bool Pedestrian::getGroupVisibility() +{ + return groupVisibilityStatus; } -void Pedestrian::setSize(double size){ - this->pedSize=size; +void Pedestrian::setSize(double size) +{ + this->pedSize=size; } -void Pedestrian::enableCaption(bool status){ - if(caption!=NULL) - this->caption->SetVisibility(status); +void Pedestrian::enableCaption(bool status) +{ + if(caption!=NULL) + this->caption->SetVisibility(status); } -void Pedestrian::plotTrail(double x, double y, double z){ +void Pedestrian::plotTrail(double x, double y, double z) +{ - trailPoint.push(new JPoint (x,y,z)); + trailPoint.push(new JPoint (x,y,z)); } -void Pedestrian::setTrailGeometry(int type){ - switch(type){ - case 0: // points - //trailPlotterLine->getActor()->SetVisibility(0); - trailPlotterPoint->getActor()->SetVisibility(1); - break; +void Pedestrian::setTrailGeometry(int type) +{ + switch(type) { + case 0: // points + //trailPlotterLine->getActor()->SetVisibility(0); + trailPlotterPoint->getActor()->SetVisibility(1); + break; - case 1: // polygone - //trailPlotterLine->getActor()->SetVisibility(1); - trailPlotterPoint->getActor()->SetVisibility(0); + case 1: // polygone + //trailPlotterLine->getActor()->SetVisibility(1); + trailPlotterPoint->getActor()->SetVisibility(0); - break; - } + break; + } } -void Pedestrian::triggerPlotTrail() { +void Pedestrian::triggerPlotTrail() +{ - if(trailPoint.isEmpty()) return; - if(trailPoint.size()<2) return; + if(trailPoint.isEmpty()) return; + if(trailPoint.size()<2) return; - // make color uniform and use only [0,255] - //double color[3]={pedsColors[0],255*pedsColors[1],255*pedsColors[2]}; + // make color uniform and use only [0,255] + //double color[3]={pedsColors[0],255*pedsColors[1],255*pedsColors[2]}; - trailPlotterLine->clear(); - trailPlotterLine->SetNumberOfPoints(trailPoint.size()); + trailPlotterLine->clear(); + trailPlotterLine->SetNumberOfPoints(trailPoint.size()); - // Point * first = trailPoint.pop(); - // first->setColorRGB(color[0],color[1],color[2]); - // trailPlotterPoint->PlotPoint(first); - // trailPlotterLine->addVertex(first); + // Point * first = trailPoint.pop(); + // first->setColorRGB(color[0],color[1],color[2]); + // trailPlotterPoint->PlotPoint(first); + // trailPlotterLine->addVertex(first); - while (!trailPoint.isEmpty()){ - JPoint * next = trailPoint.pop(); - next->setColorRGB(pedsColors[0],pedsColors[1],pedsColors[2]); + while (!trailPoint.isEmpty()) { + JPoint * next = trailPoint.pop(); + next->setColorRGB(pedsColors[0],pedsColors[1],pedsColors[2]); - //trailPlotterLine->PlotLine(first, next); - trailPlotterPoint->PlotPoint(next); - trailPlotterLine->addVertex(next); - delete(next); - } - trailPoint.clear(); + //trailPlotterLine->PlotLine(first, next); + trailPlotterPoint->PlotPoint(next); + trailPlotterLine->addVertex(next); + delete(next); + } + trailPoint.clear(); } -void Pedestrian::setCaptionSize(int size){ - vtkTextProperty* tprop = caption->GetTextProperty(); - //tprop->SetFontFamilyToArial(); - //tprop->BoldOn(); - //tprop->ShadowOn(); - //tprop->SetLineSpacing(1.0); - //tprop->SetColor(1.0,0.0,0.0); - tprop->SetFontSize(size); +void Pedestrian::setCaptionSize(int size) +{ + vtkTextProperty* tprop = caption->GetTextProperty(); + //tprop->SetFontFamilyToArial(); + //tprop->BoldOn(); + //tprop->ShadowOn(); + //tprop->SetLineSpacing(1.0); + //tprop->SetColor(1.0,0.0,0.0); + tprop->SetFontSize(size); } -void Pedestrian::setCamera(vtkCamera* cam){ - virtualCam=cam; +void Pedestrian::setCamera(vtkCamera* cam) +{ + virtualCam=cam; } -void Pedestrian::setCaptionsColor(QColor& col){ - double captionColors[3]; - captionColors[0]=(double)col.red()/255; - captionColors[1]=(double)col.green()/255; - captionColors[2]=(double)col.blue()/255; - vtkTextProperty* tprop = caption->GetTextProperty(); - //tprop->SetFontFamilyToArial(); - //tprop->BoldOn(); - //tprop->ShadowOn(); - //tprop->SetLineSpacing(1.0); - tprop->SetColor(captionColors); - // tprop->SetFontSize(size); +void Pedestrian::setCaptionsColor(QColor& col) +{ + double captionColors[3]; + captionColors[0]=(double)col.red()/255; + captionColors[1]=(double)col.green()/255; + captionColors[2]=(double)col.blue()/255; + vtkTextProperty* tprop = caption->GetTextProperty(); + //tprop->SetFontFamilyToArial(); + //tprop->BoldOn(); + //tprop->ShadowOn(); + //tprop->SetLineSpacing(1.0); + tprop->SetColor(captionColors); + // tprop->SetFontSize(size); } -void Pedestrian::setCaptionsColorModeToAuto(bool status){ - autoCaptionColorMode=status; +void Pedestrian::setCaptionsColorModeToAuto(bool status) +{ + autoCaptionColorMode=status; } -void Pedestrian::setResolution(int pts){ - spaceNeeded->SetRadialResolution(pts); - spaceNeeded->SetCircumferentialResolution(pts); +void Pedestrian::setResolution(int pts) +{ + spaceNeeded->SetRadialResolution(pts); + spaceNeeded->SetCircumferentialResolution(pts); } diff --git a/src/Pedestrian.h b/src/Pedestrian.h index 0e63744c19e48e488c4ba4f835f03d29dafcf29b..6626af9f4bdec179de1f0da83d0eb8b72205b6b2 100644 --- a/src/Pedestrian.h +++ b/src/Pedestrian.h @@ -52,189 +52,189 @@ class vtkCamera; class Pedestrian { public: - /** - * constructor - * @param ID - * @return - */ - Pedestrian(int ID); - /** - * constructor - * - * @param ID - * @param x - * @param y - * @param z - * @return - */ - Pedestrian(int ID, double x ,double y, double z); + /** + * constructor + * @param ID + * @return + */ + Pedestrian(int ID); + /** + * constructor + * + * @param ID + * @param x + * @param y + * @param z + * @return + */ + Pedestrian(int ID, double x ,double y, double z); - /** - * Class destructor - * - */ - virtual ~Pedestrian(); + /** + * Class destructor + * + */ + virtual ~Pedestrian(); - /** - * \brief to provide a virtual reality-like impression - * @param cam a vtkcamera object - */ - static void setCamera(vtkCamera* cam); + /** + * \brief to provide a virtual reality-like impression + * @param cam a vtkcamera object + */ + static void setCamera(vtkCamera* cam); - /** - * set the agent id, whose eyes you want to see the scene through, -1 - * will reset to world/scene camera - * - * @param agent, the ID of the agent you want to see the world through - */ - //static void setVirtualRealityAgent(int agent); + /** + * set the agent id, whose eyes you want to see the scene through, -1 + * will reset to world/scene camera + * + * @param agent, the ID of the agent you want to see the world through + */ + //static void setVirtualRealityAgent(int agent); - ///returns the pedestrian ID - int getID(); + ///returns the pedestrian ID + int getID(); - ///returns the pedestrians Y coordinate - double getY(); + ///returns the pedestrians Y coordinate + double getY(); - ///returns the pedestrians X coordinate - double getX(); + ///returns the pedestrians X coordinate + double getX(); - ///returns the pedestrians Z coordinate - double getZ(); + ///returns the pedestrians Z coordinate + double getZ(); - /// return the actor to the pedestrians trail/trace - vtkAssembly* getTrailActor(); + /// return the actor to the pedestrians trail/trace + vtkAssembly* getTrailActor(); - /// call after the pedestrian has been created - vtkAssembly* getActor(); + /// call after the pedestrian has been created + vtkAssembly* getActor(); - /// move the pedestrian to the next position - /// @param [x y z] coordinates and the velocities - void moveTo(TrajectoryPoint *Point ); + /// move the pedestrian to the next position + /// @param [x y z] coordinates and the velocities + void moveTo(TrajectoryPoint *Point ); - /// change the size of the caption - /// @todo: also change size and orientation - void setCaptionSize(int size); + /// change the size of the caption + /// @todo: also change size and orientation + void setCaptionSize(int size); - /// enable/disable the pedestrians captions - void enableCaption(bool status); + /// enable/disable the pedestrians captions + void enableCaption(bool status); - /// set the pedestrian individual visibility status - void setVisibility(bool isVisible); + /// set the pedestrian individual visibility status + void setVisibility(bool isVisible); - /// get the individual visibility status - bool isVisible(); + /// get the individual visibility status + bool isVisible(); - /// set the group visibility status - void setGroupVisibility(bool status); + /// set the group visibility status + void setGroupVisibility(bool status); - /// get the group visibility - bool getGroupVisibility(); + /// get the group visibility + bool getGroupVisibility(); - /// set the initial visibility status - /// this may be useful because, all pedestrians are created at the beginning. - /// and placed at the coordinates [ 0 0 0 ] - void initVisibility(bool status); + /// set the initial visibility status + /// this may be useful because, all pedestrians are created at the beginning. + /// and placed at the coordinates [ 0 0 0 ] + void initVisibility(bool status); - /// switch to 2 Dimensional - /// FIXME not working when visualisation is already started - void setVisualModeTo2D(bool mode); + /// switch to 2 Dimensional + /// FIXME not working when visualisation is already started + void setVisualModeTo2D(bool mode); - /// true if the pedestrian is out of the system - /// it might be deleted - ///void setOutOfTheSystem(bool isOut); + /// true if the pedestrian is out of the system + /// it might be deleted + ///void setOutOfTheSystem(bool isOut); - /// set the pedestrian size, height in cm - void setSize(double size); + /// set the pedestrian size, height in cm + void setSize(double size); - /// plot the pedestrian trails - void plotTrail(double x, double y, double z); - //void plotTrail(double* points,int size); + /// plot the pedestrian trails + void plotTrail(double x, double y, double z); + //void plotTrail(double* points,int size); - /// set the trail types - /// 0 points, 1 polygon - void setTrailGeometry(int type); + /// set the trail types + /// 0 points, 1 polygon + void setTrailGeometry(int type); - //tODO???? what is todo? - void setColor(int color[3]); - void setColor(int color); + //tODO???? what is todo? + void setColor(int color[3]); + void setColor(int color); - /// set the pedestrian resolution. - /// 3 will results in a triangle - void setResolution(int pts); + /// set the pedestrian resolution. + /// 3 will results in a triangle + void setResolution(int pts); - /** - * Set the caption colour. If not specified,<br> - * colour will be set to automatic mode. - * - * @brief set the caption colour - * @param a value between 0 and 255 specifying the desired colour - */ - void setCaptionsColor(QColor& col); + /** + * Set the caption colour. If not specified,<br> + * colour will be set to automatic mode. + * + * @brief set the caption colour + * @param a value between 0 and 255 specifying the desired colour + */ + void setCaptionsColor(QColor& col); - /// enable or disable automatic caption color - void setCaptionsColorModeToAuto(bool status); + /// enable or disable automatic caption color + void setCaptionsColorModeToAuto(bool status); private: - void createActor(); - void CreateActor2D(); - void CreateActor3D(); - void createSnowMan(); - void createTrailActor(); - void triggerPlotTrail(); + void createActor(); + void CreateActor2D(); + void CreateActor3D(); + void createSnowMan(); + void createTrailActor(); + void triggerPlotTrail(); private : - // pedestrian properties - int ID; - int type; - double posX; - double posY; - double posZ; + // pedestrian properties + int ID; + int type; + double posX; + double posY; + double posZ; - bool groupVisibilityStatus; - double pedSize; - double pedsColors[3]; - bool autoCaptionColorMode; + bool groupVisibilityStatus; + double pedSize; + double pedsColors[3]; + bool autoCaptionColorMode; - /// the virtual reality camera - static vtkCamera * virtualCam; + /// the virtual reality camera + static vtkCamera * virtualCam; - /// throug its eyes you will see the world - //static int virtualRealityAgent; + /// throug its eyes you will see the world + //static int virtualRealityAgent; - /// define the pedestrian body; - vtkActor* bodyActor; + /// define the pedestrian body; + vtkActor* bodyActor; - ///define the pedestrian structure - vtkAssembly* pedestrianAssembly; + ///define the pedestrian structure + vtkAssembly* pedestrianAssembly; - /// define the pedestrian structure 3D - vtkAssembly* assembly3D; + /// define the pedestrian structure 3D + vtkAssembly* assembly3D; - /// define the pedestrian structure 2D + /// define the pedestrian structure 2D - vtkAssembly* assembly2D; + vtkAssembly* assembly2D; - /// to increase the radius, the actor could be scale up or down. - vtkDiskSource* spaceNeeded ; //private sphere needed by agents for moving + /// to increase the radius, the actor could be scale up or down. + vtkDiskSource* spaceNeeded ; //private sphere needed by agents for moving - /// private sphere actor needed by the pedestrian. It is a function of the velocity - vtkActor* ellipseActor; + /// private sphere actor needed by the pedestrian. It is a function of the velocity + vtkActor* ellipseActor; - /// trail actor left by the pedestrian - vtkAssembly* trailActor; + /// trail actor left by the pedestrian + vtkAssembly* trailActor; - /// caption actor - vtkTextActor3D* caption; + /// caption actor + vtkTextActor3D* caption; - /// trails plotter - QStack<JPoint*> trailPoint; - PointPlotter* trailPlotterPoint; - LinePlotter* trailPlotterLine; + /// trails plotter + QStack<JPoint*> trailPoint; + PointPlotter* trailPlotterPoint; + LinePlotter* trailPlotterLine; }; #endif /* PEDESTRIAN_H_ */ diff --git a/src/SaxParser.cpp b/src/SaxParser.cpp index d5f2c5d10aa85ea5de2036814343342148b32a06..c4c6dbe5c5d8df3f2df2d56af06f356285f06e8d 100644 --- a/src/SaxParser.cpp +++ b/src/SaxParser.cpp @@ -75,30 +75,31 @@ using namespace std; * @param roomCaption * @return */ -SaxParser::SaxParser(FacilityGeometry* geo, SyncData* data, double* fps){ - geometry=geo; +SaxParser::SaxParser(FacilityGeometry* geo, SyncData* data, double* fps) +{ + geometry=geo; dataset=data; - para=fps; - parsingWalls=false; + para=fps; + parsingWalls=false; parsingCrossings=false; - color=0.0; + color=0.0; dataset->clearFrames(); //default header InitHeader(0,0,0); } -SaxParser::~SaxParser() { +SaxParser::~SaxParser() +{ } bool SaxParser::startElement(const QString & /* namespaceURI */, - const QString & /* localName */, const QString &qName, - const QXmlAttributes &at) + const QString & /* localName */, const QString &qName, + const QXmlAttributes &at) { if (qName == "header") { - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="version") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="version") { QStringList query = at.value(i).split("."); int major=0; int minor=0; @@ -108,8 +109,8 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, major=query.at(0).toInt(); break; case 2: - major=query.at(0).toInt(); - minor=query.at(1).toInt(); + major=query.at(0).toInt(); + minor=query.at(1).toInt(); break; case 3: major=query.at(0).toInt(); @@ -121,256 +122,171 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, //cout<<"version found:"<<at.value(i).toStdString()<<endl;exit(0); } } - }else if (qName == "file") { - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="location") - { + } else if (qName == "file") { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="location") { QString fileName=at.value(i); - if(!fileName.isEmpty()) - { - if(fileName.endsWith(".xml",Qt::CaseInsensitive)) - { + if(!fileName.isEmpty()) { + if(fileName.endsWith(".xml",Qt::CaseInsensitive)) { //SaxParser::parseGeometryJPS(fileName,geometry); - } - else if (fileName.endsWith(".trav",Qt::CaseInsensitive)) - { + } else if (fileName.endsWith(".trav",Qt::CaseInsensitive)) { SaxParser::parseGeometryTRAV(fileName,geometry); } } } } - } - else if (qName == "floor") { + } else if (qName == "floor") { double xMin=0, - xMax=0, - yMin=0, - yMax=0; + xMax=0, + yMin=0, + yMax=0; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="xMin") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="xMin") { xMin=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="xMax") - { + } else if(at.localName(i)=="xMax") { xMax=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="yMin") - { + } else if(at.localName(i)=="yMin") { yMin=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="yMax") - { + } else if(at.localName(i)=="yMax") { yMax=at.value(i).toDouble()*FAKTOR; } } geometry->addFloor(xMin,yMin,xMax,yMax); - } - else if (qName == "cuboid") { + } else if (qName == "cuboid") { double length=0, height=0, - width=0, color=0; - double center[3]={0,0,0}; + width=0, color=0; + double center[3]= {0,0,0}; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="centerX") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="centerX") { center[0]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerY") - { + } else if(at.localName(i)=="centerY") { center[1]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerZ") - { + } else if(at.localName(i)=="centerZ") { center[2]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="length") - { + } else if(at.localName(i)=="length") { length=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="height") - { + } else if(at.localName(i)=="height") { height=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="width") - { + } else if(at.localName(i)=="width") { width=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="color") - { + } else if(at.localName(i)=="color") { color=at.value(i).toDouble()*FAKTOR; } } geometry->addObjectBox(center,height,width,length,color); - } - else if (qName == "sphere") { + } else if (qName == "sphere") { double radius=0, color=0; - double center[3]={0,0,0}; + double center[3]= {0,0,0}; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="centerX") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="centerX") { center[0]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerY") - { + } else if(at.localName(i)=="centerY") { center[1]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerZ") - { + } else if(at.localName(i)=="centerZ") { center[2]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="radius") - { + } else if(at.localName(i)=="radius") { radius=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="color") - { + } else if(at.localName(i)=="color") { color=at.value(i).toDouble(); } } geometry->addObjectSphere(center,radius,color); - } - else if (qName == "label") { + } else if (qName == "label") { double color=0; - double center[3]={0,0,0}; + double center[3]= {0,0,0}; QString text; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="centerX") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="centerX") { center[0]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerY") - { + } else if(at.localName(i)=="centerY") { center[1]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerZ") - { + } else if(at.localName(i)=="centerZ") { center[2]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="text") - { + } else if(at.localName(i)=="text") { text=at.value(i); - } - else if(at.localName(i)=="color") - { + } else if(at.localName(i)=="color") { color=at.value(i).toDouble(); } } geometry->addObjectLabel(center,center,text.toStdString(),color); - } - else if (qName == "cylinder") { + } else if (qName == "cylinder") { double height=0, radius=0, color=0; - double center[3]={0,0,0}; - double rotation[3]={0,0,0}; + double center[3]= {0,0,0}; + double rotation[3]= {0,0,0}; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="centerX") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="centerX") { center[0]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerY") - { + } else if(at.localName(i)=="centerY") { center[1]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="centerZ") - { + } else if(at.localName(i)=="centerZ") { center[2]=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="height") - { + } else if(at.localName(i)=="height") { height=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="radius") - { + } else if(at.localName(i)=="radius") { radius=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="color") - { + } else if(at.localName(i)=="color") { color=at.value(i).toDouble(); - } - else if(at.localName(i)=="angleX") - { + } else if(at.localName(i)=="angleX") { rotation[0]=at.value(i).toDouble(); - } - else if(at.localName(i)=="angleY") - { + } else if(at.localName(i)=="angleY") { rotation[1]=at.value(i).toDouble(); - } - else if(at.localName(i)=="angleZ") - { + } else if(at.localName(i)=="angleZ") { rotation[2]=at.value(i).toDouble(); } } geometry->addObjectCylinder(center,radius,height,rotation,color); - } - else if (qName == "agents") { + } else if (qName == "agents") { } else if (qName == "roomCaption") { } else if (qName == "frameRate") { } else if (qName == "geometry") { - } - else if (qName == "wall") - { + } else if (qName == "wall") { parsingWalls=true; thickness=15; height=250; color=0; caption=""; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="thickness") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="thickness") { thickness=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="height") - { + } else if(at.localName(i)=="height") { height=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="color") - { + } else if(at.localName(i)=="color") { color=at.value(i).toDouble(); - } - else if(at.localName(i)=="caption") - { + } else if(at.localName(i)=="caption") { caption=at.value(i); } } - } - else if (qName == "door") - { + } else if (qName == "door") { parsingWalls=false; thickness=15; height=250; color=255; caption=""; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="thickness") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="thickness") { thickness=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="height") - { + } else if(at.localName(i)=="height") { height=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="color") - { + } else if(at.localName(i)=="color") { color=at.value(i).toDouble(); - } - else if(at.localName(i)=="caption") - { + } else if(at.localName(i)=="caption") { caption=at.value(i); } } } //FIXME - else if (qName == "crossing") - { + else if (qName == "crossing") { parsingWalls=false; parsingCrossings=true; thickness=15; @@ -378,66 +294,45 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, color=255; caption=""; - for(int i=0;i<at.length();i++){ - if(at.localName(i)=="thickness") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="thickness") { thickness=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="height") - { + } else if(at.localName(i)=="height") { height=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="color") - { + } else if(at.localName(i)=="color") { color=at.value(i).toDouble(); - } - else if(at.localName(i)=="caption") - { + } else if(at.localName(i)=="caption") { caption=at.value(i); } } - } - else if (qName == "timeFirstFrame") - { + } else if (qName == "timeFirstFrame") { unsigned long timeFirstFrame_us=0; unsigned long timeFirstFrame_s=0; - for(int i=0;i<at.length();i++) - { - if(at.localName(i)=="microsec") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="microsec") { timeFirstFrame_us=at.value(i).toULong(); - } - else if(at.localName(i)=="sec") - { + } else if(at.localName(i)=="sec") { timeFirstFrame_s=at.value(i).toULong(); } } dataset->setDelayAbsolute(timeFirstFrame_s,timeFirstFrame_us); - } - else if (qName == "point") - { + } else if (qName == "point") { double xPos=0; double yPos=0; double zPos=0; - for(int i=0;i<at.length();i++) - { - if(at.localName(i)=="xPos") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="xPos") { xPos=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="yPos") - { + } else if(at.localName(i)=="yPos") { yPos=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)=="zPos") - { + } else if(at.localName(i)=="zPos") { zPos=at.value(i).toDouble()*FAKTOR; } } - double CHT[3]={color,height,thickness}; + double CHT[3]= {color,height,thickness}; JPoint* pt= new JPoint(xPos,yPos,zPos); pt->setColorHeightThicknes(CHT); @@ -451,10 +346,10 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, double xPos=0; double yPos=0; double zPos=0; - double agent_color =std::numeric_limits<double>::quiet_NaN(); - double xVel=std::numeric_limits<double>::quiet_NaN(); - double yVel=std::numeric_limits<double>::quiet_NaN(); - double zVel=std::numeric_limits<double>::quiet_NaN(); + //double agent_color =std::numeric_limits<double>::quiet_NaN(); + //double xVel=std::numeric_limits<double>::quiet_NaN(); + //double yVel=std::numeric_limits<double>::quiet_NaN(); + //double zVel=std::numeric_limits<double>::quiet_NaN(); double dia_a=std::numeric_limits<double>::quiet_NaN(); double dia_b=std::numeric_limits<double>::quiet_NaN(); double el_angle=std::numeric_limits<double>::quiet_NaN(); @@ -463,65 +358,42 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, double el_y=std::numeric_limits<double>::quiet_NaN(); double el_z=std::numeric_limits<double>::quiet_NaN(); - for(int i=0;i<at.length();i++) - { - if(at.localName(i)=="ID") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="ID") { id=at.value(i).toInt(); //TODO: maybe you should change ur format to take the ID 0 as first valid ID. - if (id==0){ + if (id==0) { //slotErrorOutput("Person with ID=0 detected. ID should start with 1 !"); return false; } - } - else if(at.localName(i)==_jps_xPos) - { + } else if(at.localName(i)==_jps_xPos) { xPos=at.value(i).toDouble()*FAKTOR; //xPos=at.value(i).toDouble(); - } - else if(at.localName(i)==_jps_yPos) - { + } else if(at.localName(i)==_jps_yPos) { //yPos=at.value(i).toDouble(); yPos=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)==_jps_zPos) - { + } else if(at.localName(i)==_jps_zPos) { zPos=at.value(i).toDouble()*FAKTOR; } - else if(at.localName(i)==_jps_radiusA) - { + else if(at.localName(i)==_jps_radiusA) { dia_a=at.value(i).toDouble()*FAKTOR; //dia_a=at.value(i).toDouble(); - } - else if(at.localName(i)==_jps_radiusB) - { + } else if(at.localName(i)==_jps_radiusB) { dia_b=at.value(i).toDouble()*FAKTOR; //dia_b=at.value(i).toDouble(); - } - else if(at.localName(i)==_jps_ellipseOrientation) - { + } else if(at.localName(i)==_jps_ellipseOrientation) { el_angle=at.value(i).toDouble(); - } - else if(at.localName(i)==_jps_ellipseColor) - { + } else if(at.localName(i)==_jps_ellipseColor) { el_color=at.value(i).toDouble(); - } - else if(at.localName(i)=="agentColor") - { - agent_color=at.value(i).toDouble(); - } - else if(at.localName(i)==_jps_xVel) - { - xVel=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)==_jps_yVel) - { - yVel=at.value(i).toDouble()*FAKTOR; - } - else if(at.localName(i)==_jps_zVel) - { - zVel=at.value(i).toDouble()*FAKTOR; + } else if(at.localName(i)=="agentColor") { + //agent_color=at.value(i).toDouble(); + } else if(at.localName(i)==_jps_xVel) { + //xVel=at.value(i).toDouble()*FAKTOR; + } else if(at.localName(i)==_jps_yVel) { + //yVel=at.value(i).toDouble()*FAKTOR; + } else if(at.localName(i)==_jps_zVel) { + //zVel=at.value(i).toDouble()*FAKTOR; } } @@ -532,13 +404,13 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, if(isnan(el_z)) el_z=zPos; //double pos[3]={xPos,yPos,zPos}; - double vel[3]={xVel,yPos,zPos}; - double ellipse[7]={el_x,el_y,el_z,dia_a,dia_b,el_angle,el_color}; - double para[2]={agent_color,el_angle}; + //double vel[3]={xVel,yPos,zPos}; + //double ellipse[7]={el_x,el_y,el_z,dia_a,dia_b,el_angle,el_color}; + //double para[2]={agent_color,el_angle}; - double pos[3]={xPos,yPos,zPos}; - double angle[3]={0,0,el_angle}; - double radius[3]={dia_a,dia_b,30.0}; + double pos[3]= {xPos,yPos,zPos}; + double angle[3]= {0,0,el_angle}; + double radius[3]= {dia_a,dia_b,30.0}; FrameElement *element = new FrameElement(id-1); element->SetPos(pos); @@ -547,35 +419,29 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, element->SetColor(el_color); currentFrame.push_back(element); - } - else if (qName == "agentInfo") - { + } else if (qName == "agentInfo") { double height=std::numeric_limits<double>::quiet_NaN(); int color=std::numeric_limits<int>::quiet_NaN(); int id=std::numeric_limits<int>::quiet_NaN(); - for(int i=0;i<at.length();i++) - { - if(at.localName(i)=="ID") - { + for(int i=0; i<at.length(); i++) { + if(at.localName(i)=="ID") { id=at.value(i).toInt(); } - if(at.localName(i)=="height") - { + if(at.localName(i)=="height") { height=at.value(i).toDouble()*FAKTOR; } - if(at.localName(i)=="color") - { + if(at.localName(i)=="color") { color=at.value(i).toDouble(); } } if(isnan(id)) return true; - if(!isnan(height)){ + if(!isnan(height)) { initialPedestriansHeights.append(QString::number(id)); initialPedestriansHeights.append(QString::number(height)); } - if(!isnan(color)){ + if(!isnan(color)) { initialPedestriansColors.append(QString::number(id)); initialPedestriansColors.append(QString::number(color)); } @@ -583,98 +449,102 @@ bool SaxParser::startElement(const QString & /* namespaceURI */, return true; } -bool SaxParser::characters(const QString &str) { - currentText.append(str); - return true; +bool SaxParser::characters(const QString &str) +{ + currentText.append(str); + return true; } bool SaxParser::endElement(const QString & /* namespaceURI */, - const QString & /* localName */, const QString &qName) + const QString & /* localName */, const QString &qName) { - if (qName == "header") { + if (qName == "header") { - } else if (qName == "agents") { - dataset->setNumberOfAgents(currentText.toInt()); - } else if (qName == "frameRate") { - para[0]=currentText.toFloat(); - } else if (qName == "wall") { + } else if (qName == "agents") { + dataset->setNumberOfAgents(currentText.toInt()); + } else if (qName == "frameRate") { + para[0]=currentText.toFloat(); + } else if (qName == "wall") { if(currentPointsList.size()>1) - for(unsigned int i=0;i<currentPointsList.size()-1;i++){ - geometry->addWall(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); - } - clearPoints(); - } else if (qName == "door") { - for(unsigned int i=0;i<currentPointsList.size()-1;i++){ - geometry->addDoor(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); - } - clearPoints(); + for(unsigned int i=0; i<currentPointsList.size()-1; i++) { + geometry->addWall(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); + } + clearPoints(); + } else if (qName == "door") { + for(unsigned int i=0; i<currentPointsList.size()-1; i++) { + geometry->addDoor(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); + } + clearPoints(); } else if (qName == "crossing") { if(currentPointsList.size()>1) //hack - for(unsigned int i=0;i<currentPointsList.size()-1;i++){ - geometry->addNavLine(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); - } + for(unsigned int i=0; i<currentPointsList.size()-1; i++) { + geometry->addNavLine(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); + } clearPoints(); } else if (qName == "hline") { if(currentPointsList.size()>1) //hack - for(unsigned int i=0;i<currentPointsList.size()-1;i++){ - geometry->addNavLine(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); - } + for(unsigned int i=0; i<currentPointsList.size()-1; i++) { + geometry->addNavLine(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); + } clearPoints(); } else if (qName == "step") {//FIXME - for(unsigned int i=0;i<currentPointsList.size()-1;i++){ - geometry->addDoor(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); - } - clearPoints(); - } else if (qName == "frame") { - Frame* frame = new Frame(); - while(!currentFrame.empty()){ - frame->addElement(currentFrame.back()); - currentFrame.pop_back(); + for(unsigned int i=0; i<currentPointsList.size()-1; i++) { + geometry->addDoor(currentPointsList[i],currentPointsList[i+1],caption.toStdString()); + } + clearPoints(); + } else if (qName == "frame") { + Frame* frame = new Frame(); + while(!currentFrame.empty()) { + frame->addElement(currentFrame.back()); + currentFrame.pop_back(); //cout<<"not adding"<<endl; - } + } //compute the polydata, might increase the runtime frame->ComputePolyData(); dataset->addFrame(frame); - //to be on the safe side - currentFrame.clear(); - - } else if (qName == "agent") { - } else if (qName == "geometry") { - } else if (qName == "point") { - } else if (qName == "shape") { - dataset->setInitialHeights(initialPedestriansHeights); - dataset->setInitialColors(initialPedestriansColors); - } - currentText.clear(); - return true; + //to be on the safe side + currentFrame.clear(); + + } else if (qName == "agent") { + } else if (qName == "geometry") { + } else if (qName == "point") { + } else if (qName == "shape") { + dataset->setInitialHeights(initialPedestriansHeights); + dataset->setInitialColors(initialPedestriansColors); + } + currentText.clear(); + return true; } -bool SaxParser::fatalError(const QXmlParseException &exception) { - QMessageBox::warning(0, QObject::tr("SAX Handler"), QObject::tr( - "Parse error at line %1, column " - "%2:\n%3.") .arg(exception.lineNumber()) .arg( - exception.columnNumber()) .arg(exception.message())); - return false; +bool SaxParser::fatalError(const QXmlParseException &exception) +{ + QMessageBox::warning(0, QObject::tr("SAX Handler"), QObject::tr( + "Parse error at line %1, column " + "%2:\n%3.") .arg(exception.lineNumber()) .arg( + exception.columnNumber()) .arg(exception.message())); + return false; } bool SaxParser::attributeDecl(const QString& eName, const QString& aName, - const QString& type, const QString& valueDefault, const QString& value) { - //cout<<aName.toStdString()<<endl; + const QString& type, const QString& valueDefault, const QString& value) +{ + //cout<<aName.toStdString()<<endl; - QString dummy=eName+aName+type+valueDefault+value; - return (dummy==dummy); - //return true; + QString dummy=eName+aName+type+valueDefault+value; + return (dummy==dummy); + //return true; } -void SaxParser::clearPoints(){ - while (!currentPointsList.empty()){ - delete currentPointsList.back(); - currentPointsList.pop_back(); - } - currentPointsList.clear(); - return; +void SaxParser::clearPoints() +{ + while (!currentPointsList.empty()) { + delete currentPointsList.back(); + currentPointsList.pop_back(); + } + currentPointsList.clear(); + return; } @@ -705,18 +575,16 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) // Add the polygon to a list of polygons VTK_CREATE(vtkCellArray,polygons); - for (int i = 0; i < building->GetNumberOfRooms(); i++) - { + for (int i = 0; i < building->GetNumberOfRooms(); i++) { Room* r = building->GetRoom(i); //string caption = r->GetCaption(); - for (int k = 0; k < r->GetNumberOfSubRooms(); k++) - { + for (int k = 0; k < r->GetNumberOfSubRooms(); k++) { SubRoom* sub = r->GetSubRoom(k); vector<Point> poly = sub->GetPolygon(); - if(sub->IsClockwise()==true){ + if(sub->IsClockwise()==true) { std::reverse(poly.begin(),poly.end()); } @@ -724,7 +592,7 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) VTK_CREATE(vtkPolygon,polygon); polygon->GetPointIds()->SetNumberOfIds(poly.size()); - for (unsigned int s=0;s<poly.size();s++){ + for (unsigned int s=0; s<poly.size(); s++) { points->InsertNextPoint(poly[s]._x*FAKTOR,poly[s]._y*FAKTOR,sub->GetElevation(poly[s])*FAKTOR); polygon->GetPointIds()->SetId(s, currentID++); } @@ -733,18 +601,15 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) //plot the walls only for not stairs const vector<Wall>& walls= sub->GetAllWalls(); - for(unsigned int w=0;w<walls.size();w++){ + for(unsigned int w=0; w<walls.size(); w++) { Point p1 = walls[w].GetPoint1(); Point p2 = walls[w].GetPoint2(); double z1= sub->GetElevation(p1); double z2= sub->GetElevation(p2); - if(sub->GetType()=="stair") - { + if(sub->GetType()=="stair") { geometry->addStair(p1._x*FAKTOR, p1._y*FAKTOR, z1*FAKTOR, p2._x*FAKTOR, p2._y*FAKTOR,z2*FAKTOR); - } - else - { + } else { geometry->addWall(p1._x*FAKTOR, p1._y*FAKTOR, z1*FAKTOR, p2._x*FAKTOR, p2._y*FAKTOR,z2*FAKTOR); } } @@ -753,7 +618,7 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) string caption=r->GetCaption()+" ( " + QString::number(sub->GetSubRoomID()).toStdString() + " ) "; const Point& p=sub->GetCentroid(); double z= sub->GetElevation(p); - double pos[3]={p._x*FAKTOR,p._y*FAKTOR,z*FAKTOR}; + double pos[3]= {p._x*FAKTOR,p._y*FAKTOR,z*FAKTOR}; geometry->addObjectLabel(pos,pos,caption,captionsColor); //plot the obstacles @@ -761,7 +626,7 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) for( unsigned int j=0; j<obstacles.size(); j++) { Obstacle* obst= obstacles[j]; const vector<Wall>& walls= obst->GetAllWalls(); - for(unsigned int w=0;w<walls.size();w++){ + for(unsigned int w=0; w<walls.size(); w++) { Point p1 = walls[w].GetPoint1(); Point p2 = walls[w].GetPoint2(); double z1= sub->GetElevation(p1); @@ -771,7 +636,7 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) //add the obstacle caption const Point& p=obst->GetCentroid(); double z= sub->GetElevation(p); - double pos[3]={p._x*FAKTOR,p._y*FAKTOR,z*FAKTOR}; + double pos[3]= {p._x*FAKTOR,p._y*FAKTOR,z*FAKTOR}; geometry->addObjectLabel(pos,pos,obst->GetCaption(),captionsColor); } } @@ -786,8 +651,7 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) // add the crossings const map<int, Crossing*>& crossings=building->GetAllCrossings(); - for (std::map<int, Crossing*>::const_iterator it=crossings.begin(); it!=crossings.end(); ++it) - { + for (std::map<int, Crossing*>::const_iterator it=crossings.begin(); it!=crossings.end(); ++it) { Crossing* cr=it->second; Point p1 = cr->GetPoint1(); Point p2 = cr->GetPoint2(); @@ -796,14 +660,13 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) geometry->addNavLine(p1._x*FAKTOR, p1._y*FAKTOR, z1*FAKTOR, p2._x*FAKTOR, p2._y*FAKTOR,z2*FAKTOR); const Point& p =cr->GetCentre(); - double pos[3]={p._x*FAKTOR,p._y*FAKTOR,z1*FAKTOR}; + double pos[3]= {p._x*FAKTOR,p._y*FAKTOR,z1*FAKTOR}; geometry->addObjectLabel(pos,pos,"nav_"+QString::number(cr->GetID()).toStdString(),captionsColor); } // add the exits const map<int, Transition*>& transitions=building->GetAllTransitions(); - for (std::map<int, Transition*>::const_iterator it=transitions.begin(); it!=transitions.end(); ++it) - { + for (std::map<int, Transition*>::const_iterator it=transitions.begin(); it!=transitions.end(); ++it) { Transition* tr=it->second; Point p1 = tr->GetPoint1(); Point p2 = tr->GetPoint2(); @@ -812,7 +675,7 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) geometry->addDoor(p1._x*FAKTOR, p1._y*FAKTOR, z1*FAKTOR, p2._x*FAKTOR, p2._y*FAKTOR,z2*FAKTOR); const Point& p =tr->GetCentre(); - double pos[3]={p._x*FAKTOR,p._y*FAKTOR,z1*FAKTOR}; + double pos[3]= {p._x*FAKTOR,p._y*FAKTOR,z1*FAKTOR}; geometry->addObjectLabel(pos,pos,"door_"+QString::number(tr->GetID()).toStdString(),captionsColor); } @@ -829,81 +692,78 @@ bool SaxParser::parseGeometryJPS(QString fileName, FacilityGeometry *geometry) void SaxParser::parseGeometryTRAV(QString content, FacilityGeometry *geometry,QDomNode geo) { - cout<<"external geometry found"<<endl; - //creating am empty document - // to be filled - QDomDocument doc(""); - QDomNode geoNode; - - //first try to open the file - if(content.endsWith(".trav",Qt::CaseInsensitive) ) - { - QFile file(content); - if (!file.open(QIODevice::ReadOnly)) { - //slotErrorOutput("could not open the File" ); - cout<<"could not open the File"<<endl; - return ; - } - QString *errorCode = new QString(); - if (!doc.setContent(&file, errorCode)) { - file.close(); - //slotErrorOutput(*errorCode); - cout<<errorCode->toStdString()<<endl; - return ; - } - file.close(); - geoNode =doc.documentElement().namedItem("geometry"); - - if (geoNode.isNull()){ - cout<<"No geometry information found. <geometry> <geometry/> tag is missing."<<endl; - } - } - else - { - if(content.isEmpty()){ - geoNode=geo; - cout <<"parsing the old fashion way"<<endl; - }else{ - content = "<travisto>\n" +content+ "\n</travisto>\n"; - QString errorMsg=""; - doc.setContent(content,&errorMsg); - - if(!errorMsg.isEmpty()){ - Debug::Error("%s", (const char *)errorMsg.toStdString().c_str()); - return; - } - geoNode =doc.elementsByTagName("geometry").item(0); - } - } - - // for the case there is more than just one geometry Node - while (!geoNode.isNull()) { - QDomElement e = geoNode.toElement(); - QDomNodeList walls = e.elementsByTagName("wall"); - QDomNodeList doors = e.elementsByTagName("door"); - - //objects which can be positioned everywhere in the facility - QDomNodeList spheres = e.elementsByTagName("sphere"); - QDomNodeList cuboids = e.elementsByTagName("cuboid"); - QDomNodeList floors = e.elementsByTagName("floor"); - QDomNodeList cylinders = e.elementsByTagName("cylinder"); - QDomNodeList labels = e.elementsByTagName("label"); - - - //parsing the walls + cout<<"external geometry found"<<endl; + //creating am empty document + // to be filled + QDomDocument doc(""); + QDomNode geoNode; + + //first try to open the file + if(content.endsWith(".trav",Qt::CaseInsensitive) ) { + QFile file(content); + if (!file.open(QIODevice::ReadOnly)) { + //slotErrorOutput("could not open the File" ); + cout<<"could not open the File"<<endl; + return ; + } + QString *errorCode = new QString(); + if (!doc.setContent(&file, errorCode)) { + file.close(); + //slotErrorOutput(*errorCode); + cout<<errorCode->toStdString()<<endl; + return ; + } + file.close(); + geoNode =doc.documentElement().namedItem("geometry"); + + if (geoNode.isNull()) { + cout<<"No geometry information found. <geometry> <geometry/> tag is missing."<<endl; + } + } else { + if(content.isEmpty()) { + geoNode=geo; + cout <<"parsing the old fashion way"<<endl; + } else { + content = "<travisto>\n" +content+ "\n</travisto>\n"; + QString errorMsg=""; + doc.setContent(content,&errorMsg); + + if(!errorMsg.isEmpty()) { + Debug::Error("%s", (const char *)errorMsg.toStdString().c_str()); + return; + } + geoNode =doc.elementsByTagName("geometry").item(0); + } + } + + // for the case there is more than just one geometry Node + while (!geoNode.isNull()) { + QDomElement e = geoNode.toElement(); + QDomNodeList walls = e.elementsByTagName("wall"); + QDomNodeList doors = e.elementsByTagName("door"); + + //objects which can be positioned everywhere in the facility + QDomNodeList spheres = e.elementsByTagName("sphere"); + QDomNodeList cuboids = e.elementsByTagName("cuboid"); + QDomNodeList floors = e.elementsByTagName("floor"); + QDomNodeList cylinders = e.elementsByTagName("cylinder"); + QDomNodeList labels = e.elementsByTagName("label"); + + + //parsing the walls for ( int i = 0; i < walls.length(); i++) { - QDomElement el = walls.item(i).toElement(); + QDomElement el = walls.item(i).toElement(); - //wall thickness, default to 30 cm + //wall thickness, default to 30 cm double thickness = el.attribute("thickness","15").toDouble()*FAKTOR; - //wall height default to 250 cm + //wall height default to 250 cm double height = el.attribute("height","250").toDouble()*FAKTOR; - //wall color default to blue - double color = el.attribute("color","0").toDouble(); + //wall color default to blue + double color = el.attribute("color","0").toDouble(); - //get the points defining each wall - //not that a wall is not necessarily defined by two points, could be more... - QDomNodeList points = el.elementsByTagName("point"); + //get the points defining each wall + //not that a wall is not necessarily defined by two points, could be more... + QDomNodeList points = el.elementsByTagName("point"); for ( int i = 0; i < points.length() - 1; i++) { double x1=points.item(i).toElement().attribute("xPos", "0").toDouble()*FAKTOR; @@ -913,26 +773,26 @@ void SaxParser::parseGeometryTRAV(QString content, FacilityGeometry *geometry,QD double x2=points.item(i+1).toElement().attribute("xPos", "0").toDouble()*FAKTOR; double y2=points.item(i+1).toElement().attribute("yPos", "0").toDouble()*FAKTOR; double z2=points.item(i+1).toElement().attribute("zPos", "0").toDouble()*FAKTOR; - geometry->addWall(x1, y1,z1 ,x2, y2,z2,thickness,height,color); - } - } + geometry->addWall(x1, y1,z1 ,x2, y2,z2,thickness,height,color); + } + } - //parsing the doors - if(doors.length()>0) + //parsing the doors + if(doors.length()>0) for ( int i = 0; i < doors.length(); i++) { - QDomElement el = doors.item(i).toElement(); + QDomElement el = doors.item(i).toElement(); - //door thickness, default to 15 cm + //door thickness, default to 15 cm double thickness = el.attribute("thickness","15").toDouble()*FAKTOR; - //door height default to 250 cm + //door height default to 250 cm double height = el.attribute("height","250").toDouble()*FAKTOR; - //door color default to blue - double color = el.attribute("color","255").toDouble(); + //door color default to blue + double color = el.attribute("color","255").toDouble(); - //get the points defining each wall - //not that a wall is not necesarily defined by two points, could be more... - QDomNodeList points = el.elementsByTagName("point"); - //Debug::Messages("found: " << points.length() <<" for this wall" <<endl; + //get the points defining each wall + //not that a wall is not necesarily defined by two points, could be more... + QDomNodeList points = el.elementsByTagName("point"); + //Debug::Messages("found: " << points.length() <<" for this wall" <<endl; for ( int i = 0; i < points.length() - 1; i++) { double x1=points.item(i).toElement().attribute("xPos", "0").toDouble()*FAKTOR; @@ -942,39 +802,39 @@ void SaxParser::parseGeometryTRAV(QString content, FacilityGeometry *geometry,QD double x2=points.item(i+1).toElement().attribute("xPos", "0").toDouble()*FAKTOR; double y2=points.item(i+1).toElement().attribute("yPos", "0").toDouble()*FAKTOR; double z2=points.item(i+1).toElement().attribute("zPos", "0").toDouble()*FAKTOR; - geometry->addDoor(x1, y1, z1, x2, y2,z2,thickness,height,color); - } - } + geometry->addDoor(x1, y1, z1, x2, y2,z2,thickness,height,color); + } + } - // parsing the objets + // parsing the objets for ( int i = 0; i < spheres.length(); i++) { - double center[3]; + double center[3]; center[0] = spheres.item(i).toElement().attribute("centerX", "0").toDouble()*FAKTOR; center[1]= spheres.item(i).toElement().attribute("centerY", "0").toDouble()*FAKTOR; center[2]= spheres.item(i).toElement().attribute("centerZ", "0").toDouble()*FAKTOR; double color= spheres.item(i).toElement().attribute("color", "0").toDouble()*FAKTOR; double radius= spheres.item(i).toElement().attribute("radius", "0").toDouble()*FAKTOR; - //double width = spheres.item(i).toElement().attribute("width", "0").toDouble(); - //double height= spheres.item(i).toElement().attribute("height", "0").toDouble(); + //double width = spheres.item(i).toElement().attribute("width", "0").toDouble(); + //double height= spheres.item(i).toElement().attribute("height", "0").toDouble(); - geometry->addObjectSphere(center,radius,color); - } - // cubic shapes + geometry->addObjectSphere(center,radius,color); + } + // cubic shapes for ( int i = 0; i < cuboids.length(); i++) { - double center[3]; + double center[3]; center[0] = cuboids.item(i).toElement().attribute("centerX", "0").toDouble()*FAKTOR; center[1]= cuboids.item(i).toElement().attribute("centerY", "0").toDouble()*FAKTOR; center[2]= cuboids.item(i).toElement().attribute("centerZ", "0").toDouble()*FAKTOR; - double color= cuboids.item(i).toElement().attribute("color", "0").toDouble(); + double color= cuboids.item(i).toElement().attribute("color", "0").toDouble(); double length= cuboids.item(i).toElement().attribute("length", "0").toDouble()*FAKTOR; double width = cuboids.item(i).toElement().attribute("width", "0").toDouble()*FAKTOR; double height= cuboids.item(i).toElement().attribute("height", "0").toDouble()*FAKTOR; - geometry->addObjectBox(center,height,width,length,color); - // Debug::Error("cuboids: "<<length<<" || " <<width << " || "<<height<<" || "<<color<<endl; - } - // floors + geometry->addObjectBox(center,height,width,length,color); + // Debug::Error("cuboids: "<<length<<" || " <<width << " || "<<height<<" || "<<color<<endl; + } + // floors for ( int i = 0; i < floors.length(); i++) { double left =floors.item(i).toElement().attribute("xMin","0").toDouble()*FAKTOR; @@ -982,37 +842,37 @@ void SaxParser::parseGeometryTRAV(QString content, FacilityGeometry *geometry,QD double up =floors.item(i).toElement().attribute("yMax","0").toDouble()*FAKTOR; double down =floors.item(i).toElement().attribute("yMin","0").toDouble()*FAKTOR; double z =floors.item(i).toElement().attribute("z","0").toDouble()*FAKTOR; - geometry->addFloor(left,down,right,up,z); - } - // cylinders + geometry->addFloor(left,down,right,up,z); + } + // cylinders for ( int i = 0; i < cylinders.length(); i++) { - double center[3], rotation[3]; + double center[3], rotation[3]; center[0] = cylinders.item(i).toElement().attribute("centerX", "0").toDouble()*FAKTOR; center[1]= cylinders.item(i).toElement().attribute("centerY", "0").toDouble()*FAKTOR; center[2]= cylinders.item(i).toElement().attribute("centerZ", "0").toDouble()*FAKTOR; - double color= cylinders.item(i).toElement().attribute("color", "0").toDouble(); + double color= cylinders.item(i).toElement().attribute("color", "0").toDouble(); double radius= cylinders.item(i).toElement().attribute("radius", "0").toDouble()*FAKTOR; double height= cylinders.item(i).toElement().attribute("height", "0").toDouble()*FAKTOR; - rotation[0] = cylinders.item(i).toElement().attribute("angleX", "90").toDouble(); - rotation[1] = cylinders.item(i).toElement().attribute("angleY", "0").toDouble(); - rotation[2] = cylinders.item(i).toElement().attribute("angleZ", "0").toDouble(); - geometry->addObjectCylinder(center,radius,height,rotation,color); - } + rotation[0] = cylinders.item(i).toElement().attribute("angleX", "90").toDouble(); + rotation[1] = cylinders.item(i).toElement().attribute("angleY", "0").toDouble(); + rotation[2] = cylinders.item(i).toElement().attribute("angleZ", "0").toDouble(); + geometry->addObjectCylinder(center,radius,height,rotation,color); + } //Labels for ( int i = 0; i < labels.length(); i++) { - double center[3]; + double center[3]; center[0] = labels.item(i).toElement().attribute("centerX", "0").toDouble()*FAKTOR; center[1]= labels.item(i).toElement().attribute("centerY", "0").toDouble()*FAKTOR; center[2]= labels.item(i).toElement().attribute("centerZ", "0").toDouble()*FAKTOR; - double color= labels.item(i).toElement().attribute("color", "0").toDouble(); - string caption= labels.item(i).toElement().attribute("text", "").toStdString(); - geometry->addObjectLabel(center,center,caption,color); - } - // you should normally have only one geometry node, but one never knows... - geoNode = geoNode.nextSiblingElement("geometry"); + double color= labels.item(i).toElement().attribute("color", "0").toDouble(); + string caption= labels.item(i).toElement().attribute("text", "").toStdString(); + geometry->addObjectLabel(center,center,caption,color); + } + // you should normally have only one geometry node, but one never knows... + geoNode = geoNode.nextSiblingElement("geometry"); } } @@ -1022,16 +882,15 @@ QString SaxParser::extractGeometryFilename(QString &filename) //first try to look at a string <file location="filename.xml"/> QFile file(filename); QString line; - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) - { + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&file); while (!in.atEnd()) { //look for a line with line = in.readLine(); //cout<<"checking: "<<line.toStdString()<<endl; if(line.contains("location" ,Qt::CaseInsensitive)) - if(line.contains("<file" ,Qt::CaseInsensitive)) - {//try to extract what ever is inside the quotes + if(line.contains("<file" ,Qt::CaseInsensitive)) { + //try to extract what ever is inside the quotes QString begin="\""; QString end="\""; @@ -1044,8 +903,8 @@ QString SaxParser::extractGeometryFilename(QString &filename) //break;// we are done } if(line.contains("<geometry" ,Qt::CaseInsensitive)) - if(line.contains("version" ,Qt::CaseInsensitive)) - {//real geometry file + if(line.contains("version" ,Qt::CaseInsensitive)) { + //real geometry file QFileInfo fileInfoGeometry(filename); extracted_geo_name=fileInfoGeometry.fileName(); return extracted_geo_name; @@ -1072,14 +931,14 @@ QString SaxParser::extractGeometryFilename(QString &filename) void SaxParser::parseGeometryXMLV04(QString filename, FacilityGeometry *geo) { - QDomDocument doc(""); + QDomDocument doc(""); - QFile file(filename); + QFile file(filename); int size =file.size()/(1024*1024); //avoid dom parsing a very large dataset - if(size>500){ + if(size>500) { //cout<<"The file is too large: "<<filename.toStdString()<<endl; return; } @@ -1089,167 +948,167 @@ void SaxParser::parseGeometryXMLV04(QString filename, FacilityGeometry *geo) //TODO: check if you can parse this with the building classes. // This should be a fall back option - if (!file.open(QIODevice::ReadOnly)) { - qDebug()<<"could not open the file: "<<filename<<endl; - return ; - } - QString *errorCode = new QString(); - if (!doc.setContent(&file, errorCode)) { - file.close(); - qDebug()<<errorCode<<endl; - return ; - } - QDomElement root= doc.documentElement(); - - //only parsing the geometry node - if(root.tagName()!="geometry") return; - - - double version =root.attribute("version","-1").toDouble(); - - string unit=root.attribute("unit","cm").toStdString(); - double xToCmfactor=100; - if (unit=="cm") xToCmfactor=1; - if (unit=="m") xToCmfactor=100; - - if(version<0.4){ - QMessageBox::warning(0, QObject::tr("Parsing Error"), - QObject::tr("Only geometry version >= 0.4 supported")); - } - - //parsing the subrooms - QDomNodeList xSubRoomsNodeList=doc.elementsByTagName("subroom"); - //parsing the walls + if (!file.open(QIODevice::ReadOnly)) { + qDebug()<<"could not open the file: "<<filename<<endl; + return ; + } + QString *errorCode = new QString(); + if (!doc.setContent(&file, errorCode)) { + file.close(); + qDebug()<<errorCode<<endl; + return ; + } + QDomElement root= doc.documentElement(); + + //only parsing the geometry node + if(root.tagName()!="geometry") return; + + + double version =root.attribute("version","-1").toDouble(); + + string unit=root.attribute("unit","cm").toStdString(); + double xToCmfactor=100; + if (unit=="cm") xToCmfactor=1; + if (unit=="m") xToCmfactor=100; + + if(version<0.4) { + QMessageBox::warning(0, QObject::tr("Parsing Error"), + QObject::tr("Only geometry version >= 0.4 supported")); + } + + //parsing the subrooms + QDomNodeList xSubRoomsNodeList=doc.elementsByTagName("subroom"); + //parsing the walls for ( int i = 0; i < xSubRoomsNodeList.length(); i++) { - QDomElement xPoly = xSubRoomsNodeList.item(i).firstChildElement("polygon"); - double position[3]={0,0,0}; - double pos_count=1; - double color=0; - - while(!xPoly.isNull()) { - //wall thickness, default to 30 cm - double thickness = xPoly.attribute("thickness","15").toDouble(); - //wall height default to 250 cm - double height = xPoly.attribute("height","250").toDouble(); - //wall color default to blue - color = xPoly.attribute("color","0").toDouble(); - - QDomNodeList xVertices=xPoly.elementsByTagName("vertex"); - pos_count+=xVertices.count()-1; - - for( int i=0;i<xVertices.count()-1;i++){ - //all unit are converted in cm - double x1=xVertices.item(i).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y1=xVertices.item(i).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z1=xVertices.item(i).toElement().attribute("pz", "0").toDouble()*xToCmfactor; - double x2=xVertices.item(i+1).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y2=xVertices.item(i+1).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z2=xVertices.item(i+1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; - - position[0]+= x1; - position[1]+= y1; - position[2]+= z1; - - geo->addWall(x1, y1, z1, x2, y2,z2,thickness,height,color); - } - xPoly = xPoly.nextSiblingElement("polygon"); - } - - //add the caption - string roomCaption = xSubRoomsNodeList.item(i).parentNode().toElement().attribute("caption").toStdString(); - string subroomCaption=xSubRoomsNodeList.item(i).toElement().attribute("id").toStdString(); - string caption=roomCaption+" ( " + subroomCaption + " ) "; - position[0]/=pos_count; - position[1]/=pos_count; - position[2]/=pos_count; - geo->addObjectLabel(position,position,caption,color); - //cout<<"position: [" <<position[0]<<", "<<position[1]<<", "<<position[2]<<" ]"<<endl;; - - } - - QDomNodeList xObstaclesList=doc.elementsByTagName("obstacle"); + QDomElement xPoly = xSubRoomsNodeList.item(i).firstChildElement("polygon"); + double position[3]= {0,0,0}; + double pos_count=1; + double color=0; + + while(!xPoly.isNull()) { + //wall thickness, default to 30 cm + double thickness = xPoly.attribute("thickness","15").toDouble(); + //wall height default to 250 cm + double height = xPoly.attribute("height","250").toDouble(); + //wall color default to blue + color = xPoly.attribute("color","0").toDouble(); + + QDomNodeList xVertices=xPoly.elementsByTagName("vertex"); + pos_count+=xVertices.count()-1; + + for( int i=0; i<xVertices.count()-1; i++) { + //all unit are converted in cm + double x1=xVertices.item(i).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y1=xVertices.item(i).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z1=xVertices.item(i).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + double x2=xVertices.item(i+1).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y2=xVertices.item(i+1).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z2=xVertices.item(i+1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + + position[0]+= x1; + position[1]+= y1; + position[2]+= z1; + + geo->addWall(x1, y1, z1, x2, y2,z2,thickness,height,color); + } + xPoly = xPoly.nextSiblingElement("polygon"); + } + + //add the caption + string roomCaption = xSubRoomsNodeList.item(i).parentNode().toElement().attribute("caption").toStdString(); + string subroomCaption=xSubRoomsNodeList.item(i).toElement().attribute("id").toStdString(); + string caption=roomCaption+" ( " + subroomCaption + " ) "; + position[0]/=pos_count; + position[1]/=pos_count; + position[2]/=pos_count; + geo->addObjectLabel(position,position,caption,color); + //cout<<"position: [" <<position[0]<<", "<<position[1]<<", "<<position[2]<<" ]"<<endl;; + + } + + QDomNodeList xObstaclesList=doc.elementsByTagName("obstacle"); for ( int i = 0; i < xObstaclesList.length(); i++) { - QDomElement xPoly = xObstaclesList.item(i).firstChildElement("polygon"); - while(!xPoly.isNull()) { - //wall thickness, default to 30 cm - double thickness = xPoly.attribute("thickness","15").toDouble(); - //wall height default to 250 cm - double height = xPoly.attribute("height","250").toDouble(); - //wall color default to blue - double color = xPoly.attribute("color","0").toDouble(); - - QDomNodeList xVertices=xPoly.elementsByTagName("vertex"); - for( int i=0;i<xVertices.count()-1;i++){ - double x1=xVertices.item(i).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y1=xVertices.item(i).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z1=xVertices.item(i).toElement().attribute("pz", "0").toDouble()*xToCmfactor; - - double x2=xVertices.item(i+1).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y2=xVertices.item(i+1).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z2=xVertices.item(i+1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; - geo->addWall(x1, y1, z1, x2, y2,z2,thickness,height,color); - } - xPoly = xPoly.nextSiblingElement("polygon"); - } - } - - QDomNodeList xCrossingsList=doc.elementsByTagName("crossing"); + QDomElement xPoly = xObstaclesList.item(i).firstChildElement("polygon"); + while(!xPoly.isNull()) { + //wall thickness, default to 30 cm + double thickness = xPoly.attribute("thickness","15").toDouble(); + //wall height default to 250 cm + double height = xPoly.attribute("height","250").toDouble(); + //wall color default to blue + double color = xPoly.attribute("color","0").toDouble(); + + QDomNodeList xVertices=xPoly.elementsByTagName("vertex"); + for( int i=0; i<xVertices.count()-1; i++) { + double x1=xVertices.item(i).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y1=xVertices.item(i).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z1=xVertices.item(i).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + + double x2=xVertices.item(i+1).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y2=xVertices.item(i+1).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z2=xVertices.item(i+1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + geo->addWall(x1, y1, z1, x2, y2,z2,thickness,height,color); + } + xPoly = xPoly.nextSiblingElement("polygon"); + } + } + + QDomNodeList xCrossingsList=doc.elementsByTagName("crossing"); for (int i = 0; i < xCrossingsList.length(); i++) { - QDomElement xCrossing = xCrossingsList.item(i).toElement(); - QDomNodeList xVertices=xCrossing.elementsByTagName("vertex"); - - ///door thickness, default to 15 cm - double thickness = xCrossing.attribute("thickness","15").toDouble(); - //door height default to 250 cm - double height = xCrossing.attribute("height","250").toDouble(); - //door color default to blue + QDomElement xCrossing = xCrossingsList.item(i).toElement(); + QDomNodeList xVertices=xCrossing.elementsByTagName("vertex"); + + ///door thickness, default to 15 cm + double thickness = xCrossing.attribute("thickness","15").toDouble(); + //door height default to 250 cm + double height = xCrossing.attribute("height","250").toDouble(); + //door color default to blue double color = xCrossing.attribute("color","120").toDouble(); - QString id= xCrossing.attribute("id","-1"); + QString id= xCrossing.attribute("id","-1"); - double x1=xVertices.item(0).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y1=xVertices.item(0).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z1=xVertices.item(0).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + double x1=xVertices.item(0).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y1=xVertices.item(0).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z1=xVertices.item(0).toElement().attribute("pz", "0").toDouble()*xToCmfactor; - double x2=xVertices.item(1).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y2=xVertices.item(1).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z2=xVertices.item(1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + double x2=xVertices.item(1).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y2=xVertices.item(1).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z2=xVertices.item(1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; geo->addNavLine(x1, y1, z1, x2, y2,z2,thickness,height,color); - double center[3]={(x1+x2)/2.0, (y1+y2)/2.0, (z2+z1)/2.0}; - geo->addObjectLabel(center,center,id.toStdString(),21); - } + double center[3]= {(x1+x2)/2.0, (y1+y2)/2.0, (z2+z1)/2.0}; + geo->addObjectLabel(center,center,id.toStdString(),21); + } - QDomNodeList xTransitionsList=doc.elementsByTagName("transition"); + QDomNodeList xTransitionsList=doc.elementsByTagName("transition"); for (int i = 0; i < xTransitionsList.length(); i++) { - QDomElement xTransition = xTransitionsList.item(i).toElement(); - QDomNodeList xVertices=xTransition.elementsByTagName("vertex"); - - ///door thickness, default to 15 cm - double thickness = xTransition.attribute("thickness","15").toDouble(); - //door height default to 250 cm - double height = xTransition.attribute("height","250").toDouble(); - //door color default to blue - double color = xTransition.attribute("color","255").toDouble(); - - double x1=xVertices.item(0).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y1=xVertices.item(0).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z1=xVertices.item(0).toElement().attribute("pz", "0").toDouble()*xToCmfactor; - - double x2=xVertices.item(1).toElement().attribute("px", "0").toDouble()*xToCmfactor; - double y2=xVertices.item(1).toElement().attribute("py", "0").toDouble()*xToCmfactor; - double z2=xVertices.item(1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; - geo->addDoor(x1, y1, z1, x2, y2,z2,thickness,height,color); - - string id= xTransition.attribute("id","-1").toStdString(); - double center[3]={(x1+x2)/2.0, (y1+y2)/2.0, (z2+z1)/2.0}; - geo->addObjectLabel(center,center,id,21); - } + QDomElement xTransition = xTransitionsList.item(i).toElement(); + QDomNodeList xVertices=xTransition.elementsByTagName("vertex"); + + ///door thickness, default to 15 cm + double thickness = xTransition.attribute("thickness","15").toDouble(); + //door height default to 250 cm + double height = xTransition.attribute("height","250").toDouble(); + //door color default to blue + double color = xTransition.attribute("color","255").toDouble(); + + double x1=xVertices.item(0).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y1=xVertices.item(0).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z1=xVertices.item(0).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + + double x2=xVertices.item(1).toElement().attribute("px", "0").toDouble()*xToCmfactor; + double y2=xVertices.item(1).toElement().attribute("py", "0").toDouble()*xToCmfactor; + double z2=xVertices.item(1).toElement().attribute("pz", "0").toDouble()*xToCmfactor; + geo->addDoor(x1, y1, z1, x2, y2,z2,thickness,height,color); + + string id= xTransition.attribute("id","-1").toStdString(); + double center[3]= {(x1+x2)/2.0, (y1+y2)/2.0, (z2+z1)/2.0}; + geo->addObjectLabel(center,center,id,21); + } } void SaxParser::InitHeader(int major, int minor, int patch) { - if ( (minor==6) || (minor==5 && patch==1) ){ + if ( (minor==6) || (minor==5 && patch==1) ) { _jps_xPos=QString("x"); _jps_yPos=QString("y"); _jps_zPos=QString("z"); @@ -1260,9 +1119,7 @@ void SaxParser::InitHeader(int major, int minor, int patch) _jps_radiusB=QString("rB"); _jps_ellipseOrientation=QString("eO"); _jps_ellipseColor=QString("eC"); - } - else - { + } else { _jps_xPos=QString("xPos"); _jps_yPos=QString("yPos"); _jps_zPos=QString("zPos"); @@ -1274,7 +1131,7 @@ void SaxParser::InitHeader(int major, int minor, int patch) _jps_ellipseOrientation=QString("ellipseOrientation"); _jps_ellipseColor=QString("ellipseColor"); } - if(major!=0){ + if(major!=0) { cout<<"unsupported header version: "<<major<<"."<<minor<<"."<<patch<<endl; cout<<"Please use 0.5 0.5.1 or 0.6 "<<endl; exit(0); diff --git a/src/SimpleVisualisationWindow.cpp b/src/SimpleVisualisationWindow.cpp index ef749a60bc682a1a82ab2d2225d520d7a45e13b5..7dcfe5db285c3c8f76844a32caf3676eae86ba0f 100644 --- a/src/SimpleVisualisationWindow.cpp +++ b/src/SimpleVisualisationWindow.cpp @@ -42,28 +42,32 @@ #include "./geometry/LinePlotter.h" #include "./geometry/PointPlotter.h" -SimpleVisualisationWindow::SimpleVisualisationWindow() { - assembly =NULL; - //actor=NULL; +SimpleVisualisationWindow::SimpleVisualisationWindow() +{ + assembly =NULL; + //actor=NULL; } -SimpleVisualisationWindow::~SimpleVisualisationWindow() { +SimpleVisualisationWindow::~SimpleVisualisationWindow() +{ } -void SimpleVisualisationWindow::setActor(vtkAssembly* actor){ - assembly=actor; +void SimpleVisualisationWindow::setActor(vtkAssembly* actor) +{ + assembly=actor; } -void SimpleVisualisationWindow::start(){ +void SimpleVisualisationWindow::start() +{ - // Create the renderer with black bg - vtkRenderer* renderer = vtkRenderer::New(); - renderer->SetBackground(0,0,0); + // Create the renderer with black bg + vtkRenderer* renderer = vtkRenderer::New(); + renderer->SetBackground(0,0,0); // //add the line actor // LinePlotter * ln = new LinePlotter(); @@ -79,7 +83,7 @@ void SimpleVisualisationWindow::start(){ // ln->PlotLine(81,821,81,14,134,134,1); // renderer->AddActor(ln->getActor()); - // + // // PointPlotter * pt = new PointPlotter(); // pt->PlotPoint(324,34,34); // pt->PlotPoint(1,1,1); @@ -89,54 +93,54 @@ void SimpleVisualisationWindow::start(){ // pt->PlotPoint(134,14,134); // renderer->AddActor(pt->getActor()); - //add the different actors - renderer->AddActor(assembly); - //renderer->AddActor(actor); + //add the different actors + renderer->AddActor(assembly); + //renderer->AddActor(actor); - // Set up the lighting. - vtkLight *light = vtkLight::New(); - light->SetFocalPoint(1.875,0.6125,0); - light->SetPosition(3000,3000,10); - light->SetIntensity(1); - light->SetLightTypeToCameraLight(); - // renderer->AddLight(light); + // Set up the lighting. + vtkLight *light = vtkLight::New(); + light->SetFocalPoint(1.875,0.6125,0); + light->SetPosition(3000,3000,10); + light->SetIntensity(1); + light->SetLightTypeToCameraLight(); + // renderer->AddLight(light); // light->Delete(); - // Create a render window - vtkRenderWindow *renderWindow = vtkRenderWindow::New(); - renderWindow->AddRenderer( renderer ); - renderWindow->SetSize(600, 800); + // Create a render window + vtkRenderWindow *renderWindow = vtkRenderWindow::New(); + renderWindow->AddRenderer( renderer ); + renderWindow->SetSize(600, 800); - //CAUTION: this is necessary for windows to update the window name after the first render - // but this will freeze your system on linux, strange.... + //CAUTION: this is necessary for windows to update the window name after the first render + // but this will freeze your system on linux, strange.... #ifdef WIN32 - renderWindow->Render(); + renderWindow->Render(); #endif - renderWindow->SetWindowName("Visualizing a Geometry"); - - - // Create an interactor - vtkRenderWindowInteractor *renderWinInteractor = vtkRenderWindowInteractor::New(); - renderWinInteractor = vtkRenderWindowInteractor::New(); - renderWindow->SetInteractor( renderWinInteractor ); - //set full screen and catch esc to restore defaults one - //renderWindow->SetFullScreen(1); - - // Create my interactor style - vtkInteractorStyleTrackballCamera* style = vtkInteractorStyleTrackballCamera::New(); - renderWinInteractor->SetInteractorStyle( style ); - style->Delete(); - - // Initialize and enter interactive mode - renderWinInteractor->Initialize(); - renderWinInteractor->Start(); - - //cleaning up - renderWindow->Delete(); - renderWinInteractor->Delete(); - if(assembly) - assembly->Delete(); + renderWindow->SetWindowName("Visualizing a Geometry"); + + + // Create an interactor + vtkRenderWindowInteractor *renderWinInteractor = vtkRenderWindowInteractor::New(); + renderWinInteractor = vtkRenderWindowInteractor::New(); + renderWindow->SetInteractor( renderWinInteractor ); + //set full screen and catch esc to restore defaults one + //renderWindow->SetFullScreen(1); + + // Create my interactor style + vtkInteractorStyleTrackballCamera* style = vtkInteractorStyleTrackballCamera::New(); + renderWinInteractor->SetInteractorStyle( style ); + style->Delete(); + + // Initialize and enter interactive mode + renderWinInteractor->Initialize(); + renderWinInteractor->Start(); + + //cleaning up + renderWindow->Delete(); + renderWinInteractor->Delete(); + if(assembly) + assembly->Delete(); // if(actor) // actor->Delete(); diff --git a/src/SimpleVisualisationWindow.h b/src/SimpleVisualisationWindow.h index 50bebbb1e772795f738547e9cf09dc5e6c5ef502..adda3054f00ede72f10a7ec02b2971bc871caadd 100644 --- a/src/SimpleVisualisationWindow.h +++ b/src/SimpleVisualisationWindow.h @@ -43,24 +43,24 @@ class vtkActor; class SimpleVisualisationWindow { public: - ///constructor - SimpleVisualisationWindow(); - ///destructor - virtual ~SimpleVisualisationWindow(); + ///constructor + SimpleVisualisationWindow(); + ///destructor + virtual ~SimpleVisualisationWindow(); - ///add an assembly actor - void setActor(vtkAssembly* actor); + ///add an assembly actor + void setActor(vtkAssembly* actor); // ///add a simple (single) actor // void setActor(vtkActor* actor); - ///start the visualisation - //with the defaults parameters - void start(); + ///start the visualisation + //with the defaults parameters + void start(); private: - vtkAssembly* assembly; - //vtkActor* actor; + vtkAssembly* assembly; + //vtkActor* actor; }; #endif /* SIMPLEVISUALISATIONWINDOW_H_ */ diff --git a/src/SyncData.cpp b/src/SyncData.cpp index af19786306de4e48aae805727de6ebe706b26950..899727721af2f9ea3850ed4549ffcfa2fa825a9c 100644 --- a/src/SyncData.cpp +++ b/src/SyncData.cpp @@ -48,31 +48,34 @@ using namespace std; -SyncData::SyncData() { - frameCursor=0; - numberOfAgents=0; - delay_ms_rel=0; //absolute - delay_s_abs=0; //relative - delay_us_abs=0; //absolute - frameCursorOffset=0; +SyncData::SyncData() +{ + frameCursor=0; + numberOfAgents=0; + delay_ms_rel=0; //absolute + delay_s_abs=0; //relative + delay_us_abs=0; //absolute + frameCursorOffset=0; } -SyncData::~SyncData() { - // trajectories.clear(); - while (!frames.empty()){ - delete frames.back(); - frames.pop_back(); - } - frames.clear(); +SyncData::~SyncData() +{ + // trajectories.clear(); + while (!frames.empty()) { + delete frames.back(); + frames.pop_back(); + } + frames.clear(); } -void SyncData::add(std::string newData){ - // mutex.lock(); - // trajectories.push_back(newData); - // mutex.unlock(); +void SyncData::add(std::string newData) +{ + // mutex.lock(); + // trajectories.push_back(newData); + // mutex.unlock(); } @@ -85,85 +88,89 @@ void SyncData::add(std::string newData){ // // mutex.unlock(); //} -std::string SyncData::get(){ - std::string res; - // mutex.lock(); - // if(trajectories.empty()) { - // res=""; - // emit signal_controlSequences("CONTROL_STACK_EMPTY"); - // } - // else{ - // res= trajectories.front(); - // trajectories.erase(trajectories.begin()); - // } - //#ifdef _DEBUG - // std::cout<<"size: " <<trajectories.size()<<std::endl; - //#endif - // mutex.unlock(); - return res; +std::string SyncData::get() +{ + std::string res; + // mutex.lock(); + // if(trajectories.empty()) { + // res=""; + // emit signal_controlSequences("CONTROL_STACK_EMPTY"); + // } + // else{ + // res= trajectories.front(); + // trajectories.erase(trajectories.begin()); + // } + //#ifdef _DEBUG + // std::cout<<"size: " <<trajectories.size()<<std::endl; + //#endif + // mutex.unlock(); + return res; } -void SyncData::setFrameCursorOffset(int offset){ - frameCursorOffset=offset; +void SyncData::setFrameCursorOffset(int offset) +{ + frameCursorOffset=offset; } -void SyncData::addFrame(Frame* frame){ - mutex.lock(); - frames.push_back(frame); - mutex.unlock(); +void SyncData::addFrame(Frame* frame) +{ + mutex.lock(); + frames.push_back(frame); + mutex.unlock(); } -Frame* SyncData::getFrame(unsigned int i){ - mutex.lock(); - i+=frameCursorOffset; +Frame* SyncData::getFrame( int i) +{ + mutex.lock(); + i+=frameCursorOffset; - if((i<0) || (i>=frames.size())){ - mutex.unlock(); - return NULL; - } - else{ - mutex.unlock(); - return frames.at(i); - } + if((i<0) || (i>= (int)frames.size())) { + mutex.unlock(); + return NULL; + } else { + mutex.unlock(); + return frames.at(i); + } } -Frame* SyncData::getNextFrame(){ +Frame* SyncData::getNextFrame() +{ - // this may be the case if the file only contains geometry, thus no trajectories available - if(frames.empty()) return NULL; + // this may be the case if the file only contains geometry, thus no trajectories available + if(frames.empty()) return NULL; - // Navigation in the negative direction is also possible - //review - mutex.lock(); + // Navigation in the negative direction is also possible + //review + mutex.lock(); - frameCursor+=extern_update_step; + frameCursor+=extern_update_step; - //FIXME: do I really need two variables to handle this? - int cursor =frameCursor+frameCursorOffset; + //FIXME: do I really need two variables to handle this? + int cursor =frameCursor+frameCursorOffset; - if (cursor<0) { - //frameCursor=0; - emit signal_controlSequences("STACK_REACHS_BEGINNING"); - mutex.unlock(); - return NULL; + if (cursor<0) { + //frameCursor=0; + emit signal_controlSequences("STACK_REACHS_BEGINNING"); + mutex.unlock(); + return NULL; - }else if ((unsigned)cursor>=frames.size()){ + } else if ((unsigned)cursor>=frames.size()) { - //if(extern_offline_mode) - emit signal_controlSequences("CONTROL_STACK_EMPTY"); - //frameCursor=frames.size()-1; - mutex.unlock(); - // FIXME: check me, return the last frame, if in o - //return frames.at(frames.size()-1); - frameCursor-=extern_update_step; - return frames.back(); - //return NULL; - } + //if(extern_offline_mode) + emit signal_controlSequences("CONTROL_STACK_EMPTY"); + //frameCursor=frames.size()-1; + mutex.unlock(); + // FIXME: check me, return the last frame, if in o + //return frames.at(frames.size()-1); + frameCursor-=extern_update_step; + return frames.back(); + //return NULL; + } - Frame* res =frames.at(cursor); - mutex.unlock(); - return res; + Frame* res =frames.at(cursor); + mutex.unlock(); + return res; } /*** @@ -171,145 +178,156 @@ Frame* SyncData::getNextFrame(){ * The normal way to get the previous frame is: * 1. either set the variable extern_update_step to a negative value; * 2. using the function getFrame(int frameNumber). one may first get -* the current framecursor position using getFrameCursor() +* the current framecursor position using getFrameCursor() */ -Frame* SyncData::getPreviousFrame(){ - - mutex.lock(); - frameCursor--; - //FIXME: do I really need two variables to handle this? - int cursor =frameCursor+frameCursorOffset; - - if(cursor<0) { - //emit signal_controlSequences("STACK_REACHS_BEGINNING"); - //frameCursor=0; - mutex.unlock(); - return NULL; - }else - if((unsigned)cursor>=frames.size() ) { - //emit signal_controlSequences("CONTROL_STACK_EMPTY"); - mutex.unlock(); - //frameCursor=frames.size()-1; - return NULL; - } - - Frame* res =frames.at(cursor); - - mutex.unlock(); - - return res; +Frame* SyncData::getPreviousFrame() +{ + + mutex.lock(); + frameCursor--; + //FIXME: do I really need two variables to handle this? + int cursor =frameCursor+frameCursorOffset; + + if(cursor<0) { + //emit signal_controlSequences("STACK_REACHS_BEGINNING"); + //frameCursor=0; + mutex.unlock(); + return NULL; + } else if((unsigned)cursor>=frames.size() ) { + //emit signal_controlSequences("CONTROL_STACK_EMPTY"); + mutex.unlock(); + //frameCursor=frames.size()-1; + return NULL; + } + + Frame* res =frames.at(cursor); + + mutex.unlock(); + + return res; } -void SyncData::clearFrames(){ - mutex.lock(); +void SyncData::clearFrames() +{ + mutex.lock(); - frameCursor=0; - numberOfAgents=0; - frameCursorOffset=0; - pedHeight.clear(); - pedColor.clear(); + frameCursor=0; + numberOfAgents=0; + frameCursorOffset=0; + pedHeight.clear(); + pedColor.clear(); - while (!frames.empty()){ - delete frames.back(); - frames.pop_back(); - } - frames.clear(); + while (!frames.empty()) { + delete frames.back(); + frames.pop_back(); + } + frames.clear(); - mutex.unlock(); + mutex.unlock(); } -int SyncData::getFramesNumber(){ - //mutex.lock(); //FIXME - return frames.size(); - //mutex.unlock(); +int SyncData::getFramesNumber() +{ + //mutex.lock(); //FIXME + return frames.size(); + //mutex.unlock(); } -void SyncData::resetFrameCursor(){ - mutex.lock(); - frameCursor=0; - mutex.unlock(); +void SyncData::resetFrameCursor() +{ + mutex.lock(); + frameCursor=0; + mutex.unlock(); } -int SyncData::getFrameCursor(){ +int SyncData::getFrameCursor() +{ - return frameCursor; + return frameCursor; } -void SyncData::setFrameCursorTo(int position){ +void SyncData::setFrameCursorTo(int position) +{ - mutex.lock(); + mutex.lock(); - //TODO: check the unsigned - //if((unsigned)position>=frames.size()) frameCursor =frames.size()-1; - //else if (position<0) frameCursor =0; - //else - frameCursor=position; + //TODO: check the unsigned + //if((unsigned)position>=frames.size()) frameCursor =frames.size()-1; + //else if (position<0) frameCursor =0; + //else + frameCursor=position; - mutex.unlock(); + mutex.unlock(); } int SyncData::getNumberOfAgents() { - return 0; - return numberOfAgents; + return numberOfAgents; } void SyncData::setNumberOfAgents(int numberOfAgents) { - mutex.lock(); - this->numberOfAgents = numberOfAgents; - mutex.unlock(); + mutex.lock(); + this->numberOfAgents = numberOfAgents; + mutex.unlock(); } -void SyncData::setDelayAbsolute(unsigned long second, unsigned long microsecond=0){ - delay_s_abs=second; - delay_us_abs=microsecond; +void SyncData::setDelayAbsolute(unsigned long second, unsigned long microsecond=0) +{ + delay_s_abs=second; + delay_us_abs=microsecond; } ///@warning only handle seconds, microseconds are ignored -void SyncData::computeDelayRelative(unsigned long* delays){ - unsigned long sec = delays[0]; - unsigned long usec = delays[1]; - long double delay_a = sec*1000 + (double)usec/1000.0; - long double delay_b = delay_s_abs*1000 + (double)delay_us_abs/1000.0; +void SyncData::computeDelayRelative(unsigned long* delays) +{ + unsigned long sec = delays[0]; + unsigned long usec = delays[1]; + long double delay_a = sec*1000 + (double)usec/1000.0; + long double delay_b = delay_s_abs*1000 + (double)delay_us_abs/1000.0; - delay_ms_rel=delay_a-delay_b; - //std::cerr <<"the delay is: " << delay_ms_rel<<std::endl; - //delay_ms_rel=(sec-delay_s_abs)*1000; + delay_ms_rel=delay_a-delay_b; + //std::cerr <<"the delay is: " << delay_ms_rel<<std::endl; + //delay_ms_rel=(sec-delay_s_abs)*1000; - if (delay_ms_rel<0){ - Debug::Warning("warning: negative delay found"); - } + if (delay_ms_rel<0) { + Debug::Warning("warning: negative delay found"); + } } /// @warning the old value obtained from computeDelayRelative is just overwritten // -void SyncData::setDelayRelative(signed long milliseconds){ - delay_ms_rel=milliseconds; +void SyncData::setDelayRelative(signed long milliseconds) +{ + delay_ms_rel=milliseconds; } -void SyncData::getDelayAbsolute(unsigned long* delays){ - delays[0]=delay_s_abs; - delays[1]=delay_us_abs; +void SyncData::getDelayAbsolute(unsigned long* delays) +{ + delays[0]=delay_s_abs; + delays[1]=delay_us_abs; } -signed long SyncData::getDelayRelative(){ - return delay_ms_rel; +signed long SyncData::getDelayRelative() +{ + return delay_ms_rel; } -void SyncData::setInitialHeights(const QStringList& pedHeight){ - this->pedHeight.clear(); - this->pedHeight=pedHeight; +void SyncData::setInitialHeights(const QStringList& pedHeight) +{ + this->pedHeight.clear(); + this->pedHeight=pedHeight; } -unsigned int SyncData::getSize(){ - if(frames.empty()) return 0; - else return frames.size(); +unsigned int SyncData::getSize() +{ + if(frames.empty()) return 0; + else return frames.size(); } diff --git a/src/SyncData.h b/src/SyncData.h index 411507ccf2a87bb5d6b43d3b9603be3559c84310..3a7383b7a95761fada115fc626ce4d8ace24baee 100644 --- a/src/SyncData.h +++ b/src/SyncData.h @@ -48,139 +48,145 @@ extern bool extern_offline_mode; class SyncData: public QObject { - Q_OBJECT + Q_OBJECT public: - SyncData(); - virtual ~SyncData(); + SyncData(); + virtual ~SyncData(); - void add(std::string newData); - std::string get(); - //void clear(); - void resetFrameCursor(); + void add(std::string newData); + std::string get(); + //void clear(); + void resetFrameCursor(); - /// get the size - unsigned int getSize(); + /// get the size + unsigned int getSize(); - /// add a frame to the synchronized data - void addFrame(Frame* frame); + /// add a frame to the synchronized data + void addFrame(Frame* frame); - /// clears all frames - void clearFrames(); + /// clears all frames + void clearFrames(); - /// returns the total number of frames - int getFramesNumber(); + /// returns the total number of frames + int getFramesNumber(); - /// return the position of the actual frame - int getFrameCursor(); + /// return the position of the actual frame + int getFrameCursor(); - /// set to cursor position - void setFrameCursorTo(int position); + /// set to cursor position + void setFrameCursorTo(int position); - /// return the frame at position i - Frame* getFrame(unsigned int i); + /// return the frame at position i + Frame* getFrame(int i); - /// return a pointer to the next frame - Frame* getNextFrame(); + /// return a pointer to the next frame + Frame* getNextFrame(); - /// return a poiner to the previous frame - Frame* getPreviousFrame(); + /// return a poiner to the previous frame + Frame* getPreviousFrame(); - /// return the number of pedestrians involved in this dataset - int getNumberOfAgents(); + /// return the number of pedestrians involved in this dataset + int getNumberOfAgents(); - /// set the number of pedestrians - void setNumberOfAgents(int numberOfAgents); + /// set the number of pedestrians + void setNumberOfAgents(int numberOfAgents); - /// set the absolute time (delay) after which, this dataset will start to play. - /// This is useful when loading several datasets, that needs to be synchronised. - /// @para second the number of seconds elapsed since midnight 1970 - /// @para microsecond the number of microsecond(in addition to the seconds) - void setDelayAbsolute(unsigned long second, unsigned long microsecond/*=0*/); + /// set the absolute time (delay) after which, this dataset will start to play. + /// This is useful when loading several datasets, that needs to be synchronised. + /// @para second the number of seconds elapsed since midnight 1970 + /// @para microsecond the number of microsecond(in addition to the seconds) + void setDelayAbsolute(unsigned long second, unsigned long microsecond/*=0*/); - /// returns the arguments given in setDelay. - void getDelayAbsolute(unsigned long *); + /// returns the arguments given in setDelay. + void getDelayAbsolute(unsigned long *); - /// get the relative delays between the dataset in millisecond. - /// the delay of the first dataset/group will typically have the delay 0 ms. - signed long getDelayRelative(); + /// get the relative delays between the dataset in millisecond. + /// the delay of the first dataset/group will typically have the delay 0 ms. + signed long getDelayRelative(); - /// set the relative delays + /// set the relative delays - void setDelayRelative(signed long milliseconds); + void setDelayRelative(signed long milliseconds); - /// compute the relative relative - /// @deprecated [should use setDelayRelative] - void computeDelayRelative(unsigned long* delays); + /// compute the relative relative + /// @deprecated [should use setDelayRelative] + void computeDelayRelative(unsigned long* delays); - /// set the offset. - /// this is useful when several datasets needed - /// to be synchronized - void setFrameCursorOffset(int offset); + /// set the offset. + /// this is useful when several datasets needed + /// to be synchronized + void setFrameCursorOffset(int offset); - /// \brief initialize the pedestrians height. - /// the initialiation is a list, where the even terms are the IDs - /// and the odd terms are the heights - void setInitialHeights(const QStringList& pedHeight); + /// \brief initialize the pedestrians height. + /// the initialiation is a list, where the even terms are the IDs + /// and the odd terms are the heights + void setInitialHeights(const QStringList& pedHeight); - /// \brief get initial heights - QStringList getInitialHeights() { - return pedHeight; - } + /// \brief get initial heights + QStringList getInitialHeights() + { + return pedHeight; + } - /** - * \brief Set the pedestrian initial colors. - * the initialiation is a list, where the even terms are the IDs - * and the odd terms are the Colors - * @param pedColor - */ - void setInitialColors(const QStringList& pedColor){this->pedColor.clear();this->pedColor=pedColor;}; + /** + * \brief Set the pedestrian initial colors. + * the initialiation is a list, where the even terms are the IDs + * and the odd terms are the Colors + * @param pedColor + */ + void setInitialColors(const QStringList& pedColor) + { + this->pedColor.clear(); + this->pedColor=pedColor; + }; - /** - * \brief return the initial colors - */ + /** + * \brief return the initial colors + */ - QStringList getInitialColors() { - return pedColor; - } + QStringList getInitialColors() + { + return pedColor; + } - Q_SIGNALS: - /// send a control sequence to the main GUI. - /// a control sequence could be STACK_EMPTY. - void signal_controlSequences(const char* sex); +Q_SIGNALS: + /// send a control sequence to the main GUI. + /// a control sequence could be STACK_EMPTY. + void signal_controlSequences(const char* sex); private: - //general information about this dataset - float frameRate; - char roomCaption[256]; + //general information about this dataset + float frameRate; + char roomCaption[256]; - // give the actual position of the frame beeing read, in the frame dataset + // give the actual position of the frame beeing read, in the frame dataset - // the actual position (real) of the frame - int frameCursor; + // the actual position (real) of the frame + int frameCursor; - // the offset. this is 0 when all dataets are synchronised - int frameCursorOffset; + // the offset. this is 0 when all dataets are synchronised + int frameCursorOffset; - // relative delay in milliseconds - signed long delay_ms_rel; - // ablotute time elapsed since 1970 in sec - unsigned long delay_s_abs; - // absolute additional time in microsecond - unsigned long delay_us_abs; + // relative delay in milliseconds + signed long delay_ms_rel; + // ablotute time elapsed since 1970 in sec + unsigned long delay_s_abs; + // absolute additional time in microsecond + unsigned long delay_us_abs; - // list containing the initial heights of pedestrians - QStringList pedHeight; + // list containing the initial heights of pedestrians + QStringList pedHeight; - /// list containing the initial colors of pedestrians - QStringList pedColor; + /// list containing the initial colors of pedestrians + QStringList pedColor; - /// the number of agents - int numberOfAgents; - QMutex mutex; - std::vector<Frame*> frames; + /// the number of agents + int numberOfAgents; + QMutex mutex; + std::vector<Frame*> frames; }; #endif /* SYNCDATA_H_ */ diff --git a/src/SystemSettings.cpp b/src/SystemSettings.cpp index 8cbd50756b66875e835f123121a2df6ce5058099..709f29399bfb457bacc29957f96fa1a9efd13dc3 100644 --- a/src/SystemSettings.cpp +++ b/src/SystemSettings.cpp @@ -49,8 +49,8 @@ bool SystemSettings::showAgents=true; bool SystemSettings::showGeometry=true; bool SystemSettings::showFloor=true; unsigned short SystemSettings::port=8989; -double SystemSettings::bgColor[]={1.0,1.0,1.0}; -int SystemSettings::pedestriansColor[3][3]={{255 , 17, 224},{122, 255, 122},{130, 130, 130}}; +double SystemSettings::bgColor[]= {1.0,1.0,1.0}; +int SystemSettings::pedestriansColor[3][3]= {{255 , 17, 224},{122, 255, 122},{130, 130, 130}}; int SystemSettings::pedesShape=Settings::PINGUINS; int SystemSettings::ellipseResolution=10; int SystemSettings::trailCount=50; @@ -79,38 +79,46 @@ SystemSettings::SystemSettings() {} SystemSettings::~SystemSettings() {} -void SystemSettings::setShowLegend(bool legend){ - showLegend=legend; +void SystemSettings::setShowLegend(bool legend) +{ + showLegend=legend; } -bool SystemSettings::getShowLegend(){ - return showLegend; +bool SystemSettings::getShowLegend() +{ + return showLegend; } -void SystemSettings::setListningPort(unsigned short porta){ - port=porta; +void SystemSettings::setListningPort(unsigned short porta) +{ + port=porta; } -unsigned short SystemSettings::getListeningPort(){ - return port; +unsigned short SystemSettings::getListeningPort() +{ + return port; } -void SystemSettings::setShowAgentsCaptions(bool caption){ +void SystemSettings::setShowAgentsCaptions(bool caption) +{ showAgentsCaptions=caption; } -bool SystemSettings::getShowAgentsCaptions(){ +bool SystemSettings::getShowAgentsCaptions() +{ return showAgentsCaptions; } -void SystemSettings::set2D(bool lis2D){ - is2D=lis2D; +void SystemSettings::set2D(bool lis2D) +{ + is2D=lis2D; } -bool SystemSettings::get2D(){ - return is2D; +bool SystemSettings::get2D() +{ + return is2D; } // set/get the 2D visio @@ -154,107 +162,124 @@ void SystemSettings::getWorkingDirectory(QString& dir) dir=workingDir; } -void SystemSettings::getBackgroundColor(double* col){ - col[0]=bgColor[0]; - col[1]=bgColor[1]; - col[2]=bgColor[2]; +void SystemSettings::getBackgroundColor(double* col) +{ + col[0]=bgColor[0]; + col[1]=bgColor[1]; + col[2]=bgColor[2]; } -void SystemSettings::setBackgroundColor(double* col){ - bgColor[0]=col[0]; - bgColor[1]=col[1]; - bgColor[2]=col[2]; +void SystemSettings::setBackgroundColor(double* col) +{ + bgColor[0]=col[0]; + bgColor[1]=col[1]; + bgColor[2]=col[2]; } /// set/get pedestrian private sphere ellipse resolution -int SystemSettings::getEllipseResolution(){ - return ellipseResolution; +int SystemSettings::getEllipseResolution() +{ + return ellipseResolution; } -void SystemSettings::setEllipseResolution(int resolution){ - ellipseResolution=resolution; +void SystemSettings::setEllipseResolution(int resolution) +{ + ellipseResolution=resolution; } /// set/get the pedestrian shape /// 0 for default, 1 for Ellipse, 2 for pinguins -void SystemSettings::setPedestrianShape(int shape){ - pedesShape=shape; +void SystemSettings::setPedestrianShape(int shape) +{ + pedesShape=shape; } -int SystemSettings::getPedestrianShape(){ - return pedesShape; +int SystemSettings::getPedestrianShape() +{ + return pedesShape; } -void SystemSettings::setTrailsInfo(int count, int type, int geo){ - trailCount=count; - trailingType=type; - trailingGeometry=geo; +void SystemSettings::setTrailsInfo(int count, int type, int geo) +{ + trailCount=count; + trailingType=type; + trailingGeometry=geo; } -void SystemSettings::getTrailsInfo(int* count, int *type, int* geo){ - *count=trailCount; - *type=trailingType; - *geo=trailingGeometry; +void SystemSettings::getTrailsInfo(int* count, int *type, int* geo) +{ + *count=trailCount; + *type=trailingType; + *geo=trailingGeometry; } -void SystemSettings::setPedestrianColor(int groupID, int color[3]){ - if((groupID<0) || (groupID>3)) { - Debug::Error(" wrong pedestrian group ID %d",groupID); - return; - } - pedestriansColor[groupID][0]=color[0]; - pedestriansColor[groupID][1]=color[1]; - pedestriansColor[groupID][2]=color[2]; +void SystemSettings::setPedestrianColor(int groupID, int color[3]) +{ + if((groupID<0) || (groupID>3)) { + Debug::Error(" wrong pedestrian group ID %d",groupID); + return; + } + pedestriansColor[groupID][0]=color[0]; + pedestriansColor[groupID][1]=color[1]; + pedestriansColor[groupID][2]=color[2]; } -void SystemSettings::getPedestrianColor(int groupID, int color[3]){ - if((groupID<0) || (groupID>3)) { - Debug::Error(" wrong pedestrian group ID %d",groupID); - return; - } +void SystemSettings::getPedestrianColor(int groupID, int color[3]) +{ + if((groupID<0) || (groupID>3)) { + Debug::Error(" wrong pedestrian group ID %d",groupID); + return; + } - color[0]=pedestriansColor[groupID][0]; - color[1]=pedestriansColor[groupID][1]; - color[2]=pedestriansColor[groupID][2]; + color[0]=pedestriansColor[groupID][0]; + color[1]=pedestriansColor[groupID][1]; + color[2]=pedestriansColor[groupID][2]; } -void SystemSettings::setOutputDirectory(QString dir){ - outputDir=dir; +void SystemSettings::setOutputDirectory(QString dir) +{ + outputDir=dir; } -void SystemSettings::getOutputDirectory(QString& dir){ - dir=QString(outputDir); +void SystemSettings::getOutputDirectory(QString& dir) +{ + dir=QString(outputDir); } -int SystemSettings::getPedestrianCaptionSize(){ - return captionSize; +int SystemSettings::getPedestrianCaptionSize() +{ + return captionSize; } -void SystemSettings::setRecordPNGsequence(bool status){ - recordPNGsequence=status; +void SystemSettings::setRecordPNGsequence(bool status) +{ + recordPNGsequence=status; } -bool SystemSettings::getRecordPNGsequence(){ - return recordPNGsequence; +bool SystemSettings::getRecordPNGsequence() +{ + return recordPNGsequence; } -void SystemSettings::setFilenamePrefix(QString prefix){ - filesPrefix=prefix; +void SystemSettings::setFilenamePrefix(QString prefix) +{ + filesPrefix=prefix; } -QString SystemSettings::getFilenamePrefix() { +QString SystemSettings::getFilenamePrefix() +{ return filesPrefix; } void SystemSettings::CreateLogfile() { //create directory if not exits - if(!QDir(outputDir).exists()){ + if(!QDir(outputDir).exists()) { QDir dir; - if(!dir.mkpath (outputDir )){ + if(!dir.mkpath (outputDir )) { qDebug()<<"could not create directory: "<< outputDir; outputDir=""; // current } @@ -263,7 +288,7 @@ void SystemSettings::CreateLogfile() logfile = outputDir+"log_"+QDateTime::currentDateTime().toString("yyMMdd_hh_mm_").append(SystemSettings::getFilenamePrefix()).append(".txt"); } - QString &SystemSettings::getLogfile() +QString &SystemSettings::getLogfile() { return logfile; } @@ -272,48 +297,56 @@ void SystemSettings::DeleteLogfile() { //first close the opened file delete Log; - if(! QFile::remove(logfile)){ + if(! QFile::remove(logfile)) { qDebug()<<"he log file could not delete the file"<<endl; } } -void SystemSettings::setPedestrianColorProfileFromFile(bool readFromFile) { - pedColorProfileReadFromFile = readFromFile; +void SystemSettings::setPedestrianColorProfileFromFile(bool readFromFile) +{ + pedColorProfileReadFromFile = readFromFile; } -bool SystemSettings::getPedestrianColorProfileFromFile() { - return pedColorProfileReadFromFile; +bool SystemSettings::getPedestrianColorProfileFromFile() +{ + return pedColorProfileReadFromFile; } -void SystemSettings::setVirtualAgent(int agent){ - virtualAgentID=agent; +void SystemSettings::setVirtualAgent(int agent) +{ + virtualAgentID=agent; } -int SystemSettings::getVirtualAgent(){ - return virtualAgentID; +int SystemSettings::getVirtualAgent() +{ + return virtualAgentID; } void SystemSettings::setCaptionsParameters(int size, const QColor& col, int orientation, - bool automaticRotation) { - captionSize=size; - captionColor=col; - captionOrientaton=orientation; - captionAutomaticRotation=automaticRotation; + bool automaticRotation) +{ + captionSize=size; + captionColor=col; + captionOrientaton=orientation; + captionAutomaticRotation=automaticRotation; } void SystemSettings::getCaptionsParameters(int &size, QColor& col, int &orientation, - bool &automaticRotation) { - size=captionSize; - col=captionColor; - orientation=captionOrientaton; - automaticRotation=captionAutomaticRotation; + bool &automaticRotation) +{ + size=captionSize; + col=captionColor; + orientation=captionOrientaton; + automaticRotation=captionAutomaticRotation; } -void SystemSettings::setOnScreenInfos(bool status){ - onScreenInfos=status; +void SystemSettings::setOnScreenInfos(bool status) +{ + onScreenInfos=status; } -bool SystemSettings::getOnScreenInfos(){ - return onScreenInfos; +bool SystemSettings::getOnScreenInfos() +{ + return onScreenInfos; } diff --git a/src/SystemSettings.h b/src/SystemSettings.h index 54327419cd3f36e9dc44990223e1da80ef1e48e2..27dfeb7ca9cf6f5b6fef833dd7c0026a39573570 100644 --- a/src/SystemSettings.h +++ b/src/SystemSettings.h @@ -40,24 +40,24 @@ class QColor; class SystemSettings { public: - SystemSettings(); - virtual ~SystemSettings(); + SystemSettings(); + virtual ~SystemSettings(); - // set/get enable the legend - void static setShowLegend(bool legend); - bool static getShowLegend(); + // set/get enable the legend + void static setShowLegend(bool legend); + bool static getShowLegend(); - //set/get the caption status + //set/get the caption status void static setShowAgentsCaptions(bool caption); bool static getShowAgentsCaptions(); - // set/get the listening port - void static setListningPort(unsigned short port); - unsigned short static getListeningPort(); + // set/get the listening port + void static setListningPort(unsigned short port); + unsigned short static getListeningPort(); // set/get the 2D visio - void static set2D(bool is2D); - bool static get2D(); + void static set2D(bool is2D); + bool static get2D(); // set/get the agents visio void static setShowAgents(bool status); @@ -74,84 +74,84 @@ public: void static setWorkingDirectory(QString dir); void static getWorkingDirectory(QString& dir); - // set/get the bk color - // todo done directly in the travisto.cpp - void static getBackgroundColor(double* col); - void static setBackgroundColor(double* col); - - /// set/get pedestrian private sphere ellipse resolution - int static getEllipseResolution(); - void static setEllipseResolution(int resolution); - - - /// set/get the pedestrian shape - /// 0 for default, 1 for Ellipse, 2 for pinguins - void static setPedestrianShape(int shape); - int static getPedestrianShape(); - - /// define the pedestrian trail count and type - /// type =0, backwards, 1= symetric, 3=forward - //geometry= 0 point, polygones=1; - void static setTrailsInfo(int count, int type, int geometry); - void static getTrailsInfo(int* count, int *type, int *geometry); - - /// set the pedestrian colors - void static setPedestrianColor(int groupID, int color[3]); - void static getPedestrianColor(int groupID, int color[3]); - - /// set the pedestrian color profile - /// either read from file, or set manually - void static setPedestrianColorProfileFromFile(bool readFromFile); - bool static getPedestrianColorProfileFromFile(); - - ///set/get the file directory. where travisto will output video/screenshots etc.. - void static setOutputDirectory(QString dir); - void static getOutputDirectory(QString& dir); - - /// set/get the caption size - //void static setPedestrianCaptionSize( int size); - int static getPedestrianCaptionSize(); - - /** - * set the caption parameters - * - * @param size the caption size in point, default is 30 - * @param Col the color in rgb format - * @param orientation 0 is default, 1 is billboard - * @param automaticRotation true if the captions should keep their original orientation - */ - void static setCaptionsParameters(int size, const QColor& Col, int orientation=0, bool automaticRotation=true); - - /** - * - * retrieve the caption parameters - * - * @param size the caption size in point, default ist 30 - * @param Col the color in rgb format - * @param orientation 0 is default, 1 is billboard - * @param automaticRotation true if the captions should keep their original orientation - */ - void static getCaptionsParameters(int &size, QColor& Col, int &orientation, bool &automaticRotation); - - /// set/get the virtual reality agent id - void static setVirtualAgent(int agent); - int static getVirtualAgent(); - - /// set/get the png recording flag - void static setRecordPNGsequence(bool status); - bool static getRecordPNGsequence(); - - /// set/get the onscreen visibility - void static setOnScreenInfos(bool status); - bool static getOnScreenInfos(); - - ///\brief set the video/picture prefix name. - /// This is just the name of the input file. - void static setFilenamePrefix(QString prefix); - - ///\brief get the video/picture prefix name. - /// This is just the name of the input file. - static QString getFilenamePrefix(); + // set/get the bk color + // todo done directly in the travisto.cpp + void static getBackgroundColor(double* col); + void static setBackgroundColor(double* col); + + /// set/get pedestrian private sphere ellipse resolution + int static getEllipseResolution(); + void static setEllipseResolution(int resolution); + + + /// set/get the pedestrian shape + /// 0 for default, 1 for Ellipse, 2 for pinguins + void static setPedestrianShape(int shape); + int static getPedestrianShape(); + + /// define the pedestrian trail count and type + /// type =0, backwards, 1= symetric, 3=forward + //geometry= 0 point, polygones=1; + void static setTrailsInfo(int count, int type, int geometry); + void static getTrailsInfo(int* count, int *type, int *geometry); + + /// set the pedestrian colors + void static setPedestrianColor(int groupID, int color[3]); + void static getPedestrianColor(int groupID, int color[3]); + + /// set the pedestrian color profile + /// either read from file, or set manually + void static setPedestrianColorProfileFromFile(bool readFromFile); + bool static getPedestrianColorProfileFromFile(); + + ///set/get the file directory. where travisto will output video/screenshots etc.. + void static setOutputDirectory(QString dir); + void static getOutputDirectory(QString& dir); + + /// set/get the caption size + //void static setPedestrianCaptionSize( int size); + int static getPedestrianCaptionSize(); + + /** + * set the caption parameters + * + * @param size the caption size in point, default is 30 + * @param Col the color in rgb format + * @param orientation 0 is default, 1 is billboard + * @param automaticRotation true if the captions should keep their original orientation + */ + void static setCaptionsParameters(int size, const QColor& Col, int orientation=0, bool automaticRotation=true); + + /** + * + * retrieve the caption parameters + * + * @param size the caption size in point, default ist 30 + * @param Col the color in rgb format + * @param orientation 0 is default, 1 is billboard + * @param automaticRotation true if the captions should keep their original orientation + */ + void static getCaptionsParameters(int &size, QColor& Col, int &orientation, bool &automaticRotation); + + /// set/get the virtual reality agent id + void static setVirtualAgent(int agent); + int static getVirtualAgent(); + + /// set/get the png recording flag + void static setRecordPNGsequence(bool status); + bool static getRecordPNGsequence(); + + /// set/get the onscreen visibility + void static setOnScreenInfos(bool status); + bool static getOnScreenInfos(); + + ///\brief set the video/picture prefix name. + /// This is just the name of the input file. + void static setFilenamePrefix(QString prefix); + + ///\brief get the video/picture prefix name. + /// This is just the name of the input file. + static QString getFilenamePrefix(); static void CreateLogfile(); static QString &getLogfile(); @@ -159,32 +159,32 @@ public: private: - static bool recordPNGsequence; - static bool pedColorProfileReadFromFile; - static bool showLegend; + static bool recordPNGsequence; + static bool pedColorProfileReadFromFile; + static bool showLegend; static bool showAgentsCaptions; - static bool is2D; // Toggle 2D/3D mode + static bool is2D; // Toggle 2D/3D mode static bool showAgents; static bool showGeometry; static bool showFloor; - static unsigned short port; - static double bgColor[3]; - static int ellipseResolution; - static int pedestriansColor[3][3]; // 3 groups, and 3 color per groups - static int pedesShape; - static int virtualAgentID; - static int trailCount; - static int trailingType; - static int trailingGeometry; - static QString outputDir; + static unsigned short port; + static double bgColor[3]; + static int ellipseResolution; + static int pedestriansColor[3][3]; // 3 groups, and 3 color per groups + static int pedesShape; + static int virtualAgentID; + static int trailCount; + static int trailingType; + static int trailingGeometry; + static QString outputDir; static QString workingDir; static QString logfile; - static int captionSize; - static QColor captionColor; - static int captionOrientaton; - static bool captionAutomaticRotation; - static QString filesPrefix; - static bool onScreenInfos; + static int captionSize; + static QColor captionColor; + static int captionOrientaton; + static bool captionAutomaticRotation; + static QString filesPrefix; + static bool onScreenInfos; }; #endif /* SYSTEMSETTINGS_H_ */ diff --git a/src/ThreadDataTransfert.cpp b/src/ThreadDataTransfert.cpp index dc9a0da92a215140df4e18240e8e073425eff5cd..df27480a0d1c5f9668f3f9d8a9bd33cb52585341 100644 --- a/src/ThreadDataTransfert.cpp +++ b/src/ThreadDataTransfert.cpp @@ -63,187 +63,194 @@ using namespace std; ThreadDataTransfer::ThreadDataTransfer(QObject *parent): - QThread(parent) + QThread(parent) { - m_port=SystemSettings::getListeningPort(); - tcpServer=NULL; - headerParsed=false; - errNr=0; - finished=false; + m_port=SystemSettings::getListeningPort(); + tcpServer=NULL; + headerParsed=false; + errNr=0; + finished=false; //Debug::setDebugLevel(Debug::ALL); } -ThreadDataTransfer::~ThreadDataTransfer() { +ThreadDataTransfer::~ThreadDataTransfer() +{ } -void ThreadDataTransfer::shutdown(){ - finished=true; +void ThreadDataTransfer::shutdown() +{ + finished=true; } -void ThreadDataTransfer::run(){ - - finished=false; - - // - // std::cerr <<">> starting server" <<std::endl; - // - // // udpSocket = new QUdpSocket(); - // // udpSocket->bind(QHostAddress::LocalHost,SystemSettings::getListeningPort()); - // // - // // if(!connect(udpSocket, SIGNAL(readyRead()), - // // this, SLOT(slotProcessPendingDatagrams()))){ - // // cerr<<"could not create the udp connection"<<endl; - // // } - // - // tcpServer = new QTcpServer(/*this->parent()*/); - // if(!connect(tcpServer, SIGNAL(newConnection()), this, SLOT(slotHandleConnection()))){ - // cerr<<"could not create connection newconnection"<<endl; - // } - // connect(tcpServer, SIGNAL(error(QAbstractSocket::SocketError)), - // this, SLOT(displayError(QAbstractSocket::SocketError))); - // - // if (!tcpServer->listen(QHostAddress::LocalHost,SystemSettings::getListeningPort())) { - // cerr<<"\nI can't listen, sorry"<<endl; - // QMessageBox::critical(0, tr("TraVisTo Server"), - // tr("Unable to start the server: %1.") - // .arg(tcpServer->errorString())); - // quit(); - // } - // - // if(tcpServer->isListening ()) - // cout<<"\nTraVisTo is listening on port "<< tcpServer->serverPort()<<endl; - - QString data; - TraVisToServer* server = new TraVisToServer(SystemSettings::getListeningPort()); - if(!server->isListening()) { - emit signal_errorMessage("could not connect, make sure that the port is not used by another program.\n " - "Restarting the application may solve the issue!"); - emit signal_controlSequence("CONTROL_RESET"); - - }else - do{ - emit signal_CurrentAction("waiting for data"); - server->receiveMessage(data); - - if(!data.isEmpty()) - slotProcessMessage(data); - - }while(finished!=true); - - server->close(); +void ThreadDataTransfer::run() +{ + + finished=false; + + // + // std::cerr <<">> starting server" <<std::endl; + // + // // udpSocket = new QUdpSocket(); + // // udpSocket->bind(QHostAddress::LocalHost,SystemSettings::getListeningPort()); + // // + // // if(!connect(udpSocket, SIGNAL(readyRead()), + // // this, SLOT(slotProcessPendingDatagrams()))){ + // // cerr<<"could not create the udp connection"<<endl; + // // } + // + // tcpServer = new QTcpServer(/*this->parent()*/); + // if(!connect(tcpServer, SIGNAL(newConnection()), this, SLOT(slotHandleConnection()))){ + // cerr<<"could not create connection newconnection"<<endl; + // } + // connect(tcpServer, SIGNAL(error(QAbstractSocket::SocketError)), + // this, SLOT(displayError(QAbstractSocket::SocketError))); + // + // if (!tcpServer->listen(QHostAddress::LocalHost,SystemSettings::getListeningPort())) { + // cerr<<"\nI can't listen, sorry"<<endl; + // QMessageBox::critical(0, tr("TraVisTo Server"), + // tr("Unable to start the server: %1.") + // .arg(tcpServer->errorString())); + // quit(); + // } + // + // if(tcpServer->isListening ()) + // cout<<"\nTraVisTo is listening on port "<< tcpServer->serverPort()<<endl; + + QString data; + TraVisToServer* server = new TraVisToServer(SystemSettings::getListeningPort()); + if(!server->isListening()) { + emit signal_errorMessage("could not connect, make sure that the port is not used by another program.\n " + "Restarting the application may solve the issue!"); + emit signal_controlSequence("CONTROL_RESET"); + + } else + do { + emit signal_CurrentAction("waiting for data"); + server->receiveMessage(data); + + if(!data.isEmpty()) + slotProcessMessage(data); + + } while(finished!=true); + + server->close(); } -void ThreadDataTransfer::slotHandleConnection(){ +void ThreadDataTransfer::slotHandleConnection() +{ - Debug::Messages("handling new connection"); + Debug::Messages("handling new connection"); - QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); - connect(clientConnection, SIGNAL(disconnected()), - clientConnection, SLOT(deleteLater())); + QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); + connect(clientConnection, SIGNAL(disconnected()), + clientConnection, SLOT(deleteLater())); - connect(clientConnection, SIGNAL(readyRead()), this, SLOT(slotReadMessage())); + connect(clientConnection, SIGNAL(readyRead()), this, SLOT(slotReadMessage())); - connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(displayError(QAbstractSocket::SocketError))); - //Q_DECLARE_METATYPE( QAbstractSocket::SocketError ); - Debug::Messages("juhuuuu"); + connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), + this, SLOT(displayError(QAbstractSocket::SocketError))); + //Q_DECLARE_METATYPE( QAbstractSocket::SocketError ); + Debug::Messages("juhuuuu"); } -void ThreadDataTransfer::slotReadMessage(){ - Debug::Messages("new post"); - //slotProcessMessage(); +void ThreadDataTransfer::slotReadMessage() +{ + Debug::Messages("new post"); + //slotProcessMessage(); } -void ThreadDataTransfer::slotProcessMessage(QString& data){ - QDomDocument doc(""); +void ThreadDataTransfer::slotProcessMessage(QString& data) +{ + QDomDocument doc(""); //data = "<travisto>\n" +data+ "</travisto>"; //cout<<data.toStdString()<<endl; - QString errorMsg=""; - doc.setContent(data,&errorMsg); + QString errorMsg=""; + doc.setContent(data,&errorMsg); - if(!errorMsg.isEmpty()){ - errNr++; + if(!errorMsg.isEmpty()) { + errNr++; //Debug::Error(">> %s",(const char *)errorMsg.toStdString().c_str()); //Debug::Error(">> %s",(const char *)data.toStdString().c_str()); - return; - } - - QDomNode header =doc.elementsByTagName("header").item(0); - QDomNode geometry =doc.elementsByTagName("geometry").item(0); - QDomNode shapes =doc.elementsByTagName("shape").item(0); - - QDomNodeList dataList = doc.elementsByTagName("frame"); - - if(!header.isNull()) { - parseHeaderNode(header); - Debug::Messages("header received and parsed"); - } - if(!shapes.isNull()) { - parseShapeNode(shapes); - Debug::Messages("header received and parsed"); - } - - if(!geometry.isNull()) { - //emit signal_loadGeometry(data); - geoData=data; + return; + } + + QDomNode header =doc.elementsByTagName("header").item(0); + QDomNode geometry =doc.elementsByTagName("geometry").item(0); + QDomNode shapes =doc.elementsByTagName("shape").item(0); + + QDomNodeList dataList = doc.elementsByTagName("frame"); + + if(!header.isNull()) { + parseHeaderNode(header); + Debug::Messages("header received and parsed"); + } + if(!shapes.isNull()) { + parseShapeNode(shapes); + Debug::Messages("header received and parsed"); + } + + if(!geometry.isNull()) { + //emit signal_loadGeometry(data); + geoData=data; Debug::Messages("geometry received and parsed"); - //parseGeometryNode(geometry); - } - if(!dataList.isEmpty()) { - parseDataNode(dataList); - } + //parseGeometryNode(geometry); + } + if(!dataList.isEmpty()) { + parseDataNode(dataList); + } - data.clear(); + data.clear(); } -void ThreadDataTransfer::slotConnectionClosed(){ - Debug::Error("connection lost"); +void ThreadDataTransfer::slotConnectionClosed() +{ + Debug::Error("connection lost"); } -void ThreadDataTransfer::parseHeaderNode(QDomNode header ){ - +void ThreadDataTransfer::parseHeaderNode(QDomNode header ) +{ - emit signal_CurrentAction("parsing new header"); - bool ok; - numberOfAgents = getTagValueFromElement(header, "agents").toInt(&ok); + emit signal_CurrentAction("parsing new header"); - if(!ok){ - Debug::Error("The number of agents is invalid"); - Debug::Error("The number must be between 1...65355"); - emit signal_errorMessage("The number of agents is invalid"); - numberOfAgents=1000; - } + bool ok; + numberOfAgents = getTagValueFromElement(header, "agents").toInt(&ok); - if(numberOfAgents==extern_trajectories_firstSet.getNumberOfAgents()){ - // only clear - emit signal_stopVisualisationThread(false); - }else{ - emit signal_stopVisualisationThread(true); - } + if(!ok) { + Debug::Error("The number of agents is invalid"); + Debug::Error("The number must be between 1...65355"); + emit signal_errorMessage("The number of agents is invalid"); + numberOfAgents=1000; + } - QString frameRateStr=getTagValueFromElement(header, "frameRate"); - frameRate =frameRateStr.toFloat(&ok); + if(numberOfAgents==extern_trajectories_firstSet.getNumberOfAgents()) { + // only clear + emit signal_stopVisualisationThread(false); + } else { + emit signal_stopVisualisationThread(true); + } - if(!ok){ - Debug::Error("The frame rate is invalid"); - Debug::Error("The number must be between 1...1000"); - QMessageBox msgBox; - msgBox.setText("The frame rate is invalid"); - msgBox.setInformativeText("The number must be between 1...1000, I will consider 25"); - msgBox.setStandardButtons(QMessageBox::Ok); - msgBox.setIcon(QMessageBox::Critical); - msgBox.exec(); - frameRate=25; - } + QString frameRateStr=getTagValueFromElement(header, "frameRate"); + frameRate =frameRateStr.toFloat(&ok); + + if(!ok) { + Debug::Error("The frame rate is invalid"); + Debug::Error("The number must be between 1...1000"); + QMessageBox msgBox; + msgBox.setText("The frame rate is invalid"); + msgBox.setInformativeText("The number must be between 1...1000, I will consider 25"); + msgBox.setStandardButtons(QMessageBox::Ok); + msgBox.setIcon(QMessageBox::Critical); + msgBox.exec(); + frameRate=25; + } //get the header version - if(header.toElement().hasAttributes()) - { + if(header.toElement().hasAttributes()) { QString version=header.toElement().attribute("version"); QStringList query = version.split("."); int major=0; @@ -254,8 +261,8 @@ void ThreadDataTransfer::parseHeaderNode(QDomNode header ){ major=query.at(0).toInt(); break; case 2: - major=query.at(0).toInt(); - minor=query.at(1).toInt(); + major=query.at(0).toInt(); + minor=query.at(1).toInt(); break; case 3: major=query.at(0).toInt(); @@ -267,48 +274,51 @@ void ThreadDataTransfer::parseHeaderNode(QDomNode header ){ //cout<<"version found:"<<at.value(i).toStdString()<<endl;exit(0); } - headerParsed=true; + headerParsed=true; } QString ThreadDataTransfer::getTagValueFromElement(QDomNode node, - const char * tagName) { - if (node.isNull()) - return ""; - return node.toElement().namedItem(tagName).firstChild().nodeValue(); + const char * tagName) +{ + if (node.isNull()) + return ""; + return node.toElement().namedItem(tagName).firstChild().nodeValue(); } -void ThreadDataTransfer::parseDataNode(QDomNodeList frames){ +void ThreadDataTransfer::parseDataNode(QDomNodeList frames) +{ for (int i = 0; i < frames.length(); i++) { - Frame *newFrame = new Frame(); - QDomElement el = frames.item(i).toElement(); - QDomNodeList agents = el.elementsByTagName("agent"); - - for (int i = 0; i < agents.length(); i++) - { - bool ok=false; - int id=agents.item(i).toElement().attribute("ID").toInt(&ok); - if(!ok) continue; // invalid ID + Frame *newFrame = new Frame(); + QDomElement el = frames.item(i).toElement(); + QDomNodeList agents = el.elementsByTagName("agent"); + + for (int i = 0; i < agents.length(); i++) { + bool ok=false; + int id=agents.item(i).toElement().attribute("ID").toInt(&ok); + if(!ok) continue; // invalid ID double xPos=agents.item(i).toElement().attribute(_jps_xPos,"0").toDouble()*FAKTOR; double yPos=agents.item(i).toElement().attribute(_jps_yPos,"0").toDouble()*FAKTOR; double zPos=agents.item(i).toElement().attribute(_jps_zPos,"0").toDouble()*FAKTOR; double dia_a=agents.item(i).toElement().attribute(_jps_radiusA).toDouble(&ok)*FAKTOR; - if(!ok)dia_a=std::numeric_limits<double>::quiet_NaN(); + if(!ok)dia_a=std::numeric_limits<double>::quiet_NaN(); double dia_b=agents.item(i).toElement().attribute(_jps_radiusB).toDouble(&ok)*FAKTOR; - if(!ok)dia_b=std::numeric_limits<double>::quiet_NaN(); + if(!ok)dia_b=std::numeric_limits<double>::quiet_NaN(); double el_angle=agents.item(i).toElement().attribute(_jps_ellipseOrientation).toDouble(&ok); - if(!ok){el_angle=std::numeric_limits<double>::quiet_NaN(); } + if(!ok) { + el_angle=std::numeric_limits<double>::quiet_NaN(); + } double el_color=agents.item(i).toElement().attribute(_jps_ellipseColor).toDouble(&ok); - if(!ok)el_color=std::numeric_limits<double>::quiet_NaN(); + if(!ok)el_color=std::numeric_limits<double>::quiet_NaN(); - double pos[3]={xPos,yPos,zPos}; + double pos[3]= {xPos,yPos,zPos}; //double vel[3]={xVel,yPos,zPos}; //double ellipse[7]={el_x,el_y,el_z,dia_a,dia_b,el_angle,el_color}; //double para[2]={agent_color,el_angle}; - double angle[3]={0,0,el_angle}; - double radius[3]={dia_a,dia_b,30.0}; + double angle[3]= {0,0,el_angle}; + double radius[3]= {dia_a,dia_b,30.0}; FrameElement *element = new FrameElement(id-1); element->SetPos(pos); @@ -316,102 +326,105 @@ void ThreadDataTransfer::parseDataNode(QDomNodeList frames){ element->SetRadius(radius); element->SetColor(el_color); newFrame->addElement(element); - } + } - //adding the new frame to the right dataset + //adding the new frame to the right dataset newFrame->ComputePolyData(); - extern_trajectories_firstSet.addFrame(newFrame); - // frameNumbers++; - } - - if(headerParsed==true){ - // static int count=1; - // count++; - // if (count<100) return; // start after 100 frames - emit signal_startVisualisationThread(geoData,numberOfAgents,frameRate); - headerParsed=false; - } + extern_trajectories_firstSet.addFrame(newFrame); + // frameNumbers++; + } + + if(headerParsed==true) { + // static int count=1; + // count++; + // if (count<100) return; // start after 100 frames + emit signal_startVisualisationThread(geoData,numberOfAgents,frameRate); + headerParsed=false; + } } -void ThreadDataTransfer::slotDisplayError(QAbstractSocket::SocketError socketError){ +void ThreadDataTransfer::slotDisplayError(QAbstractSocket::SocketError socketError) +{ - switch (socketError) { + switch (socketError) { + + case QAbstractSocket::RemoteHostClosedError: + Debug::Error( "The host closes the connection "); + break; + + case QAbstractSocket::HostNotFoundError: + Debug::Error("The host was not found. Please check the "); + Debug::Error("host name and port settings."); + break; + + case QAbstractSocket::ConnectionRefusedError: + Debug::Error("The connection was refused by the peer. "); + Debug::Error("Make sure the fortune server is running"); + Debug::Error("and check that the host name and port "); + Debug::Error("settings are correct."); + break; + + default: + Debug::Error("TraVisTo Client:"); + Debug::Error("The following error occurred: "); + //cerr<< clientConnection->errorString().toStdString()<<endl; + break; + } - case QAbstractSocket::RemoteHostClosedError: - Debug::Error( "The host closes the connection "); - break; - case QAbstractSocket::HostNotFoundError: - Debug::Error("The host was not found. Please check the "); - Debug::Error("host name and port settings."); - break; +} - case QAbstractSocket::ConnectionRefusedError: - Debug::Error("The connection was refused by the peer. "); - Debug::Error("Make sure the fortune server is running"); - Debug::Error("and check that the host name and port "); - Debug::Error("settings are correct."); - break; +void ThreadDataTransfer::slotProcessPendingDatagrams() +{ + Debug::Messages("connected"); + while (udpSocket->hasPendingDatagrams()) { + QByteArray datagram; + datagram.resize(udpSocket->pendingDatagramSize()); + udpSocket->readDatagram(datagram.data(), datagram.size()); + // Debug::Messages("%s",(const char *) datagram.data().c_str())); + } +} - default: - Debug::Error("TraVisTo Client:"); - Debug::Error("The following error occurred: "); - //cerr<< clientConnection->errorString().toStdString()<<endl; - break; - } +void ThreadDataTransfer::parseShapeNode(QDomNode shape) +{ -} -void ThreadDataTransfer::slotProcessPendingDatagrams() { - Debug::Messages("connected"); - while (udpSocket->hasPendingDatagrams()) { - QByteArray datagram; - datagram.resize(udpSocket->pendingDatagramSize()); - udpSocket->readDatagram(datagram.data(), datagram.size()); - // Debug::Messages("%s",(const char *) datagram.data().c_str())); - } -} + QDomNodeList agents = shape.toElement().elementsByTagName("agentInfo"); + QStringList heights; + QStringList colors; + for (int i = 0; i < agents.length(); i++) { + bool ok=false; + int id=agents.item(i).toElement().attribute("ID").toInt(&ok); + if(!ok) continue; // invalid ID + double height=agents.item(i).toElement().attribute("height").toDouble(&ok); + if(!ok)height=std::numeric_limits<double>::quiet_NaN(); -void ThreadDataTransfer::parseShapeNode(QDomNode shape){ + int color=agents.item(i).toElement().attribute("color").toDouble(&ok); + if(!ok)color=std::numeric_limits<int>::quiet_NaN(); + //cout <<"id= " <<id <<" height= "<<height<<" color= "<<color<<endl; + if(!isnan(height)) { + heights.append(QString::number(id)); + heights.append(QString::number(height)); + } + if(!isnan(color)) { + colors.append(QString::number(id)); + colors.append(QString::number(color)); + } - QDomNodeList agents = shape.toElement().elementsByTagName("agentInfo"); - QStringList heights; - QStringList colors; - for (int i = 0; i < agents.length(); i++) { + } - bool ok=false; - int id=agents.item(i).toElement().attribute("ID").toInt(&ok); - if(!ok) continue; // invalid ID - double height=agents.item(i).toElement().attribute("height").toDouble(&ok); - if(!ok)height=std::numeric_limits<double>::quiet_NaN(); - - int color=agents.item(i).toElement().attribute("color").toDouble(&ok); - if(!ok)color=std::numeric_limits<int>::quiet_NaN(); - //cout <<"id= " <<id <<" height= "<<height<<" color= "<<color<<endl; - - if(!isnan(height)){ - heights.append(QString::number(id)); - heights.append(QString::number(height)); - } - if(!isnan(color)){ - colors.append(QString::number(id)); - colors.append(QString::number(color)); - } - - } - - extern_trajectories_firstSet.setInitialHeights(heights); - extern_trajectories_firstSet.setInitialColors(colors); + extern_trajectories_firstSet.setInitialHeights(heights); + extern_trajectories_firstSet.setInitialColors(colors); } void ThreadDataTransfer::InitHeader(int major, int minor, int patch) { // set the parsing String map - if(minor==5 && patch==0){ + if(minor==5 && patch==0) { _jps_xPos=QString("xPos"); _jps_yPos=QString("yPos"); _jps_zPos=QString("zPos"); @@ -419,8 +432,7 @@ void ThreadDataTransfer::InitHeader(int major, int minor, int patch) _jps_radiusB=QString("radiusB"); _jps_ellipseOrientation=QString("ellipseOrientation"); _jps_ellipseColor=QString("ellipseColor"); - } - else if ( (minor==6) || (minor==5 && patch==1) ){ + } else if ( (minor==6) || (minor==5 && patch==1) ) { _jps_xPos=QString("x"); _jps_yPos=QString("y"); _jps_zPos=QString("z"); @@ -428,9 +440,7 @@ void ThreadDataTransfer::InitHeader(int major, int minor, int patch) _jps_radiusB=QString("rB"); _jps_ellipseOrientation=QString("eO"); _jps_ellipseColor=QString("eC"); - } - else - { + } else { cout<<"unsupported header version: "<<major<<"."<<minor<<"."<<patch<<endl; cout<<"Please use 0.5 0.5.1 or 0.6 "<<endl; } diff --git a/src/ThreadDataTransfert.h b/src/ThreadDataTransfert.h index f738cfe13c4cab602b4343b7e8ea88631a5ea038..3ad8f21d3600d20f6bf89c97da811235e8fb3220 100644 --- a/src/ThreadDataTransfert.h +++ b/src/ThreadDataTransfert.h @@ -54,75 +54,75 @@ extern bool extern_shutdown_visual_thread; class ThreadDataTransfer: public QThread { - Q_OBJECT + Q_OBJECT public: - ThreadDataTransfer(QObject *parent = 0); - virtual ~ThreadDataTransfer(); - void run(); - void setListeningPort(int port); + ThreadDataTransfer(QObject *parent = 0); + virtual ~ThreadDataTransfer(); + void run(); + void setListeningPort(int port); - /// \brief force the thread to do some cleaning work and shutdown - void shutdown(); + /// \brief force the thread to do some cleaning work and shutdown + void shutdown(); - /// parse a shape node - void parseShapeNode(QDomNode shapes); + /// parse a shape node + void parseShapeNode(QDomNode shapes); - /// parse a geometry node - void parseHeaderNode(QDomNode header); + /// parse a geometry node + void parseHeaderNode(QDomNode header); - /// parse data node - void parseDataNode(QDomNodeList data); + /// parse data node + void parseDataNode(QDomNodeList data); //old and new geometry format void InitHeader(int major, int minor, int patch); private: - QString getTagValueFromElement(QDomNode node, - const char * tagName); + QString getTagValueFromElement(QDomNode node, + const char * tagName); - Q_SIGNALS: - void signal_start(); - void signal_stop(); - void signal_controlSequence(const char* sex); +Q_SIGNALS: + void signal_start(); + void signal_stop(); + void signal_controlSequence(const char* sex); - void signal_CurrentAction(QString msg); + void signal_CurrentAction(QString msg); - /// connect to the setFrameRateSlot - /// of the visualisation Thread - //void signal_frameRate(float fps); + /// connect to the setFrameRateSlot + /// of the visualisation Thread + //void signal_frameRate(float fps); - /// start the visual thread, - /// once header has been received - void signal_startVisualisationThread(QString data, int numberOfAgents,float frameRate); + /// start the visual thread, + /// once header has been received + void signal_startVisualisationThread(QString data, int numberOfAgents,float frameRate); - /// shutdown the visio thread - void signal_stopVisualisationThread(bool clearAndStop); + /// shutdown the visio thread + void signal_stopVisualisationThread(bool clearAndStop); - void signal_errorMessage(QString geometry); + void signal_errorMessage(QString geometry); public Q_SLOTS: - //udp - void slotProcessPendingDatagrams(); - //tcp - void slotHandleConnection(); - void slotReadMessage(); - void slotProcessMessage(QString& data); - void slotConnectionClosed(); - void slotDisplayError(QAbstractSocket::SocketError socketError); + //udp + void slotProcessPendingDatagrams(); + //tcp + void slotHandleConnection(); + void slotReadMessage(); + void slotProcessMessage(QString& data); + void slotConnectionClosed(); + void slotDisplayError(QAbstractSocket::SocketError socketError); private: - int m_port; - QUdpSocket* udpSocket; - QTcpServer* tcpServer; - bool headerParsed; - long errNr; - QString geoData; - int numberOfAgents; - float frameRate; - bool finished; + int m_port; + QUdpSocket* udpSocket; + QTcpServer* tcpServer; + bool headerParsed; + long errNr; + QString geoData; + int numberOfAgents; + float frameRate; + bool finished; // temp variables to be removed in the next versions //header dependant variables diff --git a/src/ThreadVisualisation.cpp b/src/ThreadVisualisation.cpp index 7f7753a197e19d971ff28e6f027ee91cb9aac1c3..0843f3cfa2f85dde38034a9a980b534ae62dc2f2 100644 --- a/src/ThreadVisualisation.cpp +++ b/src/ThreadVisualisation.cpp @@ -98,64 +98,62 @@ ThreadVisualisation::ThreadVisualisation(QObject *parent): -QThread(parent) + QThread(parent) { - renderer=NULL; - renderWindow=NULL; - renderWinInteractor=NULL; - framePerSecond=25; - axis=NULL; - winTitle="header without room caption"; - geometry=new FacilityGeometry(); + renderer=NULL; + renderWindow=NULL; + renderWinInteractor=NULL; + framePerSecond=25; + axis=NULL; + winTitle="header without room caption"; + geometry=new FacilityGeometry(); } -ThreadVisualisation::~ThreadVisualisation() { - // if(renderer) - // renderer->Delete(); - // if(renderWindow) - // renderWindow->Delete(); - // if(renderWinInteractor) - // renderWinInteractor->Delete(); - // if(geometry) - // geometry->Delete(); - - if(axis) - axis->Delete(); - delete geometry; - // vtkRenderer* renderer; - // vtkRenderWindow* renderWindow; - // vtkRenderWindowInteractor* renderWinInteractor; +ThreadVisualisation::~ThreadVisualisation() +{ + + if(axis) + axis->Delete(); + delete geometry; + if(extern_glyphs_pedestrians_3D) extern_glyphs_pedestrians_3D->Delete(); + if(extern_glyphs_pedestrians_actor_3D) extern_glyphs_pedestrians_actor_3D->Delete(); + if(extern_glyphs_pedestrians) extern_glyphs_pedestrians->Delete(); + if(extern_glyphs_pedestrians_actor_2D) extern_glyphs_pedestrians_actor_2D->Delete(); + if(extern_pedestrians_labels) extern_pedestrians_labels->Delete(); } -void ThreadVisualisation::setFullsreen(bool status){ - renderWindow->SetFullScreen(status); +void ThreadVisualisation::setFullsreen(bool status) +{ + renderWindow->SetFullScreen(status); } -void ThreadVisualisation::slotSetFrameRate(float fps){ - framePerSecond=fps; +void ThreadVisualisation::slotSetFrameRate(float fps) +{ + framePerSecond=fps; } -void ThreadVisualisation::run(){ +void ThreadVisualisation::run() +{ //deactivate the output windows //vtkObject::GlobalWarningDisplayOff(); - //emit signalStatusMessage("running"); + //emit signalStatusMessage("running"); - // Create the renderer - renderer = vtkRenderer::New(); - // set the background - //renderer->SetBackground(.00,.00,.00); - renderer->SetBackground(1.0,1.0,1.0); - //add the geometry + // Create the renderer + renderer = vtkRenderer::New(); + // set the background + //renderer->SetBackground(.00,.00,.00); + renderer->SetBackground(1.0,1.0,1.0); + //add the geometry geometry->CreateActors(); renderer->AddActor(geometry->getActor2D()); renderer->AddActor(geometry->getActor3D()); - //initialize the datasets + //initialize the datasets //mem leak @@ -166,121 +164,121 @@ void ThreadVisualisation::run(){ extern_trail_plotter = new PointPlotter(); renderer->AddActor(extern_trail_plotter->getActor()); - // add axis + // add axis //axis= vtkAxesActor::New(); - //axis->SetScale(10); - //axis->SetConeRadius(30); - //axis->SetXAxisLabelText("1 Meter"); - //axis->SetYAxisLabelText("1 Meter"); - //axis->SetZAxisLabelText("1 Meter"); + //axis->SetScale(10); + //axis->SetConeRadius(30); + //axis->SetXAxisLabelText("1 Meter"); + //axis->SetYAxisLabelText("1 Meter"); + //axis->SetZAxisLabelText("1 Meter"); //axis->AxisLabelsOff(); - //axis->SetCylinderRadius(100); - //axis->set + //axis->SetCylinderRadius(100); + //axis->set //axis->SetTotalLength(1000,1000,1000); //axis->SetVisibility(true); - //renderer->AddActor(axis); - - //add big circle at null point - { - vtkSphereSource* org = vtkSphereSource::New(); - org->SetRadius(300); - - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(org->GetOutputPort()); - org->Delete(); - - // create actor - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(.90,.90,0.0); - //renderer->AddActor(actor); - } - //add another big circle at null point - { - vtkSphereSource* org = vtkSphereSource::New(); - org->SetRadius(300); - //org->SetCenter(50,80,0); - - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInputConnection(org->GetOutputPort()); - org->Delete(); - - // create actor - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); - mapper->Delete(); - actor->GetProperty()->SetColor(.90,.90,0.0); - actor->SetPosition(5000,8000,0); - //renderer->AddActor(actor); - } - - - // Create a real circle, not a sphere - { - VTK_CREATE(vtkRegularPolygonSource, polygonSource); - polygonSource->GeneratePolygonOff(); - polygonSource->SetNumberOfSides(50); - polygonSource->SetRadius(1000); - polygonSource->SetCenter(0,0,0); - polygonSource->Update(); - - VTK_CREATE(vtkPolyDataMapper,mapper); - mapper->SetInputConnection(polygonSource->GetOutputPort()); - VTK_CREATE(vtkActor,actor); - actor->GetProperty()->SetColor(180.0/255,180.0/255.0,180.0/255.0); - actor->SetMapper(mapper); - //renderer->AddActor(actor); - } - - //compute the relatives delays - // necessary in the case several dataset were loaded - computeDelays(); - - // Create the render window - renderWindow = vtkRenderWindow::New(); - renderWindow->AddRenderer( renderer ); - renderWindow->SetSize(960, 800); - //renderWindow->SetSize(640, 480); - //renderWindow->SetSize(800, 586); - //renderWindow->SetSize(1280, 960); - - // add the legend + //renderer->AddActor(axis); + + //add big circle at null point + { + vtkSphereSource* org = vtkSphereSource::New(); + org->SetRadius(300); + + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(org->GetOutputPort()); + org->Delete(); + + // create actor + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(.90,.90,0.0); + //renderer->AddActor(actor); + } + //add another big circle at null point + { + vtkSphereSource* org = vtkSphereSource::New(); + org->SetRadius(300); + //org->SetCenter(50,80,0); + + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInputConnection(org->GetOutputPort()); + org->Delete(); + + // create actor + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); + mapper->Delete(); + actor->GetProperty()->SetColor(.90,.90,0.0); + actor->SetPosition(5000,8000,0); + //renderer->AddActor(actor); + } + + + // Create a real circle, not a sphere + { + VTK_CREATE(vtkRegularPolygonSource, polygonSource); + polygonSource->GeneratePolygonOff(); + polygonSource->SetNumberOfSides(50); + polygonSource->SetRadius(1000); + polygonSource->SetCenter(0,0,0); + polygonSource->Update(); + + VTK_CREATE(vtkPolyDataMapper,mapper); + mapper->SetInputConnection(polygonSource->GetOutputPort()); + VTK_CREATE(vtkActor,actor); + actor->GetProperty()->SetColor(180.0/255,180.0/255.0,180.0/255.0); + actor->SetMapper(mapper); + //renderer->AddActor(actor); + } + + //compute the relatives delays + // necessary in the case several dataset were loaded + computeDelays(); + + // Create the render window + renderWindow = vtkRenderWindow::New(); + renderWindow->AddRenderer( renderer ); + renderWindow->SetSize(960, 800); + //renderWindow->SetSize(640, 480); + //renderWindow->SetSize(800, 586); + //renderWindow->SetSize(1280, 960); + + // add the legend //if(SystemSettings::getShowLegend()) // initLegend(); - //add the running time frame - runningTime = vtkTextActor::New(); - runningTime->SetTextScaleModeToViewport(); - //runningTime->SetTextScaleModeToProp(); - //runningTime->SetMinimumSize(10,10); - //runningTime->SetMinimumSize(180,80); - //runningTime->SetInput(txt); - //runningTime->SetDisplayPosition(500,700); - runningTime->SetVisibility(SystemSettings::getOnScreenInfos()); - - // set the properties of the caption - vtkTextProperty* tprop = runningTime->GetTextProperty(); - //tprop->SetFontFamilyToArial(); - //tprop->BoldOn(); - //tprop->SetLineSpacing(1.0); - tprop->SetFontSize(10); - tprop->SetColor(1.0,0.0,0.0); - - renderer->AddActor2D(runningTime); - - //CAUTION: this is necessary for WIN32 to update the window name - // but his will freeze your system on linux + //add the running time frame + runningTime = vtkTextActor::New(); + runningTime->SetTextScaleModeToViewport(); + //runningTime->SetTextScaleModeToProp(); + //runningTime->SetMinimumSize(10,10); + //runningTime->SetMinimumSize(180,80); + //runningTime->SetInput(txt); + //runningTime->SetDisplayPosition(500,700); + runningTime->SetVisibility(SystemSettings::getOnScreenInfos()); + + // set the properties of the caption + vtkTextProperty* tprop = runningTime->GetTextProperty(); + //tprop->SetFontFamilyToArial(); + //tprop->BoldOn(); + //tprop->SetLineSpacing(1.0); + tprop->SetFontSize(10); + tprop->SetColor(1.0,0.0,0.0); + + renderer->AddActor2D(runningTime); + + //CAUTION: this is necessary for WIN32 to update the window name + // but his will freeze your system on linux #ifdef WIN32 - renderWindow->Render(); + renderWindow->Render(); #endif - renderWindow->SetWindowName(winTitle.toStdString().c_str()); + renderWindow->SetWindowName(winTitle.toStdString().c_str()); - // Create an interactor - renderWinInteractor = vtkRenderWindowInteractor::New(); - renderWindow->SetInteractor( renderWinInteractor ); - renderWinInteractor->Initialize(); + // Create an interactor + renderWinInteractor = vtkRenderWindowInteractor::New(); + renderWindow->SetInteractor( renderWinInteractor ); + renderWinInteractor->Initialize(); //add a light kit { @@ -295,60 +293,60 @@ void ThreadVisualisation::run(){ } - if(true || SystemSettings::get2D()){ + if(true || SystemSettings::get2D()) { renderer->GetActiveCamera()->OrthogonalizeViewUp(); renderer->GetActiveCamera()->ParallelProjectionOn(); renderer->ResetCamera(); } - //create a timer for rendering the window - TimerCallback *renderingTimer = new TimerCallback(); - int timer= renderWinInteractor->CreateRepeatingTimer(1000.0/framePerSecond); - renderingTimer->SetRenderTimerId(timer); - renderingTimer->setTextActor(runningTime); - renderWinInteractor->AddObserver(vtkCommand::TimerEvent,renderingTimer); + //create a timer for rendering the window + TimerCallback *renderingTimer = new TimerCallback(); + int timer= renderWinInteractor->CreateRepeatingTimer(1000.0/framePerSecond); + renderingTimer->SetRenderTimerId(timer); + renderingTimer->setTextActor(runningTime); + renderWinInteractor->AddObserver(vtkCommand::TimerEvent,renderingTimer); - //create the necessary connections - QObject::connect(renderingTimer, SIGNAL(signalRunningTime(unsigned long )), - this->parent(), SLOT(slotRunningTime(unsigned long ))); + //create the necessary connections + QObject::connect(renderingTimer, SIGNAL(signalRunningTime(unsigned long )), + this->parent(), SLOT(slotRunningTime(unsigned long ))); - QObject::connect(renderingTimer, SIGNAL(signalFrameNumber(unsigned long )), - this->parent(), SLOT(slotFrameNumber(unsigned long ))); + QObject::connect(renderingTimer, SIGNAL(signalFrameNumber(unsigned long )), + this->parent(), SLOT(slotFrameNumber(unsigned long ))); - QObject::connect(renderingTimer, SIGNAL(signalRenderingTime(int)), - this->parent(), SLOT(slotRenderingTime(int))); + QObject::connect(renderingTimer, SIGNAL(signalRenderingTime(int)), + this->parent(), SLOT(slotRenderingTime(int))); - // Create my interactor style - InteractorStyle* style = InteractorStyle::New(); - renderWinInteractor->SetInteractorStyle( style ); - style->Delete(); + // Create my interactor style + InteractorStyle* style = InteractorStyle::New(); + renderWinInteractor->SetInteractorStyle( style ); + style->Delete(); - //create special camera for the virtual reality feeling - //renderer->GetActiveCamera()->SetRoll(90); - //renderer->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); + //create special camera for the virtual reality feeling + //renderer->GetActiveCamera()->SetRoll(90); + //renderer->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); //Pedestrian::setCamera(renderer->GetActiveCamera()); //renderer->ResetCamera(); - // just a workaround - - //if(LinePlotter2D::doorColorsToDefault) - { - //LinePlotter2D::doorColorsToDefault=false; - double col[3]={82.0/255,218.0 /255.0,255.0/255.0}; - double wallcol[3]={180.0/255,180.0/255.0,180.0/255.0}; - double exitcol[3]={175.0/255,175.0/255.0,255.0/255.0}; - double navlinecol[3]={165.0/255,175.0/255.0,225.0/255.0}; - setExitsColor(exitcol); - setWallsColor(wallcol); + // just a workaround + + //if(LinePlotter2D::doorColorsToDefault) + { + //LinePlotter2D::doorColorsToDefault=false; + double col[3]= {82.0/255,218.0 /255.0,255.0/255.0}; + double wallcol[3]= {180.0/255,180.0/255.0,180.0/255.0}; + double exitcol[3]= {175.0/255,175.0/255.0,255.0/255.0}; + double navlinecol[3]= {165.0/255,175.0/255.0,225.0/255.0}; + setExitsColor(exitcol); + setWallsColor(wallcol); //setNavLinesColor(navlinecol); - //showDoors(false); - } - //renderWinInteractor->Initialize(); - // Initialize and enter interactive mode - // should be called after the observer has been added + //showDoors(false); + } + //renderWinInteractor->Initialize(); + // Initialize and enter interactive mode + // should be called after the observer has been added //renderWindow->Modified(); //style->SetKeyPressActivationValue('R'); @@ -366,54 +364,58 @@ void ThreadVisualisation::run(){ renderWinInteractor->Start(); - //emit signalStatusMessage("Idle"); - emit signal_controlSequences("CONTROL_RESET"); + //emit signalStatusMessage("Idle"); + emit signal_controlSequences("CONTROL_RESET"); - //clear some stuffs + //clear some stuffs delete extern_trail_plotter; - finalize(); + finalize(); - renderer->Delete(); - renderWindow->Delete(); - renderWinInteractor->Delete(); + renderer->Delete(); + renderWindow->Delete(); + renderWinInteractor->Delete(); _topViewCamera->Delete(); - renderer=NULL; + renderer=NULL; } -void ThreadVisualisation::slotControlSequence(const char* para){ +void ThreadVisualisation::slotControlSequence(const char* para) +{ - //cout <<"control sequence received: " <<sex<<endl; + //cout <<"control sequence received: " <<sex<<endl; } -void ThreadVisualisation::setGeometryVisibility( bool status){ - if(geometry){ - if(SystemSettings::get2D()){ - geometry->set2D(status); - }else{ - geometry->set3D(status); - } - } +void ThreadVisualisation::setGeometryVisibility( bool status) +{ + if(geometry) { + if(SystemSettings::get2D()) { + geometry->set2D(status); + } else { + geometry->set3D(status); + } + } } /// show / hide the walls -void ThreadVisualisation::showWalls(bool status){ - if(geometry){ - geometry->showWalls(status); - } +void ThreadVisualisation::showWalls(bool status) +{ + if(geometry) { + geometry->showWalls(status); + } } /// show/ hide the exits -void ThreadVisualisation::showDoors(bool status){ - if(geometry){ - geometry->showDoors(status); +void ThreadVisualisation::showDoors(bool status) +{ + if(geometry) { + geometry->showDoors(status); } } void ThreadVisualisation::showNavLines(bool status) { - if(geometry){ + if(geometry) { geometry->showNavLines(status); } } @@ -425,8 +427,13 @@ void ThreadVisualisation::showFloor(bool status) void ThreadVisualisation::initGlyphs2D() { + if(extern_glyphs_pedestrians) extern_glyphs_pedestrians->Delete(); + if(extern_glyphs_pedestrians_actor_2D) extern_glyphs_pedestrians_actor_2D->Delete(); + if(extern_pedestrians_labels) extern_pedestrians_labels->Delete(); extern_glyphs_pedestrians = vtkTensorGlyph::New(); + extern_glyphs_pedestrians_actor_2D = vtkActor::New(); + extern_pedestrians_labels = vtkActor2D::New(); //glyphs with ellipsoids // VTK_CREATE (vtkSphereSource, agentShape); @@ -487,7 +494,9 @@ void ThreadVisualisation::initGlyphs2D() extern_glyphs_pedestrians_actor_2D->SetMapper(mapper); //extern_glyphs_pedestrians_actor_2D->GetProperty()->BackfaceCullingOn(); - renderer->AddActor(extern_glyphs_pedestrians_actor_2D); + + if(extern_trajectories_firstSet.getNumberOfAgents()>0) + renderer->AddActor(extern_glyphs_pedestrians_actor_2D); // structure for the labels VTK_CREATE(vtkLabeledDataMapper, labelMapper); @@ -501,7 +510,11 @@ void ThreadVisualisation::initGlyphs2D() void ThreadVisualisation::initGlyphs3D() { + if(extern_glyphs_pedestrians_3D) extern_glyphs_pedestrians_3D->Delete(); + if(extern_glyphs_pedestrians_actor_3D) extern_glyphs_pedestrians_actor_3D->Delete(); + extern_glyphs_pedestrians_3D = vtkTensorGlyph::New(); + extern_glyphs_pedestrians_actor_3D = vtkActor::New(); //now create the glyphs with zylinders VTK_CREATE (vtkCylinderSource, agentShape); @@ -533,7 +546,7 @@ void ThreadVisualisation::initGlyphs3D() tris->SetInputData(dataCharlie); VTK_CREATE(vtkStripper, agentShape); agentShape->SetInputConnection(tris->GetOutputPort()); -*/ + */ extern_glyphs_pedestrians_3D->SetSourceConnection(agentShape->GetOutputPort()); @@ -544,10 +557,10 @@ void ThreadVisualisation::initGlyphs3D() #if VTK_MAJOR_VERSION <= 5 extern_glyphs_pedestrians_3D->SetSource(agentShape->GetOutput()); - if (frame )extern_glyphs_pedestrians_3D->SetInput(pData); + if (frame )extern_glyphs_pedestrians_3D->SetInput(pData); #else extern_glyphs_pedestrians_3D->SetInputConnection(agentShape->GetOutputPort()); - if (frame )extern_glyphs_pedestrians_3D->SetInputData(pData); + if (frame )extern_glyphs_pedestrians_3D->SetInputData(pData); #endif extern_glyphs_pedestrians_3D->ThreeGlyphsOff(); @@ -568,518 +581,142 @@ void ThreadVisualisation::initGlyphs3D() extern_glyphs_pedestrians_actor_3D->SetMapper(mapper); //extern_glyphs_pedestrians_actor_3D->GetProperty()->BackfaceCullingOn(); - renderer->AddActor(extern_glyphs_pedestrians_actor_3D); + if(extern_trajectories_firstSet.getNumberOfAgents()>0) + renderer->AddActor(extern_glyphs_pedestrians_actor_3D); + extern_glyphs_pedestrians_actor_3D->SetVisibility(false); } -void ThreadVisualisation::init(){ -// //get the datasets parameters. -// // CAUTION: the functions will return 0 if no datasets were initialized -// int numOfAgents1=extern_trajectories_firstSet.getNumberOfAgents(); -// int numOfAgents2=extern_trajectories_secondSet.getNumberOfAgents(); -// int numOfAgents3=extern_trajectories_thirdSet.getNumberOfAgents(); - -// // super Pedestrians are declared extern -// // CAUTION: the start ID is 1. -// if(numOfAgents1>0){ -// //get the first frame from the trajectories and initialize pedes positions -// Frame * frame = extern_trajectories_firstSet.getNextFrame(); -// // this is not usual, but may happen -// //just get out if the frame is empty -// if(frame==NULL) { -// cerr<<"FATAL 1: Frame is null, the first dataset was not initialised"<<endl; -// //exit(1); - -// } - -// //extern_pedestrians_firstSet = new Pedestrian*[numOfAgents1]; -// extern_pedestrians_firstSet =(Pedestrian **)malloc(numOfAgents1*sizeof(Pedestrian*)); - -// //extern_pedestrians_firstSet =(Pedestrian **)malloc(numOfAgents1*sizeof(Pedestrian*)); -// if(extern_pedestrians_firstSet==NULL){ -// cerr<<"could not allocate memory"<<endl; -// exit(1); -// } - -// //The initialisation is just to avoid -// // pedestrians having not defined (0,0,0) position at beginning. - -// for(int i=0;i<numOfAgents1;i++){ - -// TrajectoryPoint* point=NULL; -// int color[3]; -// SystemSettings::getPedestrianColor(0,color); - -// if( (NULL!=frame) && (NULL!=(point=frame->getNextElement()))){ -// extern_pedestrians_firstSet[i]=new Pedestrian(i,point->getX(),point->getY(),point->getZ()); -// // they are all of type 1 (belonging to the first sets) -// // extern_pedestrians_firstSet[i]->setType(1); -// extern_pedestrians_firstSet[i]->setColor(color); - -// }else{ - -// extern_pedestrians_firstSet[i]=new Pedestrian(i,0.0,0.0,0.0); -// extern_pedestrians_firstSet[i]->setVisibility(false); - -// //extern_pedestrians_firstSet[i]->initVisibility(false); -// //extern_pedestrians_firstSet[i]->setType(1); -// extern_pedestrians_firstSet[i]->setColor(color); -// } - -// } - -// //CAUTION: reset the fucking counter. -// //TODO: include the reset cursor in the getnextFrame routine -// // which shall be executed when null is returned -// if (NULL!=frame) -// frame->resetCursor(); - -// // init the pedestrians sizes -// QStringList heights=extern_trajectories_firstSet.getInitialHeights(); -// for(int i=0;i<heights.size()-1;i+=2){ -// bool ok=false; -// int id = heights[i].toInt(&ok); -// if(!ok) {cerr<<"skipping size arguments" <<endl;continue;} -// double size= heights[i+1].toDouble(&ok); -// if(!ok) {cerr<<"skipping size arguments" <<endl;continue;} -// //caution: id start with 0 -// extern_pedestrians_firstSet[id-1]->setSize(size); -// } - -// //init the pedestrians colors, -// // overwrite the previously set colors -// if(SystemSettings::getPedestrianColorProfileFromFile()){ -// QStringList colors=extern_trajectories_firstSet.getInitialColors(); -// for(int i=0;i<colors.size()-1;i+=2){ -// bool ok=false; -// int id = colors[i].toInt(&ok); -// if(!ok) {cerr<<"skipping color arguments" <<endl;continue;} -// int color= colors[i+1].toInt(&ok); -// if(!ok) {cerr<<"skipping color arguments" <<endl;continue;} -// //cout << id<< " :"<<size<<endl; -// //caution: id start with 0 -// extern_pedestrians_firstSet[id-1]->setColor(color); - -// } -// } - -// //all initialisations are done , now create the actors -// for(int i=0;i<numOfAgents1;i++){ -// renderer->AddActor((vtkProp*)extern_pedestrians_firstSet[i]->getActor()); -// renderer->AddActor((vtkProp*)extern_pedestrians_firstSet[i]->getTrailActor()); - -// } -// } - -// // initialize the second dataset -// if(numOfAgents2>0){ -// Frame * frame = extern_trajectories_secondSet.getNextFrame(); -// extern_pedestrians_secondSet =(Pedestrian **)malloc(numOfAgents2*sizeof(Pedestrian*)); -// for(int i=0;i<numOfAgents2;i++){ - -// // this is not usual, but may happen -// //just get out if the frame is empty -// if(frame==NULL) { -// cerr<<"FATAL 2: Frame is null, the second dataset was not initialised"<<endl; -// //exit(1); -// //return; -// } - -// TrajectoryPoint* point=NULL; -// int color[3]; -// SystemSettings::getPedestrianColor(1,color); - -// if( (NULL!=frame) && (NULL!=(point=frame->getNextElement()))){ -// extern_pedestrians_secondSet[i]=new Pedestrian(i,point->getX(),point->getY(),point->getZ()); -// // they are all of type 1 (belonging to the first sets) -// extern_pedestrians_secondSet[i]->setColor(color); -// //extern_pedestrians_secondSet[i]->setType(2); -// //extern_pedestrians_firstSet[i]->CreateActor(); -// }else{ -// extern_pedestrians_secondSet[i]=new Pedestrian(i,0.0,0.0,0.0); -// extern_pedestrians_secondSet[i]->setColor(color); -// // extern_pedestrians_secondSet[i]->setType(2); -// //extern_pedestrians_secondSet[i]->initVisibility(false); -// extern_pedestrians_secondSet[i]->setVisibility(false); -// } - -// //renderer->AddActor((vtkProp*)extern_pedestrians_secondSet[i]->getActor()); -// //renderer->AddActor((vtkProp*)extern_pedestrians_secondSet[i]->getTrailActor()); -// } -// //CAUTION: reset the fucking counter -// // the frame objects are passed by reference, so the "cursor" stays -// // at the last index used. -// frame->resetCursor(); - -// // init the pedestians sizes -// QStringList tokens=extern_trajectories_secondSet.getInitialHeights(); -// for(int i=0;i<tokens.size()-1;i+=2){ - -// bool ok=false; -// int id = tokens[i].toInt(&ok); -// if(!ok) {cerr<<"skipping size arguments" <<endl;continue;} -// double size= tokens[i+1].toDouble(&ok); -// if(!ok) {cerr<<"skipping size arguments" <<endl;continue;} -// extern_pedestrians_secondSet[id-1]->setSize(size); -// } - -// //init the pedestrians colors, -// // overwrite the previously set colors -// if(SystemSettings::getPedestrianColorProfileFromFile()){ -// QStringList colors=extern_trajectories_secondSet.getInitialColors(); -// for(int i=0;i<colors.size()-1;i+=2){ -// bool ok=false; -// int id = colors[i].toInt(&ok); -// if(!ok) {cerr<<"skipping color arguments" <<endl;continue;} -// int color= colors[i+1].toInt(&ok); -// if(!ok) {cerr<<"skipping color arguments" <<endl;continue;} -// //caution: id start with 0 -// extern_pedestrians_secondSet[id-1]->setColor(color); - -// } -// } - -// //all initialisations are done , now create the actors -// for(int i=0;i<numOfAgents2;i++){ -// renderer->AddActor((vtkProp*)extern_pedestrians_secondSet[i]->getActor()); -// renderer->AddActor((vtkProp*)extern_pedestrians_secondSet[i]->getTrailActor()); - -// } - -// } - -// if(numOfAgents3>0){ - -// Frame * frame = extern_trajectories_thirdSet.getNextFrame(); -// extern_pedestrians_thirdSet =(Pedestrian **)malloc(numOfAgents3*sizeof(Pedestrian*)); -// for(int i=0;i<numOfAgents3;i++){ - -// // this is not usual, but may happen -// //just get out if the frame is empty -// if(frame==NULL) { -// cerr<<"FATAL 3: Frame is null, the third dataset was not initialised"<<endl; -// //exit(1); - -// } - -// TrajectoryPoint* point=NULL; -// int color[3]; -// SystemSettings::getPedestrianColor(2,color); - -// if( (NULL!=frame) && (NULL!=(point=frame->getNextElement()))){ -// extern_pedestrians_thirdSet[i]=new Pedestrian(i,point->getX(),point->getY(),point->getZ()); -// // they are all of type 1 (belonging to the first sets) -// //extern_pedestrians_thirdSet[i]->setType(3); -// extern_pedestrians_thirdSet[i]->setColor(color); -// //extern_pedestrians_firstSet[i]->CreateActor(); -// }else{ -// extern_pedestrians_thirdSet[i]=new Pedestrian(i,0.0,0.0,0.0); -// // extern_pedestrians_thirdSet[i]->setType(3); -// extern_pedestrians_thirdSet[i]->setColor(color); -// //extern_pedestrians_thirdSet[i]->initVisibility(false); -// extern_pedestrians_thirdSet[i]->setVisibility(false); -// } - -// //renderer->AddActor((vtkProp*)extern_pedestrians_thirdSet[i]->getActor()); -// //renderer->AddActor((vtkProp*)extern_pedestrians_thirdSet[i]->getTrailActor()); -// } -// //CAUTION: reset the fucking counter. -// frame->resetCursor(); - -// // init the pedestians sizes -// QStringList tokens=extern_trajectories_thirdSet.getInitialHeights(); -// for(int i=0;i<tokens.size()-1;i+=2){ -// bool ok=false; -// int id = tokens[i].toInt(&ok); -// if(!ok) {cerr<<"skipping size arguments" <<endl;continue;} -// double size= tokens[i+1].toDouble(&ok); -// if(!ok) {cerr<<"skipping size arguments" <<endl;continue;} -// //cout << id<< " :"<<size<<endl; -// extern_pedestrians_thirdSet[id-1]->setSize(size); -// } -// //init the pedestrians colors, -// // overwrite the previously set colors -// if(SystemSettings::getPedestrianColorProfileFromFile()){ -// QStringList colors=extern_trajectories_thirdSet.getInitialColors(); -// for(int i=0;i<colors.size()-1;i+=2){ -// bool ok=false; -// int id = colors[i].toInt(&ok); -// if(!ok) {cerr<<"skipping color arguments" <<endl;continue;} -// int color= colors[i+1].toInt(&ok); -// if(!ok) {cerr<<"skipping color arguments" <<endl;continue;} -// //caution: id start with 0 -// extern_pedestrians_thirdSet[id-1]->setColor(color); -// } -// } - -// //all initialisations are done , now create the actors -// for(int i=0;i<numOfAgents3;i++){ -// renderer->AddActor((vtkProp*)extern_pedestrians_thirdSet[i]->getActor()); -// renderer->AddActor((vtkProp*)extern_pedestrians_thirdSet[i]->getTrailActor()); - -// } - -// } -} +void ThreadVisualisation::init() {} -void ThreadVisualisation::finalize(){ - //get the datasets parameters. - // CAUTION: the functions will return 0 if no datasets were initialized - int numOfAgents1=extern_trajectories_firstSet.getNumberOfAgents(); - int numOfAgents2=extern_trajectories_secondSet.getNumberOfAgents(); - int numOfAgents3=extern_trajectories_thirdSet.getNumberOfAgents(); - - - if(numOfAgents1>0){ - //extern_trajectories_firstSet.clear(); - for(int i=0;i<numOfAgents1;i++){ - delete(extern_pedestrians_firstSet[i]); - } - free(extern_pedestrians_firstSet); - extern_pedestrians_firstSet=NULL; - } - - if(numOfAgents2>0){ - //extern_trajectories_secondSet.clear(); - for(int i=0;i<numOfAgents2;i++){ - delete(extern_pedestrians_secondSet[i]); - } - free(extern_pedestrians_secondSet); - extern_pedestrians_secondSet=NULL; - } - - if(numOfAgents3>0){ - //extern_trajectories_thirdSet.clear(); - for(int i=0;i<numOfAgents3;i++){ - delete(extern_pedestrians_thirdSet[i]); - } - free(extern_pedestrians_thirdSet); - extern_pedestrians_thirdSet=NULL; - } - +void ThreadVisualisation::finalize() +{ } /// compute the relative delays to the datasets -void ThreadVisualisation::computeDelays(){ - - unsigned long delay1[2]; - unsigned long delay2[2]; - unsigned long delay3[2]; - - bool first_set_loaded = (extern_trajectories_firstSet.getNumberOfAgents()>0)?true:false; - bool second_set_loaded = (extern_trajectories_secondSet.getNumberOfAgents()>0)?true:false; - bool third_set_loaded = (extern_trajectories_thirdSet.getNumberOfAgents()>0)?true:false; - - if(first_set_loaded) - extern_trajectories_firstSet.getDelayAbsolute(delay1); - if(second_set_loaded) - extern_trajectories_secondSet.getDelayAbsolute(delay2); - if(third_set_loaded) - extern_trajectories_thirdSet.getDelayAbsolute(delay3); - - // three datasets were loaded - if(first_set_loaded & second_set_loaded & third_set_loaded){ - // relative delays are computed with respect to the first dataset - extern_trajectories_secondSet.computeDelayRelative(delay1); - extern_trajectories_thirdSet.computeDelayRelative(delay1); - - signed long delay_first=extern_trajectories_firstSet.getDelayRelative(); - signed long delay_second=extern_trajectories_secondSet.getDelayRelative(); - signed long delay_third=extern_trajectories_thirdSet.getDelayRelative(); - - if(delay_first<0) { - delay_second+=-delay_first; - delay_third+=-delay_first; - delay_first=0; - } - if(delay_second<0){ - delay_first+=-delay_second; - delay_third+=-delay_second; - delay_second=0; - } - if(delay_third<0){ - delay_first+=-delay_third; - delay_second+=-delay_third; - delay_third=0; - } - Debug::Messages("delay first data set: %f \n",delay_first); - Debug::Messages("delay second data set: %f \n",delay_second); - Debug::Messages("delay third data set: %f \n",delay_third); - - //at this point all delays should be positive - // this step is no loner necessary - extern_trajectories_firstSet.setDelayRelative(delay_first); - extern_trajectories_secondSet.setDelayRelative(delay_second); - extern_trajectories_thirdSet.setDelayRelative(delay_third); - - - extern_trajectories_firstSet.setFrameCursorOffset(- (delay_first*framePerSecond/1000.0f)); - extern_trajectories_secondSet.setFrameCursorOffset(- (delay_second*framePerSecond/1000.0f)); - extern_trajectories_thirdSet.setFrameCursorOffset(- (delay_third*framePerSecond/1000.0f)); - - } - - else if (first_set_loaded & second_set_loaded){ - // relative delays are computed with respect to the first dataset - extern_trajectories_secondSet.computeDelayRelative(delay1); - - signed long delay_first=extern_trajectories_firstSet.getDelayRelative(); - signed long delay_second=extern_trajectories_secondSet.getDelayRelative(); - - //implement me in a while loop - if(delay_first<0) { - delay_second+=-delay_first; - delay_first=0; - } - if(delay_second<0){ - delay_first+=-delay_second; - delay_second=0; - } - - if(delay_first<0) { - delay_second+=-delay_first; - delay_first=0; - } - if(delay_second<0){ - delay_first+=-delay_second; - delay_second=0; - } - - Debug::Messages("delay first data set: %f \n",delay_first); - Debug::Messages("delay second data set: %f \n",delay_second); - - //at this point all delays should be positive - extern_trajectories_firstSet.setDelayRelative(delay_first); - extern_trajectories_secondSet.setDelayRelative(delay_second); - - extern_trajectories_firstSet.setFrameCursorOffset(- (delay_first*framePerSecond/1000.0f)); - extern_trajectories_secondSet.setFrameCursorOffset(- (delay_second*framePerSecond/1000.0f)); - - - }else if (first_set_loaded & third_set_loaded){ - Debug::Error("Hudston, we got a problem"); - }else if (third_set_loaded & second_set_loaded){ - Debug::Error("Hudston, the matter is serious"); - }else{ - //cerr<<"Only one dataset loaded !,no delays/offsets are computed"<<endl; - } +void ThreadVisualisation::computeDelays() {} -} +void ThreadVisualisation::initLegend(/*std::vector scalars*/) +{ + + //lookup table + vtkLookupTable* lut = vtkLookupTable::New(); + lut->SetHueRange(0.0,0.566); + lut->SetTableRange(20.0, 50.0); + //lut->SetSaturationRange(0,0); + //lut->SetValueRange(0.0,1.0); + lut->SetNumberOfTableValues(50); + lut->Build(); -void ThreadVisualisation::initLegend(/*std::vector scalars*/){ - - //lookup table - vtkLookupTable* lut = vtkLookupTable::New(); - lut->SetHueRange(0.0,0.566); - lut->SetTableRange(20.0, 50.0); - //lut->SetSaturationRange(0,0); - //lut->SetValueRange(0.0,1.0); - lut->SetNumberOfTableValues(50); - lut->Build(); - - //vtkPolyData* polyData = vtkPolyData::New(); - //polyData->sets - //polyData->SetPoints(pts); - //polyData->GetPointData()->SetScalars(scalars); - //vtkPolyDataMapper* mapper =vtkPolyDataMapper::New(); - //mapper->SetLookupTable(lut); - // mapper->SetInput(polyData->GetPolyDataOutput()); - // mapper->SetScalarRange(randomColors->GetPolyDataOutput()->GetScalarRange()); - - vtkTextProperty* titleProp = vtkTextProperty::New(); - titleProp->SetFontSize(14); - - vtkTextProperty* labelProp = vtkTextProperty::New(); - labelProp->SetFontSize(10); - - // cerr<<"label: " <<labelProp->GetFontSize()<<endl; - // cerr<<" : " <<labelProp->GetFontFamilyAsString()<<endl; - // - // cerr<<"title: " <<titleProp->GetFontSize()<<endl; - // cerr<<" : " <<titleProp->GetFontFamilyAsString()<<endl; - - vtkScalarBarActor* scalarBar = vtkScalarBarActor::New(); - scalarBar->SetLookupTable(lut); - //scalarBar->SetLookupTable(mapper->GetLookupTable()); - scalarBar->SetTitle("Velocities ( cm/s )"); - scalarBar->SetTitleTextProperty(titleProp); - scalarBar->SetLabelTextProperty (labelProp); - scalarBar->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); - // scalarBar->GetPositionCoordinate()->SetValue(0.1, 0.05); - scalarBar->GetPositionCoordinate()->SetValue(0.005, 0.90075); - scalarBar->SetOrientationToVertical(); - scalarBar->SetNumberOfLabels(7); - scalarBar->SetMaximumNumberOfColors(20); - scalarBar->SetWidth(0.105); - scalarBar->SetHeight(0.10); - //scalarBar->SetPickable(1); - //scalarBar->SetTextPositionToPrecedeScalarBar(); - //scalarBar->SetLabelFormat("%-#5.1f"); - renderer->AddActor2D(scalarBar); - renderer->Render(); + //vtkPolyData* polyData = vtkPolyData::New(); + //polyData->sets + //polyData->SetPoints(pts); + //polyData->GetPointData()->SetScalars(scalars); + //vtkPolyDataMapper* mapper =vtkPolyDataMapper::New(); + //mapper->SetLookupTable(lut); + // mapper->SetInput(polyData->GetPolyDataOutput()); + // mapper->SetScalarRange(randomColors->GetPolyDataOutput()->GetScalarRange()); + + vtkTextProperty* titleProp = vtkTextProperty::New(); + titleProp->SetFontSize(14); + + vtkTextProperty* labelProp = vtkTextProperty::New(); + labelProp->SetFontSize(10); + + // cerr<<"label: " <<labelProp->GetFontSize()<<endl; + // cerr<<" : " <<labelProp->GetFontFamilyAsString()<<endl; + // + // cerr<<"title: " <<titleProp->GetFontSize()<<endl; + // cerr<<" : " <<titleProp->GetFontFamilyAsString()<<endl; + + vtkScalarBarActor* scalarBar = vtkScalarBarActor::New(); + scalarBar->SetLookupTable(lut); + //scalarBar->SetLookupTable(mapper->GetLookupTable()); + scalarBar->SetTitle("Velocities ( cm/s )"); + scalarBar->SetTitleTextProperty(titleProp); + scalarBar->SetLabelTextProperty (labelProp); + scalarBar->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); + // scalarBar->GetPositionCoordinate()->SetValue(0.1, 0.05); + scalarBar->GetPositionCoordinate()->SetValue(0.005, 0.90075); + scalarBar->SetOrientationToVertical(); + scalarBar->SetNumberOfLabels(7); + scalarBar->SetMaximumNumberOfColors(20); + scalarBar->SetWidth(0.105); + scalarBar->SetHeight(0.10); + //scalarBar->SetPickable(1); + //scalarBar->SetTextPositionToPrecedeScalarBar(); + //scalarBar->SetLabelFormat("%-#5.1f"); + renderer->AddActor2D(scalarBar); + renderer->Render(); } -void ThreadVisualisation::setAxisVisible(bool status){ - axis->SetVisibility(status); +void ThreadVisualisation::setAxisVisible(bool status) +{ + axis->SetVisibility(status); } -void ThreadVisualisation::setCameraPerspective(int mode){ - if(renderer==NULL) return; +void ThreadVisualisation::setCameraPerspective(int mode) +{ + if(renderer==NULL) return; - switch (mode) { + switch (mode) { case 1: //TOP oder RESET - renderer->GetActiveCamera()->DeepCopy(_topViewCamera); - break; + renderer->GetActiveCamera()->DeepCopy(_topViewCamera); + break; - case 2://SIDE + case 2://SIDE - break; + break; - case 3: - //FRONT - break; + case 3: + //FRONT + break; - case 4:// agent virtual reality - { - //vtkCamera *camera = renderer->GetActiveCamera(); - //camera->SetRoll(-90); - //std::cout <<"roll [ "<< camera->GetRoll()<<" ]"<<std::endl; - //double roll=camera->GetRoll(); - //camera->Roll(-90-camera->GetRoll()); - //camera->Modified(); - } + case 4: { // agent virtual reality + //vtkCamera *camera = renderer->GetActiveCamera(); + //camera->SetRoll(-90); + //std::cout <<"roll [ "<< camera->GetRoll()<<" ]"<<std::endl; + //double roll=camera->GetRoll(); + //camera->Roll(-90-camera->GetRoll()); + //camera->Modified(); + } - break; - } + break; + } } -void ThreadVisualisation::setBackgroundColor(double* color){ - if (renderer!=NULL) - renderer->SetBackground(color); +void ThreadVisualisation::setBackgroundColor(double* color) +{ + if (renderer!=NULL) + renderer->SetBackground(color); } -void ThreadVisualisation::setWindowTitle(QString title){ - if(title.isEmpty())return; - winTitle=title; +void ThreadVisualisation::setWindowTitle(QString title) +{ + if(title.isEmpty())return; + winTitle=title; } /// @todo check this construct -void ThreadVisualisation::setGeometry(FacilityGeometry* geometry){ - this->geometry=geometry; +void ThreadVisualisation::setGeometry(FacilityGeometry* geometry) +{ + this->geometry=geometry; } -FacilityGeometry* ThreadVisualisation::getGeometry() { +FacilityGeometry* ThreadVisualisation::getGeometry() +{ //if(geometry==NULL){ - geometry=new FacilityGeometry(); + geometry=new FacilityGeometry(); //} - return geometry; + return geometry; } -void ThreadVisualisation::setWallsColor(double* color){ +void ThreadVisualisation::setWallsColor(double* color) +{ geometry->changeWallsColor(color); } @@ -1088,11 +725,13 @@ void ThreadVisualisation::setFloorColor(double *color) geometry->changeFloorColor(color); } -void ThreadVisualisation::setGeometryLabelsVisibility(int v){ - geometry->showGeometryLabels(v); +void ThreadVisualisation::setGeometryLabelsVisibility(int v) +{ + geometry->showGeometryLabels(v); } -void ThreadVisualisation::setExitsColor(double* color){ +void ThreadVisualisation::setExitsColor(double* color) +{ geometry->changeExitsColor(color); } @@ -1103,19 +742,22 @@ void ThreadVisualisation::setNavLinesColor(double *color) /// enable/disable 2D /// todo: consider disabling the 2d option in the 3d, and vice-versa -void ThreadVisualisation::setGeometryVisibility2D(bool status){ - if(geometry!=NULL) //FIXME this should never happens - geometry->set2D(status); +void ThreadVisualisation::setGeometryVisibility2D(bool status) +{ + if(geometry!=NULL) //FIXME this should never happens + geometry->set2D(status); } /// enable/disable 3D /// todo: consider disabling the 2d option in the 3d, and vice-versa -void ThreadVisualisation::setGeometryVisibility3D(bool status){ - if(geometry!=NULL) //FIXME this should never happens, seems to be called by slotReset() ! - geometry->set3D(status); +void ThreadVisualisation::setGeometryVisibility3D(bool status) +{ + if(geometry!=NULL) //FIXME this should never happens, seems to be called by slotReset() ! + geometry->set3D(status); } -void ThreadVisualisation::setOnscreenInformationVisibility(bool show){ - runningTime->SetVisibility(show); +void ThreadVisualisation::setOnscreenInformationVisibility(bool show) +{ + runningTime->SetVisibility(show); } diff --git a/src/ThreadVisualisation.h b/src/ThreadVisualisation.h index 56159ca758d2387b9decbe61e4dc08c4066beacb..6fe79b5ae5777342500b37ef36471ec0b7ec48ea 100644 --- a/src/ThreadVisualisation.h +++ b/src/ThreadVisualisation.h @@ -68,74 +68,73 @@ extern Pedestrian** extern_pedestrians_thirdSet; extern PointPlotter* extern_trail_plotter; -//extern vtkSmartPointer<vtkGlyph3D> extern_glyphs_pedestrians; -extern vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians; -extern vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians_3D; -extern vtkSmartPointer<vtkActor> extern_glyphs_pedestrians_actor_2D; -extern vtkSmartPointer<vtkActor> extern_glyphs_pedestrians_actor_3D; +extern vtkTensorGlyph* extern_glyphs_pedestrians; +extern vtkTensorGlyph* extern_glyphs_pedestrians_3D; +extern vtkActor* extern_glyphs_pedestrians_actor_2D; +extern vtkActor* extern_glyphs_pedestrians_actor_3D; extern SyncData extern_trajectories_firstSet; extern SyncData extern_trajectories_secondSet; extern SyncData extern_trajectories_thirdSet; class ThreadVisualisation :public QThread { - Q_OBJECT + Q_OBJECT public: - ThreadVisualisation(QObject *parent = 0); - virtual ~ThreadVisualisation(); - virtual void run(); + ThreadVisualisation(QObject *parent = 0); + virtual ~ThreadVisualisation(); + virtual void run(); - void setAxisVisible(bool status); + void setAxisVisible(bool status); - void setFullsreen(bool status); + void setFullsreen(bool status); - /// set the camera to one of TOP/FRONT/SIDE - void setCameraPerspective(int mode); + /// set the camera to one of TOP/FRONT/SIDE + void setCameraPerspective(int mode); - /// load and display the geometry where - /// the pedestrians will move - void setGeometry(FacilityGeometry* geometry); + /// load and display the geometry where + /// the pedestrians will move + void setGeometry(FacilityGeometry* geometry); - FacilityGeometry* getGeometry(); + FacilityGeometry* getGeometry(); - ///this is for convenience and will be delete later - void setWindowTitle(QString title); + ///this is for convenience and will be delete later + void setWindowTitle(QString title); - /// shutdown the thread - //void shutdown(); + /// shutdown the thread + //void shutdown(); - void setGeometryLabelsVisibility(int v); + void setGeometryLabelsVisibility(int v); - /// set geometry visibility - void setGeometryVisibility(bool status); + /// set geometry visibility + void setGeometryVisibility(bool status); - /// enable/disable 2D - void setGeometryVisibility2D(bool status); + /// enable/disable 2D + void setGeometryVisibility2D(bool status); - /// enable/disable 3D - void setGeometryVisibility3D(bool status); + /// enable/disable 3D + void setGeometryVisibility3D(bool status); - /// change the background color of the rendering windows - void setBackgroundColor(double* color); + /// change the background color of the rendering windows + void setBackgroundColor(double* color); - /// change the walls color - void setWallsColor(double* color); + /// change the walls color + void setWallsColor(double* color); /// change the floor color void setFloorColor(double* color); - /// change the exits color. - void setExitsColor(double* color); + /// change the exits color. + void setExitsColor(double* color); /// change the exits color. void setNavLinesColor(double* color); - /// show / hide the walls - void showWalls(bool status); + /// show / hide the walls + void showWalls(bool status); - /// show/ hide the exits - void showDoors(bool status); + /// show/ hide the exits + void showDoors(bool status); /// show/ hide the exits void showNavLines(bool status); @@ -143,18 +142,18 @@ public: /// show/ hide the floor void showFloor(bool status); - /// show / hide stairs - ///not implemented - void showStairs(bool status); + /// show / hide stairs + ///not implemented + void showStairs(bool status); - void setOnscreenInformationVisibility(bool show); + void setOnscreenInformationVisibility(bool show); public Q_SLOTS: - /**control sequence received*/ + /**control sequence received*/ void slotControlSequence(const char* para); - /// set the frame rate in frames per second - void slotSetFrameRate( float fps); + /// set the frame rate in frames per second + void slotSetFrameRate( float fps); Q_SIGNALS: @@ -162,46 +161,39 @@ Q_SIGNALS: private: - /// initialize the legend - void initLegend(/*std::vector scalars*/); + /// initialize the legend + void initLegend(/*std::vector scalars*/); - /// initialize the datasets - void init(); + /// initialize the datasets + void init(); - /// initialize the datasets + /// initialize the datasets void initGlyphs2D(); //initialize the 3D agents void initGlyphs3D(); - //finalize the datasets - void finalize(); + //finalize the datasets + void finalize(); - /// compute the relative delays to the datasets - void computeDelays(); + /// compute the relative delays to the datasets + void computeDelays(); - /// window change events - //static void WindowModifiedCallback(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ); + /// window change events + //static void WindowModifiedCallback(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ); private: - FacilityGeometry* geometry; - vtkRenderer* renderer; - vtkRenderWindow* renderWindow; - vtkRenderWindowInteractor* renderWinInteractor; - vtkAxesActor* axis; - vtkTextActor* runningTime; + FacilityGeometry* geometry; + vtkRenderer* renderer; + vtkRenderWindow* renderWindow; + vtkRenderWindowInteractor* renderWinInteractor; + vtkAxesActor* axis; + vtkTextActor* runningTime; vtkCamera* _topViewCamera; - QString winTitle; - - float framePerSecond; - double camPosTop[3]; - double camClipTop[3]; - double camFocalPointTop[3]; - double camViewUpTop[3]; - double camViewAngleTop; - double camParallelScale; - double camViewPlanNormalTop[3]; + QString winTitle; + + float framePerSecond; }; diff --git a/src/TimerCallback.cpp b/src/TimerCallback.cpp index 13d57b866645627475b6121e641e7522fb78cb71..97516232c2335e58bbff86a1f22b1c143b710ee2 100644 --- a/src/TimerCallback.cpp +++ b/src/TimerCallback.cpp @@ -78,6 +78,7 @@ #include <vtkSmartPointer.h> #include <vtkPolyDataMapper.h> #include <vtkLabeledDataMapper.h> +#include <vtkMath.h> @@ -111,16 +112,15 @@ TimerCallback* TimerCallback::New() void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, - void *callData){ - if (vtkCommand::TimerEvent == eventId) - { + void *callData) +{ + if (vtkCommand::TimerEvent == eventId) { int frameNumber=0; int nPeds=0; static bool isRecording =false; int tid = * static_cast<int *>(callData); - if (tid == this->RenderTimerId) - { + if (tid == this->RenderTimerId) { //dont update anything if the system is actually paused //if(extern_is_pause) return; @@ -128,8 +128,7 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, vtkRenderWindow *renderWindow = iren->GetRenderWindow(); vtkRenderer *renderer =renderWindow->GetRenderers()->GetFirstRenderer(); - if (iren && renderWindow && renderer) - { + if (iren && renderWindow && renderer) { //first pedestrian group if(extern_first_dataset_loaded) { @@ -144,17 +143,13 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, else frame = extern_trajectories_firstSet.getNextFrame(); - if(frame==NULL) - { + if(frame==NULL) { - } - else - { + } else { frameNumber=extern_trajectories_firstSet.getFrameCursor(); nPeds= frame->getSize(); - if(SystemSettings::get2D()==true) - { + if(SystemSettings::get2D()==true) { vtkPolyData* pData=frame->GetPolyData2D(); #if VTK_MAJOR_VERSION <= 5 extern_glyphs_pedestrians->SetInput(pData); @@ -164,9 +159,7 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, extern_pedestrians_labels->GetMapper()->SetInputDataObject(pData); #endif extern_glyphs_pedestrians->Update(); - } - else - { + } else { vtkPolyData* pData=frame->GetPolyData3D(); #if VTK_MAJOR_VERSION <= 5 extern_glyphs_pedestrians_3D->SetInput(pData); @@ -178,12 +171,10 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, extern_glyphs_pedestrians_3D->Update(); } - if(extern_tracking_enable) - { + if(extern_tracking_enable) { const std::vector<FrameElement *> &elements=frame->GetFrameElements(); - for(unsigned int i=0;i<elements.size();i++) - { + for(unsigned int i=0; i<elements.size(); i++) { FrameElement* el = elements[i]; double pos[3]; double color; @@ -192,10 +183,14 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, extern_trail_plotter->PlotPoint(pos,color); } } + + //virtual cam + if(SystemSettings::getVirtualAgent()!=-1){ + updateVirtualCamera(frame,renderer); + } } } - int* winSize=renderWindow->GetSize(); static int lastWinX=winSize[0]+1; // +1 to trigger a first change static int lastWinY=winSize[1]; @@ -204,8 +199,7 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, runningTime->SetInput(runningTimeText); runningTime->Modified(); - if((lastWinX!=winSize[0]) || (lastWinY!=winSize[1]) || (frameNumber<10)) - { + if((lastWinX!=winSize[0]) || (lastWinY!=winSize[1]) || (frameNumber<10)) { static std::string winBaseName(renderWindow->GetWindowName()); std::string winName=winBaseName; std::string s; @@ -228,13 +222,13 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, iren->Render(); - if(extern_force_system_update){ + if(extern_force_system_update) { updateSettings(renderWindow); } - if(extern_take_screenshot){ + if(extern_take_screenshot) { takeScreenshot(renderWindow); } - if(SystemSettings::getRecordPNGsequence()){ + if(SystemSettings::getRecordPNGsequence()) { takeScreenshotSequence(renderWindow); } @@ -251,7 +245,7 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, #ifdef TRAVISTO_FFMPEG - if(extern_launch_recording){ + if(extern_launch_recording) { extern_launch_recording=false; //reset windowToImageFilter=vtkWindowToImageFilter::New(); @@ -269,9 +263,9 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, QString videoName; SystemSettings::getOutputDirectory(videoName); //create directory if not exits - if(!QDir(videoName).exists()){ + if(!QDir(videoName).exists()) { QDir dir; - if(!dir.mkpath (videoName )){ + if(!dir.mkpath (videoName )) { cerr<<"could not create directory: "<< videoName.toStdString(); videoName=""; // current } @@ -282,7 +276,7 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, pAVIWriter->SetFileName(videoName.toStdString().c_str()); if(windowToImageFilter!=NULL) - if(windowToImageFilter->GetInput()==NULL){ //should be the case by first call + if(windowToImageFilter->GetInput()==NULL) { //should be the case by first call windowToImageFilter->SetInput(renderWindow); #if VTK_MAJOR_VERSION <= 5 pAVIWriter->SetInput(windowToImageFilter->GetOutput()); @@ -295,12 +289,12 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, isRecording=true; } - if(isRecording){ + if(isRecording) { windowToImageFilter->Modified(); // only write when not paused if(!extern_is_pause) pAVIWriter->Write(); - if(extern_recording_enable==false){ //stop the recording + if(extern_recording_enable==false) { //stop the recording pAVIWriter->End(); windowToImageFilter->Delete(); pAVIWriter->Delete(); @@ -309,7 +303,7 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, } #endif //TRAVISTO_FFMPEG - if(extern_shutdown_visual_thread){ + if(extern_shutdown_visual_thread) { emit signalFrameNumber(0); // this will force an update of the windows @@ -322,9 +316,12 @@ void TimerCallback::Execute(vtkObject *caller, unsigned long eventId, } } } + + } -void TimerCallback::updateSettings(vtkRenderWindow* renderWindow) { +void TimerCallback::updateSettings(vtkRenderWindow* renderWindow) +{ static bool fullscreen=false; @@ -338,7 +335,7 @@ void TimerCallback::updateSettings(vtkRenderWindow* renderWindow) { //geometry captions //enable / disable full screen - if(fullscreen!=extern_fullscreen_enable){ + if(fullscreen!=extern_fullscreen_enable) { renderWindow->SetFullScreen(extern_fullscreen_enable); //renderWindow->GetRenderers()->GetFirstRenderer()->ResetCamera(); fullscreen=extern_fullscreen_enable; @@ -349,7 +346,8 @@ void TimerCallback::updateSettings(vtkRenderWindow* renderWindow) { } -void TimerCallback::getTrail(int datasetID, int frameNumber){ +void TimerCallback::getTrail(int datasetID, int frameNumber) +{ int trailCount=0; int trailType=0; @@ -359,7 +357,7 @@ void TimerCallback::getTrail(int datasetID, int frameNumber){ SystemSettings::getTrailsInfo(&trailCount,&trailType,&trailForm); - switch(trailType){ + switch(trailType) { case 0://backward tcMin=frameNumber-trailCount; tcMax=frameNumber; @@ -379,13 +377,13 @@ void TimerCallback::getTrail(int datasetID, int frameNumber){ } - for (int i=tcMin;i<tcMax;i++){ + for (int i=tcMin; i<tcMax; i++) { Frame* frame = extern_trajectories_firstSet.getFrame(i); - if(frame==NULL){ + if(frame==NULL) { // cerr<<"Trajectory not available in getTrail(), first data set"<<endl; - }else { + } else { FrameElement* point=NULL; - while(NULL!=(point=frame->getNextElement())){ + while(NULL!=(point=frame->getNextElement())) { //extern_pedestrians_firstSet[point->getIndex()]->plotTrail(point->getX(),point->getY(),point->getZ()); //extern_pedestrians_firstSet[point->getIndex()]->setTrailGeometry(trailForm); } @@ -394,8 +392,56 @@ void TimerCallback::getTrail(int datasetID, int frameNumber){ } } +void TimerCallback::updateVirtualCamera(Frame *frame, vtkRenderer *renderer) +{ + //look for the position of that agent + const std::vector <FrameElement *> elements= frame->GetFrameElements(); + + for(unsigned int i=0;i<elements.size();i++){ + FrameElement * el= elements[i]; + if(el->GetId()==SystemSettings::getVirtualAgent()) + { + static bool cam=true; + double pos[3]={0,0,0}; + double orien[3]={0,0,0}; + double pedSize=170; + el->GetPos(pos); + el->GetOrientation(orien); + double angle=vtkMath::RadiansFromDegrees(orien[2]); + + //cout<<"new Pos: "<<pos[0]<<" " <<pos[1] <<" "<<pos[2]<<endl; + + vtkCamera* virtualCam=renderer->GetActiveCamera(); + + virtualCam->Print(std::cout); exit(0); + virtualCam->SetPosition(pos[0]+15,pos[1],pos[2]+pedSize); + + //new focal point + double eyeRange=150;//15m + + double x=pos[0]+eyeRange*cos(angle); + double y=pos[1]+eyeRange*sin(angle); + double z = pos[2]; + //virtualCam->SetFocalPoint(pos[0]+15,pos[1],pos[2]+pedSize+8); + virtualCam->SetFocalPoint(x,y,z+pedSize+8); + //virtualCam->Azimuth(pedestrianOrienation); + //virtualCam->Azimuth(pedestrianOrienation); + //virtualCam->Yaw(pedestrianOrienation); + + virtualCam->SetDistance(eyeRange); + if(cam)virtualCam->SetRoll(90); + cam=false; + + virtualCam->Modified(); + + return; + } + } +} + -void TimerCallback::takeScreenshot(vtkRenderWindow *renderWindow){ +void TimerCallback::takeScreenshot(vtkRenderWindow *renderWindow) +{ static int imageID=0; vtkWindowToImageFilter * winToImFilter = vtkWindowToImageFilter::New(); winToImFilter->SetInput( renderWindow ); @@ -409,9 +455,9 @@ void TimerCallback::takeScreenshot(vtkRenderWindow *renderWindow){ QString screenshots; SystemSettings::getOutputDirectory(screenshots); //create directory if not exits - if(!QDir(screenshots).exists()){ + if(!QDir(screenshots).exists()) { QDir dir; - if(!dir.mkpath (screenshots )){ + if(!dir.mkpath (screenshots )) { //Debug::Error("could not create directory: %s",screenshots.toStdString().c_str()); //try with the current directory screenshots=""; @@ -419,7 +465,7 @@ void TimerCallback::takeScreenshot(vtkRenderWindow *renderWindow){ } - char filename[256]={0}; + char filename[256]= {0}; // sprintf(filename,"travisto_video_%d.png",imageID++); std::string date= QString(QDateTime::currentDateTime().toString("yyMMdd_hh")).toStdString(); @@ -437,7 +483,8 @@ void TimerCallback::takeScreenshot(vtkRenderWindow *renderWindow){ } /// take png screenshot sequence -void TimerCallback::takeScreenshotSequence(vtkRenderWindow* renderWindow){ +void TimerCallback::takeScreenshotSequence(vtkRenderWindow* renderWindow) +{ static int imageID=0; vtkWindowToImageFilter * winToImFilter = vtkWindowToImageFilter::New(); winToImFilter->SetInput( renderWindow ); @@ -454,9 +501,9 @@ void TimerCallback::takeScreenshotSequence(vtkRenderWindow* renderWindow){ screenshots.truncate(screenshots.size()-1); //create directory if not exits - if(!QDir(screenshots).exists()){ + if(!QDir(screenshots).exists()) { QDir dir; - if(!dir.mkpath (screenshots )){ + if(!dir.mkpath (screenshots )) { cerr<<"could not create directory: "<< screenshots.toStdString(); //try with the current directory screenshots="./png_seq_"+QDateTime::currentDateTime().toString("yyMMdd")+"_"+SystemSettings::getFilenamePrefix(); @@ -465,7 +512,7 @@ void TimerCallback::takeScreenshotSequence(vtkRenderWindow* renderWindow){ } - char filename[30]={0}; + char filename[30]= {0}; sprintf(filename,"/tmp_%07d.png",imageID++); screenshots.append(filename); image->SetFileName(screenshots.toStdString().c_str()); @@ -481,7 +528,8 @@ void TimerCallback::SetRenderTimerId(int tid) this->RenderTimerId = tid; } -void TimerCallback::setTextActor(vtkTextActor* ra){ +void TimerCallback::setTextActor(vtkTextActor* ra) +{ runningTime=ra; } diff --git a/src/TimerCallback.h b/src/TimerCallback.h index 6ebd21d2734b0a53724a7b3dfaa101676d2e6b3a..3871ce11b4f290d5808636b7c3aa7c7de5db3a1b 100644 --- a/src/TimerCallback.h +++ b/src/TimerCallback.h @@ -83,11 +83,11 @@ extern Pedestrian** extern_pedestrians_firstSet; extern Pedestrian** extern_pedestrians_secondSet; extern Pedestrian** extern_pedestrians_thirdSet; -extern vtkSmartPointer<vtkActor2D> extern_pedestrians_labels; -extern vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians; -extern vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians_3D; -extern vtkSmartPointer<vtkActor> extern_glyphs_pedestrians_actor_2D; -extern vtkSmartPointer<vtkActor> extern_glyphs_pedestrians_actor_3D; +extern vtkActor2D* extern_pedestrians_labels; +extern vtkTensorGlyph* extern_glyphs_pedestrians; +extern vtkTensorGlyph* extern_glyphs_pedestrians_3D; +extern vtkActor* extern_glyphs_pedestrians_actor_2D; +extern vtkActor* extern_glyphs_pedestrians_actor_3D; extern PointPlotter* extern_trail_plotter; extern SyncData extern_trajectories_firstSet; @@ -106,66 +106,58 @@ extern bool extern_third_dataset_visible; -class TimerCallback :public QObject, public vtkCommand{ +class TimerCallback :public QObject, public vtkCommand { - Q_OBJECT + Q_OBJECT private: - int RenderTimerId; - vtkWindowToImageFilter* windowToImageFilter; - vtkPNGWriter *pngWriter; - vtkTextActor* runningTime; - char runningTimeText[50]; + int RenderTimerId; + vtkWindowToImageFilter* windowToImageFilter; + vtkPNGWriter *pngWriter; + vtkTextActor* runningTime; + char runningTimeText[50]; #ifdef WIN32 - vtkAVIWriter* pAVIWriter; + vtkAVIWriter* pAVIWriter; #endif #ifdef __linux__ - vtkFFMPEGWriter* pAVIWriter; + vtkFFMPEGWriter* pAVIWriter; #endif public: - static TimerCallback *New(); + static TimerCallback *New(); - virtual void Execute(vtkObject *caller, unsigned long eventId, void *callData); + virtual void Execute(vtkObject *caller, unsigned long eventId, void *callData); - void SetRenderTimerId(int tid); + void SetRenderTimerId(int tid); - void setTextActor(vtkTextActor* runningTime); + void setTextActor(vtkTextActor* runningTime); private: - ///updates system global changes, like fullscreen, ffw and soone - void updateSettings(vtkRenderWindow* renderWindow); + ///updates system global changes, like fullscreen, ffw and soone + void updateSettings(vtkRenderWindow* renderWindow); - /// make a png screenshot of the renderwindows - void takeScreenshot(vtkRenderWindow* renderWindow); + /// make a png screenshot of the renderwindows + void takeScreenshot(vtkRenderWindow* renderWindow); - /// take png screenshots sequence - void takeScreenshotSequence(vtkRenderWindow* renderWindow); + /// take png screenshots sequence + void takeScreenshotSequence(vtkRenderWindow* renderWindow); + /// extract from the + void getTrail(int datasetID,int frameNumber); - /// create directory - //bool createDirectory( const std::string& ac_sPath ); + ///update the virtual camera + void updateVirtualCamera(Frame* frame, vtkRenderer *renderer); - /// mark pedestrians as out of the system - /// when they were present in the last frame - /// but not in the current - /// @param previous Frame current Frame datasetID (1, 2 or 3) - // void checkIfOutOfSystem(Frame* previous, Frame* current,int datasetID); - /// extract from the - //void getTrail(int datasetID,double* trailX, double* trailY, double* trailZ, int frameNumber,int trailCount); - void getTrail(int datasetID,int frameNumber); - - - Q_SIGNALS: - void signalStatusMessage(QString msg); - void signalFrameNumber(unsigned long timems); - void signalRunningTime(unsigned long timems); - void signalRenderingTime(int fps); +Q_SIGNALS: + void signalStatusMessage(QString msg); + void signalFrameNumber(unsigned long timems); + void signalRunningTime(unsigned long timems); + void signalRenderingTime(int fps); }; diff --git a/src/TrailPlotter.cpp b/src/TrailPlotter.cpp index 9c7b1e85a6e4df60f17f2186d031a1f994c9cfcc..92396f6fb0d37faa7c27178085c8647c8b400c97 100644 --- a/src/TrailPlotter.cpp +++ b/src/TrailPlotter.cpp @@ -42,7 +42,7 @@ TrailPlotter::TrailPlotter() //Create a mapper and actor vtkSmartPointer<vtkPolyDataMapper> mapper = - vtkSmartPointer<vtkPolyDataMapper>::New(); + vtkSmartPointer<vtkPolyDataMapper>::New(); //mapper->SetInputConnection(_cleanFilter->GetOutputPort()); _trailActor = vtkSmartPointer<vtkActor>::New(); @@ -69,10 +69,10 @@ void TrailPlotter::AddDataSet(vtkPolyData *_polydata) vtkActor *TrailPlotter::getActor() { - return _trailActor; + return _trailActor; } void TrailPlotter::SetVisibility(bool status) { - _trailActor->SetVisibility(status); + _trailActor->SetVisibility(status); } diff --git a/src/TrailPlotter.h b/src/TrailPlotter.h index c9cc3dcfcb76fe12c9d58d32aaaf540c1688b7c7..d6c73abe61a8c57b793f84cd6ec0e20505cfbf8d 100644 --- a/src/TrailPlotter.h +++ b/src/TrailPlotter.h @@ -9,8 +9,7 @@ class vtkAppendPolyData; class vtkCleanPolyData; -class TrailPlotter -{ +class TrailPlotter { public: /// constructor TrailPlotter(); diff --git a/src/TrajectoryPoint.cpp b/src/TrajectoryPoint.cpp index 664df0c0d675172a10b7fe404f325fef89722165..755227ae51584be0cc75076e7241b118de84f112 100644 --- a/src/TrajectoryPoint.cpp +++ b/src/TrajectoryPoint.cpp @@ -36,106 +36,122 @@ -TrajectoryPoint::TrajectoryPoint(int index){ - this->index=index; - this->x = std::numeric_limits<double>::quiet_NaN(); - this->y = std::numeric_limits<double>::quiet_NaN(); - this->z = std::numeric_limits<double>::quiet_NaN(); - this->xVel = std::numeric_limits<double>::quiet_NaN(); - this->yVel = std::numeric_limits<double>::quiet_NaN(); - this->zVel = std::numeric_limits<double>::quiet_NaN(); +TrajectoryPoint::TrajectoryPoint(int index) +{ + this->index=index; + this->x = std::numeric_limits<double>::quiet_NaN(); + this->y = std::numeric_limits<double>::quiet_NaN(); + this->z = std::numeric_limits<double>::quiet_NaN(); + this->xVel = std::numeric_limits<double>::quiet_NaN(); + this->yVel = std::numeric_limits<double>::quiet_NaN(); + this->zVel = std::numeric_limits<double>::quiet_NaN(); + + this->agentOrientation = std::numeric_limits<double>::quiet_NaN(); + this->ellipseRadiusA = std::numeric_limits<double>::quiet_NaN(); + this->ellipseRadiusB = std::numeric_limits<double>::quiet_NaN(); + this->ellipseColor = std::numeric_limits<double>::quiet_NaN(); + this->agentHeight = std::numeric_limits<double>::quiet_NaN(); - this->agentOrientation = std::numeric_limits<double>::quiet_NaN(); - this->ellipseRadiusA = std::numeric_limits<double>::quiet_NaN(); - this->ellipseRadiusB = std::numeric_limits<double>::quiet_NaN(); - this->ellipseColor = std::numeric_limits<double>::quiet_NaN(); - this->agentHeight = std::numeric_limits<double>::quiet_NaN(); +} + +TrajectoryPoint::TrajectoryPoint(int index,double x, double y, double z) +{ + this->index = index; + this->x = x; + this->y = y; + this->z = z; + this->xVel = std::numeric_limits<double>::quiet_NaN(); + this->yVel = std::numeric_limits<double>::quiet_NaN(); + this->zVel = std::numeric_limits<double>::quiet_NaN(); + + this->agentOrientation = std::numeric_limits<double>::quiet_NaN(); + this->ellipseRadiusA = std::numeric_limits<double>::quiet_NaN(); + this->ellipseRadiusB = std::numeric_limits<double>::quiet_NaN(); + this->ellipseColor = std::numeric_limits<double>::quiet_NaN(); + this->agentHeight = std::numeric_limits<double>::quiet_NaN(); +} +TrajectoryPoint::~TrajectoryPoint() +{ } -TrajectoryPoint::TrajectoryPoint(int index,double x, double y, double z) { - this->index = index; - this->x = x; - this->y = y; - this->z = z; - this->xVel = std::numeric_limits<double>::quiet_NaN(); - this->yVel = std::numeric_limits<double>::quiet_NaN(); - this->zVel = std::numeric_limits<double>::quiet_NaN(); - this->agentOrientation = std::numeric_limits<double>::quiet_NaN(); - this->ellipseRadiusA = std::numeric_limits<double>::quiet_NaN(); - this->ellipseRadiusB = std::numeric_limits<double>::quiet_NaN(); - this->ellipseColor = std::numeric_limits<double>::quiet_NaN(); - this->agentHeight = std::numeric_limits<double>::quiet_NaN(); +//setter +void TrajectoryPoint::setIndex(int index) +{ + this->index = index; +} +void TrajectoryPoint::setPos(double pos[3]) +{ + x = pos[0]; + y = pos[1]; + z = pos[2]; +} +void TrajectoryPoint::setVel(double vel[3]) +{ + xVel = vel[0]; + yVel = vel[1]; + zVel = vel[2]; } -TrajectoryPoint::~TrajectoryPoint() { +void TrajectoryPoint::setEllipse(double ellipse[7]) +{ + ellipseCenter[0] = ellipse[0]; + ellipseCenter[1] = ellipse[1]; + ellipseCenter[2] = ellipse[2]; + ellipseRadiusA = ellipse[3]; + ellipseRadiusB = ellipse[4]; + agentOrientation = ellipse[5]; + ellipseColor = ellipse[6]; } +int TrajectoryPoint::getIndex() +{ + return index; +} +double TrajectoryPoint::getX() +{ + return x; +} +double TrajectoryPoint::getY() +{ + return y; +} +double TrajectoryPoint::getZ() +{ + return z; +} +void TrajectoryPoint::getPos(double pos[3]) +{ + pos[0] = x; + pos[1] = y; + pos[2] = z; +} +void TrajectoryPoint::getVel(double vel[3]) +{ + vel[0] = xVel; + vel[1] = yVel; + vel[2] = zVel; +} +void TrajectoryPoint::getEllipse(double ellipse[7]) +{ + ellipse[0] = ellipseCenter[0]; + ellipse[1] = ellipseCenter[1]; + ellipse[2] = ellipseCenter[2]; + + ellipse[3] = ellipseRadiusA; + ellipse[4] = ellipseRadiusB; + ellipse[5] = agentOrientation; + ellipse[6] = ellipseColor; +} +void TrajectoryPoint::setAgentInfo(double para[2]) +{ + agentColor=para[0]; + agentOrientation=para[1]; +} -//setter -void TrajectoryPoint::setIndex(int index) { - this->index = index; -} -void TrajectoryPoint::setPos(double pos[3]) { - x = pos[0]; - y = pos[1]; - z = pos[2]; -} -void TrajectoryPoint::setVel(double vel[3]) { - xVel = vel[0]; - yVel = vel[1]; - zVel = vel[2]; -} - -void TrajectoryPoint::setEllipse(double ellipse[7]) { - ellipseCenter[0] = ellipse[0]; - ellipseCenter[1] = ellipse[1]; - ellipseCenter[2] = ellipse[2]; - ellipseRadiusA = ellipse[3]; - ellipseRadiusB = ellipse[4]; - agentOrientation = ellipse[5]; - ellipseColor = ellipse[6]; -} - -int TrajectoryPoint::getIndex() { - return index; -} -double TrajectoryPoint::getX() { - return x; -} -double TrajectoryPoint::getY() { - return y; -} -double TrajectoryPoint::getZ() { - return z; -} -void TrajectoryPoint::getPos(double pos[3]) { - pos[0] = x; - pos[1] = y; - pos[2] = z; -} -void TrajectoryPoint::getVel(double vel[3]) { - vel[0] = xVel; - vel[1] = yVel; - vel[2] = zVel; -} -void TrajectoryPoint::getEllipse(double ellipse[7]) { - ellipse[0] = ellipseCenter[0]; - ellipse[1] = ellipseCenter[1]; - ellipse[2] = ellipseCenter[2]; - - ellipse[3] = ellipseRadiusA; - ellipse[4] = ellipseRadiusB; - ellipse[5] = agentOrientation; - ellipse[6] = ellipseColor; -} - void TrajectoryPoint::setAgentInfo(double para[2]){ - agentColor=para[0]; - agentOrientation=para[1]; - } - - void TrajectoryPoint::getAgentInfo(double para[2]){ - para[0]=agentColor; - para[1]=agentOrientation; - } +void TrajectoryPoint::getAgentInfo(double para[2]) +{ + para[0]=agentColor; + para[1]=agentOrientation; +} diff --git a/src/TrajectoryPoint.h b/src/TrajectoryPoint.h index 0714bf3288587c1019d90fbb31bc988b7a4f6cd8..f3aa21f090adc96192aebf7a0bf652f7a2d36742 100644 --- a/src/TrajectoryPoint.h +++ b/src/TrajectoryPoint.h @@ -35,69 +35,69 @@ class TrajectoryPoint { public: - TrajectoryPoint(int index); - TrajectoryPoint(int index, double x, double y, double z); - virtual ~TrajectoryPoint(); - - /// set/get the point ID - void setIndex(int index); - /// set/get the point ID - int getIndex(); - - /// set/get the position of the point/agent - void getPos(double pos[3]); - /// set/get the position of the point/agent - void setPos(double pos[3]); - - /// set/get the velocity of the point/agent - void getVel(double vel[3]); - /// set/get the velocity of the point/agent - void setVel(double vel[3]); - - /** - * set/get the coordinate of the modelled ellipse. - * @param ellipse, the center coordinates and the 2 semi-axes - */ - void getEllipse(double ellipse[7]); - - /** - * set/get the coordinate of the modelled ellipse. - * @param ellipse, the center coordinates , the 2 semi-axes, the color and the orientation - */ - void setEllipse(double ellipse[7]); - - /** - * set/get other agents infos: the color and the orientation. - * IF ommitted the orientation will be calculated based on the last coordinates - * - * @param param, Color[0 255] and orientation[0..360] - */ - void setAgentInfo(double param[2]); - void getAgentInfo(double para[2]); - - double getX(); - double getY(); - double getZ(); + TrajectoryPoint(int index); + TrajectoryPoint(int index, double x, double y, double z); + virtual ~TrajectoryPoint(); + + /// set/get the point ID + void setIndex(int index); + /// set/get the point ID + int getIndex(); + + /// set/get the position of the point/agent + void getPos(double pos[3]); + /// set/get the position of the point/agent + void setPos(double pos[3]); + + /// set/get the velocity of the point/agent + void getVel(double vel[3]); + /// set/get the velocity of the point/agent + void setVel(double vel[3]); + + /** + * set/get the coordinate of the modelled ellipse. + * @param ellipse, the center coordinates and the 2 semi-axes + */ + void getEllipse(double ellipse[7]); + + /** + * set/get the coordinate of the modelled ellipse. + * @param ellipse, the center coordinates , the 2 semi-axes, the color and the orientation + */ + void setEllipse(double ellipse[7]); + + /** + * set/get other agents infos: the color and the orientation. + * IF ommitted the orientation will be calculated based on the last coordinates + * + * @param param, Color[0 255] and orientation[0..360] + */ + void setAgentInfo(double param[2]); + void getAgentInfo(double para[2]); + + double getX(); + double getY(); + double getZ(); private: - int index; - double x; - double y; - double z; - - double xVel; - double yVel; - double zVel; - - double agentColor; - double agentHeight; - double agentOrientation; - - double ellipseCenter[3]; - double ellipseRadiusA; - double ellipseRadiusB; - double ellipseColor; + int index; + double x; + double y; + double z; + + double xVel; + double yVel; + double zVel; + + double agentColor; + double agentHeight; + double agentOrientation; + + double ellipseCenter[3]; + double ellipseRadiusA; + double ellipseRadiusB; + double ellipseColor; }; #endif /* TRAJECTORYPOINT_H_ */ diff --git a/src/extern_var.h b/src/extern_var.h index b88416aea16f6c9445c5b19c13907d55f2903ad2..843e2e6509c1e3d190a7dab5b819d2c41c9335af 100644 --- a/src/extern_var.h +++ b/src/extern_var.h @@ -82,40 +82,33 @@ double extern_scale_pedestrian=0.1; // At most three pedestrians groups can be loaded ///The first pedestrian group Pedestrian** extern_pedestrians_firstSet=NULL; -///The second pedestrian group -Pedestrian** extern_pedestrians_secondSet=NULL; -///The third pedestrian group -Pedestrian** extern_pedestrians_thirdSet=NULL; -vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians=NULL; -vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians_3D=NULL; + +//vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians=NULL; +//vtkSmartPointer<vtkTensorGlyph> extern_glyphs_pedestrians_3D=NULL; + +vtkTensorGlyph* extern_glyphs_pedestrians=NULL; +vtkTensorGlyph* extern_glyphs_pedestrians_3D=NULL; +vtkActor2D* extern_pedestrians_labels = NULL; +vtkActor* extern_glyphs_pedestrians_actor_2D = NULL; +vtkActor* extern_glyphs_pedestrians_actor_3D = NULL; //VTK_CREATE (vtkTensorGlyph, extern_glyphs_pedestrians); //VTK_CREATE (vtkTensorGlyph, extern_glyphs_pedestrians_3D); -VTK_CREATE (vtkActor2D, extern_pedestrians_labels); - -VTK_CREATE (vtkActor, extern_glyphs_pedestrians_actor_2D); -VTK_CREATE (vtkActor, extern_glyphs_pedestrians_actor_3D); +//VTK_CREATE (vtkActor2D, extern_pedestrians_labels); +//VTK_CREATE (vtkActor, extern_glyphs_pedestrians_actor_2D); +//VTK_CREATE (vtkActor, extern_glyphs_pedestrians_actor_3D); // and here the corresponding dataset ///The first dataset SyncData extern_trajectories_firstSet; -///The second dataset -SyncData extern_trajectories_secondSet; -///The third dataset -SyncData extern_trajectories_thirdSet; - //states if the datasets are loaded. bool extern_first_dataset_loaded=false; -bool extern_second_dataset_loaded=false; -bool extern_third_dataset_loaded=false; //states whether the loaded datasets are visible bool extern_first_dataset_visible=false; -bool extern_second_dataset_visible=false; -bool extern_third_dataset_visible=false; #endif /* EXTERN_VAR_H_ */ diff --git a/src/general/Macros.h b/src/general/Macros.h index c0620a554d3b357daefd057e2183991d4f0dde6d..c49a8bfd89e49aa867608c9638138659810b3acc 100644 --- a/src/general/Macros.h +++ b/src/general/Macros.h @@ -71,39 +71,63 @@ enum RoomState { - ROOM_CLEAN=0, - ROOM_SMOKED=1, + ROOM_CLEAN=0, + ROOM_SMOKED=1, }; enum FileFormat { - FORMAT_XML_PLAIN, - FORMAT_XML_BIN, - FORMAT_PLAIN, - FORMAT_VTK, - FORMAT_XML_PLAIN_WITH_MESH + FORMAT_XML_PLAIN, + FORMAT_XML_BIN, + FORMAT_PLAIN, + FORMAT_VTK, + FORMAT_XML_PLAIN_WITH_MESH }; enum RoutingStrategy { - ROUTING_LOCAL_SHORTEST, - ROUTING_GLOBAL_SHORTEST, - ROUTING_QUICKEST, - ROUTING_DYNAMIC, - ROUTING_FROM_FILE, - ROUTING_NAV_MESH, - ROUTING_DUMMY, - ROUTING_SAFEST, - ROUTING_UNDEFINED =-1 + ROUTING_LOCAL_SHORTEST, + ROUTING_GLOBAL_SHORTEST, + ROUTING_QUICKEST, + ROUTING_DYNAMIC, + ROUTING_FROM_FILE, + ROUTING_NAV_MESH, + ROUTING_DUMMY, + ROUTING_SAFEST, + ROUTING_UNDEFINED =-1 }; //global functions for convenience -inline char xmltob(const char * t,char v=0){ if (t&&(*t)) return (char)atoi(t); return v; } -inline int xmltoi(const char * t,int v=0){ if (t&&(*t)) return atoi(t); return v; } -inline long xmltol(const char * t,long v=0){ if (t&&(*t)) return atol(t); return v; } -inline double xmltof(const char * t,double v=0.0){ if (t&&(*t)) return atof(t); return v; } -inline const char * xmltoa(const char * t, const char * v=""){ if (t) return t; return v; } -inline char xmltoc(const char * t,const char v='\0'){ if (t&&(*t)) return *t; return v; } +inline char xmltob(const char * t,char v=0) +{ + if (t&&(*t)) return (char)atoi(t); + return v; +} +inline int xmltoi(const char * t,int v=0) +{ + if (t&&(*t)) return atoi(t); + return v; +} +inline long xmltol(const char * t,long v=0) +{ + if (t&&(*t)) return atol(t); + return v; +} +inline double xmltof(const char * t,double v=0.0) +{ + if (t&&(*t)) return atof(t); + return v; +} +inline const char * xmltoa(const char * t, const char * v="") +{ + if (t) return t; + return v; +} +inline char xmltoc(const char * t,const char v='\0') +{ + if (t&&(*t)) return *t; + return v; +} #endif /* _MACROS_H */ diff --git a/src/geometry/Building.cpp b/src/geometry/Building.cpp index 6039ed264ff9effaf46fab620259863004c19da5..9308e6e868ef775698da92e4397e74425b512d24 100644 --- a/src/geometry/Building.cpp +++ b/src/geometry/Building.cpp @@ -56,1414 +56,1470 @@ using namespace std; Konstruktoren ************************************************************/ -Building::Building() { - _caption = "no_caption"; - _projectFilename = ""; - _rooms = vector<Room*>(); - _routingEngine = NULL; - _linkedCellGrid = NULL; - _savePathway = false; +Building::Building() +{ + _caption = "no_caption"; + _projectFilename = ""; + _rooms = vector<Room*>(); + _routingEngine = NULL; + _linkedCellGrid = NULL; + _savePathway = false; Log = new FileHandler(SystemSettings::getLogfile().toStdString().c_str()); } -Building::~Building() { - for (int i = 0; i < GetNumberOfRooms(); i++) - delete _rooms[i]; +Building::~Building() +{ + for (int i = 0; i < GetNumberOfRooms(); i++) + delete _rooms[i]; #ifdef _SIMULATOR - delete _routingEngine; - delete _linkedCellGrid; + delete _routingEngine; + delete _linkedCellGrid; #endif - if (_pathWayStream.is_open()) - _pathWayStream.close(); - - - for (map<int, Crossing*>::const_iterator iter = _crossings.begin(); - iter != _crossings.end(); ++iter) { - delete iter->second; - } - for (map<int, Transition*>::const_iterator iter = _transitions.begin(); - iter != _transitions.end(); ++iter) { - delete iter->second; - } - for (map<int, Hline*>::const_iterator iter = _hLines.begin(); - iter != _hLines.end(); ++iter) { - delete iter->second; - } - for (map<int, Goal*>::const_iterator iter = _goals.begin(); - iter != _goals.end(); ++iter) { - delete iter->second; - } + if (_pathWayStream.is_open()) + _pathWayStream.close(); + + + for (map<int, Crossing*>::const_iterator iter = _crossings.begin(); + iter != _crossings.end(); ++iter) { + delete iter->second; + } + for (map<int, Transition*>::const_iterator iter = _transitions.begin(); + iter != _transitions.end(); ++iter) { + delete iter->second; + } + for (map<int, Hline*>::const_iterator iter = _hLines.begin(); + iter != _hLines.end(); ++iter) { + delete iter->second; + } + for (map<int, Goal*>::const_iterator iter = _goals.begin(); + iter != _goals.end(); ++iter) { + delete iter->second; + } } /************************************************************ Setter-Funktionen ************************************************************/ -void Building::SetCaption(const std::string& s) { - _caption = s; +void Building::SetCaption(const std::string& s) +{ + _caption = s; } -void Building::SetRoutingEngine(RoutingEngine* r) { - _routingEngine = r; +void Building::SetRoutingEngine(RoutingEngine* r) +{ + _routingEngine = r; } -void Building::SetRoom(Room* room, int index) { - if ((index >= 0) && (index < (int) _rooms.size())) { - _rooms[index] = room; - } else { - Log->Write("ERROR: \tWrong Index in CBuilding::SetRoom()"); - exit(0); - } +void Building::SetRoom(Room* room, int index) +{ + if ((index >= 0) && (index < (int) _rooms.size())) { + _rooms[index] = room; + } else { + Log->Write("ERROR: \tWrong Index in CBuilding::SetRoom()"); + exit(0); + } } /************************************************************* Getter-Funktionen ************************************************************/ -string Building::GetCaption() const { - return _caption; +string Building::GetCaption() const +{ + return _caption; } -RoutingEngine* Building::GetRoutingEngine() const { - return _routingEngine; +RoutingEngine* Building::GetRoutingEngine() const +{ + return _routingEngine; } -int Building::GetNumberOfRooms() const { - return _rooms.size(); +int Building::GetNumberOfRooms() const +{ + return _rooms.size(); } -int Building::GetNumberOfGoals() const { - return _transitions.size() + _hLines.size() + _crossings.size(); +int Building::GetNumberOfGoals() const +{ + return _transitions.size() + _hLines.size() + _crossings.size(); } -const vector<Room*>& Building::GetAllRooms() const { - return _rooms; +const vector<Room*>& Building::GetAllRooms() const +{ + return _rooms; } -Room* Building::GetRoom(int index) const { - if ((index >= 0) && (index < (int) _rooms.size())) { - return _rooms[index]; - } else { - char tmp[CLENGTH]; - sprintf(tmp, - "ERROR: Wrong 'index' in CBuiling::GetRoom() index: %d size: %d", - index, _rooms.size()); - Log->Write(tmp); - exit(0); - } +Room* Building::GetRoom(int index) const +{ + if ((index >= 0) && (index < (int) _rooms.size())) { + return _rooms[index]; + } else { + char tmp[CLENGTH]; + sprintf(tmp, + "ERROR: Wrong 'index' in CBuiling::GetRoom() index: %d size: %d", + index, _rooms.size()); + Log->Write(tmp); + exit(0); + } } -LCGrid* Building::GetGrid() const { - return _linkedCellGrid; +LCGrid* Building::GetGrid() const +{ + return _linkedCellGrid; } -void Building::AddRoom(Room* room) { - _rooms.push_back(room); +void Building::AddRoom(Room* room) +{ + _rooms.push_back(room); } -void Building::AddSurroundingRoom() { - Log->Write("INFO: \tAdding the room 'outside' "); - // first look for the geometry boundaries - double x_min = FLT_MAX; - double x_max = -FLT_MAX; - double y_min = FLT_MAX; - double y_max = -FLT_MAX; - //finding the bounding of the grid - // and collect the pedestrians - for (unsigned int r = 0; r < _rooms.size(); r++) { - Room* room = _rooms[r]; - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - const vector<Wall>& allWalls = sub->GetAllWalls(); - - for (unsigned int a = 0; a < allWalls.size(); a++) { - double x1 = allWalls[a].GetPoint1().GetX(); - double y1 = allWalls[a].GetPoint1().GetY(); - double x2 = allWalls[a].GetPoint2().GetX(); - double y2 = allWalls[a].GetPoint2().GetY(); - - double xmax = (x1 > x2) ? x1 : x2; - double xmin = (x1 > x2) ? x2 : x1; - double ymax = (y1 > y2) ? y1 : y2; - double ymin = (y1 > y2) ? y2 : y1; - - x_min = (xmin <= x_min) ? xmin : x_min; - x_max = (xmax >= x_max) ? xmax : x_max; - y_max = (ymax >= y_max) ? ymax : y_max; - y_min = (ymin <= y_min) ? ymin : y_min; - } - } - } - - for (map<int, Goal*>::const_iterator itr = _goals.begin(); - itr != _goals.end(); ++itr) { - - const vector<Wall>& allWalls = itr->second->GetAllWalls(); - - for (unsigned int a = 0; a < allWalls.size(); a++) { - double x1 = allWalls[a].GetPoint1().GetX(); - double y1 = allWalls[a].GetPoint1().GetY(); - double x2 = allWalls[a].GetPoint2().GetX(); - double y2 = allWalls[a].GetPoint2().GetY(); - - double xmax = (x1 > x2) ? x1 : x2; - double xmin = (x1 > x2) ? x2 : x1; - double ymax = (y1 > y2) ? y1 : y2; - double ymin = (y1 > y2) ? y2 : y1; - - x_min = (xmin <= x_min) ? xmin : x_min; - x_max = (xmax >= x_max) ? xmax : x_max; - y_max = (ymax >= y_max) ? ymax : y_max; - y_min = (ymin <= y_min) ? ymin : y_min; - } - } - - //make the grid slightly larger. - x_min = x_min - 10.0; - x_max = x_max + 10.0; - y_min = y_min - 10.0; - y_max = y_max + 10.0; - - SubRoom* bigSubroom = new NormalSubRoom(); - bigSubroom->SetRoomID(_rooms.size()); - bigSubroom->SetSubRoomID(0); // should be the single subroom - bigSubroom->AddWall(Wall(Point(x_min, y_min), Point(x_min, y_max))); - bigSubroom->AddWall(Wall(Point(x_min, y_max), Point(x_max, y_max))); - bigSubroom->AddWall(Wall(Point(x_max, y_max), Point(x_max, y_min))); - bigSubroom->AddWall(Wall(Point(x_max, y_min), Point(x_min, y_min))); - - Room * bigRoom = new Room(); - bigRoom->AddSubRoom(bigSubroom); - bigRoom->SetCaption("outside"); - bigRoom->SetID(_rooms.size()); - AddRoom(bigRoom); +void Building::AddSurroundingRoom() +{ + Log->Write("INFO: \tAdding the room 'outside' "); + // first look for the geometry boundaries + double x_min = FLT_MAX; + double x_max = -FLT_MAX; + double y_min = FLT_MAX; + double y_max = -FLT_MAX; + //finding the bounding of the grid + // and collect the pedestrians + for (unsigned int r = 0; r < _rooms.size(); r++) { + Room* room = _rooms[r]; + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + const vector<Wall>& allWalls = sub->GetAllWalls(); + + for (unsigned int a = 0; a < allWalls.size(); a++) { + double x1 = allWalls[a].GetPoint1().GetX(); + double y1 = allWalls[a].GetPoint1().GetY(); + double x2 = allWalls[a].GetPoint2().GetX(); + double y2 = allWalls[a].GetPoint2().GetY(); + + double xmax = (x1 > x2) ? x1 : x2; + double xmin = (x1 > x2) ? x2 : x1; + double ymax = (y1 > y2) ? y1 : y2; + double ymin = (y1 > y2) ? y2 : y1; + + x_min = (xmin <= x_min) ? xmin : x_min; + x_max = (xmax >= x_max) ? xmax : x_max; + y_max = (ymax >= y_max) ? ymax : y_max; + y_min = (ymin <= y_min) ? ymin : y_min; + } + } + } + + for (map<int, Goal*>::const_iterator itr = _goals.begin(); + itr != _goals.end(); ++itr) { + + const vector<Wall>& allWalls = itr->second->GetAllWalls(); + + for (unsigned int a = 0; a < allWalls.size(); a++) { + double x1 = allWalls[a].GetPoint1().GetX(); + double y1 = allWalls[a].GetPoint1().GetY(); + double x2 = allWalls[a].GetPoint2().GetX(); + double y2 = allWalls[a].GetPoint2().GetY(); + + double xmax = (x1 > x2) ? x1 : x2; + double xmin = (x1 > x2) ? x2 : x1; + double ymax = (y1 > y2) ? y1 : y2; + double ymin = (y1 > y2) ? y2 : y1; + + x_min = (xmin <= x_min) ? xmin : x_min; + x_max = (xmax >= x_max) ? xmax : x_max; + y_max = (ymax >= y_max) ? ymax : y_max; + y_min = (ymin <= y_min) ? ymin : y_min; + } + } + + //make the grid slightly larger. + x_min = x_min - 10.0; + x_max = x_max + 10.0; + y_min = y_min - 10.0; + y_max = y_max + 10.0; + + SubRoom* bigSubroom = new NormalSubRoom(); + bigSubroom->SetRoomID(_rooms.size()); + bigSubroom->SetSubRoomID(0); // should be the single subroom + bigSubroom->AddWall(Wall(Point(x_min, y_min), Point(x_min, y_max))); + bigSubroom->AddWall(Wall(Point(x_min, y_max), Point(x_max, y_max))); + bigSubroom->AddWall(Wall(Point(x_max, y_max), Point(x_max, y_min))); + bigSubroom->AddWall(Wall(Point(x_max, y_min), Point(x_min, y_min))); + + Room * bigRoom = new Room(); + bigRoom->AddSubRoom(bigSubroom); + bigRoom->SetCaption("outside"); + bigRoom->SetID(_rooms.size()); + AddRoom(bigRoom); } -bool Building::InitGeometry() { - Log->Write("INFO: \tInit Geometry"); - for (int i = 0; i < GetNumberOfRooms(); i++) { - Room* room = GetRoom(i); - // Polygone berechnen - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* s = room->GetSubRoom(j); - // Alle Übergänge in diesem Raum bestimmen - // Übergänge müssen zu Wänden ergänzt werden - vector<Line*> goals = vector<Line*>(); - - // crossings - const vector<Crossing*>& crossings = s->GetAllCrossings(); - for (unsigned int i = 0; i < crossings.size(); i++) { - goals.push_back(crossings[i]); - } - - // and transitions - const vector<Transition*>& transitions = s->GetAllTransitions(); - for (unsigned int i = 0; i < transitions.size(); i++) { - goals.push_back(transitions[i]); - } - - // initialize the poly +bool Building::InitGeometry() +{ + Log->Write("INFO: \tInit Geometry"); + for (int i = 0; i < GetNumberOfRooms(); i++) { + Room* room = GetRoom(i); + // Polygone berechnen + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* s = room->GetSubRoom(j); + // Alle Übergänge in diesem Raum bestimmen + // Übergänge müssen zu Wänden ergänzt werden + vector<Line*> goals = vector<Line*>(); + + // crossings + const vector<Crossing*>& crossings = s->GetAllCrossings(); + for (unsigned int i = 0; i < crossings.size(); i++) { + goals.push_back(crossings[i]); + } + + // and transitions + const vector<Transition*>& transitions = s->GetAllTransitions(); + for (unsigned int i = 0; i < transitions.size(); i++) { + goals.push_back(transitions[i]); + } + + // initialize the poly if(!s->ConvertLineToPoly(goals)) return false; - s->CalculateArea(); - goals.clear(); + s->CalculateArea(); + goals.clear(); - //do the same for the obstacles that are closed - const vector<Obstacle*>& obstacles = s->GetAllObstacles(); - for (unsigned int obs = 0; obs < obstacles.size(); ++obs) { - if (obstacles[obs]->GetClosed() == 1) + //do the same for the obstacles that are closed + const vector<Obstacle*>& obstacles = s->GetAllObstacles(); + for (unsigned int obs = 0; obs < obstacles.size(); ++obs) { + if (obstacles[obs]->GetClosed() == 1) if(!obstacles[obs]->ConvertLineToPoly()) return false; - } - } - } - Log->Write("INFO: \tInit Geometry successful!!!\n"); + } + } + } + Log->Write("INFO: \tInit Geometry successful!!!\n"); return true; } -const string& Building::GetProjectFilename() const{ - return _projectFilename; +const string& Building::GetProjectFilename() const +{ + return _projectFilename; } -void Building::SetProjectFilename(const std::string &filename){ - _projectFilename=filename; +void Building::SetProjectFilename(const std::string &filename) +{ + _projectFilename=filename; } -void Building::SetProjectRootDir(const std::string &filename){ - _projectRootDir= filename; +void Building::SetProjectRootDir(const std::string &filename) +{ + _projectRootDir= filename; } -const string& Building::GetProjectRootDir() const{ - return _projectRootDir; +const string& Building::GetProjectRootDir() const +{ + return _projectRootDir; } -bool Building::LoadBuildingFromFile(const std::string &filename) { +bool Building::LoadBuildingFromFile(const std::string &filename) +{ - //get the geometry filename from the project file if none was supplied - string geoFilename=filename; - if(geoFilename==""){ - TiXmlDocument doc(_projectFilename); - if (!doc.LoadFile()){ - Log->Write("ERROR: \t%s", doc.ErrorDesc()); - Log->Write("ERROR: \t could not parse the project file"); + //get the geometry filename from the project file if none was supplied + string geoFilename=filename; + if(geoFilename=="") { + TiXmlDocument doc(_projectFilename); + if (!doc.LoadFile()) { + Log->Write("ERROR: \t%s", doc.ErrorDesc()); + Log->Write("ERROR: \t could not parse the project file"); return false; - } - - Log->Write("INFO: \tParsing the geometry file"); - TiXmlElement* xMainNode = doc.RootElement(); - if(xMainNode->FirstChild("geometry")){ - geoFilename=_projectRootDir+xMainNode->FirstChild("geometry")->FirstChild()->Value(); - Log->Write("INFO: \tgeometry <"+geoFilename+">"); - } + } + + Log->Write("INFO: \tParsing the geometry file"); + TiXmlElement* xMainNode = doc.RootElement(); + if(xMainNode->FirstChild("geometry")) { + geoFilename=_projectRootDir+xMainNode->FirstChild("geometry")->FirstChild()->Value(); + Log->Write("INFO: \tgeometry <"+geoFilename+">"); + } } else { geoFilename=_projectRootDir+geoFilename; } - TiXmlDocument docGeo(geoFilename); - if (!docGeo.LoadFile()){ - Log->Write("ERROR: \t%s", docGeo.ErrorDesc()); + TiXmlDocument docGeo(geoFilename); + if (!docGeo.LoadFile()) { + Log->Write("ERROR: \t%s", docGeo.ErrorDesc()); Log->Write("ERROR: \t could not parse the geometry file [%s]",geoFilename.c_str()); return false; - } - - TiXmlElement* xRootNode = docGeo.RootElement(); - if( ! xRootNode ) { - Log->Write("ERROR:\tRoot element does not exist"); - return false; - } - - if( xRootNode->ValueStr () != "geometry" ) { - Log->Write("ERROR:\tRoot element value is not 'geometry'."); - return false; - } - - if(string(xRootNode->Attribute("unit"))!="m") { - Log->Write("ERROR:\tOnly the unit m (metres) is supported. \n\tYou supplied [%s]",xRootNode->Attribute("unit")); - return false; - } - - double version = xmltof(xRootNode->Attribute("version"), -1); - if (version < 0.4) { + } + + TiXmlElement* xRootNode = docGeo.RootElement(); + if( ! xRootNode ) { + Log->Write("ERROR:\tRoot element does not exist"); + return false; + } + + if( xRootNode->ValueStr () != "geometry" ) { + Log->Write("ERROR:\tRoot element value is not 'geometry'."); + return false; + } + + if(string(xRootNode->Attribute("unit"))!="m") { + Log->Write("ERROR:\tOnly the unit m (metres) is supported. \n\tYou supplied [%s]",xRootNode->Attribute("unit")); + return false; + } + + double version = xmltof(xRootNode->Attribute("version"), -1); + if (version < 0.4) { Log->Write("ERROR: \tOnly version > 0.4 supported. Your version is %f",version); - Log->Write("ERROR: \tparsing geometry file failed!"); - return false; - } - _caption = xmltoa(xRootNode->Attribute("caption"), "virtual building"); + Log->Write("ERROR: \tparsing geometry file failed!"); + return false; + } + _caption = xmltoa(xRootNode->Attribute("caption"), "virtual building"); + + + //The file has two main nodes + //<rooms> and <transitions> - //The file has two main nodes - //<rooms> and <transitions> - - - //processing the rooms node - TiXmlNode* xRoomsNode = xRootNode->FirstChild("rooms"); - if (!xRoomsNode){ - Log->Write("ERROR: \tThe geometry should have at least one room and one subroom"); - return false; - } - - for(TiXmlElement* xRoom = xRoomsNode->FirstChildElement("room"); xRoom; - xRoom = xRoom->NextSiblingElement("room")) { - - Room* room = new Room(); - - string room_id = xmltoa(xRoom->Attribute("id"), "-1"); - room->SetID(xmltoi(room_id.c_str(), -1)); - - string caption = "room " + room_id; - room->SetCaption( - xmltoa(xRoom->Attribute("caption"), caption.c_str())); - - double position = xmltof(xRoom->Attribute("zpos"), 0.0); - - //TODO?? what the hell is that for ? - //if(position>6.0) position+=50; - room->SetZPos(position); - - //parsing the subrooms - //processing the rooms node - //TiXmlNode* xSubroomsNode = xRoom->FirstChild("subroom"); - - for(TiXmlElement* xSubRoom = xRoom->FirstChildElement("subroom"); xSubRoom; - xSubRoom = xSubRoom->NextSiblingElement("subroom")) { - - - string subroom_id = xmltoa(xSubRoom->Attribute("id"), "-1"); - string closed = xmltoa(xSubRoom->Attribute("closed"), "0"); - string type = xmltoa(xSubRoom->Attribute("class"),"subroom"); - - //get the equation of the plane if any - double A_x = xmltof(xSubRoom->Attribute("A_x"), 0.0); - double B_y = xmltof(xSubRoom->Attribute("B_y"), 0.0); - double C_z = xmltof(xSubRoom->Attribute("C_z"), 0.0); - - SubRoom* subroom = NULL; - - if (type == "stair") { - if(xSubRoom->FirstChildElement("up")==NULL){ - Log->Write("ERROR:\t the attribute <up> and <down> are missing for the stair"); - Log->Write("ERROR:\t check your geometry file"); - exit(EXIT_FAILURE); - } - double up_x = xmltof( xSubRoom->FirstChildElement("up")->Attribute("px"), 0.0); - double up_y = xmltof( xSubRoom->FirstChildElement("up")->Attribute("py"), 0.0); - double down_x = xmltof( xSubRoom->FirstChildElement("down")->Attribute("py"), 0.0); - double down_y = xmltof( xSubRoom->FirstChildElement("down")->Attribute("py"), 0.0); - subroom = new Stair(); - ((Stair*)subroom)->SetUp(Point(up_x,up_y)); - ((Stair*)subroom)->SetDown(Point(down_x,down_y)); - } else { - //normal subroom or corridor - subroom = new NormalSubRoom(); - } - - subroom->SetType(type); - subroom->SetPlanEquation(A_x,B_y,C_z); - subroom->SetRoomID(room->GetID()); - subroom->SetSubRoomID(xmltoi(subroom_id.c_str(), -1)); - - //looking for polygons (walls) - for(TiXmlElement* xPolyVertices = xSubRoom->FirstChildElement("polygon"); xPolyVertices; - xPolyVertices = xPolyVertices->NextSiblingElement("polygon")) { - - for (TiXmlElement* xVertex = xPolyVertices->FirstChildElement( - "vertex"); - xVertex && xVertex != xPolyVertices->LastChild("vertex"); - xVertex = xVertex->NextSiblingElement("vertex")) { - - double x1 = xmltof(xVertex->Attribute("px")); - double y1 = xmltof(xVertex->Attribute("py")); - double x2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("px")); - double y2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("py")); - - subroom->AddWall(Wall(Point(x1, y1), Point(x2, y2))); - } - - } - - //looking for obstacles - for(TiXmlElement* xObstacle = xSubRoom->FirstChildElement("obstacle"); xObstacle; - xObstacle = xObstacle->NextSiblingElement("obstacle")) { - - int id = xmltof(xObstacle->Attribute("id"), -1); - int height = xmltof(xObstacle->Attribute("height"), 0); - double closed = xmltof(xObstacle->Attribute("closed"), 0); - string caption = xmltoa(xObstacle->Attribute("caption"),"-1"); - - Obstacle* obstacle = new Obstacle(); - obstacle->SetId(id); - obstacle->SetCaption(caption); - obstacle->SetClosed(closed); - obstacle->SetHeight(height); - - //looking for polygons (walls) - for(TiXmlElement* xPolyVertices = xObstacle->FirstChildElement("polygon"); xPolyVertices; - xPolyVertices = xPolyVertices->NextSiblingElement("polygon")) { - - for (TiXmlElement* xVertex = xPolyVertices->FirstChildElement( - "vertex"); - xVertex && xVertex != xPolyVertices->LastChild("vertex"); - xVertex = xVertex->NextSiblingElement("vertex")) { - - double x1 = xmltof(xVertex->Attribute("px")); - double y1 = xmltof(xVertex->Attribute("py")); - double x2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("px")); - double y2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("py")); - obstacle->AddWall(Wall(Point(x1, y1), Point(x2, y2))); - } - } - subroom->AddObstacle(obstacle); - } - room->AddSubRoom(subroom); - } - - //parsing the crossings - TiXmlNode* xCrossingsNode = xRoom->FirstChild("crossings"); - if(xCrossingsNode) - for(TiXmlElement* xCrossing = xCrossingsNode->FirstChildElement("crossing"); xCrossing; - xCrossing = xCrossing->NextSiblingElement("crossing")) { - - int id = xmltoi(xCrossing->Attribute("id"), -1); - int sub1_id = xmltoi(xCrossing->Attribute("subroom1_id"), -1); - int sub2_id = xmltoi(xCrossing->Attribute("subroom2_id"), -1); - - double x1 = xmltof( xCrossing->FirstChildElement("vertex")->Attribute("px")); - double y1 = xmltof( xCrossing->FirstChildElement("vertex")->Attribute("py")); - double x2 = xmltof( xCrossing->LastChild("vertex")->ToElement()->Attribute("px")); - double y2 = xmltof( xCrossing->LastChild("vertex")->ToElement()->Attribute("py")); - - Crossing* c = new Crossing(); - c->SetID(id); - c->SetPoint1(Point(x1, y1)); - c->SetPoint2(Point(x2, y2)); - - c->SetSubRoom1(room->GetSubRoom(sub1_id)); - c->SetSubRoom2(room->GetSubRoom(sub2_id)); - c->SetRoom1(room); - AddCrossing(c); - - room->GetSubRoom(sub1_id)->AddCrossing(c); - room->GetSubRoom(sub2_id)->AddCrossing(c); - } - - AddRoom(room); - } - - - // all rooms are read, now proceed with transitions - TiXmlNode* xTransNode = xRootNode->FirstChild("transitions"); - if(xTransNode) - for(TiXmlElement* xTrans = xTransNode->FirstChildElement("transition"); xTrans; - xTrans = xTrans->NextSiblingElement("transition")) { - - int id = xmltoi(xTrans->Attribute("id"), -1); - string caption = "door " + id; - caption = xmltoa(xTrans->Attribute("caption"), caption.c_str()); - int room1_id = xmltoi(xTrans->Attribute("room1_id"), -1); - int room2_id = xmltoi(xTrans->Attribute("room2_id"), -1); - int subroom1_id = xmltoi(xTrans->Attribute("subroom1_id"), -1); - int subroom2_id = xmltoi(xTrans->Attribute("subroom2_id"), -1); - string type = xmltoa(xTrans->Attribute("type"), "normal"); - - double x1 = xmltof( xTrans->FirstChildElement("vertex")->Attribute("px")); - double y1 = xmltof( xTrans->FirstChildElement("vertex")->Attribute("py")); - - double x2 = xmltof( xTrans->LastChild("vertex")->ToElement()->Attribute("px")); - double y2 = xmltof( xTrans->LastChild("vertex")->ToElement()->Attribute("py")); - - - Transition* t = new Transition(); - t->SetID(id); - t->SetCaption(caption); - t->SetPoint1(Point(x1, y1)); - t->SetPoint2(Point(x2, y2)); - t->SetType(type); - - if (room1_id != -1 && subroom1_id != -1) { - Room* room = _rooms[room1_id]; - SubRoom* subroom = room->GetSubRoom(subroom1_id); - - //subroom->AddGoalID(t->GetUniqueID()); - //MPI - room->AddTransitionID(t->GetUniqueID()); - t->SetRoom1(room); - t->SetSubRoom1(subroom); - - //new implementation - subroom->AddTransition(t); - } - if (room2_id != -1 && subroom2_id != -1) { - Room* room = _rooms[room2_id]; - SubRoom* subroom = room->GetSubRoom(subroom2_id); - //subroom->AddGoalID(t->GetUniqueID()); - //MPI - room->AddTransitionID(t->GetUniqueID()); - t->SetRoom2(room); - t->SetSubRoom2(subroom); - - //new implementation - subroom->AddTransition(t); - } - - AddTransition(t); - } - - - Log->Write("INFO: \tLoading building file successful!!!\n"); + //processing the rooms node + TiXmlNode* xRoomsNode = xRootNode->FirstChild("rooms"); + if (!xRoomsNode) { + Log->Write("ERROR: \tThe geometry should have at least one room and one subroom"); + return false; + } + + for(TiXmlElement* xRoom = xRoomsNode->FirstChildElement("room"); xRoom; + xRoom = xRoom->NextSiblingElement("room")) { + + Room* room = new Room(); + + string room_id = xmltoa(xRoom->Attribute("id"), "-1"); + room->SetID(xmltoi(room_id.c_str(), -1)); + + string caption = "room " + room_id; + room->SetCaption( + xmltoa(xRoom->Attribute("caption"), caption.c_str())); + + double position = xmltof(xRoom->Attribute("zpos"), 0.0); + + //TODO?? what the hell is that for ? + //if(position>6.0) position+=50; + room->SetZPos(position); + + //parsing the subrooms + //processing the rooms node + //TiXmlNode* xSubroomsNode = xRoom->FirstChild("subroom"); + + for(TiXmlElement* xSubRoom = xRoom->FirstChildElement("subroom"); xSubRoom; + xSubRoom = xSubRoom->NextSiblingElement("subroom")) { + + + string subroom_id = xmltoa(xSubRoom->Attribute("id"), "-1"); + string closed = xmltoa(xSubRoom->Attribute("closed"), "0"); + string type = xmltoa(xSubRoom->Attribute("class"),"subroom"); + + //get the equation of the plane if any + double A_x = xmltof(xSubRoom->Attribute("A_x"), 0.0); + double B_y = xmltof(xSubRoom->Attribute("B_y"), 0.0); + double C_z = xmltof(xSubRoom->Attribute("C_z"), 0.0); + + SubRoom* subroom = NULL; + + if (type == "stair") { + if(xSubRoom->FirstChildElement("up")==NULL) { + Log->Write("ERROR:\t the attribute <up> and <down> are missing for the stair"); + Log->Write("ERROR:\t check your geometry file"); + exit(EXIT_FAILURE); + } + double up_x = xmltof( xSubRoom->FirstChildElement("up")->Attribute("px"), 0.0); + double up_y = xmltof( xSubRoom->FirstChildElement("up")->Attribute("py"), 0.0); + double down_x = xmltof( xSubRoom->FirstChildElement("down")->Attribute("py"), 0.0); + double down_y = xmltof( xSubRoom->FirstChildElement("down")->Attribute("py"), 0.0); + subroom = new Stair(); + ((Stair*)subroom)->SetUp(Point(up_x,up_y)); + ((Stair*)subroom)->SetDown(Point(down_x,down_y)); + } else { + //normal subroom or corridor + subroom = new NormalSubRoom(); + } + + subroom->SetType(type); + subroom->SetPlanEquation(A_x,B_y,C_z); + subroom->SetRoomID(room->GetID()); + subroom->SetSubRoomID(xmltoi(subroom_id.c_str(), -1)); + + //looking for polygons (walls) + for(TiXmlElement* xPolyVertices = xSubRoom->FirstChildElement("polygon"); xPolyVertices; + xPolyVertices = xPolyVertices->NextSiblingElement("polygon")) { + + for (TiXmlElement* xVertex = xPolyVertices->FirstChildElement( + "vertex"); + xVertex && xVertex != xPolyVertices->LastChild("vertex"); + xVertex = xVertex->NextSiblingElement("vertex")) { + + double x1 = xmltof(xVertex->Attribute("px")); + double y1 = xmltof(xVertex->Attribute("py")); + double x2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("px")); + double y2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("py")); + + subroom->AddWall(Wall(Point(x1, y1), Point(x2, y2))); + } + + } + + //looking for obstacles + for(TiXmlElement* xObstacle = xSubRoom->FirstChildElement("obstacle"); xObstacle; + xObstacle = xObstacle->NextSiblingElement("obstacle")) { + + int id = xmltof(xObstacle->Attribute("id"), -1); + int height = xmltof(xObstacle->Attribute("height"), 0); + double closed = xmltof(xObstacle->Attribute("closed"), 0); + string caption = xmltoa(xObstacle->Attribute("caption"),"-1"); + + Obstacle* obstacle = new Obstacle(); + obstacle->SetId(id); + obstacle->SetCaption(caption); + obstacle->SetClosed(closed); + obstacle->SetHeight(height); + + //looking for polygons (walls) + for(TiXmlElement* xPolyVertices = xObstacle->FirstChildElement("polygon"); xPolyVertices; + xPolyVertices = xPolyVertices->NextSiblingElement("polygon")) { + + for (TiXmlElement* xVertex = xPolyVertices->FirstChildElement( + "vertex"); + xVertex && xVertex != xPolyVertices->LastChild("vertex"); + xVertex = xVertex->NextSiblingElement("vertex")) { + + double x1 = xmltof(xVertex->Attribute("px")); + double y1 = xmltof(xVertex->Attribute("py")); + double x2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("px")); + double y2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("py")); + obstacle->AddWall(Wall(Point(x1, y1), Point(x2, y2))); + } + } + subroom->AddObstacle(obstacle); + } + room->AddSubRoom(subroom); + } + + //parsing the crossings + TiXmlNode* xCrossingsNode = xRoom->FirstChild("crossings"); + if(xCrossingsNode) + for(TiXmlElement* xCrossing = xCrossingsNode->FirstChildElement("crossing"); xCrossing; + xCrossing = xCrossing->NextSiblingElement("crossing")) { + + int id = xmltoi(xCrossing->Attribute("id"), -1); + int sub1_id = xmltoi(xCrossing->Attribute("subroom1_id"), -1); + int sub2_id = xmltoi(xCrossing->Attribute("subroom2_id"), -1); + + double x1 = xmltof( xCrossing->FirstChildElement("vertex")->Attribute("px")); + double y1 = xmltof( xCrossing->FirstChildElement("vertex")->Attribute("py")); + double x2 = xmltof( xCrossing->LastChild("vertex")->ToElement()->Attribute("px")); + double y2 = xmltof( xCrossing->LastChild("vertex")->ToElement()->Attribute("py")); + + Crossing* c = new Crossing(); + c->SetID(id); + c->SetPoint1(Point(x1, y1)); + c->SetPoint2(Point(x2, y2)); + + c->SetSubRoom1(room->GetSubRoom(sub1_id)); + c->SetSubRoom2(room->GetSubRoom(sub2_id)); + c->SetRoom1(room); + AddCrossing(c); + + room->GetSubRoom(sub1_id)->AddCrossing(c); + room->GetSubRoom(sub2_id)->AddCrossing(c); + } + + AddRoom(room); + } + + + // all rooms are read, now proceed with transitions + TiXmlNode* xTransNode = xRootNode->FirstChild("transitions"); + if(xTransNode) + for(TiXmlElement* xTrans = xTransNode->FirstChildElement("transition"); xTrans; + xTrans = xTrans->NextSiblingElement("transition")) { + + int id = xmltoi(xTrans->Attribute("id"), -1); + string caption = "door " + id; + caption = xmltoa(xTrans->Attribute("caption"), caption.c_str()); + int room1_id = xmltoi(xTrans->Attribute("room1_id"), -1); + int room2_id = xmltoi(xTrans->Attribute("room2_id"), -1); + int subroom1_id = xmltoi(xTrans->Attribute("subroom1_id"), -1); + int subroom2_id = xmltoi(xTrans->Attribute("subroom2_id"), -1); + string type = xmltoa(xTrans->Attribute("type"), "normal"); + + double x1 = xmltof( xTrans->FirstChildElement("vertex")->Attribute("px")); + double y1 = xmltof( xTrans->FirstChildElement("vertex")->Attribute("py")); + + double x2 = xmltof( xTrans->LastChild("vertex")->ToElement()->Attribute("px")); + double y2 = xmltof( xTrans->LastChild("vertex")->ToElement()->Attribute("py")); + + + Transition* t = new Transition(); + t->SetID(id); + t->SetCaption(caption); + t->SetPoint1(Point(x1, y1)); + t->SetPoint2(Point(x2, y2)); + t->SetType(type); + + if (room1_id != -1 && subroom1_id != -1) { + Room* room = _rooms[room1_id]; + SubRoom* subroom = room->GetSubRoom(subroom1_id); + + //subroom->AddGoalID(t->GetUniqueID()); + //MPI + room->AddTransitionID(t->GetUniqueID()); + t->SetRoom1(room); + t->SetSubRoom1(subroom); + + //new implementation + subroom->AddTransition(t); + } + if (room2_id != -1 && subroom2_id != -1) { + Room* room = _rooms[room2_id]; + SubRoom* subroom = room->GetSubRoom(subroom2_id); + //subroom->AddGoalID(t->GetUniqueID()); + //MPI + room->AddTransitionID(t->GetUniqueID()); + t->SetRoom2(room); + t->SetSubRoom2(subroom); + + //new implementation + subroom->AddTransition(t); + } + + AddTransition(t); + } + + + Log->Write("INFO: \tLoading building file successful!!!\n"); + return true; } -void Building::WriteToErrorLog() const { - Log->Write("GEOMETRY: "); - for (int i = 0; i < GetNumberOfRooms(); i++) { - Room* r = GetRoom(i); - r->WriteToErrorLog(); - } - Log->Write("ROUTING: "); - - for (map<int, Crossing*>::const_iterator iter = _crossings.begin(); - iter != _crossings.end(); ++iter) { - iter->second->WriteToErrorLog(); - } - for (map<int, Transition*>::const_iterator iter = _transitions.begin(); - iter != _transitions.end(); ++iter) { - iter->second->WriteToErrorLog(); - } - for (map<int, Hline*>::const_iterator iter = _hLines.begin(); - iter != _hLines.end(); ++iter) { - iter->second->WriteToErrorLog(); - } - Log->Write("\n"); +void Building::WriteToErrorLog() const +{ + Log->Write("GEOMETRY: "); + for (int i = 0; i < GetNumberOfRooms(); i++) { + Room* r = GetRoom(i); + r->WriteToErrorLog(); + } + Log->Write("ROUTING: "); + + for (map<int, Crossing*>::const_iterator iter = _crossings.begin(); + iter != _crossings.end(); ++iter) { + iter->second->WriteToErrorLog(); + } + for (map<int, Transition*>::const_iterator iter = _transitions.begin(); + iter != _transitions.end(); ++iter) { + iter->second->WriteToErrorLog(); + } + for (map<int, Hline*>::const_iterator iter = _hLines.begin(); + iter != _hLines.end(); ++iter) { + iter->second->WriteToErrorLog(); + } + Log->Write("\n"); } -Room* Building::GetRoom(string caption) const { - for (unsigned int r = 0; r < _rooms.size(); r++) { - if (_rooms[r]->GetCaption() == caption) - return _rooms[r]; - } - Log->Write("Warning: Room not found with caption " + caption); - //return NULL; - exit(EXIT_FAILURE); +Room* Building::GetRoom(string caption) const +{ + for (unsigned int r = 0; r < _rooms.size(); r++) { + if (_rooms[r]->GetCaption() == caption) + return _rooms[r]; + } + Log->Write("Warning: Room not found with caption " + caption); + //return NULL; + exit(EXIT_FAILURE); } -void Building::AddCrossing(Crossing* line) { - if (_crossings.count(line->GetID()) != 0) { - char tmp[CLENGTH]; - sprintf(tmp, - "ERROR: Duplicate index for crossing found [%d] in Routing::AddCrossing()", - line->GetID()); - Log->Write(tmp); - exit(EXIT_FAILURE); - } - _crossings[line->GetID()] = line; +void Building::AddCrossing(Crossing* line) +{ + if (_crossings.count(line->GetID()) != 0) { + char tmp[CLENGTH]; + sprintf(tmp, + "ERROR: Duplicate index for crossing found [%d] in Routing::AddCrossing()", + line->GetID()); + Log->Write(tmp); + exit(EXIT_FAILURE); + } + _crossings[line->GetID()] = line; } -void Building::AddTransition(Transition* line) { - if (_transitions.count(line->GetID()) != 0) { - char tmp[CLENGTH]; - sprintf(tmp, - "ERROR: Duplicate index for transition found [%d] in Routing::AddTransition()", - line->GetID()); - Log->Write(tmp); - exit(EXIT_FAILURE); - } - _transitions[line->GetID()] = line; +void Building::AddTransition(Transition* line) +{ + if (_transitions.count(line->GetID()) != 0) { + char tmp[CLENGTH]; + sprintf(tmp, + "ERROR: Duplicate index for transition found [%d] in Routing::AddTransition()", + line->GetID()); + Log->Write(tmp); + exit(EXIT_FAILURE); + } + _transitions[line->GetID()] = line; } -void Building::AddHline(Hline* line) { - if (_hLines.count(line->GetID()) != 0) { - Log->Write( - "ERROR: Duplicate index for hlines found [%d] in Routing::AddHline()", - line->GetID()); - exit(EXIT_FAILURE); - } - _hLines[line->GetID()] = line; +void Building::AddHline(Hline* line) +{ + if (_hLines.count(line->GetID()) != 0) { + Log->Write( + "ERROR: Duplicate index for hlines found [%d] in Routing::AddHline()", + line->GetID()); + exit(EXIT_FAILURE); + } + _hLines[line->GetID()] = line; } -void Building::AddGoal(Goal* goal) { - if (_goals.count(goal->GetId()) != 0) { - Log->Write( - "ERROR: Duplicate index for goal found [%d] in Routing::AddGoal()", - goal->GetId()); - exit(EXIT_FAILURE); - } - _goals[goal->GetId()] = goal; +void Building::AddGoal(Goal* goal) +{ + if (_goals.count(goal->GetId()) != 0) { + Log->Write( + "ERROR: Duplicate index for goal found [%d] in Routing::AddGoal()", + goal->GetId()); + exit(EXIT_FAILURE); + } + _goals[goal->GetId()] = goal; } -const map<int, Crossing*>& Building::GetAllCrossings() const { - return _crossings; +const map<int, Crossing*>& Building::GetAllCrossings() const +{ + return _crossings; } -const map<int, Transition*>& Building::GetAllTransitions() const { - return _transitions; +const map<int, Transition*>& Building::GetAllTransitions() const +{ + return _transitions; } -const map<int, Hline*>& Building::GetAllHlines() const { - return _hLines; +const map<int, Hline*>& Building::GetAllHlines() const +{ + return _hLines; } -const map<int, Goal*>& Building::GetAllGoals() const { - return _goals; +const map<int, Goal*>& Building::GetAllGoals() const +{ + return _goals; } -Transition* Building::GetTransition(string caption) const { - //eventually - map<int, Transition*>::const_iterator itr; - for(itr = _transitions.begin(); itr != _transitions.end(); ++itr){ - if (itr->second->GetCaption() == caption) - return itr->second; - } +Transition* Building::GetTransition(string caption) const +{ + //eventually + map<int, Transition*>::const_iterator itr; + for(itr = _transitions.begin(); itr != _transitions.end(); ++itr) { + if (itr->second->GetCaption() == caption) + return itr->second; + } - Log->Write("WARNING: No Transition with Caption: " + caption); - exit(EXIT_FAILURE); + Log->Write("WARNING: No Transition with Caption: " + caption); + exit(EXIT_FAILURE); } -Transition* Building::GetTransition(int ID) { - if (_transitions.count(ID) == 1) { - return _transitions[ID]; - } else { - if (ID == -1) - return NULL; - else { - Log->Write( - "ERROR: I could not find any transition with the 'ID' [%d]. You have defined [%d] transitions", - ID, _transitions.size()); - exit(EXIT_FAILURE); - } - } +Transition* Building::GetTransition(int ID) +{ + if (_transitions.count(ID) == 1) { + return _transitions[ID]; + } else { + if (ID == -1) + return NULL; + else { + Log->Write( + "ERROR: I could not find any transition with the 'ID' [%d]. You have defined [%d] transitions", + ID, _transitions.size()); + exit(EXIT_FAILURE); + } + } } -Goal* Building::GetFinalGoal(int ID) { - if (_goals.count(ID) == 1) { - return _goals[ID]; - } else { - if (ID == -1) - return NULL; - else { - Log->Write( - "ERROR: I could not find any goal with the 'ID' [%d]. You have defined [%d] goals", - ID, _goals.size()); - exit(EXIT_FAILURE); - } - } +Goal* Building::GetFinalGoal(int ID) +{ + if (_goals.count(ID) == 1) { + return _goals[ID]; + } else { + if (ID == -1) + return NULL; + else { + Log->Write( + "ERROR: I could not find any goal with the 'ID' [%d]. You have defined [%d] goals", + ID, _goals.size()); + exit(EXIT_FAILURE); + } + } } -Crossing* Building::GetTransOrCrossByName(string caption) const { - - { - //eventually - map<int, Transition*>::const_iterator itr; - for(itr = _transitions.begin(); itr != _transitions.end(); ++itr){ - if (itr->second->GetCaption() == caption) - return itr->second; - } - } - { - //finally the crossings - map<int, Crossing*>::const_iterator itr; - for(itr = _crossings.begin(); itr != _crossings.end(); ++itr){ - if (itr->second->GetCaption() == caption) - return itr->second; - } - } - - Log->Write("WARNING: No Transition or Crossing with Caption: " + caption); - return NULL; +Crossing* Building::GetTransOrCrossByName(string caption) const +{ + + { + //eventually + map<int, Transition*>::const_iterator itr; + for(itr = _transitions.begin(); itr != _transitions.end(); ++itr) { + if (itr->second->GetCaption() == caption) + return itr->second; + } + } + { + //finally the crossings + map<int, Crossing*>::const_iterator itr; + for(itr = _crossings.begin(); itr != _crossings.end(); ++itr) { + if (itr->second->GetCaption() == caption) + return itr->second; + } + } + + Log->Write("WARNING: No Transition or Crossing with Caption: " + caption); + return NULL; } -Crossing* Building::GetTransOrCrossByID(int id) const { - { - //eventually - map<int, Transition*>::const_iterator itr; - for(itr = _transitions.begin(); itr != _transitions.end(); ++itr){ - if (itr->second->GetUniqueID()== id) - return itr->second; - } - } - { - //finally the crossings - map<int, Crossing*>::const_iterator itr; - for(itr = _crossings.begin(); itr != _crossings.end(); ++itr){ - if (itr->second->GetUniqueID() == id) - return itr->second; - } - } - - Log->Write("WARNING: No Transition or Crossing with ID %d: " ,id); - return NULL; +Crossing* Building::GetTransOrCrossByID(int id) const +{ + { + //eventually + map<int, Transition*>::const_iterator itr; + for(itr = _transitions.begin(); itr != _transitions.end(); ++itr) { + if (itr->second->GetUniqueID()== id) + return itr->second; + } + } + { + //finally the crossings + map<int, Crossing*>::const_iterator itr; + for(itr = _crossings.begin(); itr != _crossings.end(); ++itr) { + if (itr->second->GetUniqueID() == id) + return itr->second; + } + } + + Log->Write("WARNING: No Transition or Crossing with ID %d: " ,id); + return NULL; } -bool Building::IsVisible(Line* l1, Line* l2, bool considerHlines){ - for (unsigned int i = 0; i < _rooms.size();i++) { - Room* room = _rooms[i]; - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - if(sub->IsVisible(l1,l2,considerHlines)==false) return false; - } - } - return true; +bool Building::IsVisible(Line* l1, Line* l2, bool considerHlines) +{ + for (unsigned int i = 0; i < _rooms.size(); i++) { + Room* room = _rooms[i]; + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + if(sub->IsVisible(l1,l2,considerHlines)==false) return false; + } + } + return true; } -bool Building::IsVisible(const Point& p1, const Point& p2, bool considerHlines){ - for (unsigned int i = 0; i < _rooms.size();i++) { - Room* room = _rooms[i]; - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - if(sub->IsVisible(p1,p2,considerHlines)==false) return false; - } - } - return true; +bool Building::IsVisible(const Point& p1, const Point& p2, bool considerHlines) +{ + for (unsigned int i = 0; i < _rooms.size(); i++) { + Room* room = _rooms[i]; + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + if(sub->IsVisible(p1,p2,considerHlines)==false) return false; + } + } + return true; } -void Building::SanityCheck(){ - Log->Write("INFO: \tChecking the geometry for artifacts"); - for (unsigned int i = 0; i < _rooms.size();i++) { - Room* room = _rooms[i]; - - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - sub->SanityCheck(); - } - } - Log->Write("INFO: \t...Done!!!\n"); +void Building::SanityCheck() +{ + Log->Write("INFO: \tChecking the geometry for artifacts"); + for (unsigned int i = 0; i < _rooms.size(); i++) { + Room* room = _rooms[i]; + + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + sub->SanityCheck(); + } + } + Log->Write("INFO: \t...Done!!!\n"); } #ifdef _SIMULATOR //TODO: merge this with Update and improve runtime -void Building::UpdateVerySlow(){ - - vector<Pedestrian*> nonConformPeds; - for (int i = 0; i < GetNumberOfRooms(); i++) { - Room* room = GetRoom(i); - - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { - Pedestrian* ped = sub->GetPedestrian(k); - //set the new room if needed - if ((ped->GetFinalDestination() == FINAL_DEST_OUT) - && (GetRoom(ped->GetRoomID())->GetCaption() == "outside")) { - - sub->DeletePedestrian(k--); - DeletePedestrian(ped); - } else if ((ped->GetFinalDestination() != FINAL_DEST_OUT) - && (_goals[ped->GetFinalDestination()]->Contains( - ped->GetPos()))) { - sub->DeletePedestrian(k--); - DeletePedestrian(ped); - } else if (!sub->IsInSubRoom(ped)) { - nonConformPeds.push_back(ped); - sub->DeletePedestrian(k--); - } - } - } - } - - // reset that pedestrians who left their room not via the intended exit - for (int p = 0; p < (int) nonConformPeds.size(); p++) { - Pedestrian* ped = nonConformPeds[p]; - bool assigned = false; - for (int i = 0; i < GetNumberOfRooms(); i++) { - Room* room = GetRoom(i); - //if(room->GetCaption()=="outside") continue; - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - SubRoom* old_sub= _rooms[ped->GetRoomID()]->GetSubRoom(ped->GetSubRoomID()); - if ((sub->IsInSubRoom(ped->GetPos())) && (sub->IsDirectlyConnectedWith(old_sub))) { - ped->SetRoomID(room->GetID(), room->GetCaption()); - ped->SetSubRoomID(sub->GetSubRoomID()); - ped->ClearMentalMap(); // reset the destination - //ped->FindRoute(); - sub->AddPedestrian(ped); - assigned = true; - break; - } - } - if (assigned == true) - break; // stop the loop - } - if (assigned == false) { - DeletePedestrian(ped); - } - } - - // find the new goals, the parallel way - - unsigned int nSize = _allPedestians.size(); - int nThreads = omp_get_max_threads(); - - // check if worth sharing the work - if (nSize < 12) - nThreads = 1; - - int partSize = nSize / nThreads; - -#pragma omp parallel default(shared) num_threads(nThreads) - { - const int threadID = omp_get_thread_num(); - int start = threadID * partSize; - int end = (threadID + 1) * partSize - 1; - if ((threadID == nThreads - 1)) - end = nSize - 1; - - for (int p = start; p <= end; ++p) { - if (_allPedestians[p]->FindRoute() == -1) { - //a destination could not be found for that pedestrian - //Log->Write("\tINFO: \tCould not found a route for pedestrian %d",_allPedestians[p]->GetID()); - //Log->Write("\tINFO: \tHe has reached the target cell"); - DeletePedFromSim(_allPedestians[p]); - //exit(EXIT_FAILURE); - } - } - } -} +void Building::UpdateVerySlow() +{ + + vector<Pedestrian*> nonConformPeds; + for (int i = 0; i < GetNumberOfRooms(); i++) { + Room* room = GetRoom(i); + + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { + Pedestrian* ped = sub->GetPedestrian(k); + //set the new room if needed + if ((ped->GetFinalDestination() == FINAL_DEST_OUT) + && (GetRoom(ped->GetRoomID())->GetCaption() == "outside")) { + + sub->DeletePedestrian(k--); + DeletePedestrian(ped); + } else if ((ped->GetFinalDestination() != FINAL_DEST_OUT) + && (_goals[ped->GetFinalDestination()]->Contains( + ped->GetPos()))) { + sub->DeletePedestrian(k--); + DeletePedestrian(ped); + } else if (!sub->IsInSubRoom(ped)) { + nonConformPeds.push_back(ped); + sub->DeletePedestrian(k--); + } + } + } + } -void Building::Update() { - // some peds may change the room via another crossing than the primary intended one - // in that case they are set in the wrong room. - vector<Pedestrian*> nonConformPeds; - for (int i = 0; i < GetNumberOfRooms(); i++) { - Room* room = GetRoom(i); - - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { - Pedestrian* ped = sub->GetPedestrian(k); - //set the new room if needed - if (!sub->IsInSubRoom(ped)) { - // the peds has changed the room and is farther than 50 cm from - // the exit, thats a real problem. - if (ped->GetExitLine()->DistTo(ped->GetPos()) > 0.50) { - Log->Write( - "WARNING: Building::update() pedestrian [%d] left the room/subroom [%s][%d/%d] " - "via unknown exit[??%d] \n Position: (%f, %f), distance to exit: (%f)", - ped->GetID(), - _rooms[ped->GetRoomID()]->GetCaption().c_str(), - ped->GetRoomID(), ped->GetSubRoomID(), - ped->GetExitIndex(), ped->GetPos().GetX(), - ped->GetPos().GetY(),ped->GetExitLine()->DistTo(ped->GetPos())); - //ped->Dump(ped->GetPedIndex()); - //std::cout << ped->GetLastDestination() << " " - // << ped->GetNextDestination() << std::endl; - //exit(0); - nonConformPeds.push_back(ped); - sub->DeletePedestrian(k--); - continue; // next pedestrian - } - - //safely converting (upcasting) the NavLine to a crossing. - Crossing* cross = - dynamic_cast<Crossing*>(ped->GetExitLine()); - if (cross == NULL) { - Log->Write("ERROR: Building::update() type casting error for ped %d",ped->GetID()); - Log->Write("ERROR: Fix Me !"); - nonConformPeds.push_back(ped); - exit(EXIT_FAILURE); - continue; - //fixme all portal should be derived from crossings - } - - SubRoom* other_sub = cross->GetOtherSubRoom( - room->GetID(), j); - - if (other_sub) { - int nextSubRoom = other_sub->GetSubRoomID(); - int nextRoom = other_sub->GetRoomID(); - ped->SetSubRoomID(nextSubRoom); - ped->SetRoomID(nextRoom, - GetRoom(nextRoom)->GetCaption()); - other_sub->AddPedestrian(ped); - - } else { - DeletePedestrian(ped); - //continue; - } - // Lösche Fußgänger aus aktuellem SubRoom - sub->DeletePedestrian(k--); // k--; - } - // neues Ziel setzten - //pRouting->FindExit(ped); - } - } - } - - // reset that pedestrians who left their room not via the intended exit - for (int p = 0; p < (int) nonConformPeds.size(); p++) { - Pedestrian* ped = nonConformPeds[p]; - bool assigned = false; - for (int i = 0; i < GetNumberOfRooms(); i++) { - Room* room = GetRoom(i); - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - //only relocate in the same room - // or only in neighbouring rooms - if (room->GetID() != ped->GetRoomID()) - continue; - if (sub->IsInSubRoom(ped->GetPos())) { - //set in the new room - Log->Write("pedestrian %d relocated from room/subroom [%s] %d/%d to [%s] %d/%d ", - ped->GetID(), - GetRoom(ped->GetRoomID())->GetCaption().c_str(), - ped->GetRoomID(), ped->GetSubRoomID(), - room->GetCaption().c_str(), i, j); - ped->SetRoomID(room->GetID(), room->GetCaption()); - ped->SetSubRoomID(sub->GetSubRoomID()); - ped->ClearMentalMap(); // reset the destination - ped->FindRoute(); - sub->AddPedestrian(ped); - assigned = true; - break; - } - } - if (assigned == true) - break; // stop the loop - } - if (assigned == false) { - DeletePedestrian(ped); - } - } - - // find the new goals, the parallel way - - unsigned int nSize = _allPedestians.size(); - int nThreads = omp_get_max_threads(); - - // check if worth sharing the work - if (nSize < 12) - nThreads = 1; - - int partSize = nSize / nThreads; - -#pragma omp parallel default(shared) num_threads(nThreads) - { - const int threadID = omp_get_thread_num(); - int start = threadID * partSize; - int end = (threadID + 1) * partSize - 1; - if ((threadID == nThreads - 1)) - end = nSize - 1; - - for (int p = start; p <= end; ++p) { - if (_allPedestians[p]->FindRoute() == -1) { - //a destination could not be found for that pedestrian - //Log->Write("\tINFO: \tCould not found a route for pedestrian %d",_allPedestians[p]->GetID()); - //Log->Write("\tINFO: \tHe has reached the target cell"); - DeletePedFromSim(_allPedestians[p]); - //exit(EXIT_FAILURE); - } - } - } - - //cleaning up - //CleanUpTheScene(); + // reset that pedestrians who left their room not via the intended exit + for (int p = 0; p < (int) nonConformPeds.size(); p++) { + Pedestrian* ped = nonConformPeds[p]; + bool assigned = false; + for (int i = 0; i < GetNumberOfRooms(); i++) { + Room* room = GetRoom(i); + //if(room->GetCaption()=="outside") continue; + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + SubRoom* old_sub= _rooms[ped->GetRoomID()]->GetSubRoom(ped->GetSubRoomID()); + if ((sub->IsInSubRoom(ped->GetPos())) && (sub->IsDirectlyConnectedWith(old_sub))) { + ped->SetRoomID(room->GetID(), room->GetCaption()); + ped->SetSubRoomID(sub->GetSubRoomID()); + ped->ClearMentalMap(); // reset the destination + //ped->FindRoute(); + sub->AddPedestrian(ped); + assigned = true; + break; + } + } + if (assigned == true) + break; // stop the loop + } + if (assigned == false) { + DeletePedestrian(ped); + } + } + + // find the new goals, the parallel way + + unsigned int nSize = _allPedestians.size(); + int nThreads = omp_get_max_threads(); + + // check if worth sharing the work + if (nSize < 12) + nThreads = 1; + + int partSize = nSize / nThreads; + + #pragma omp parallel default(shared) num_threads(nThreads) + { + const int threadID = omp_get_thread_num(); + int start = threadID * partSize; + int end = (threadID + 1) * partSize - 1; + if ((threadID == nThreads - 1)) + end = nSize - 1; + + for (int p = start; p <= end; ++p) { + if (_allPedestians[p]->FindRoute() == -1) { + //a destination could not be found for that pedestrian + //Log->Write("\tINFO: \tCould not found a route for pedestrian %d",_allPedestians[p]->GetID()); + //Log->Write("\tINFO: \tHe has reached the target cell"); + DeletePedFromSim(_allPedestians[p]); + //exit(EXIT_FAILURE); + } + } + } } +void Building::Update() +{ + // some peds may change the room via another crossing than the primary intended one + // in that case they are set in the wrong room. + vector<Pedestrian*> nonConformPeds; + for (int i = 0; i < GetNumberOfRooms(); i++) { + Room* room = GetRoom(i); + + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { + Pedestrian* ped = sub->GetPedestrian(k); + //set the new room if needed + if (!sub->IsInSubRoom(ped)) { + // the peds has changed the room and is farther than 50 cm from + // the exit, thats a real problem. + if (ped->GetExitLine()->DistTo(ped->GetPos()) > 0.50) { + Log->Write( + "WARNING: Building::update() pedestrian [%d] left the room/subroom [%s][%d/%d] " + "via unknown exit[??%d] \n Position: (%f, %f), distance to exit: (%f)", + ped->GetID(), + _rooms[ped->GetRoomID()]->GetCaption().c_str(), + ped->GetRoomID(), ped->GetSubRoomID(), + ped->GetExitIndex(), ped->GetPos().GetX(), + ped->GetPos().GetY(),ped->GetExitLine()->DistTo(ped->GetPos())); + //ped->Dump(ped->GetPedIndex()); + //std::cout << ped->GetLastDestination() << " " + // << ped->GetNextDestination() << std::endl; + //exit(0); + nonConformPeds.push_back(ped); + sub->DeletePedestrian(k--); + continue; // next pedestrian + } + + //safely converting (upcasting) the NavLine to a crossing. + Crossing* cross = + dynamic_cast<Crossing*>(ped->GetExitLine()); + if (cross == NULL) { + Log->Write("ERROR: Building::update() type casting error for ped %d",ped->GetID()); + Log->Write("ERROR: Fix Me !"); + nonConformPeds.push_back(ped); + exit(EXIT_FAILURE); + continue; + //fixme all portal should be derived from crossings + } + + SubRoom* other_sub = cross->GetOtherSubRoom( + room->GetID(), j); + + if (other_sub) { + int nextSubRoom = other_sub->GetSubRoomID(); + int nextRoom = other_sub->GetRoomID(); + ped->SetSubRoomID(nextSubRoom); + ped->SetRoomID(nextRoom, + GetRoom(nextRoom)->GetCaption()); + other_sub->AddPedestrian(ped); + + } else { + DeletePedestrian(ped); + //continue; + } + // Lösche Fußgänger aus aktuellem SubRoom + sub->DeletePedestrian(k--); // k--; + } + // neues Ziel setzten + //pRouting->FindExit(ped); + } + } + } + + // reset that pedestrians who left their room not via the intended exit + for (int p = 0; p < (int) nonConformPeds.size(); p++) { + Pedestrian* ped = nonConformPeds[p]; + bool assigned = false; + for (int i = 0; i < GetNumberOfRooms(); i++) { + Room* room = GetRoom(i); + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + //only relocate in the same room + // or only in neighbouring rooms + if (room->GetID() != ped->GetRoomID()) + continue; + if (sub->IsInSubRoom(ped->GetPos())) { + //set in the new room + Log->Write("pedestrian %d relocated from room/subroom [%s] %d/%d to [%s] %d/%d ", + ped->GetID(), + GetRoom(ped->GetRoomID())->GetCaption().c_str(), + ped->GetRoomID(), ped->GetSubRoomID(), + room->GetCaption().c_str(), i, j); + ped->SetRoomID(room->GetID(), room->GetCaption()); + ped->SetSubRoomID(sub->GetSubRoomID()); + ped->ClearMentalMap(); // reset the destination + ped->FindRoute(); + sub->AddPedestrian(ped); + assigned = true; + break; + } + } + if (assigned == true) + break; // stop the loop + } + if (assigned == false) { + DeletePedestrian(ped); + } + } + + // find the new goals, the parallel way + + unsigned int nSize = _allPedestians.size(); + int nThreads = omp_get_max_threads(); + + // check if worth sharing the work + if (nSize < 12) + nThreads = 1; + + int partSize = nSize / nThreads; + + #pragma omp parallel default(shared) num_threads(nThreads) + { + const int threadID = omp_get_thread_num(); + int start = threadID * partSize; + int end = (threadID + 1) * partSize - 1; + if ((threadID == nThreads - 1)) + end = nSize - 1; + + for (int p = start; p <= end; ++p) { + if (_allPedestians[p]->FindRoute() == -1) { + //a destination could not be found for that pedestrian + //Log->Write("\tINFO: \tCould not found a route for pedestrian %d",_allPedestians[p]->GetID()); + //Log->Write("\tINFO: \tHe has reached the target cell"); + DeletePedFromSim(_allPedestians[p]); + //exit(EXIT_FAILURE); + } + } + } -void Building::InitPhiAllPeds(double pDt) { - for (int i = 0; i < GetNumberOfRooms(); i++) { - Room* room = GetRoom(i); - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { - double cosPhi, sinPhi; - Pedestrian* ped = sub->GetPedestrian(k); - ped->Setdt(pDt); //set the simulation step - ped->SetRoomID(room->GetID(), room->GetCaption()); - //a destination could not be found for that pedestrian - if (ped->FindRoute() == -1) { - // DeletePedFromSim(ped); - sub->DeletePedestrian(k--); - continue; - } - Line* e = ped->GetExitLine(); - const Point& e1 = e->GetPoint1(); - const Point& e2 = e->GetPoint2(); - Point target = (e1 + e2) * 0.5; - Point d = target - ped->GetPos(); - double dist = d.Norm(); - if (dist != 0.0) { - cosPhi = d.GetX() / dist; - sinPhi = d.GetY() / dist; - } else { - Log->Write( - "ERROR: \tBuilding::InitPhiAllPeds() cannot initialise phi! " - "dist to target ist 0\n"); - exit(0); - } - - JEllipse E = ped->GetEllipse(); - E.SetCosPhi(cosPhi); - E.SetSinPhi(sinPhi); - ped->SetEllipse(E); - } - } - } + //cleaning up + //CleanUpTheScene(); } -void Building::UpdateGrid() { - _linkedCellGrid->Update(_allPedestians); + +void Building::InitPhiAllPeds(double pDt) +{ + for (int i = 0; i < GetNumberOfRooms(); i++) { + Room* room = GetRoom(i); + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { + double cosPhi, sinPhi; + Pedestrian* ped = sub->GetPedestrian(k); + ped->Setdt(pDt); //set the simulation step + ped->SetRoomID(room->GetID(), room->GetCaption()); + //a destination could not be found for that pedestrian + if (ped->FindRoute() == -1) { + // DeletePedFromSim(ped); + sub->DeletePedestrian(k--); + continue; + } + Line* e = ped->GetExitLine(); + const Point& e1 = e->GetPoint1(); + const Point& e2 = e->GetPoint2(); + Point target = (e1 + e2) * 0.5; + Point d = target - ped->GetPos(); + double dist = d.Norm(); + if (dist != 0.0) { + cosPhi = d.GetX() / dist; + sinPhi = d.GetY() / dist; + } else { + Log->Write( + "ERROR: \tBuilding::InitPhiAllPeds() cannot initialise phi! " + "dist to target ist 0\n"); + exit(0); + } + + JEllipse E = ped->GetEllipse(); + E.SetCosPhi(cosPhi); + E.SetSinPhi(sinPhi); + ped->SetEllipse(E); + } + } + } } -void Building::InitGrid(double cellSize) { - - // first look for the geometry boundaries - double x_min = FLT_MAX; - double x_max = FLT_MIN; - double y_min = FLT_MAX; - double y_max = FLT_MIN; - - //finding the bounding of the grid - // and collect the pedestrians - for (unsigned int r = 0; r < _rooms.size(); r++) { - Room* room = _rooms[r]; - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - const vector<Wall>& allWalls = sub->GetAllWalls(); - - for (unsigned int a = 0; a < allWalls.size(); a++) { - double x1 = allWalls[a].GetPoint1().GetX(); - double y1 = allWalls[a].GetPoint1().GetY(); - double x2 = allWalls[a].GetPoint2().GetX(); - double y2 = allWalls[a].GetPoint2().GetY(); - - double xmax = (x1 > x2) ? x1 : x2; - double xmin = (x1 > x2) ? x2 : x1; - double ymax = (y1 > y2) ? y1 : y2; - double ymin = (y1 > y2) ? y2 : y1; - - x_min = (xmin <= x_min) ? xmin : x_min; - x_max = (xmax >= x_max) ? xmax : x_max; - y_max = (ymax >= y_max) ? ymax : y_max; - y_min = (ymin <= y_min) ? ymin : y_min; - } - } - } - - for (unsigned int wa = 0; wa < _rooms.size(); wa++) { - Room* room = _rooms[wa]; - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { - Pedestrian* ped = sub->GetPedestrian(k); - _allPedestians.push_back(ped); - } - } - } - - //make the grid slightly larger. - x_min = x_min - 1.0; - x_max = x_max + 1.0; - y_min = y_min - 1.0; - y_max = y_max + 1.0; - - double boundaries[] = { x_min, x_max, y_min, y_max }; - int pedsCount = _allPedestians.size(); - - //no algorithms - // the domain is made of a sigle cell - if(cellSize==-1){ - Log->Write("INFO: \tBrute Force will be used for neighborhoods query"); - if ( (x_max-x_min) < (y_max-y_min) ){ - cellSize=(y_max-y_min); - }else { - cellSize=(x_max-x_min); - } - - }else{ - Log->Write("INFO: \tInitializing the grid with cell size: %f ", cellSize); - } - - _linkedCellGrid = new LCGrid(boundaries, cellSize, pedsCount); - _linkedCellGrid->ShallowCopy(_allPedestians); - - Log->Write("INFO: \tDone with Initializing the grid "); +void Building::UpdateGrid() +{ + _linkedCellGrid->Update(_allPedestians); } +void Building::InitGrid(double cellSize) +{ + + // first look for the geometry boundaries + double x_min = FLT_MAX; + double x_max = FLT_MIN; + double y_min = FLT_MAX; + double y_max = FLT_MIN; + + //finding the bounding of the grid + // and collect the pedestrians + for (unsigned int r = 0; r < _rooms.size(); r++) { + Room* room = _rooms[r]; + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + const vector<Wall>& allWalls = sub->GetAllWalls(); + + for (unsigned int a = 0; a < allWalls.size(); a++) { + double x1 = allWalls[a].GetPoint1().GetX(); + double y1 = allWalls[a].GetPoint1().GetY(); + double x2 = allWalls[a].GetPoint2().GetX(); + double y2 = allWalls[a].GetPoint2().GetY(); + + double xmax = (x1 > x2) ? x1 : x2; + double xmin = (x1 > x2) ? x2 : x1; + double ymax = (y1 > y2) ? y1 : y2; + double ymin = (y1 > y2) ? y2 : y1; + + x_min = (xmin <= x_min) ? xmin : x_min; + x_max = (xmax >= x_max) ? xmax : x_max; + y_max = (ymax >= y_max) ? ymax : y_max; + y_min = (ymin <= y_min) ? ymin : y_min; + } + } + } + for (unsigned int wa = 0; wa < _rooms.size(); wa++) { + Room* room = _rooms[wa]; + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { + Pedestrian* ped = sub->GetPedestrian(k); + _allPedestians.push_back(ped); + } + } + } -void Building::DumpSubRoomInRoom(int roomID, int subID) { - SubRoom* sub = GetRoom(roomID)->GetSubRoom(subID); - if (sub->GetNumberOfPedestrians() == 0) - return; - cout << "dumping room/subroom " << roomID << " / " << subID << endl; - for (int p = 0; p < sub->GetNumberOfPedestrians(); p++) { - Pedestrian* ped = sub->GetPedestrian(p); - cout << " ID: " << ped->GetID(); - cout << " Index: " << p << endl; - } + //make the grid slightly larger. + x_min = x_min - 1.0; + x_max = x_max + 1.0; + y_min = y_min - 1.0; + y_max = y_max + 1.0; + + double boundaries[] = { x_min, x_max, y_min, y_max }; + int pedsCount = _allPedestians.size(); + + //no algorithms + // the domain is made of a sigle cell + if(cellSize==-1) { + Log->Write("INFO: \tBrute Force will be used for neighborhoods query"); + if ( (x_max-x_min) < (y_max-y_min) ) { + cellSize=(y_max-y_min); + } else { + cellSize=(x_max-x_min); + } -} + } else { + Log->Write("INFO: \tInitializing the grid with cell size: %f ", cellSize); + } + _linkedCellGrid = new LCGrid(boundaries, cellSize, pedsCount); + _linkedCellGrid->ShallowCopy(_allPedestians); -void Building::LoadRoutingInfo(const string &filename) { - - - Log->Write("INFO:\tLoading extra routing information"); - if (filename == "") { - Log->Write("INFO:\t No file supplied !"); - Log->Write("INFO:\t done with loading extra routing information"); - return; - } - TiXmlDocument docRouting(filename); - if (!docRouting.LoadFile()){ - Log->Write("ERROR: \t%s", docRouting.ErrorDesc()); - Log->Write("ERROR: \t could not parse the routing file"); - exit(EXIT_FAILURE); - } - - TiXmlElement* xRootNode = docRouting.RootElement(); - if( ! xRootNode ) { - Log->Write("ERROR:\tRoot element does not exist"); - exit(EXIT_FAILURE); - } - - //load goals and routes - TiXmlNode* xGoalsNode = xRootNode->FirstChild("routing")->FirstChild("goals"); - - - if(xGoalsNode) - for(TiXmlElement* e = xGoalsNode->FirstChildElement("goal"); e; - e = e->NextSiblingElement("goal")) { - - int id = xmltof(e->Attribute("id"), -1); - int isFinal= string(e->Attribute("final"))=="true"?true:false; - string caption = xmltoa(e->Attribute("caption"),"-1"); - - Goal* goal = new Goal(); - goal->SetId(id); - goal->SetCaption(caption); - goal->SetIsFinalGoal(isFinal); - - //looking for polygons (walls) - for(TiXmlElement* xPolyVertices = e->FirstChildElement("polygon"); xPolyVertices; - xPolyVertices = xPolyVertices->NextSiblingElement("polygon")) { - - for (TiXmlElement* xVertex = xPolyVertices->FirstChildElement( - "vertex"); - xVertex && xVertex != xPolyVertices->LastChild("vertex"); - xVertex = xVertex->NextSiblingElement("vertex")) { - - double x1 = xmltof(xVertex->Attribute("px")); - double y1 = xmltof(xVertex->Attribute("py")); - double x2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("px")); - double y2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("py")); - goal->AddWall(Wall(Point(x1, y1), Point(x2, y2))); - } - } - - goal->ConvertLineToPoly(); - AddGoal(goal); - _routingEngine->AddFinalDestinationID(goal->GetId()); - } - - //load routes - TiXmlNode* xTripsNode = xRootNode->FirstChild("routing")->FirstChild("routes"); - - if(xTripsNode) - for(TiXmlElement* trip = xTripsNode->FirstChildElement("route"); trip; - trip = trip->NextSiblingElement("route")) { - - double id = xmltof(trip->Attribute("id"), -1); - if (id == -1) { - Log->Write("ERROR:\t id missing for trip"); - exit(EXIT_FAILURE); - } - string sTrip = trip->FirstChild()->ValueStr(); - vector<string> vTrip; - vTrip.clear(); - - char* str = (char*) sTrip.c_str(); - char *p = strtok(str, ":"); - while (p) { - vTrip.push_back(xmltoa(p)); - p = strtok(NULL, ":"); - } - _routingEngine->AddTrip(vTrip); - } - Log->Write("INFO:\tdone with loading extra routing information"); + Log->Write("INFO: \tDone with Initializing the grid "); } -void Building::LoadTrafficInfo() { - - Log->Write("INFO:\tLoading the traffic info file"); - - string trafficFile=""; - TiXmlDocument doc(_projectFilename); - if (!doc.LoadFile()){ - Log->Write("ERROR: \t%s", doc.ErrorDesc()); - Log->Write("ERROR: \t could not parse the project file"); - exit(EXIT_FAILURE); - } - - TiXmlNode* xRootNode = doc.RootElement()->FirstChild("traffic_constraints"); - if( ! xRootNode ) { - Log->Write("WARNING:\tcould not find any traffic information"); - return; - //exit(EXIT_FAILURE); - } - - //processing the rooms node - TiXmlNode* xRoomsNode = xRootNode->FirstChild("rooms"); - if(xRoomsNode) - for(TiXmlElement* xRoom = xRoomsNode->FirstChildElement("room"); xRoom; - xRoom = xRoom->NextSiblingElement("room")) { - - double id = xmltof(xRoom->Attribute("room_id"), -1); - string state = xmltoa(xRoom->Attribute("state"), "good"); - RoomState status = (state == "good") ? ROOM_CLEAN : ROOM_SMOKED; - _rooms[id]->SetState(status); - } - - //processing the doors node - TiXmlNode* xDoorsNode = xRootNode->FirstChild("doors"); - if(xDoorsNode) - for(TiXmlElement* xDoor = xDoorsNode->FirstChildElement("door"); xDoor; - xDoor = xDoor->NextSiblingElement("door")) { - - int id = xmltoi(xDoor->Attribute("trans_id"), -1); - string state = xmltoa(xDoor->Attribute("state"), "open"); - - //store transition in a map and call getTransition/getCrossin - if (state == "open") { - GetTransition(id)->Open(); - } else if (state == "close") { - GetTransition(id)->Close(); - } else { - Log->Write("WARNING:\t Unknown door state: %s", state.c_str()); - } - } - Log->Write("INFO:\tDone with loading traffic info file"); -} -void Building::DeletePedestrian(Pedestrian* ped) { - vector<Pedestrian*>::iterator it; - it = find(_allPedestians.begin(), _allPedestians.end(), ped); - if (it == _allPedestians.end()) { - Log->Write ("\tINFO: \tPed not found with ID %d ",ped->GetID()); - //FIXME: the pedestrians should always exists. check this in connection with the mesh router. - return; - } else { - //save the path history for this pedestrian before removing from the simulation - if (_savePathway) { - string results; - string path = (*it)->GetPath(); - vector<string> brokenpaths; - StringExplode(path, ">", &brokenpaths); - for (unsigned int i = 0; i < brokenpaths.size(); i++) { - vector<string> tags; - StringExplode(brokenpaths[i], ":", &tags); - string room = _rooms[atoi(tags[0].c_str())]->GetCaption(); - string trans =GetTransition(atoi(tags[1].c_str()))->GetCaption(); - //ignore crossings/hlines - if (trans != "") - _pathWayStream << room << " " << trans << endl; - } - - } - cout << "rescued agent: " << (*it)->GetID() << endl; - _allPedestians.erase(it); - } - delete ped; -} +void Building::DumpSubRoomInRoom(int roomID, int subID) +{ + SubRoom* sub = GetRoom(roomID)->GetSubRoom(subID); + if (sub->GetNumberOfPedestrians() == 0) + return; + cout << "dumping room/subroom " << roomID << " / " << subID << endl; + for (int p = 0; p < sub->GetNumberOfPedestrians(); p++) { + Pedestrian* ped = sub->GetPedestrian(p); + cout << " ID: " << ped->GetID(); + cout << " Index: " << p << endl; + } -void Building::DeletePedFromSim(Pedestrian* ped) { - SubRoom* sub = _rooms[ped->GetRoomID()]->GetSubRoom(ped->GetSubRoomID()); - for (int p = 0; p < sub->GetNumberOfPedestrians(); p++) { - if (sub->GetPedestrian(p)->GetID() == ped->GetID()) { - sub->DeletePedestrian(p); - DeletePedestrian(ped); - return; - } - } } -const vector<Pedestrian*>& Building::GetAllPedestrians() const { - return _allPedestians; + +void Building::LoadRoutingInfo(const string &filename) +{ + + + Log->Write("INFO:\tLoading extra routing information"); + if (filename == "") { + Log->Write("INFO:\t No file supplied !"); + Log->Write("INFO:\t done with loading extra routing information"); + return; + } + TiXmlDocument docRouting(filename); + if (!docRouting.LoadFile()) { + Log->Write("ERROR: \t%s", docRouting.ErrorDesc()); + Log->Write("ERROR: \t could not parse the routing file"); + exit(EXIT_FAILURE); + } + + TiXmlElement* xRootNode = docRouting.RootElement(); + if( ! xRootNode ) { + Log->Write("ERROR:\tRoot element does not exist"); + exit(EXIT_FAILURE); + } + + //load goals and routes + TiXmlNode* xGoalsNode = xRootNode->FirstChild("routing")->FirstChild("goals"); + + + if(xGoalsNode) + for(TiXmlElement* e = xGoalsNode->FirstChildElement("goal"); e; + e = e->NextSiblingElement("goal")) { + + int id = xmltof(e->Attribute("id"), -1); + int isFinal= string(e->Attribute("final"))=="true"?true:false; + string caption = xmltoa(e->Attribute("caption"),"-1"); + + Goal* goal = new Goal(); + goal->SetId(id); + goal->SetCaption(caption); + goal->SetIsFinalGoal(isFinal); + + //looking for polygons (walls) + for(TiXmlElement* xPolyVertices = e->FirstChildElement("polygon"); xPolyVertices; + xPolyVertices = xPolyVertices->NextSiblingElement("polygon")) { + + for (TiXmlElement* xVertex = xPolyVertices->FirstChildElement( + "vertex"); + xVertex && xVertex != xPolyVertices->LastChild("vertex"); + xVertex = xVertex->NextSiblingElement("vertex")) { + + double x1 = xmltof(xVertex->Attribute("px")); + double y1 = xmltof(xVertex->Attribute("py")); + double x2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("px")); + double y2 = xmltof(xVertex->NextSiblingElement("vertex")->Attribute("py")); + goal->AddWall(Wall(Point(x1, y1), Point(x2, y2))); + } + } + + goal->ConvertLineToPoly(); + AddGoal(goal); + _routingEngine->AddFinalDestinationID(goal->GetId()); + } + + //load routes + TiXmlNode* xTripsNode = xRootNode->FirstChild("routing")->FirstChild("routes"); + + if(xTripsNode) + for(TiXmlElement* trip = xTripsNode->FirstChildElement("route"); trip; + trip = trip->NextSiblingElement("route")) { + + double id = xmltof(trip->Attribute("id"), -1); + if (id == -1) { + Log->Write("ERROR:\t id missing for trip"); + exit(EXIT_FAILURE); + } + string sTrip = trip->FirstChild()->ValueStr(); + vector<string> vTrip; + vTrip.clear(); + + char* str = (char*) sTrip.c_str(); + char *p = strtok(str, ":"); + while (p) { + vTrip.push_back(xmltoa(p)); + p = strtok(NULL, ":"); + } + _routingEngine->AddTrip(vTrip); + } + Log->Write("INFO:\tdone with loading extra routing information"); } -void Building::AddPedestrian(Pedestrian* ped) { +void Building::LoadTrafficInfo() +{ + + Log->Write("INFO:\tLoading the traffic info file"); - // for(unsigned int p = 0;p<pAllPedestians.size();p++){ - // Pedestrian* ped1=pAllPedestians[p]; - // if(ped->GetPedIndex()==ped1->GetPedIndex()){ - // cout<<"Pedestrian already in the room ??? "<<ped->GetPedIndex()<<endl; - // return; - // } - // } - _allPedestians.push_back(ped); + string trafficFile=""; + TiXmlDocument doc(_projectFilename); + if (!doc.LoadFile()) { + Log->Write("ERROR: \t%s", doc.ErrorDesc()); + Log->Write("ERROR: \t could not parse the project file"); + exit(EXIT_FAILURE); + } + + TiXmlNode* xRootNode = doc.RootElement()->FirstChild("traffic_constraints"); + if( ! xRootNode ) { + Log->Write("WARNING:\tcould not find any traffic information"); + return; + //exit(EXIT_FAILURE); + } + + //processing the rooms node + TiXmlNode* xRoomsNode = xRootNode->FirstChild("rooms"); + if(xRoomsNode) + for(TiXmlElement* xRoom = xRoomsNode->FirstChildElement("room"); xRoom; + xRoom = xRoom->NextSiblingElement("room")) { + + double id = xmltof(xRoom->Attribute("room_id"), -1); + string state = xmltoa(xRoom->Attribute("state"), "good"); + RoomState status = (state == "good") ? ROOM_CLEAN : ROOM_SMOKED; + _rooms[id]->SetState(status); + } + + //processing the doors node + TiXmlNode* xDoorsNode = xRootNode->FirstChild("doors"); + if(xDoorsNode) + for(TiXmlElement* xDoor = xDoorsNode->FirstChildElement("door"); xDoor; + xDoor = xDoor->NextSiblingElement("door")) { + + int id = xmltoi(xDoor->Attribute("trans_id"), -1); + string state = xmltoa(xDoor->Attribute("state"), "open"); + + //store transition in a map and call getTransition/getCrossin + if (state == "open") { + GetTransition(id)->Open(); + } else if (state == "close") { + GetTransition(id)->Close(); + } else { + Log->Write("WARNING:\t Unknown door state: %s", state.c_str()); + } + } + Log->Write("INFO:\tDone with loading traffic info file"); } -//obsolete -void Building::InitSavePedPathway(const string &filename) { - _pathWayStream.open(filename.c_str()); - _savePathway = true; - - if (_pathWayStream.is_open()) { - Log->Write("#INFO:\tsaving pedestrian paths to [ " + filename + " ]"); - _pathWayStream << "##pedestrian ways" << endl; - _pathWayStream << "#nomenclature roomid caption" << endl; - // for (unsigned int r=0;r< pRooms.size();r++){ - // Room* room= GetRoom(r); - // const vector<int>& goals=room->GetAllTransitionsIDs(); - // - // for(unsigned int g=0;g<goals.size();g++){ - // int exitid=goals[g]; - // string exit_caption=pRouting->GetGoal(exitid)->GetCaption(); - // PpathWayStream<<exitid<<" "<<exit_caption<<endl; - // } - // } - // - _pathWayStream << "#data room exit_id" << endl; - } else { - Log->Write("#INFO:\t Unable to open [ " + filename + " ]"); - Log->Write("#INFO:\t saving to stdout"); - - } +void Building::DeletePedestrian(Pedestrian* ped) +{ + vector<Pedestrian*>::iterator it; + it = find(_allPedestians.begin(), _allPedestians.end(), ped); + if (it == _allPedestians.end()) { + Log->Write ("\tINFO: \tPed not found with ID %d ",ped->GetID()); + //FIXME: the pedestrians should always exists. check this in connection with the mesh router. + return; + } else { + //save the path history for this pedestrian before removing from the simulation + if (_savePathway) { + string results; + string path = (*it)->GetPath(); + vector<string> brokenpaths; + StringExplode(path, ">", &brokenpaths); + for (unsigned int i = 0; i < brokenpaths.size(); i++) { + vector<string> tags; + StringExplode(brokenpaths[i], ":", &tags); + string room = _rooms[atoi(tags[0].c_str())]->GetCaption(); + string trans =GetTransition(atoi(tags[1].c_str()))->GetCaption(); + //ignore crossings/hlines + if (trans != "") + _pathWayStream << room << " " << trans << endl; + } + + } + cout << "rescued agent: " << (*it)->GetID() << endl; + _allPedestians.erase(it); + } + delete ped; } -void Building::CleanUpTheScene() { - //return; - static int counter = 0; - counter++; - static int totalSliced = 0; +void Building::DeletePedFromSim(Pedestrian* ped) +{ + SubRoom* sub = _rooms[ped->GetRoomID()]->GetSubRoom(ped->GetSubRoomID()); + for (int p = 0; p < sub->GetNumberOfPedestrians(); p++) { + if (sub->GetPedestrian(p)->GetID() == ped->GetID()) { + sub->DeletePedestrian(p); + DeletePedestrian(ped); + return; + } + } +} - int updateRate = 80.0 / 0.01; // 20 seconds/pDt +const vector<Pedestrian*>& Building::GetAllPedestrians() const +{ + return _allPedestians; +} - if (counter % updateRate == 0) { - for (unsigned int i = 0; i < _allPedestians.size(); i++) { - Pedestrian* ped = _allPedestians[i]; +void Building::AddPedestrian(Pedestrian* ped) +{ + + // for(unsigned int p = 0;p<pAllPedestians.size();p++){ + // Pedestrian* ped1=pAllPedestians[p]; + // if(ped->GetPedIndex()==ped1->GetPedIndex()){ + // cout<<"Pedestrian already in the room ??? "<<ped->GetPedIndex()<<endl; + // return; + // } + // } + _allPedestians.push_back(ped); +} - if (ped->GetDistanceSinceLastRecord() < 0.1) { - //delete from the simulation - DeletePedFromSim(ped); - totalSliced++; - char msg[CLENGTH]; - sprintf(msg, "INFO:\t slicing Ped %d from room %s, total [%d]", - ped->GetID(), - _rooms[ped->GetRoomID()]->GetCaption().c_str(), - totalSliced); - Log->Write(msg); - } else { - ped->RecordActualPosition(); - } +//obsolete +void Building::InitSavePedPathway(const string &filename) +{ + _pathWayStream.open(filename.c_str()); + _savePathway = true; + + if (_pathWayStream.is_open()) { + Log->Write("#INFO:\tsaving pedestrian paths to [ " + filename + " ]"); + _pathWayStream << "##pedestrian ways" << endl; + _pathWayStream << "#nomenclature roomid caption" << endl; + // for (unsigned int r=0;r< pRooms.size();r++){ + // Room* room= GetRoom(r); + // const vector<int>& goals=room->GetAllTransitionsIDs(); + // + // for(unsigned int g=0;g<goals.size();g++){ + // int exitid=goals[g]; + // string exit_caption=pRouting->GetGoal(exitid)->GetCaption(); + // PpathWayStream<<exitid<<" "<<exit_caption<<endl; + // } + // } + // + _pathWayStream << "#data room exit_id" << endl; + } else { + Log->Write("#INFO:\t Unable to open [ " + filename + " ]"); + Log->Write("#INFO:\t saving to stdout"); + + } +} - } - } +void Building::CleanUpTheScene() +{ + //return; + static int counter = 0; + counter++; + static int totalSliced = 0; + + int updateRate = 80.0 / 0.01; // 20 seconds/pDt + + if (counter % updateRate == 0) { + for (unsigned int i = 0; i < _allPedestians.size(); i++) { + Pedestrian* ped = _allPedestians[i]; + + if (ped->GetDistanceSinceLastRecord() < 0.1) { + //delete from the simulation + DeletePedFromSim(ped); + + totalSliced++; + char msg[CLENGTH]; + sprintf(msg, "INFO:\t slicing Ped %d from room %s, total [%d]", + ped->GetID(), + _rooms[ped->GetRoomID()]->GetCaption().c_str(), + totalSliced); + Log->Write(msg); + } else { + ped->RecordActualPosition(); + } + + } + } } void Building::StringExplode(string str, string separator, - vector<string>* results) { - size_t found; - found = str.find_first_of(separator); - while (found != string::npos) { - if (found > 0) { - results->push_back(str.substr(0, found)); - } - str = str.substr(found + 1); - found = str.find_first_of(separator); - } - if (str.length() > 0) { - results->push_back(str); - } + vector<string>* results) +{ + size_t found; + found = str.find_first_of(separator); + while (found != string::npos) { + if (found > 0) { + results->push_back(str.substr(0, found)); + } + str = str.substr(found + 1); + found = str.find_first_of(separator); + } + if (str.length() > 0) { + results->push_back(str); + } } -Pedestrian* Building::GetPedestrian(int pedID) const { - for (unsigned int i = 0; i < _rooms.size(); i++) { - Room* room = _rooms[i]; - for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { - SubRoom* sub = room->GetSubRoom(j); - for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { - Pedestrian* p = sub->GetPedestrian(k); - if (p->GetID() == pedID) { - return p; - } - } - } - } - return NULL; +Pedestrian* Building::GetPedestrian(int pedID) const +{ + for (unsigned int i = 0; i < _rooms.size(); i++) { + Room* room = _rooms[i]; + for (int j = 0; j < room->GetNumberOfSubRooms(); j++) { + SubRoom* sub = room->GetSubRoom(j); + for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) { + Pedestrian* p = sub->GetPedestrian(k); + if (p->GetID() == pedID) { + return p; + } + } + } + } + return NULL; } -int Building::GetNumberOfPedestrians() const { - int sum = 0; - for (unsigned int wa = 0; wa < _rooms.size(); wa++) { - sum += _rooms[wa]->GetNumberOfPedestrians(); - } - return sum; +int Building::GetNumberOfPedestrians() const +{ + int sum = 0; + for (unsigned int wa = 0; wa < _rooms.size(); wa++) { + sum += _rooms[wa]->GetNumberOfPedestrians(); + } + return sum; } // FIXME: you should get rid of this method diff --git a/src/geometry/Building.h b/src/geometry/Building.h index 514f48618603c97180a06bf27cbeec03a5e9e93d..c7ba1bba78e0167a23a535c9a551a4337efe5cbd 100644 --- a/src/geometry/Building.h +++ b/src/geometry/Building.h @@ -160,36 +160,36 @@ public: void AddSurroundingRoom(); // add a final room (outside or world), that encompasses the complete geometry void DumpSubRoomInRoom(int roomID, int subID); - const std::map<int, Crossing*>& GetAllCrossings() const; - const std::map<int, Transition*>& GetAllTransitions() const; - const std::map<int, Hline*>& GetAllHlines() const; - const std::map<int, Goal*>& GetAllGoals() const; - - void AddCrossing(Crossing* line); - void AddTransition(Transition* line); - void AddHline(Hline* line); - void AddGoal(Goal* goal); - - const std::string& GetProjectRootDir() const; - const std::string& GetProjectFilename() const; - void SetProjectFilename(const std::string &filename) ; - void SetProjectRootDir(const std::string &filename); + const std::map<int, Crossing*>& GetAllCrossings() const; + const std::map<int, Transition*>& GetAllTransitions() const; + const std::map<int, Hline*>& GetAllHlines() const; + const std::map<int, Goal*>& GetAllGoals() const; + + void AddCrossing(Crossing* line); + void AddTransition(Transition* line); + void AddHline(Hline* line); + void AddGoal(Goal* goal); + + const std::string& GetProjectRootDir() const; + const std::string& GetProjectFilename() const; + void SetProjectFilename(const std::string &filename) ; + void SetProjectRootDir(const std::string &filename); bool LoadBuildingFromFile(const std::string &filename=""); void LoadTrafficInfo(); void LoadRoutingInfo(const std::string &filename); void WriteToErrorLog() const; - void CleanUpTheScene(); + void CleanUpTheScene(); - /** - * Check the scenario for possible errors and - * output user specific informations. - */ - void SanityCheck(); + /** + * Check the scenario for possible errors and + * output user specific informations. + */ + void SanityCheck(); private: - void StringExplode(std::string str, std::string separator, std::vector<std::string>* results); + void StringExplode(std::string str, std::string separator, std::vector<std::string>* results); }; diff --git a/src/geometry/Crossing.cpp b/src/geometry/Crossing.cpp index d96317bd9723f61dc4a6ab05b4097b19d3b1d6b0..08f238d7e1e690fa91556f243217e11ac42c8838 100644 --- a/src/geometry/Crossing.cpp +++ b/src/geometry/Crossing.cpp @@ -35,80 +35,97 @@ using namespace std; -Crossing::Crossing(){ +Crossing::Crossing() +{ _id = -1; _room1 = NULL; _subRoom1 = NULL; _subRoom2 = NULL; - _caption = ""; + _caption = ""; } -Crossing::~Crossing() { +Crossing::~Crossing() +{ } -void Crossing::SetID(int ID) { +void Crossing::SetID(int ID) +{ _id = ID; } -void Crossing::SetRoom1(Room* r) { +void Crossing::SetRoom1(Room* r) +{ _room1 = r; } -void Crossing::SetSubRoom1(SubRoom* r1) { +void Crossing::SetSubRoom1(SubRoom* r1) +{ _subRoom1 = r1; } -void Crossing::SetSubRoom2(SubRoom* r2) { +void Crossing::SetSubRoom2(SubRoom* r2) +{ _subRoom2 = r2; } -void Crossing::SetCaption(string s) { - _caption = s; +void Crossing::SetCaption(string s) +{ + _caption = s; } // Getter-Funktionen -int Crossing::GetID() const { +int Crossing::GetID() const +{ return _id; } -string Crossing::GetCaption() const { - return _caption; +string Crossing::GetCaption() const +{ + return _caption; } -Room* Crossing::GetRoom1() const { +Room* Crossing::GetRoom1() const +{ return _room1; } -SubRoom* Crossing::GetSubRoom1() const { +SubRoom* Crossing::GetSubRoom1() const +{ return _subRoom1; } -SubRoom* Crossing::GetSubRoom2() const { +SubRoom* Crossing::GetSubRoom2() const +{ return _subRoom2; } // Sonstiges -bool Crossing::IsExit() const { +bool Crossing::IsExit() const +{ return false; } -bool Crossing::IsOpen() const { +bool Crossing::IsOpen() const +{ return true; } -bool Crossing::IsTransition() const { - return false; +bool Crossing::IsTransition() const +{ + return false; } -bool Crossing::IsInRoom(int roomID) const { +bool Crossing::IsInRoom(int roomID) const +{ return _room1->GetID() == roomID; } -bool Crossing::IsInSubRoom(int subroomID) const { +bool Crossing::IsInSubRoom(int subroomID) const +{ bool r1, r2; if (_subRoom1 != NULL) r1 = _subRoom1->GetSubRoomID() == subroomID; @@ -124,22 +141,24 @@ bool Crossing::IsInSubRoom(int subroomID) const { /* gibt den ANDEREN Subroom != subroomID zurück * roomID wird hier nicht benötigt, aber in Transition::GetOtherSubRoom() * (virtuelle Funktion) */ -SubRoom* Crossing::GetOtherSubRoom(int roomID, int subroomID) const { +SubRoom* Crossing::GetOtherSubRoom(int roomID, int subroomID) const +{ if (_subRoom1->GetSubRoomID() == subroomID) return _subRoom2; else if (_subRoom2->GetSubRoomID() == subroomID) return _subRoom1; else { - Log->Write("WARMING: \tCrossing::GetOtherSubRoom No exit found " - "on the other side\n ID=%hd, roomID=%hd, subroomID=%hd\n",GetID(),roomID,subroomID); - return NULL; + Log->Write("WARMING: \tCrossing::GetOtherSubRoom No exit found " + "on the other side\n ID=%hd, roomID=%hd, subroomID=%hd\n",GetID(),roomID,subroomID); + return NULL; } } // Ausgabe -void Crossing::WriteToErrorLog() const { +void Crossing::WriteToErrorLog() const +{ string s; char tmp[CLENGTH]; sprintf(tmp, "\t\tCROSS: %d (%f, %f) -- (%f, %f)\n", GetID(), GetPoint1().GetX(), @@ -153,8 +172,9 @@ void Crossing::WriteToErrorLog() const { // TraVisTo Ausgabe -string Crossing::WriteElement() const { - //return ""; +string Crossing::WriteElement() const +{ + //return ""; string geometry; char tmp[CLENGTH] = ""; sprintf(tmp,"\t\t<door ID=\"%d\" color = \"250\" caption=\"%d_%d\">\n",GetUniqueID(),GetID(),GetUniqueID()); diff --git a/src/geometry/Crossing.h b/src/geometry/Crossing.h index 55db521010604961457bab08714e4a265a9887e8..1d90365400aa4e5923f6f26fb0447c2d6bf6affe 100644 --- a/src/geometry/Crossing.h +++ b/src/geometry/Crossing.h @@ -38,8 +38,8 @@ class SubRoom; class Crossing : public NavLine { private: /// ? unique between crossings and transitions ? - int _id; - /// only one room needed, since a crossing only separates 2 subrooms + int _id; + /// only one room needed, since a crossing only separates 2 subrooms Room* _room1; std::string _caption; SubRoom* _subRoom1; diff --git a/src/geometry/FacilityGeometry.cpp b/src/geometry/FacilityGeometry.cpp index 853e2a2080f271657110f83540ddb97b0bf9a370..f62a37b64a5aa5d2919c4d8f794dad045ac848eb 100644 --- a/src/geometry/FacilityGeometry.cpp +++ b/src/geometry/FacilityGeometry.cpp @@ -68,7 +68,8 @@ using namespace std; vtkSmartPointer<type> name = vtkSmartPointer<type>::New() -FacilityGeometry::FacilityGeometry() { +FacilityGeometry::FacilityGeometry() +{ assembly = vtkAssembly::New(); assembly2D = vtkAssembly::New(); @@ -105,7 +106,8 @@ FacilityGeometry::FacilityGeometry() { navlineColor=95; } -FacilityGeometry::~FacilityGeometry() { +FacilityGeometry::~FacilityGeometry() +{ if(assembly) assembly->Delete(); @@ -197,7 +199,8 @@ void FacilityGeometry::CreateActors() * This is the main build method and should be called by all functions * drawing a wall or a door. Important */ -void FacilityGeometry::addNewElement(double center[3], double length, double orientation, ELEMENT_TYPE type){ +void FacilityGeometry::addNewElement(double center[3], double length, double orientation, ELEMENT_TYPE type) +{ vtkCubeSource* src = vtkCubeSource::New(); src->SetCenter(center[0],center[1],center[2]); @@ -220,10 +223,8 @@ void FacilityGeometry::addNewElement(double center[3], double length, double ori // actor->GetPosition(data); // actor->SetPosition(data[0],data[1],src->GetZLength()/2); - switch (type) - { - case DOOR: - { + switch (type) { + case DOOR: { double colorRGB[3]; lookupTable->GetColor(doorColor, colorRGB); actor->GetProperty()->SetColor(colorRGB); @@ -233,9 +234,8 @@ void FacilityGeometry::addNewElement(double center[3], double length, double ori actor->GetProperty()->SetOpacity(0.5); assemblyDoors3D->AddPart(actor); } - break; - case WALL: - { + break; + case WALL: { double colorRGB[3]; lookupTable->GetColor(wallColor, colorRGB); actor->GetProperty()->SetColor(colorRGB); @@ -248,9 +248,8 @@ void FacilityGeometry::addNewElement(double center[3], double length, double ori //src->SetRadius(wallWidth); assemblyWalls3D->AddPart(actor); } - break; - case STEP: - { + break; + case STEP: { double colorRGB[3]; lookupTable->GetColor(stepColor, colorRGB); actor->GetProperty()->SetColor(colorRGB); @@ -258,9 +257,9 @@ void FacilityGeometry::addNewElement(double center[3], double length, double ori src->SetZLength(stepHeight); assemblyDoors3D->AddPart(actor); } - break; + break; - //default behaviour not defined + //default behaviour not defined default: break; } @@ -272,14 +271,15 @@ void FacilityGeometry::addNewElement(double center[3], double length, double ori actor->Delete(); } -void FacilityGeometry::addWall(double x1, double y1, double z1, double x2, double y2, double z2,double thickness,double height,double color){ +void FacilityGeometry::addWall(double x1, double y1, double z1, double x2, double y2, double z2,double thickness,double height,double color) +{ // all walls will have this parameters until changed wallColor=color; // if(SystemSettings::get2D()){ - double m[]={x1,y1,z1}; - double n[]={x2,y2,z2}; + double m[]= {x1,y1,z1}; + double n[]= {x2,y2,z2}; linesPlotter2D->PlotWall(m,n,wallColor/255.0); @@ -296,14 +296,15 @@ void FacilityGeometry::addWall(double x1, double y1, double z1, double x2, doubl delete center; } -void FacilityGeometry::addStair(double x1, double y1, double z1, double x2, double y2, double z2,double thickness,double height,double color){ +void FacilityGeometry::addStair(double x1, double y1, double z1, double x2, double y2, double z2,double thickness,double height,double color) +{ // all walls will have this parameters until changed wallColor=color; // if(SystemSettings::get2D()){ - double m[]={x1,y1,z1}; - double n[]={x2,y2,z2}; + double m[]= {x1,y1,z1}; + double n[]= {x2,y2,z2}; linesPlotter2D->PlotWall(m,n,wallColor/255.0); @@ -320,14 +321,15 @@ void FacilityGeometry::addStair(double x1, double y1, double z1, double x2, doub // delete center; } -void FacilityGeometry::addDoor(double x1, double y1, double z1, double x2, double y2, double z2,double thickness ,double height, double color){ +void FacilityGeometry::addDoor(double x1, double y1, double z1, double x2, double y2, double z2,double thickness ,double height, double color) +{ // all doors will take this color upon changed doorColor=color; //constructing the 2D assembly // if(SystemSettings::get2D()){ - double m[]={x1,y1,z1}; - double n[]={x2,y2,z2}; + double m[]= {x1,y1,z1}; + double n[]= {x2,y2,z2}; linesPlotter2D->PlotDoor(m,n,doorColor/255.0); @@ -344,14 +346,15 @@ void FacilityGeometry::addDoor(double x1, double y1, double z1, double x2, doubl delete center; } -void FacilityGeometry::addNavLine(double x1, double y1, double z1, double x2, double y2, double z2,double thickness ,double height, double color){ +void FacilityGeometry::addNavLine(double x1, double y1, double z1, double x2, double y2, double z2,double thickness ,double height, double color) +{ // all doors will take this color upon changed navlineColor=color; //constructing the 2D assembly // if(SystemSettings::get2D()){ - double m[]={x1,y1,z1}; - double n[]={x2,y2,z2}; + double m[]= {x1,y1,z1}; + double n[]= {x2,y2,z2}; linesPlotter2D->PlotNavLine(m,n,navlineColor/255.0); @@ -370,8 +373,8 @@ void FacilityGeometry::addNavLine(double x1, double y1, double z1, double x2, do void FacilityGeometry::addStep(double x1, double y1, double z1, double x2, double y2, double z2) { - double m[]={x1,y1,z1}; - double n[]={x2,y2,z2}; + double m[]= {x1,y1,z1}; + double n[]= {x2,y2,z2}; linesPlotter2D->PlotDoor(m,n,doorColor/255.0); JPoint *p1 = new JPoint(x1,y1,z1); @@ -387,7 +390,8 @@ void FacilityGeometry::addStep(double x1, double y1, double z1, double x2, doubl delete center; } -void FacilityGeometry::addStep(JPoint* p1, JPoint* p2){ +void FacilityGeometry::addStep(JPoint* p1, JPoint* p2) +{ double m[3]; double n[3]; @@ -409,7 +413,8 @@ void FacilityGeometry::addStep(JPoint* p1, JPoint* p2){ } -void FacilityGeometry::addWall(JPoint* p1, JPoint* p2, string caption){ +void FacilityGeometry::addWall(JPoint* p1, JPoint* p2, string caption) +{ double m[3]; double n[3]; double CHT[3]; @@ -422,13 +427,13 @@ void FacilityGeometry::addWall(JPoint* p1, JPoint* p2, string caption){ wallColor = CHT[0]; linesPlotter2D->PlotWall(m,n,wallColor/255.0); - if (caption.compare("") != 0){ + if (caption.compare("") != 0) { double center[3]; center[0]=0.5*(m[0]+n[0]); center[1]=0.5*(m[1]+n[1]); center[2]=0.5*(m[2]+n[2]); - double orientation[3]={0,0,0}; + double orientation[3]= {0,0,0}; addNewElementText(center,orientation,caption.c_str(),50); } @@ -438,7 +443,8 @@ void FacilityGeometry::addWall(JPoint* p1, JPoint* p2, string caption){ addNewElement( center, length, angle, WALL); } -void FacilityGeometry::addStair(JPoint* p1, JPoint* p2, string caption){ +void FacilityGeometry::addStair(JPoint* p1, JPoint* p2, string caption) +{ double m[3]; double n[3]; double CHT[3]; @@ -451,13 +457,13 @@ void FacilityGeometry::addStair(JPoint* p1, JPoint* p2, string caption){ wallColor = CHT[0]; linesPlotter2D->PlotWall(m,n,wallColor/255.0); - if (caption.compare("") != 0){ + if (caption.compare("") != 0) { double center[3]; center[0]=0.5*(m[0]+n[0]); center[1]=0.5*(m[1]+n[1]); center[2]=0.5*(m[2]+n[2]); - double orientation[3]={0,0,0}; + double orientation[3]= {0,0,0}; addNewElementText(center,orientation,caption.c_str(),50); } @@ -467,7 +473,8 @@ void FacilityGeometry::addStair(JPoint* p1, JPoint* p2, string caption){ // addNewElement( center, length, angle, WALL); } -void FacilityGeometry::addDoor(JPoint* p1, JPoint* p2, string caption){ +void FacilityGeometry::addDoor(JPoint* p1, JPoint* p2, string caption) +{ double m[3]; double n[3]; @@ -486,13 +493,13 @@ void FacilityGeometry::addDoor(JPoint* p1, JPoint* p2, string caption){ linesPlotter2D->PlotDoor(m,n,doorColor/255.0); - if (caption.compare("") != 0){ + if (caption.compare("") != 0) { double center[3]; center[0]=0.5*(m[0]+n[0]); center[1]=0.5*(m[1]+n[1]); center[2]=0.5*(m[2]+n[2]); - double orientation[3]={0,0,0}; + double orientation[3]= {0,0,0}; addNewElementText(center,orientation,caption.c_str(),0); } @@ -502,7 +509,8 @@ void FacilityGeometry::addDoor(JPoint* p1, JPoint* p2, string caption){ addNewElement( center, length, angle, DOOR); } -void FacilityGeometry::addNavLine(JPoint* p1, JPoint* p2, string caption){ +void FacilityGeometry::addNavLine(JPoint* p1, JPoint* p2, string caption) +{ double m[3]; double n[3]; @@ -521,13 +529,13 @@ void FacilityGeometry::addNavLine(JPoint* p1, JPoint* p2, string caption){ linesPlotter2D->PlotNavLine(m,n,doorColor/255.0); - if (caption.compare("") != 0){ + if (caption.compare("") != 0) { double center[3]; center[0]=0.5*(m[0]+n[0]); center[1]=0.5*(m[1]+n[1]); center[2]=0.5*(m[2]+n[2]); - double orientation[3]={0,0,0}; + double orientation[3]= {0,0,0}; addNewElementText(center,orientation,caption.c_str(),0); } } @@ -557,7 +565,8 @@ void FacilityGeometry::addFloor(vtkPolyData* polygonPolyData ) } -void FacilityGeometry::addFloor(double x1, double y1, double x2, double y2, double z){ +void FacilityGeometry::addFloor(double x1, double y1, double x2, double y2, double z) +{ //if(z!=1)return; const double cellSize=40; //cm // const int dimX=(x2-x1)/cellSize+1; @@ -571,19 +580,19 @@ void FacilityGeometry::addFloor(double x1, double y1, double x2, double y2, doub vtkDataArray* pData = vtkUnsignedCharArray::New(); pData->SetNumberOfComponents(3); - double color[2][3]={{100, 100, 100},{150,150,150}}; + double color[2][3]= {{100, 100, 100},{150,150,150}}; bool idx=0; bool lastColorUsed=0; - for(int i=0;i<dimY-1;i++){ + for(int i=0; i<dimY-1; i++) { - if(idx==lastColorUsed){ + if(idx==lastColorUsed) { lastColorUsed= !lastColorUsed; idx=lastColorUsed; - }else{ + } else { lastColorUsed=idx; } - for(int j=0;j<dimX-1;j++){ + for(int j=0; j<dimX-1; j++) { pData->InsertNextTuple3(color[idx][0],color[idx][1],color[idx][2]); idx=!idx; } @@ -618,7 +627,8 @@ void FacilityGeometry::addFloor(double x1, double y1, double x2, double y2, doub void FacilityGeometry::addObjectSphere(double center[3], double radius, -double color) { + double color) +{ double colorRGB[3]; lookupTable->GetColor(color, colorRGB); @@ -644,7 +654,8 @@ double color) { void FacilityGeometry::addObjectCylinder(double center[3], double radius, -double height, double orientation[3],double color) { + double height, double orientation[3],double color) +{ double colorRGB[3]; lookupTable->GetColor(color, colorRGB); @@ -670,7 +681,8 @@ double height, double orientation[3],double color) { } void FacilityGeometry::addObjectBox(double center[3], double height, -double width, double length, double color) { + double width, double length, double color) +{ double colorRGB[3]; lookupTable->GetColor(color, colorRGB); @@ -707,7 +719,7 @@ void FacilityGeometry::changeWallsColor(double* color) assemblyWalls3D->GetActors(col); int count = col->GetNumberOfItems(); - for (int i=0;i<count;i++){ + for (int i=0; i<count; i++) { ((vtkActor*)col->GetItemAsObject(i))->GetProperty()->SetColor(color); } assemblyWalls3D->Modified(); @@ -724,7 +736,7 @@ void FacilityGeometry::changeExitsColor(double* color) assemblyDoors3D->GetActors(col); int count = col->GetNumberOfItems(); - for (int i=0;i<count;i++){ + for (int i=0; i<count; i++) { ((vtkActor*)col->GetItemAsObject(i))->GetProperty()->SetColor(color); } assemblyDoors3D->Modified(); @@ -743,16 +755,19 @@ void FacilityGeometry::changeFloorColor(double *color) floorActor->GetProperty()->SetColor(color); } -void FacilityGeometry::set2D(bool status){ +void FacilityGeometry::set2D(bool status) +{ assembly2D->SetVisibility(status); } -void FacilityGeometry::set3D(bool status){ +void FacilityGeometry::set3D(bool status) +{ if(assembly3D!=NULL) assembly3D->SetVisibility(status); } -void FacilityGeometry::showDoors(bool status){ +void FacilityGeometry::showDoors(bool status) +{ linesPlotter2D->showDoors(status); assembly2D->Modified(); @@ -761,7 +776,7 @@ void FacilityGeometry::showDoors(bool status){ assemblyDoors3D->GetActors(col); int count = col->GetNumberOfItems(); - for (int i=0;i<count;i++){ + for (int i=0; i<count; i++) { ((vtkActor*)col->GetItemAsObject(i))->SetVisibility(status); } assemblyDoors3D->Modified(); @@ -781,7 +796,7 @@ void FacilityGeometry::showWalls(bool status) assemblyWalls3D->GetActors(col); int count = col->GetNumberOfItems(); - for (int i=0;i<count;i++){ + for (int i=0; i<count; i++) { ((vtkActor*)col->GetItemAsObject(i))->SetVisibility(status); } assemblyWalls3D->Modified(); @@ -797,18 +812,21 @@ void FacilityGeometry::showFloor(bool status) floorActor->SetVisibility(status); } -void FacilityGeometry::addObjectLabel(double center[3], double orientation[3], std::string caption, double color){ +void FacilityGeometry::addObjectLabel(double center[3], double orientation[3], std::string caption, double color) +{ addNewElementText(center, orientation, caption, color); } -vtkActor2DCollection* FacilityGeometry::getCaptions(){ +vtkActor2DCollection* FacilityGeometry::getCaptions() +{ return captions; } // orientation and color ignored void FacilityGeometry::addNewElementText(double center[3], double orientation[3], -string text, double color) { + string text, double color) +{ //return ; @@ -836,13 +854,14 @@ string text, double color) { } -void FacilityGeometry::showGeometryLabels(int status){ +void FacilityGeometry::showGeometryLabels(int status) +{ vtkProp3DCollection* col=assemblyCaptions->GetParts(); assemblyCaptions->GetActors(col); int count = col->GetNumberOfItems(); - for (int i=0;i<count;i++){ + for (int i=0; i<count; i++) { ((vtkActor*)col->GetItemAsObject(i))->SetVisibility(status); } assemblyCaptions->Modified(); diff --git a/src/geometry/FacilityGeometry.h b/src/geometry/FacilityGeometry.h index 37d5db7048084ed8de8951bd9f322630c2b64d56..0553a10e275dfc52c7f7048903f16c6f9c70e68f 100644 --- a/src/geometry/FacilityGeometry.h +++ b/src/geometry/FacilityGeometry.h @@ -45,26 +45,26 @@ class vtkLookupTable; class LinePlotter2D; class vtkActor2DCollection; -class FacilityGeometry{ +class FacilityGeometry { public: - /** - * Building element types that are actually supported - */ - enum ELEMENT_TYPE{ - DOOR, //!< DOOR defined by two coordinates points are needed. - STEP, //!< STEP @todo not fully implemented - WALL, //!< WALL defined by two coordinates points are needed. - SPHERE, //!< SPHERE defined by centre[x,y,z] and radius. - CONE, //!< CONE defined by centre, radius and height - CYLINDER,//!< CYLINDER defined by centre ,radius and height - BOX //!< BOX defined by centre, length, width and height - }; - - FacilityGeometry(); - virtual ~FacilityGeometry(); + /** + * Building element types that are actually supported + */ + enum ELEMENT_TYPE { + DOOR, //!< DOOR defined by two coordinates points are needed. + STEP, //!< STEP @todo not fully implemented + WALL, //!< WALL defined by two coordinates points are needed. + SPHERE, //!< SPHERE defined by centre[x,y,z] and radius. + CONE, //!< CONE defined by centre, radius and height + CYLINDER,//!< CYLINDER defined by centre ,radius and height + BOX //!< BOX defined by centre, length, width and height + }; + + FacilityGeometry(); + virtual ~FacilityGeometry(); vtkAssembly* getActor2D(); @@ -72,14 +72,14 @@ public: vtkAssembly* getCaptionsActor(); - vtkActor2DCollection* getCaptions(); + vtkActor2DCollection* getCaptions(); void CreateActors(); - ///draw a wall - void addWall(double x1, double y1, double z1, double x2, double y2, double z2, double thickness=15, double height=250,double col=255); - //void addWall(double center[3], double width, double orientation); - void addWall(JPoint* p1, JPoint* p2, std::string caption=""); + ///draw a wall + void addWall(double x1, double y1, double z1, double x2, double y2, double z2, double thickness=15, double height=250,double col=255); + //void addWall(double center[3], double width, double orientation); + void addWall(JPoint* p1, JPoint* p2, std::string caption=""); ///draw a stair void addStair(double x1, double y1, double z1, double x2, double y2, double z2, double thickness=15, double height=250,double col=255); @@ -87,74 +87,74 @@ public: void addStair(JPoint* p1, JPoint* p2, std::string caption=""); - ///draw a door - void addDoor(double x1, double y1, double z1 ,double x2, double y2, double z2, double thickness=17, double height=250,double col=30); - //void addDoor(double center[3], double width, double orientation); - void addDoor(JPoint* p1, JPoint* p2, std::string caption=""); + ///draw a door + void addDoor(double x1, double y1, double z1 ,double x2, double y2, double z2, double thickness=17, double height=250,double col=30); + //void addDoor(double center[3], double width, double orientation); + void addDoor(JPoint* p1, JPoint* p2, std::string caption=""); - ///draw a step - ///todo: implement thickness and color - void addStep(double x1, double y1, double z1, double x2, double y2, double z2=0/*, double thickness=30, double height=10,double col=50*/); - //void addStep(double center[3], double width, double orientation); - void addStep(JPoint* p1, JPoint* p2); + ///draw a step + ///todo: implement thickness and color + void addStep(double x1, double y1, double z1, double x2, double y2, double z2=0/*, double thickness=30, double height=10,double col=50*/); + //void addStep(double center[3], double width, double orientation); + void addStep(JPoint* p1, JPoint* p2); /// draw a navigation line void addNavLine(double x1, double y1, double z1, double x2, double y2, double z2, double thickness=2, double height=250, double color=95); void addNavLine(JPoint* p1, JPoint* p2, std::string caption=""); /// draw a floor, divided in cells, - void addFloor(double x1, double y1, double x2, double y2, double z=0); + void addFloor(double x1, double y1, double x2, double y2, double z=0); void addFloor(vtkPolyData* polygonPolyData); - /// draw other kinds of objects - void addObjectSphere(double center[3], double radius, double couleur=1); - void addObjectCone(double center[3], double height, double radius, double couleur=2); - void addObjectCylinder(double center[3],double radius, double height,double orientation[3], double couleur =3); - void addObjectBox(double center[3],double height, double width, double length, double couleur =4); - void addObjectLabel(double center[3], double orientation[3], std::string caption, double color); + /// draw other kinds of objects + void addObjectSphere(double center[3], double radius, double couleur=1); + void addObjectCone(double center[3], double height, double radius, double couleur=2); + void addObjectCylinder(double center[3],double radius, double height,double orientation[3], double couleur =3); + void addObjectBox(double center[3],double height, double width, double length, double couleur =4); + void addObjectLabel(double center[3], double orientation[3], std::string caption, double color); - void changeWallsColor(double* color); - void changeExitsColor(double* color); + void changeWallsColor(double* color); + void changeExitsColor(double* color); void changeNavLinesColor(double* color); void changeFloorColor(double* color); - void set2D(bool status); - void set3D(bool status); + void set2D(bool status); + void set3D(bool status); - void showDoors(bool status); - void showStairs(bool status); - void showWalls(bool status); + void showDoors(bool status); + void showStairs(bool status); + void showWalls(bool status); void showNavLines(bool status); void showFloor(bool status); void showGeometryLabels(int status); private: - // TODO Check if this function is really necessary - //vtkActor* MapToActor(vtkDataSet *ds); //for drawing floor - vtkLookupTable* lookupTable; - void drawWall(JPoint* p1, JPoint* p2); - void drawDoor(JPoint* p1, JPoint* p2); - void addNewElement(double center[3], double orientation, double width, ELEMENT_TYPE type); - void addNewElementText(double center[3], double orientation[3], std::string text, double color); - - // geometry parameters - double doorThickness ; - double wallThickness ; - double wallHeight; - double doorHeight; - double stepHeight; - double wallColor; - double stepColor; - double doorColor; + // TODO Check if this function is really necessary + //vtkActor* MapToActor(vtkDataSet *ds); //for drawing floor + vtkLookupTable* lookupTable; + void drawWall(JPoint* p1, JPoint* p2); + void drawDoor(JPoint* p1, JPoint* p2); + void addNewElement(double center[3], double orientation, double width, ELEMENT_TYPE type); + void addNewElementText(double center[3], double orientation[3], std::string text, double color); + + // geometry parameters + double doorThickness ; + double wallThickness ; + double wallHeight; + double doorHeight; + double stepHeight; + double wallColor; + double stepColor; + double doorColor; double navlineColor; - // geometry assembly - vtkAssembly* assembly; + // geometry assembly + vtkAssembly* assembly; - //2-d parts - LinePlotter2D* linesPlotter2D; - vtkAssembly* assembly2D; + //2-d parts + LinePlotter2D* linesPlotter2D; + vtkAssembly* assembly2D; // 3-d parts //vtkAssembly* assemblyObjects; @@ -164,9 +164,9 @@ private: vtkActor* floorActor; - // other parts - vtkAssembly* assemblyCaptions; - vtkActor2DCollection* captions; + // other parts + vtkAssembly* assemblyCaptions; + vtkActor2DCollection* captions; }; #endif /* FACILITYGEOMETRY_H_ */ diff --git a/src/geometry/Goal.cpp b/src/geometry/Goal.cpp index 54aecafd0ea8f215f8d5745c798b95456d6b1892..e62d5397d8aa37b000dbe25c8820607634f3839d 100644 --- a/src/geometry/Goal.cpp +++ b/src/geometry/Goal.cpp @@ -34,187 +34,205 @@ using namespace std; -Goal::Goal() { - _id=-1; - _caption="Goal"; - _isFinalGoal=0; - _walls = vector<Wall > (); - _poly = vector<Point > (); +Goal::Goal() +{ + _id=-1; + _caption="Goal"; + _isFinalGoal=0; + _walls = vector<Wall > (); + _poly = vector<Point > (); } -Goal::~Goal() { +Goal::~Goal() +{ } -void Goal::AddWall(const Wall& w) { - _walls.push_back(w); +void Goal::AddWall(const Wall& w) +{ + _walls.push_back(w); } -string Goal::GetCaption() const { - return _caption; +string Goal::GetCaption() const +{ + return _caption; } -void Goal::SetCaption(string caption) { - _caption = caption; +void Goal::SetCaption(string caption) +{ + _caption = caption; } -int Goal::GetId() const { - return _id; +int Goal::GetId() const +{ + return _id; } -void Goal::SetId(int id) { - _id = id; +void Goal::SetId(int id) +{ + _id = id; } -const vector<Point>& Goal::GetPolygon() const { - return _poly; +const vector<Point>& Goal::GetPolygon() const +{ + return _poly; } -string Goal::Write() { - string s; - Point pos; - - for (unsigned int j = 0; j < _walls.size(); j++) { - const Wall& w = _walls[j]; - s.append(w.Write()); - pos = pos + w.GetPoint1() + w.GetPoint2(); - } - pos = pos * (0.5 / _walls.size()); - - // add some fancy stuffs - if(_poly.size()>=4){ - s.append(Wall(_poly[0],_poly[2]).Write()); - s.append(Wall(_poly[1],_poly[3]).Write()); - } - //add the Goal caption - char tmp[CLENGTH]; - sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%s\" color=\"100\" />\n" - , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, _caption.c_str()); - s.append(tmp); - - return s; +string Goal::Write() +{ + string s; + Point pos; + + for (unsigned int j = 0; j < _walls.size(); j++) { + const Wall& w = _walls[j]; + s.append(w.Write()); + pos = pos + w.GetPoint1() + w.GetPoint2(); + } + pos = pos * (0.5 / _walls.size()); + + // add some fancy stuffs + if(_poly.size()>=4) { + s.append(Wall(_poly[0],_poly[2]).Write()); + s.append(Wall(_poly[1],_poly[3]).Write()); + } + //add the Goal caption + char tmp[CLENGTH]; + sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%s\" color=\"100\" />\n" + , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, _caption.c_str()); + s.append(tmp); + + return s; } -const vector<Wall>& Goal::GetAllWalls() const { - return _walls; +const vector<Wall>& Goal::GetAllWalls() const +{ + return _walls; } -int Goal::WhichQuad(const Point& vertex, const Point& hitPos) const { - return (vertex.GetX() > hitPos.GetX()) ? ((vertex.GetY() > hitPos.GetY()) ? 1 : 4) : - ((vertex.GetY() > hitPos.GetY()) ? 2 : 3); +int Goal::WhichQuad(const Point& vertex, const Point& hitPos) const +{ + return (vertex.GetX() > hitPos.GetX()) ? ((vertex.GetY() > hitPos.GetY()) ? 1 : 4) : + ((vertex.GetY() > hitPos.GetY()) ? 2 : 3); } -int Goal::GetIsFinalGoal() const { - return _isFinalGoal; +int Goal::GetIsFinalGoal() const +{ + return _isFinalGoal; } -void Goal::SetIsFinalGoal(int isFinalGoal) { - _isFinalGoal = isFinalGoal; +void Goal::SetIsFinalGoal(int isFinalGoal) +{ + _isFinalGoal = isFinalGoal; } // x-Koordinate der Linie von einer Eccke zur nächsten -double Goal::Xintercept(const Point& point1, const Point& point2, double hitY) const { - return (point2.GetX() - (((point2.GetY() - hitY) * (point1.GetX() - point2.GetX())) / - (point1.GetY() - point2.GetY()))); +double Goal::Xintercept(const Point& point1, const Point& point2, double hitY) const +{ + return (point2.GetX() - (((point2.GetY() - hitY) * (point1.GetX() - point2.GetX())) / + (point1.GetY() - point2.GetY()))); } -bool Goal::Contains(const Point& ped) const { - - - short edge, first, next; - short quad, next_quad, delta, total; - - ///////////////////////////////////////////////////////////// - edge = first = 0; - quad = WhichQuad(_poly[edge], ped); - total = 0; // COUNT OF ABSOLUTE SECTORS CROSSED - /* LOOP THROUGH THE VERTICES IN A SECTOR */ - do { - next = (edge + 1) % _poly.size(); - next_quad = WhichQuad(_poly[next], ped); - delta = next_quad - quad; // HOW MANY QUADS HAVE I MOVED - - // SPECIAL CASES TO HANDLE CROSSINGS OF MORE THEN ONE - //QUAD - - switch (delta) { - case 2: // IF WE CROSSED THE MIDDLE, FIGURE OUT IF IT - //WAS CLOCKWISE OR COUNTER - case -2: // US THE X POSITION AT THE HIT POINT TO - // DETERMINE WHICH WAY AROUND - if (Xintercept(_poly[edge], _poly[next], ped.GetY()) > ped.GetX()) - delta = -(delta); - break; - case 3: // MOVING 3 QUADS IS LIKE MOVING BACK 1 - delta = -1; - break; - case -3: // MOVING BACK 3 IS LIKE MOVING FORWARD 1 - delta = 1; - break; - } - /* ADD IN THE DELTA */ - total += delta; - quad = next_quad; // RESET FOR NEXT STEP - edge = next; - } while (edge != first); - - /* AFTER ALL IS DONE IF THE TOTAL IS 4 THEN WE ARE INSIDE */ - if (abs(total) == 4) - return true; - else - return false; +bool Goal::Contains(const Point& ped) const +{ + + + short edge, first, next; + short quad, next_quad, delta, total; + + ///////////////////////////////////////////////////////////// + edge = first = 0; + quad = WhichQuad(_poly[edge], ped); + total = 0; // COUNT OF ABSOLUTE SECTORS CROSSED + /* LOOP THROUGH THE VERTICES IN A SECTOR */ + do { + next = (edge + 1) % _poly.size(); + next_quad = WhichQuad(_poly[next], ped); + delta = next_quad - quad; // HOW MANY QUADS HAVE I MOVED + + // SPECIAL CASES TO HANDLE CROSSINGS OF MORE THEN ONE + //QUAD + + switch (delta) { + case 2: // IF WE CROSSED THE MIDDLE, FIGURE OUT IF IT + //WAS CLOCKWISE OR COUNTER + case -2: // US THE X POSITION AT THE HIT POINT TO + // DETERMINE WHICH WAY AROUND + if (Xintercept(_poly[edge], _poly[next], ped.GetY()) > ped.GetX()) + delta = -(delta); + break; + case 3: // MOVING 3 QUADS IS LIKE MOVING BACK 1 + delta = -1; + break; + case -3: // MOVING BACK 3 IS LIKE MOVING FORWARD 1 + delta = 1; + break; + } + /* ADD IN THE DELTA */ + total += delta; + quad = next_quad; // RESET FOR NEXT STEP + edge = next; + } while (edge != first); + + /* AFTER ALL IS DONE IF THE TOTAL IS 4 THEN WE ARE INSIDE */ + if (abs(total) == 4) + return true; + else + return false; } -void Goal::ConvertLineToPoly() { - - vector<Line*> copy; - vector<Point> tmpPoly; - Point point; - Line* line; - // Alle Linienelemente in copy speichern - for (unsigned int i = 0; i < _walls.size(); i++) { - copy.push_back(&_walls[i]); - } - - line = copy[0]; - tmpPoly.push_back(line->GetPoint1()); - point = line->GetPoint2(); - copy.erase(copy.begin()); - // Polygon aus allen Linen erzeugen - for (int i = 0; i < (int) copy.size(); i++) { - line = copy[i]; - if ((point - line->GetPoint1()).Norm() < J_TOLERANZ) { - tmpPoly.push_back(line->GetPoint1()); - point = line->GetPoint2(); - copy.erase(copy.begin() + i); - // von vorne suchen - i = -1; - } else if ((point - line->GetPoint2()).Norm() < J_TOLERANZ) { - tmpPoly.push_back(line->GetPoint2()); - point = line->GetPoint1(); - copy.erase(copy.begin() + i); - // von vorne suchen - i = -1; - } - } - if ((tmpPoly[0] - point).Norm() > J_TOLERANZ) { - char tmp[CLENGTH]; - sprintf(tmp, "ERROR: \tGoal::ConvertLineToPoly(): ID %d !!!\n", _id); - Log->Write(tmp); - exit(0); - } - _poly = tmpPoly; - - ComputeControid(); +void Goal::ConvertLineToPoly() +{ + + vector<Line*> copy; + vector<Point> tmpPoly; + Point point; + Line* line; + // Alle Linienelemente in copy speichern + for (unsigned int i = 0; i < _walls.size(); i++) { + copy.push_back(&_walls[i]); + } + + line = copy[0]; + tmpPoly.push_back(line->GetPoint1()); + point = line->GetPoint2(); + copy.erase(copy.begin()); + // Polygon aus allen Linen erzeugen + for (int i = 0; i < (int) copy.size(); i++) { + line = copy[i]; + if ((point - line->GetPoint1()).Norm() < J_TOLERANZ) { + tmpPoly.push_back(line->GetPoint1()); + point = line->GetPoint2(); + copy.erase(copy.begin() + i); + // von vorne suchen + i = -1; + } else if ((point - line->GetPoint2()).Norm() < J_TOLERANZ) { + tmpPoly.push_back(line->GetPoint2()); + point = line->GetPoint1(); + copy.erase(copy.begin() + i); + // von vorne suchen + i = -1; + } + } + if ((tmpPoly[0] - point).Norm() > J_TOLERANZ) { + char tmp[CLENGTH]; + sprintf(tmp, "ERROR: \tGoal::ConvertLineToPoly(): ID %d !!!\n", _id); + Log->Write(tmp); + exit(0); + } + _poly = tmpPoly; + + ComputeControid(); } -const Point& Goal::GetCentroid() const { - return _centroid; +const Point& Goal::GetCentroid() const +{ + return _centroid; } -void Goal::ComputeControid() { +void Goal::ComputeControid() +{ double px=0,py=0; double signedArea = 0.0; @@ -226,8 +244,7 @@ void Goal::ComputeControid() { // For all vertices except last unsigned int i=0; - for (i=0; i<_poly.size()-1; ++i) - { + for (i=0; i<_poly.size()-1; ++i) { x0 = _poly[i].GetX(); y0 = _poly[i].GetY(); x1 = _poly[i+1].GetX(); diff --git a/src/geometry/Goal.h b/src/geometry/Goal.h index 9efec6590455d3e9074ea56d67ce97a467e9e379..866a7eccdeca5452363d99c30f94cf00e8c2e304 100644 --- a/src/geometry/Goal.h +++ b/src/geometry/Goal.h @@ -38,95 +38,95 @@ class Wall; class Goal { private: - int _isFinalGoal; - int _id; - Point _centroid; - std::string _caption; - std::vector<Wall> _walls; - std::vector<Point> _poly; + int _isFinalGoal; + int _id; + Point _centroid; + std::string _caption; + std::vector<Wall> _walls; + std::vector<Point> _poly; public: - Goal(); - virtual ~Goal(); - - /** - * Set/Get the obstacles' caption - */ - std::string GetCaption() const; - - /** - * Set/Get the obstacles' caption - */ - void SetCaption(std::string caption); - - /** - * Set/Get the id of the Goal - */ - int GetId() const; - - /** - * Set/Get the id of the Goal - */ - void SetId(int id); - - /** - * construct the Goal by adding more walls - */ - void AddWall(const Wall& w); - - /** - * @return All walls that constitute the Goal - */ - const std::vector<Wall>& GetAllWalls() const; - - /** - * @return true if the point p is contained within the Closed Goal - */ - bool Contains(const Point& p) const; - - /** - * Create the obstacles polygonal structure from the walls - */ - void ConvertLineToPoly(); - - /** - * @return the Goal as a polygon - */ - const std::vector<Point>& GetPolygon() const; - - /** - * agents are remove from the simulation when they reached a final goal - */ - int GetIsFinalGoal() const; - - /** - * agents are remove from the simulation when they reached a final goal - */ - void SetIsFinalGoal(int isFinalGoal); - - /** - * @return the centroid of the subroom - * @see http://en.wikipedia.org/wiki/Centroid - */ - void ComputeControid() ; - - /** - * @return the centroid of the goal - * @see ComputeControid - */ - const Point& GetCentroid() const; - - /** - * @return a nicely formatted string representation of the Goal - */ - std::string Write(); + Goal(); + virtual ~Goal(); + + /** + * Set/Get the obstacles' caption + */ + std::string GetCaption() const; + + /** + * Set/Get the obstacles' caption + */ + void SetCaption(std::string caption); + + /** + * Set/Get the id of the Goal + */ + int GetId() const; + + /** + * Set/Get the id of the Goal + */ + void SetId(int id); + + /** + * construct the Goal by adding more walls + */ + void AddWall(const Wall& w); + + /** + * @return All walls that constitute the Goal + */ + const std::vector<Wall>& GetAllWalls() const; + + /** + * @return true if the point p is contained within the Closed Goal + */ + bool Contains(const Point& p) const; + + /** + * Create the obstacles polygonal structure from the walls + */ + void ConvertLineToPoly(); + + /** + * @return the Goal as a polygon + */ + const std::vector<Point>& GetPolygon() const; + + /** + * agents are remove from the simulation when they reached a final goal + */ + int GetIsFinalGoal() const; + + /** + * agents are remove from the simulation when they reached a final goal + */ + void SetIsFinalGoal(int isFinalGoal); + + /** + * @return the centroid of the subroom + * @see http://en.wikipedia.org/wiki/Centroid + */ + void ComputeControid() ; + + /** + * @return the centroid of the goal + * @see ComputeControid + */ + const Point& GetCentroid() const; + + /** + * @return a nicely formatted string representation of the Goal + */ + std::string Write(); private: - int WhichQuad(const Point& vertex, const Point& hitPos) const; + int WhichQuad(const Point& vertex, const Point& hitPos) const; - // x-Koordinate der Linie von einer Eccke zur nächsten - double Xintercept(const Point& point1, const Point& point2, - double hitY) const; + // x-Koordinate der Linie von einer Eccke zur nächsten + double Xintercept(const Point& point1, const Point& point2, + double hitY) const; }; diff --git a/src/geometry/Hline.cpp b/src/geometry/Hline.cpp index 1600a95330b770cce308705dac397560bed5e7b9..dafb48147883b0646dc6e3086e638b96e1db6a1f 100644 --- a/src/geometry/Hline.cpp +++ b/src/geometry/Hline.cpp @@ -30,56 +30,69 @@ using namespace std; -Hline::Hline() { - _room=NULL; - _subRoom=NULL; - _id=-1; +Hline::Hline() +{ + _room=NULL; + _subRoom=NULL; + _id=-1; } -Hline::~Hline() { +Hline::~Hline() +{ } -void Hline::SetID(int ID) { - _id=ID; +void Hline::SetID(int ID) +{ + _id=ID; } -void Hline::SetRoom(Room* r) { - _room=r; +void Hline::SetRoom(Room* r) +{ + _room=r; } -void Hline::SetCaption(string s) { - _caption=s; +void Hline::SetCaption(string s) +{ + _caption=s; } -void Hline::SetSubRoom(SubRoom* s) { - _subRoom=s; +void Hline::SetSubRoom(SubRoom* s) +{ + _subRoom=s; } -int Hline::GetID() const { - return _id; +int Hline::GetID() const +{ + return _id; } -string Hline::GetCaption() const { - return _caption; +string Hline::GetCaption() const +{ + return _caption; } -Room* Hline::GetRoom() const { - return _room; +Room* Hline::GetRoom() const +{ + return _room; } -SubRoom* Hline::GetSubRoom() const { - return _subRoom; +SubRoom* Hline::GetSubRoom() const +{ + return _subRoom; } -bool Hline::IsInSubRoom(int subroomID) const { - return _subRoom->GetSubRoomID() == subroomID; +bool Hline::IsInSubRoom(int subroomID) const +{ + return _subRoom->GetSubRoomID() == subroomID; } -bool Hline::IsInRoom(int roomID) const { - return _room->GetID() == roomID; +bool Hline::IsInRoom(int roomID) const +{ + return _room->GetID() == roomID; } -void Hline::WriteToErrorLog() const { +void Hline::WriteToErrorLog() const +{ string s; char tmp[CLENGTH]; sprintf(tmp, "\t\tHline: %d (%f, %f) -- (%f, %f)\n", GetID(), GetPoint1().GetX(), @@ -93,7 +106,8 @@ void Hline::WriteToErrorLog() const { // TraVisTo Ausgabe -string Hline::WriteElement() const { +string Hline::WriteElement() const +{ string geometry; char tmp[CLENGTH] = ""; sprintf(tmp,"\t\t<door ID=\"%d\" color = \"250\" caption=\"%d_%d\">\n",GetUniqueID(),GetID(),GetUniqueID()); diff --git a/src/geometry/Hline.h b/src/geometry/Hline.h index 120b7f0363069de177ea70438a543e4dc807710c..dd91ead7aec942ecd4e6723c041d530169f25706 100644 --- a/src/geometry/Hline.h +++ b/src/geometry/Hline.h @@ -39,76 +39,76 @@ class Room; class Hline: public NavLine { private: - int _id; - Room* _room; - std::string _caption; - SubRoom* _subRoom; + int _id; + Room* _room; + std::string _caption; + SubRoom* _subRoom; public: - Hline(); - virtual ~Hline(); - - /** - * Set/Get the id of the line - */ - void SetID(int ID); - - /** - * Set/Get the Room containing this line - */ - void SetRoom(Room* r); - - /** - * Set/Get the line caption - */ - void SetCaption(std::string s); - - /** - * Set/Get the subroom containing this line - */ - void SetSubRoom(SubRoom* r); - - - /** - * Set/Get the id of the line - */ - int GetID() const; - - /** - * Set/Get the line caption - */ - std::string GetCaption() const; - - /** - * Set/Get the Room containing this line - */ - Room* GetRoom() const; - - /** - * Set/Get the subroom containing this line - */ - SubRoom* GetSubRoom() const; - - - /** - * @return true if the line is in the given subroom - */ - bool IsInSubRoom(int subroomID) const; - - /** - * @return true if the line is in the given room - */ - bool IsInRoom(int roomID) const; - - /** - * Debug output - */ - void WriteToErrorLog() const; - - /** - * @return a nicely formatted string representation of the object - */ - std::string WriteElement() const; + Hline(); + virtual ~Hline(); + + /** + * Set/Get the id of the line + */ + void SetID(int ID); + + /** + * Set/Get the Room containing this line + */ + void SetRoom(Room* r); + + /** + * Set/Get the line caption + */ + void SetCaption(std::string s); + + /** + * Set/Get the subroom containing this line + */ + void SetSubRoom(SubRoom* r); + + + /** + * Set/Get the id of the line + */ + int GetID() const; + + /** + * Set/Get the line caption + */ + std::string GetCaption() const; + + /** + * Set/Get the Room containing this line + */ + Room* GetRoom() const; + + /** + * Set/Get the subroom containing this line + */ + SubRoom* GetSubRoom() const; + + + /** + * @return true if the line is in the given subroom + */ + bool IsInSubRoom(int subroomID) const; + + /** + * @return true if the line is in the given room + */ + bool IsInRoom(int roomID) const; + + /** + * Debug output + */ + void WriteToErrorLog() const; + + /** + * @return a nicely formatted string representation of the object + */ + std::string WriteElement() const; }; #endif /* HLINE_H_ */ diff --git a/src/geometry/JPoint.cpp b/src/geometry/JPoint.cpp index d7321be1a08d600fd910b54b3c174a4b501a0afa..f892dc549a72ca097a66dbf99e58d354bc1cc7d7 100644 --- a/src/geometry/JPoint.cpp +++ b/src/geometry/JPoint.cpp @@ -39,119 +39,155 @@ #include <cstdlib> #include <iostream> -JPoint::JPoint(double xyz[3], char color[]/*="abc"*/) { - x=xyz[0]; - y=xyz[1]; - z=xyz[2]; - r=color[0]; - g=color[1]; - b=color[2]; +JPoint::JPoint(double xyz[3], const char *color/*="abc"*/) +{ + x=xyz[0]; + y=xyz[1]; + z=xyz[2]; + r=color[0]; + g=color[1]; + b=color[2]; } -JPoint::JPoint(double x, double y, double z, unsigned char r/*=100*/, unsigned char g/*=100*/ , unsigned char b/*=100*/){ - this->setColorRGB(r,g, b); - this->x=x; - this->y=y; - this->z=z; +JPoint::JPoint(double x, double y, double z, unsigned char r/*=100*/, unsigned char g/*=100*/ , unsigned char b/*=100*/) +{ + this->setColorRGB(r,g, b); + this->x=x; + this->y=y; + this->z=z; } -JPoint::JPoint(){ - x=0; - y=0; - z=0;//creates a point centered at the origin +JPoint::JPoint() +{ + x=0; + y=0; + z=0;//creates a point centered at the origin } -JPoint::~JPoint() { +JPoint::~JPoint() +{ } -void JPoint::setColorRGB(unsigned char r1, unsigned char g1,unsigned char b1){ - r=r1; - g=g1; - b=b1; +void JPoint::setColorRGB(unsigned char r1, unsigned char g1,unsigned char b1) +{ + r=r1; + g=g1; + b=b1; } -void JPoint::setXYZ(double*xyz){ - x=xyz[0]; - y=xyz[1]; - z=xyz[2]; +void JPoint::setXYZ(double*xyz) +{ + x=xyz[0]; + y=xyz[1]; + z=xyz[2]; } -void JPoint::getXYZ(double*xyz){ - xyz[0]=x; - xyz[1]=y; - xyz[2]=z; +void JPoint::getXYZ(double*xyz) +{ + xyz[0]=x; + xyz[1]=y; + xyz[2]=z; } /* - * return the coordinates + * return the coordinates */ -double JPoint::getX(){return x;} -double JPoint::getY(){return y;} -double JPoint::getZ(){return z;} +double JPoint::getX() +{ + return x; +} +double JPoint::getY() +{ + return y; +} +double JPoint::getZ() +{ + return z; +} /** - * return the angle of intersection between the 2 points and the x axis + * return the angle of intersection between the 2 points and the x axis * @return the angle in degree - * FIXME: why +90?? + * FIXME: why +90?? */ -double JPoint::angleMadeWith(JPoint& pt){ - double dx=x-pt.x; - double dy=y-pt.y; - //double dist=distanceTo(pt); - - if((dx==0) && (dy==0)){ - Debug::Error("error found in geometry"); - Debug::Error("wrong angle might be returned"); - return 0; - //return vtkMath::DegreesFromRadians(asin(dx/dist)); - } - - // return vtkMath::DegreesFromRadians(asin(dx/dist)); - return vtkMath::DegreesFromRadians(atan2(dy,dx))+90 ; +double JPoint::angleMadeWith(JPoint& pt) +{ + double dx=x-pt.x; + double dy=y-pt.y; + //double dist=distanceTo(pt); + + if((dx==0) && (dy==0)) { + Debug::Error("error found in geometry"); + Debug::Error("wrong angle might be returned"); + return 0; + //return vtkMath::DegreesFromRadians(asin(dx/dist)); + } + + // return vtkMath::DegreesFromRadians(asin(dx/dist)); + return vtkMath::DegreesFromRadians(atan2(dy,dx))+90 ; } -double JPoint::distanceTo(JPoint& pt){ - double dx=x-pt.x; dx*=dx; - double dy=y-pt.y; dy*=dy; - double dz=z-pt.z; dz*=dz; - return sqrt(dx+dy+dz); +double JPoint::distanceTo(JPoint& pt) +{ + double dx=x-pt.x; + dx*=dx; + double dy=y-pt.y; + dy*=dy; + double dz=z-pt.z; + dz*=dz; + return sqrt(dx+dy+dz); } -double * JPoint::centreCoordinatesWith(JPoint &pt){ - double *res= new double[3]; - res[0]=(x+pt.getX())/2; - res[1]=(y+pt.getY())/2; - res[2]=(z+pt.getZ())/2; - return res; +double * JPoint::centreCoordinatesWith(JPoint &pt) +{ + double *res= new double[3]; + res[0]=(x+pt.getX())/2; + res[1]=(y+pt.getY())/2; + res[2]=(z+pt.getZ())/2; + return res; } -double JPoint::distanceBetween(JPoint& pt1, JPoint& pt2){ - return pt1.distanceTo(pt2); +double JPoint::distanceBetween(JPoint& pt1, JPoint& pt2) +{ + return pt1.distanceTo(pt2); } -double JPoint::angleMadeBetween(JPoint& pt1, JPoint& pt2){ - return pt1.angleMadeWith(pt2); +double JPoint::angleMadeBetween(JPoint& pt1, JPoint& pt2) +{ + return pt1.angleMadeWith(pt2); } -double *JPoint::centreCoordinatesBetween(JPoint& pt1, JPoint& pt2){ - return pt1.centreCoordinatesWith(pt2); +double *JPoint::centreCoordinatesBetween(JPoint& pt1, JPoint& pt2) +{ + return pt1.centreCoordinatesWith(pt2); } /* * return the color */ -unsigned char JPoint::getR(){return r;} -unsigned char JPoint::getG(){return g;} -unsigned char JPoint::getB(){return b;} +unsigned char JPoint::getR() +{ + return r; +} +unsigned char JPoint::getG() +{ + return g; +} +unsigned char JPoint::getB() +{ + return b; +} -void JPoint::setColorHeightThicknes(double CHT[3]){ - thickness=CHT[2]; - height=CHT[1]; - color=CHT[0]; +void JPoint::setColorHeightThicknes(double CHT[3]) +{ + thickness=CHT[2]; + height=CHT[1]; + color=CHT[0]; } -void JPoint::getColorHeightThicknes(double *CHT){ - CHT[0]=color; - CHT[1]=height; - CHT[2]=thickness; +void JPoint::getColorHeightThicknes(double *CHT) +{ + CHT[0]=color; + CHT[1]=height; + CHT[2]=thickness; } diff --git a/src/geometry/JPoint.h b/src/geometry/JPoint.h index 39446347783964dd8f2d24f8b65f29296354820e..64c558a6509c65bba92f3d49369710e56e631765 100644 --- a/src/geometry/JPoint.h +++ b/src/geometry/JPoint.h @@ -35,43 +35,43 @@ class JPoint { private: - double x,y,z; - unsigned char r,g,b; - double thickness; - double height; - double color; + double x,y,z; + unsigned char r,g,b; + double thickness; + double height; + double color; public: - JPoint(); //default constructor - JPoint(double x, double y, double z, unsigned char r='a', unsigned char g='b',unsigned char b='c'); - JPoint(double xyz[3], char col[]="abc"); - virtual ~JPoint(); + JPoint(); //default constructor + JPoint(double x, double y, double z, unsigned char r='a', unsigned char g='b',unsigned char b='c'); + JPoint(double xyz[3], const char* col="abc"); + virtual ~JPoint(); - double getX(); - double getY(); - double getZ(); - double distanceTo(JPoint& pt); - double angleMadeWith(JPoint &pt); - double* centreCoordinatesWith(JPoint &pt); + double getX(); + double getY(); + double getZ(); + double distanceTo(JPoint& pt); + double angleMadeWith(JPoint &pt); + double* centreCoordinatesWith(JPoint &pt); - static double distanceBetween(JPoint& pt1, JPoint& pt2); - static double angleMadeBetween(JPoint& pt1, JPoint& pt2); - static double *centreCoordinatesBetween(JPoint& pt1, JPoint& pt2); + static double distanceBetween(JPoint& pt1, JPoint& pt2); + static double angleMadeBetween(JPoint& pt1, JPoint& pt2); + static double *centreCoordinatesBetween(JPoint& pt1, JPoint& pt2); - void setColorRGB(unsigned char r, unsigned char g, unsigned char b); - void getColorRGB(unsigned char *rgb); + void setColorRGB(unsigned char r, unsigned char g, unsigned char b); + void getColorRGB(unsigned char *rgb); - void setXYZ(double* xyz); - void getXYZ(double* xyz); + void setXYZ(double* xyz); + void getXYZ(double* xyz); - unsigned char getR(); - unsigned char getG(); - unsigned char getB(); + unsigned char getR(); + unsigned char getG(); + unsigned char getB(); - //methods for convenience in the case - //this is the end point of a door/wall for instance - void setColorHeightThicknes(double CHT[3]); - void getColorHeightThicknes(double *CHT); + //methods for convenience in the case + //this is the end point of a door/wall for instance + void setColorHeightThicknes(double CHT[3]); + void getColorHeightThicknes(double *CHT); }; #endif /* POINT_H_ */ diff --git a/src/geometry/Line.cpp b/src/geometry/Line.cpp index 1686f22f044958f65bd36ed4e2b061213649962a..0b6ccc4ad46383ed4ac69291b456541187b8a563 100644 --- a/src/geometry/Line.cpp +++ b/src/geometry/Line.cpp @@ -39,77 +39,88 @@ using namespace std; /************************************************************ Konstruktoren ************************************************************/ -Line::Line() { - SetPoint1(Point()); //Default-Constructor (0.0,0.0) - SetPoint2(Point()); - _uid = _static_UID++; +Line::Line() +{ + SetPoint1(Point()); //Default-Constructor (0.0,0.0) + SetPoint2(Point()); + _uid = _static_UID++; } -Line::Line(const Point& p1, const Point& p2) { - SetPoint1(p1); - SetPoint2(p2); - _uid = _static_UID++; +Line::Line(const Point& p1, const Point& p2) +{ + SetPoint1(p1); + SetPoint2(p2); + _uid = _static_UID++; } -int Line::GetUniqueID() const { - return _uid; +int Line::GetUniqueID() const +{ + return _uid; } -Line::Line(const Line& orig) { - _point1 = orig.GetPoint1(); - _point2 = orig.GetPoint2(); - _centre = orig.GetCentre(); - _uid = orig.GetUniqueID(); +Line::Line(const Line& orig) +{ + _point1 = orig.GetPoint1(); + _point2 = orig.GetPoint2(); + _centre = orig.GetCentre(); + _uid = orig.GetUniqueID(); } -Line::~Line() { +Line::~Line() +{ } /************************************************************* Setter-Funktionen ************************************************************/ -void Line::SetPoint1(const Point& p) { - _point1 = p; - _centre = (_point1+_point2)*0.5; +void Line::SetPoint1(const Point& p) +{ + _point1 = p; + _centre = (_point1+_point2)*0.5; } -void Line::SetPoint2(const Point& p) { - _point2 = p; - _centre = (_point1+_point2)*0.5; +void Line::SetPoint2(const Point& p) +{ + _point2 = p; + _centre = (_point1+_point2)*0.5; } /************************************************************* Getter-Funktionen ************************************************************/ -const Point& Line::GetPoint1() const { - return _point1; +const Point& Line::GetPoint1() const +{ + return _point1; } -const Point& Line::GetPoint2() const { - return _point2; +const Point& Line::GetPoint2() const +{ + return _point2; } -const Point& Line::GetCentre()const { - return _centre; +const Point& Line::GetCentre()const +{ + return _centre; } /************************************************************* Ausgabe ************************************************************/ -string Line::Write() const { - string geometry; - char wall[500] = ""; - geometry.append("\t\t<wall color=\"100\">\n"); - sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\"/>\n", - (GetPoint1().GetX()) * FAKTOR, - (GetPoint1().GetY()) * FAKTOR); - geometry.append(wall); - sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\"/>\n", - (GetPoint2().GetX()) * FAKTOR, - (GetPoint2().GetY()) * FAKTOR); - geometry.append(wall); - geometry.append("\t\t</wall>\n"); - return geometry; +string Line::Write() const +{ + string geometry; + char wall[500] = ""; + geometry.append("\t\t<wall color=\"100\">\n"); + sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\"/>\n", + (GetPoint1().GetX()) * FAKTOR, + (GetPoint1().GetY()) * FAKTOR); + geometry.append(wall); + sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\"/>\n", + (GetPoint2().GetX()) * FAKTOR, + (GetPoint2().GetY()) * FAKTOR); + geometry.append(wall); + geometry.append("\t\t</wall>\n"); + return geometry; } @@ -118,87 +129,91 @@ string Line::Write() const { ************************************************************/ // Normalen vector zur Linie -Point Line::NormalVec() const { - double nx, ny, norm; - Point r = GetPoint2() - GetPoint1(); - - if (r.GetX() == 0.0) { - nx = 1; - ny = 0; - } else { - nx = -r.GetY() / r.GetX(); - ny = 1; - /* Normieren */ - norm = sqrt(nx * nx + ny * ny); - if (fabs(norm) < J_EPS) { - Log->Write("ERROR: \tLine::NormalVec() norm==0\n"); - exit(0); - } - nx /= norm; - ny /= norm; - } - return Point(nx, ny); +Point Line::NormalVec() const +{ + double nx, ny, norm; + Point r = GetPoint2() - GetPoint1(); + + if (r.GetX() == 0.0) { + nx = 1; + ny = 0; + } else { + nx = -r.GetY() / r.GetX(); + ny = 1; + /* Normieren */ + norm = sqrt(nx * nx + ny * ny); + if (fabs(norm) < J_EPS) { + Log->Write("ERROR: \tLine::NormalVec() norm==0\n"); + exit(0); + } + nx /= norm; + ny /= norm; + } + return Point(nx, ny); } // Normale Komponente von v auf l -double Line::NormalComp(const Point& v) const { - // Normierte Vectoren - Point l = (GetPoint2() - GetPoint1()).Normalized(); - const Point& n = NormalVec(); +double Line::NormalComp(const Point& v) const +{ + // Normierte Vectoren + Point l = (GetPoint2() - GetPoint1()).Normalized(); + const Point& n = NormalVec(); - double lx = l.GetX(); - double ly = l.GetY(); - double nx = n.GetX(); - double ny = n.GetY(); - double alpha; + double lx = l.GetX(); + double ly = l.GetY(); + double nx = n.GetX(); + double ny = n.GetY(); + double alpha; - if (fabs(lx) < J_EPS) { - alpha = v.GetX() / nx; - } else if (fabs(ly) < J_EPS) { - alpha = v.GetY() / ny; - } else { - alpha = (v.GetY() * lx - v.GetX() * ly) / (nx * ly - ny * lx); - } + if (fabs(lx) < J_EPS) { + alpha = v.GetX() / nx; + } else if (fabs(ly) < J_EPS) { + alpha = v.GetY() / ny; + } else { + alpha = (v.GetY() * lx - v.GetX() * ly) / (nx * ly - ny * lx); + } - return fabs(alpha); + return fabs(alpha); } // Lotfußpunkt zur Geraden Line // Muss nicht im Segment liegen -Point Line::LotPoint(const Point& p) const { - const Point& r = GetPoint1(); - const Point& s = GetPoint2(); - const Point& t = r - s; - Point tmp; - double lambda; +Point Line::LotPoint(const Point& p) const +{ + const Point& r = GetPoint1(); + const Point& s = GetPoint2(); + const Point& t = r - s; + Point tmp; + double lambda; - tmp = p - s; - lambda = tmp.ScalarP(t) / t.ScalarP(t); - Point f = s + t*lambda; - return f; + tmp = p - s; + lambda = tmp.ScalarP(t) / t.ScalarP(t); + Point f = s + t*lambda; + return f; } /* Punkt auf der Linie mit kürzestem Abstand zu p * In der Regel Lotfußpunkt, Ist der Lotfußpunkt nicht im Segment * wird der entsprechende Eckpunkt der Line genommen * */ -Point Line::ShortestPoint(const Point& p) const { +Point Line::ShortestPoint(const Point& p) const +{ - const Point& t = _point1 - _point2; + const Point& t = _point1 - _point2; - Point tmp = p - _point2; - double lambda = tmp.ScalarP(t) / t.ScalarP(t); - Point f = _point2 + t*lambda; + Point tmp = p - _point2; + double lambda = tmp.ScalarP(t) / t.ScalarP(t); + Point f = _point2 + t*lambda; - /* Prüfen ob Punkt in der Linie,sonst entsprechenden Eckpunkt zurückgeben */ - if (lambda < 0) - f = _point2; - if (lambda > 1) - f = _point1; + /* Prüfen ob Punkt in der Linie,sonst entsprechenden Eckpunkt zurückgeben */ + if (lambda < 0) + f = _point2; + if (lambda > 1) + f = _point1; - return f; + return f; } /* Prüft, ob Punkt p im Liniensegment enthalten ist @@ -232,233 +247,253 @@ Point Line::ShortestPoint(const Point& p) const { * algorithm from: * http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment * */ -bool Line::IsInLineSegment(const Point& p) const { - //const Point& _point1 = GetPoint1(); - //const Point& _point2 = GetPoint2(); - double ax = _point1.GetX(); - double ay = _point1.GetY(); - double bx = _point2.GetX(); - double by = _point2.GetY(); - double px = p._x; - double py = p._y; - - // cross product to check if point i colinear - double crossp = (py-ay)*(bx-ax)-(px-ax)*(by-ay); - if(fabs(crossp) > J_EPS) return false; - - // dotproduct and distSquared to check if point is in segment and not just in line - double dotp = (px-ax)*(bx-ax)+(py-ay)*(by-ay); - if(dotp < 0 || (_point1-_point2).NormSquare() < dotp) return false; - - return true; - +bool Line::IsInLineSegment(const Point& p) const +{ + //const Point& _point1 = GetPoint1(); + //const Point& _point2 = GetPoint2(); + double ax = _point1.GetX(); + double ay = _point1.GetY(); + double bx = _point2.GetX(); + double by = _point2.GetY(); + double px = p._x; + double py = p._y; + + // cross product to check if point i colinear + double crossp = (py-ay)*(bx-ax)-(px-ax)*(by-ay); + if(fabs(crossp) > J_EPS) return false; + + // dotproduct and distSquared to check if point is in segment and not just in line + double dotp = (px-ax)*(bx-ax)+(py-ay)*(by-ay); + if(dotp < 0 || (_point1-_point2).NormSquare() < dotp) return false; + + return true; + } /* Berechnet direkt den Abstand von p zum Segment l * dazu wird die Funktion Line::ShortestPoint() * benuzt * */ -double Line::DistTo(const Point& p) const { - return (p - ShortestPoint(p)).Norm(); +double Line::DistTo(const Point& p) const +{ + return (p - ShortestPoint(p)).Norm(); } -double Line::DistToSquare(const Point& p) const { - return (p - ShortestPoint(p)).NormSquare(); +double Line::DistToSquare(const Point& p) const +{ + return (p - ShortestPoint(p)).NormSquare(); } /* Zwei Linien sind gleich, wenn ihre beiden Punkte * gleich sind * */ -bool Line::operator==(const Line& l) const { - return ((_point1 == l.GetPoint1() && _point2 == l.GetPoint2()) || - (_point2 == l.GetPoint1() && _point1 == l.GetPoint2())); +bool Line::operator==(const Line& l) const +{ + return ((_point1 == l.GetPoint1() && _point2 == l.GetPoint2()) || + (_point2 == l.GetPoint1() && _point1 == l.GetPoint2())); } /* Zwei Linien sind ungleich, wenn ihre beiden Punkte * ungleich sind * */ -bool Line::operator!=(const Line& l) const { - return ((_point1 != l.GetPoint1() && _point2 != l.GetPoint2()) && - (_point2 != l.GetPoint1() && _point1 != l.GetPoint2())); +bool Line::operator!=(const Line& l) const +{ + return ((_point1 != l.GetPoint1() && _point2 != l.GetPoint2()) && + (_point2 != l.GetPoint1() && _point1 != l.GetPoint2())); } -double Line::Length() const { - return (_point1 - _point2).Norm(); +double Line::Length() const +{ + return (_point1 - _point2).Norm(); } -double Line::LengthSquare() const { - return (_point1 - _point2).NormSquare(); +double Line::LengthSquare() const +{ + return (_point1 - _point2).NormSquare(); } -bool Line::IntersectionWith(const Line& l) const { +bool Line::IntersectionWith(const Line& l) const +{ - //if(ShareCommonPointWith(l)) return true; + //if(ShareCommonPointWith(l)) return true; - double deltaACy = _point1.GetY() - l.GetPoint1().GetY(); - double deltaDCx = l.GetPoint2().GetX() - l.GetPoint1().GetX(); - double deltaACx = _point1.GetX() - l.GetPoint1().GetX(); - double deltaDCy = l.GetPoint2().GetY() - l.GetPoint1().GetY(); - double deltaBAx = _point2.GetX() - _point1.GetX(); - double deltaBAy = _point2.GetY() - _point1.GetY(); + double deltaACy = _point1.GetY() - l.GetPoint1().GetY(); + double deltaDCx = l.GetPoint2().GetX() - l.GetPoint1().GetX(); + double deltaACx = _point1.GetX() - l.GetPoint1().GetX(); + double deltaDCy = l.GetPoint2().GetY() - l.GetPoint1().GetY(); + double deltaBAx = _point2.GetX() - _point1.GetX(); + double deltaBAy = _point2.GetY() - _point1.GetY(); - double denominator = deltaBAx * deltaDCy - deltaBAy * deltaDCx; - double numerator = deltaACy * deltaDCx - deltaACx * deltaDCy; + double denominator = deltaBAx * deltaDCy - deltaBAy * deltaDCx; + double numerator = deltaACy * deltaDCx - deltaACx * deltaDCy; - // the lines are parallel - if (denominator == 0.0) { + // the lines are parallel + if (denominator == 0.0) { - // the lines are superposed - if (numerator == 0.0) { + // the lines are superposed + if (numerator == 0.0) { - // the segment are superposed - if(IsInLineSegment(l.GetPoint1()) || - IsInLineSegment(l.GetPoint2()) ) return true; - else return false; + // the segment are superposed + if(IsInLineSegment(l.GetPoint1()) || + IsInLineSegment(l.GetPoint2()) ) return true; + else return false; - } else { // the lines are just parallel and do not share a common point + } else { // the lines are just parallel and do not share a common point - return false; - } - } + return false; + } + } - // the lines intersect - double r = numerator / denominator; - if (r < 0.0 || r > 1.0) { - return false; - } + // the lines intersect + double r = numerator / denominator; + if (r < 0.0 || r > 1.0) { + return false; + } - double s = (deltaACy * deltaBAx - deltaACx * deltaBAy) / denominator; - if (s < 0.0 || s > 1.0) { - return false; - } + double s = (deltaACy * deltaBAx - deltaACx * deltaBAy) / denominator; + if (s < 0.0 || s > 1.0) { + return false; + } - //Point PointF = Point ((float) (_point1._x + r * deltaBAx), (float) (_point1._y + r * deltaBAy)); - //cout<< l.toString() << " intersects with " << toString() <<endl; - //cout<<" at point " << PointF.toString()<<endl; - return true; + //Point PointF = Point ((float) (_point1._x + r * deltaBAx), (float) (_point1._y + r * deltaBAy)); + //cout<< l.toString() << " intersects with " << toString() <<endl; + //cout<<" at point " << PointF.toString()<<endl; + return true; } -bool Line::IsHorizontal(){ - return fabs (_point1._y-_point2._y ) <= J_EPS; +bool Line::IsHorizontal() +{ + return fabs (_point1._y-_point2._y ) <= J_EPS; } -bool Line::IsVertical(){ - return fabs (_point1._x-_point2._x ) <= J_EPS; +bool Line::IsVertical() +{ + return fabs (_point1._x-_point2._x ) <= J_EPS; } -int Line::WichSide(const Point& pt) { - //special case for horizontal lines - if (IsVertical()) { - //left - if (pt._x < _point1._x) - return 0; - //right or colinear - if (pt._x >= _point1._x) - return 1; - } +int Line::WichSide(const Point& pt) +{ + //special case for horizontal lines + if (IsVertical()) { + //left + if (pt._x < _point1._x) + return 0; + //right or colinear + if (pt._x >= _point1._x) + return 1; + } - return ((_point2._x - _point1._x) * (pt._y - _point1._y) - - (_point2._y - _point1._y) * (pt._x - _point1._x)) > 0; + return ((_point2._x - _point1._x) * (pt._y - _point1._y) + - (_point2._y - _point1._y) * (pt._x - _point1._x)) > 0; } -bool Line::ShareCommonPointWith(const Line& line) const { - if(line.GetPoint1()==_point1) return true; - if(line.GetPoint2()==_point1) return true; +bool Line::ShareCommonPointWith(const Line& line) const +{ + if(line.GetPoint1()==_point1) return true; + if(line.GetPoint2()==_point1) return true; - if(line.GetPoint1()==_point2) return true; - if(line.GetPoint2()==_point2) return true; + if(line.GetPoint1()==_point2) return true; + if(line.GetPoint2()==_point2) return true; - return false; + return false; } -bool Line::HasEndPoint(const Point& point) const { - if (_point1==point) return true; - if (_point2==point) return true; - return false; +bool Line::HasEndPoint(const Point& point) const +{ + if (_point1==point) return true; + if (_point2==point) return true; + return false; } -bool Line::IntersectionWithCircle(const Point& centre, double radius /*cm for pedestrians*/){ +bool Line::IntersectionWithCircle(const Point& centre, double radius /*cm for pedestrians*/) +{ - double r=radius; - double x1=_point1.GetX(); - double y1=_point1.GetY(); + double r=radius; + double x1=_point1.GetX(); + double y1=_point1.GetY(); - double x2=_point2.GetX(); - double y2=_point2.GetY(); + double x2=_point2.GetX(); + double y2=_point2.GetY(); - double xc=centre.GetX(); - double yc=centre.GetY(); + double xc=centre.GetX(); + double yc=centre.GetY(); - //this formula assumes that the circle is centered the origin. - // so we translate the complete stuff such that the circle ends up at the origin - x1=x1-xc;y1=y1-yc; - x2=x2-xc;y2=y2-yc; - //xc=xc-xc;yc=yc-yc; to make it perfect + //this formula assumes that the circle is centered the origin. + // so we translate the complete stuff such that the circle ends up at the origin + x1=x1-xc; + y1=y1-yc; + x2=x2-xc; + y2=y2-yc; + //xc=xc-xc;yc=yc-yc; to make it perfect - // we first check the intersection of the circle and the infinite line defined by the segment - double dr2=((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); - double D2=(x1*y2-x2*y1)*(x1*y2-x2*y1); - double r2=radius*radius; + // we first check the intersection of the circle and the infinite line defined by the segment + double dr2=((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); + double D2=(x1*y2-x2*y1)*(x1*y2-x2*y1); + double r2=radius*radius; - double delta=r2*dr2-D2; - if(delta<=0.0) return false; + double delta=r2*dr2-D2; + if(delta<=0.0) return false; - double a=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1); - double b=2*((x1*(x2-x1))+y1*(y2-y1)); - double c=x1*x1+y1*y1-r*r; + double a=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1); + double b=2*((x1*(x2-x1))+y1*(y2-y1)); + double c=x1*x1+y1*y1-r*r; - delta=b*b-4*a*c; + delta=b*b-4*a*c; - if((x1==x2)&&(y1==y2)){ - Log->Write("isLineCrossingCircle: Your line is a point"); - return false; - } - if(delta<0.0){ - char tmp[CLENGTH]; - sprintf(tmp,"there is a bug in 'isLineCrossingCircle', delta(%f) can t be <0 at this point.",delta); - Log->Write(tmp); - Log->Write("press ENTER"); - return false; //fixme - //getc(stdin); - } + if((x1==x2)&&(y1==y2)) { + Log->Write("isLineCrossingCircle: Your line is a point"); + return false; + } + if(delta<0.0) { + char tmp[CLENGTH]; + sprintf(tmp,"there is a bug in 'isLineCrossingCircle', delta(%f) can t be <0 at this point.",delta); + Log->Write(tmp); + Log->Write("press ENTER"); + return false; //fixme + //getc(stdin); + } - double t1= (-b + sqrt(delta))/(2*a); - double t2= (-b - sqrt(delta))/(2*a); - if((t1<0.0) || (t1>1.0)) return false; - if((t2<0.0) || (t2>1.0)) return false; - return true; + double t1= (-b + sqrt(delta))/(2*a); + double t2= (-b - sqrt(delta))/(2*a); + if((t1<0.0) || (t1>1.0)) return false; + if((t2<0.0) || (t2>1.0)) return false; + return true; } //TODO: Consider numerical stability and special case pt is on line // Returns true if pt is on the left side ( from point1 toward point2) -bool Line::IsLeft(const Point& pt){ - double test=(_point2._x-_point1._x)*(pt.GetY()-_point1._y)-(_point2._y-_point1._y)*(pt.GetX()-_point1._x); - if (test>0.0) - return true; - else - return false; -} - -const Point& Line::GetLeft(const Point& pt){ - if (IsLeft(pt)){ - return _point2; - }else{ - return _point1; - } -} - -const Point& Line::GetRight(const Point& pt){ - if (!IsLeft(pt)){ - return _point2; - }else{ - return _point1; - } -} - -std::string Line::toString() const { - std::stringstream tmp; - tmp<<_point1.toString()<<"--"<<_point2.toString(); - return tmp.str(); +bool Line::IsLeft(const Point& pt) +{ + double test=(_point2._x-_point1._x)*(pt.GetY()-_point1._y)-(_point2._y-_point1._y)*(pt.GetX()-_point1._x); + if (test>0.0) + return true; + else + return false; +} + +const Point& Line::GetLeft(const Point& pt) +{ + if (IsLeft(pt)) { + return _point2; + } else { + return _point1; + } +} + +const Point& Line::GetRight(const Point& pt) +{ + if (!IsLeft(pt)) { + return _point2; + } else { + return _point1; + } +} + +std::string Line::toString() const +{ + std::stringstream tmp; + tmp<<_point1.toString()<<"--"<<_point2.toString(); + return tmp.str(); } diff --git a/src/geometry/Line.h b/src/geometry/Line.h index 6f61c6859359ac39888a4102ce7fc0bdf5eed5b5..1dbf40722a37a3ecc5e4784a9fca36ae65b9f16f 100644 --- a/src/geometry/Line.h +++ b/src/geometry/Line.h @@ -40,51 +40,51 @@ extern OutputHandler* Log; class Line { private: - Point _point1; - Point _point2; - Point _centre; + Point _point1; + Point _point2; + Point _centre; - //unique identifier for all line elements - static int _static_UID; - int _uid; + //unique identifier for all line elements + static int _static_UID; + int _uid; public: - Line(); - Line(const Point& p1, const Point& p2); - Line(const Line& orig); - virtual ~Line(); + Line(); + Line(const Point& p1, const Point& p2); + Line(const Line& orig); + virtual ~Line(); - /** - * All Line elements (also derived class) have a unique ID - * @return the unique ID of this line element. - */ - int GetUniqueID() const; + /** + * All Line elements (also derived class) have a unique ID + * @return the unique ID of this line element. + */ + int GetUniqueID() const; - /** - * Set/Get the first end point of the line - */ - void SetPoint1(const Point& p); + /** + * Set/Get the first end point of the line + */ + void SetPoint1(const Point& p); - /** - * Set/Get the second end point of the line - */ - void SetPoint2(const Point& p); + /** + * Set/Get the second end point of the line + */ + void SetPoint2(const Point& p); - /** - * Set/Get the first end point of the line - */ - const Point& GetPoint1(void) const; + /** + * Set/Get the first end point of the line + */ + const Point& GetPoint1(void) const; - /** - * Set/Get the second end point of the line - */ - const Point& GetPoint2(void) const; + /** + * Set/Get the second end point of the line + */ + const Point& GetPoint2(void) const; - /** - * Return the center of the line - */ - const Point& GetCentre(void) const; + /** + * Return the center of the line + */ + const Point& GetCentre(void) const; /** * @return a normal vector to this line @@ -117,7 +117,7 @@ public: * @return true if the point p is within the line segment defined the line end points */ bool IsInLineSegment(const Point& p) const; - + /** * @return the distance from the line to the point p */ @@ -142,77 +142,77 @@ public: * @return true if both segments are equal. The end points must be in the range of J_EPS. * @see Macro.h */ - bool operator==(const Line& l) const; + bool operator==(const Line& l) const; /** * @return true if both segments are not equal. The end points must be in the range of J_EPS. * @see Macro.h */ - bool operator!=(const Line& l) const; - - /** - * @see http://alienryderflex.com/intersect/ - * @see http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/e5993847-c7a9-46ec-8edc-bfb86bd689e3/ - * @return true if both segments intersect - */ - bool IntersectionWith(const Line& l) const; // check two segments for intersections - - /** - * @return true if the segment intersects with the circle of radius r - */ - bool IntersectionWithCircle(const Point& centre, double radius=0.30 /*m for pedestrians*/); - - - /** - * @return true if both segments share at least one common point - */ - bool ShareCommonPointWith(const Line& line) const; - - /** - * @return true if the given point is one end point of the segment - */ - bool HasEndPoint(const Point& point) const; - - /** - * return the same value if the checked points are all situated on the same side. - * @return 0 or 1 depending on which side of the line the point is located. - */ - int WichSide (const Point& pt); - - /** - * @return true if the point is located in the left hand side of the line. - * For horizontal lines return true if the point is above the line. - */ - bool IsLeft (const Point& pt); - - /** - * @return true for horizontal lines - */ - bool IsHorizontal(); - - /** - * @return true for vertical lines - */ - bool IsVertical(); - - /** - * @return left point wrt. the point pt - */ - const Point& GetLeft(const Point& pt); - - /** - * @return left point wrt. the point pt - */ - const Point& GetRight(const Point& pt); - - /** - * @return a nice formated string describing the line - */ - virtual std::string Write() const; - - /** - * @return a nice formated string describing the line - */ + bool operator!=(const Line& l) const; + + /** + * @see http://alienryderflex.com/intersect/ + * @see http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/e5993847-c7a9-46ec-8edc-bfb86bd689e3/ + * @return true if both segments intersect + */ + bool IntersectionWith(const Line& l) const; // check two segments for intersections + + /** + * @return true if the segment intersects with the circle of radius r + */ + bool IntersectionWithCircle(const Point& centre, double radius=0.30 /*m for pedestrians*/); + + + /** + * @return true if both segments share at least one common point + */ + bool ShareCommonPointWith(const Line& line) const; + + /** + * @return true if the given point is one end point of the segment + */ + bool HasEndPoint(const Point& point) const; + + /** + * return the same value if the checked points are all situated on the same side. + * @return 0 or 1 depending on which side of the line the point is located. + */ + int WichSide (const Point& pt); + + /** + * @return true if the point is located in the left hand side of the line. + * For horizontal lines return true if the point is above the line. + */ + bool IsLeft (const Point& pt); + + /** + * @return true for horizontal lines + */ + bool IsHorizontal(); + + /** + * @return true for vertical lines + */ + bool IsVertical(); + + /** + * @return left point wrt. the point pt + */ + const Point& GetLeft(const Point& pt); + + /** + * @return left point wrt. the point pt + */ + const Point& GetRight(const Point& pt); + + /** + * @return a nice formated string describing the line + */ + virtual std::string Write() const; + + /** + * @return a nice formated string describing the line + */ std::string toString() const; diff --git a/src/geometry/LinePlotter.cpp b/src/geometry/LinePlotter.cpp index 942b9045720522a68d697196059500720f517b97..6abd3241af3b4d27490ec929528dba905cb389fb 100644 --- a/src/geometry/LinePlotter.cpp +++ b/src/geometry/LinePlotter.cpp @@ -55,97 +55,101 @@ int LinePlotter::m_allLineWidth = 2; LinePlotter::LinePlotter() { - m_curPointID = 0; + m_curPointID = 0; - m_scalars = vtkUnsignedCharArray::New(); - m_scalars->SetNumberOfComponents(3); - m_points = vtkPoints::New(); - m_lines = vtkCellArray::New(); + m_scalars = vtkUnsignedCharArray::New(); + m_scalars->SetNumberOfComponents(3); + m_points = vtkPoints::New(); + m_lines = vtkCellArray::New(); - //m_lineScalars = vtkFloatArray::New(); - // create a color lookup table - //m_lookupTable = vtkLookupTable::New(); + //m_lineScalars = vtkFloatArray::New(); + // create a color lookup table + //m_lookupTable = vtkLookupTable::New(); - //create the poly data + //create the poly data // vtkPolyData* polyData = vtkPolyData::New(); - VTK_CREATE(vtkPolyData,polyData); - polyData->SetPoints(m_points); - polyData->SetLines(m_lines); - //polyData->SetVerts(m_lines); - polyData->GetPointData()->SetScalars(m_scalars); - - // create mapper - VTK_CREATE(vtkPolyDataMapper,mapper); - //vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + VTK_CREATE(vtkPolyData,polyData); + polyData->SetPoints(m_points); + polyData->SetLines(m_lines); + //polyData->SetVerts(m_lines); + polyData->GetPointData()->SetScalars(m_scalars); + + // create mapper + VTK_CREATE(vtkPolyDataMapper,mapper); + //vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); #if VTK_MAJOR_VERSION <= 5 mapper->SetInput(polyData); #else mapper->SetInputData(polyData); #endif - //polyData->Delete(); - - // mapper->SetLookupTable(m_lookupTable); - // mapper->SetColorModeToMapScalars(); - // mapper->SetScalarRange(m_scalarMin, m_scalarMax); - // mapper->SetScalarModeToUsePointData(); - - // create actor - m_lineActors = vtkActor::New(); - m_lineActors->SetMapper(mapper); - //mapper->Delete(); - m_lineActors->GetProperty()->SetLineWidth(m_allLineWidth); + //polyData->Delete(); + + // mapper->SetLookupTable(m_lookupTable); + // mapper->SetColorModeToMapScalars(); + // mapper->SetScalarRange(m_scalarMin, m_scalarMax); + // mapper->SetScalarModeToUsePointData(); + + // create actor + m_lineActors = vtkActor::New(); + m_lineActors->SetMapper(mapper); + //mapper->Delete(); + m_lineActors->GetProperty()->SetLineWidth(m_allLineWidth); } LinePlotter::~LinePlotter() { - m_points->Delete(); - m_lineActors->Delete(); - m_lines->Delete(); - m_scalars->Delete(); + m_points->Delete(); + m_lineActors->Delete(); + m_lines->Delete(); + m_scalars->Delete(); } -void LinePlotter::setLineWidth(int width) { - m_allLineWidth = width; +void LinePlotter::setLineWidth(int width) +{ + m_allLineWidth = width; } -void LinePlotter::SetNumberOfPoints(int nPoints) { - //m_lines->InsertNextCell(nPoints); - m_lines->InsertNextCell(nPoints); +void LinePlotter::SetNumberOfPoints(int nPoints) +{ + //m_lines->InsertNextCell(nPoints); + m_lines->InsertNextCell(nPoints); } -void LinePlotter::PlotLine(JPoint* pt1, JPoint* pt2) { +void LinePlotter::PlotLine(JPoint* pt1, JPoint* pt2) +{ - double m[3], n[3]; - unsigned char col[3]; + double m[3], n[3]; + unsigned char col[3]; - m[0] = pt1->getX(); - m[1] = pt1->getY(); - m[2] = pt1->getZ(); + m[0] = pt1->getX(); + m[1] = pt1->getY(); + m[2] = pt1->getZ(); - n[0] = pt2->getX(); - n[1] = pt2->getY(); - n[2] = pt2->getZ(); + n[0] = pt2->getX(); + n[1] = pt2->getY(); + n[2] = pt2->getZ(); - col[0] = pt1->getR(); - col[1] = pt1->getG(); - col[2] = pt1->getB(); - PlotLine(m,n,col); + col[0] = pt1->getR(); + col[1] = pt1->getG(); + col[2] = pt1->getB(); + PlotLine(m,n,col); } -void LinePlotter::addVertex(JPoint *pt1) { - double m[3]; - unsigned char col[3]; +void LinePlotter::addVertex(JPoint *pt1) +{ + double m[3]; + unsigned char col[3]; - m[0] = pt1->getX(); - m[1] = pt1->getY(); - m[2] = pt1->getZ()+10; + m[0] = pt1->getX(); + m[1] = pt1->getY(); + m[2] = pt1->getZ()+10; - col[0] = pt1->getR(); - col[1] = pt1->getG(); - col[2] = pt1->getB(); + col[0] = pt1->getR(); + col[1] = pt1->getG(); + col[2] = pt1->getB(); // //m_points->InsertNextPoint(m); // m_points->InsertPoint(m_curPointID,m); @@ -155,75 +159,80 @@ void LinePlotter::addVertex(JPoint *pt1) { // m_points->Modified(); // m_lines->Modified(); - //m_points->InsertNextPoint(m); - m_points->InsertNextPoint(m); - m_scalars->InsertTuple3(m_curPointID,col[0], col[1], col[2]); - m_lines->InsertCellPoint(m_curPointID++); - m_scalars->Modified(); - m_points->Modified(); - m_lines->Modified(); + //m_points->InsertNextPoint(m); + m_points->InsertNextPoint(m); + m_scalars->InsertTuple3(m_curPointID,col[0], col[1], col[2]); + m_lines->InsertCellPoint(m_curPointID++); + m_scalars->Modified(); + m_points->Modified(); + m_lines->Modified(); } -void LinePlotter::addVertex(double vertex[3],double col[3]) { +void LinePlotter::addVertex(double vertex[3],double col[3]) +{ - JPoint *pts = new JPoint(); - pts->setColorRGB(col[0],col[1],col[2]); - pts->setXYZ(vertex); - addVertex(pts); + JPoint *pts = new JPoint(); + pts->setColorRGB(col[0],col[1],col[2]); + pts->setXYZ(vertex); + addVertex(pts); - delete pts; + delete pts; } // caution: // this work only for a line with 2 points. so for a line // not a polyline -void LinePlotter::PlotLine(double m[3], double n[3], unsigned char col[3]) { +void LinePlotter::PlotLine(double m[3], double n[3], unsigned char col[3]) +{ - m_points->InsertNextPoint(m); - m_points->InsertNextPoint(n); + m_points->InsertNextPoint(m); + m_points->InsertNextPoint(n); - m_scalars->InsertNextTuple3(col[0], col[1], col[2]); + m_scalars->InsertNextTuple3(col[0], col[1], col[2]); - m_lines->InsertNextCell(2); - m_lines->InsertCellPoint(m_curPointID); - m_lines->InsertCellPoint(m_curPointID + 1); + m_lines->InsertNextCell(2); + m_lines->InsertCellPoint(m_curPointID); + m_lines->InsertCellPoint(m_curPointID + 1); - m_curPointID += 2; + m_curPointID += 2; - // force the update - m_scalars->Modified(); - m_points->Modified(); - m_lines->Modified(); + // force the update + m_scalars->Modified(); + m_points->Modified(); + m_lines->Modified(); } void LinePlotter::PlotLine(double x, double y, double z, double x2, double y2, - double z2, unsigned char color[3]) { - double m[3], n[3]; - m[0] = x; - m[1] = y; - m[2] = z; - n[0] = x2; - n[1] = y2; - n[2] = z2; - PlotLine(m, n,color); + double z2, unsigned char color[3]) +{ + double m[3], n[3]; + m[0] = x; + m[1] = y; + m[2] = z; + n[0] = x2; + n[1] = y2; + n[2] = z2; + PlotLine(m, n,color); } -vtkActor* LinePlotter::getActor() { +vtkActor* LinePlotter::getActor() +{ - return m_lineActors; + return m_lineActors; } -void LinePlotter::clear() { +void LinePlotter::clear() +{ - m_curPointID = 0; - m_points->Squeeze(); - m_lines->Squeeze(); + m_curPointID = 0; + m_points->Squeeze(); + m_lines->Squeeze(); - m_points->Reset(); - m_lines->Reset(); + m_points->Reset(); + m_lines->Reset(); - m_lineActors->GetProperty()->SetLineWidth(m_allLineWidth); + m_lineActors->GetProperty()->SetLineWidth(m_allLineWidth); } diff --git a/src/geometry/LinePlotter.h b/src/geometry/LinePlotter.h index b10885cec327fe6a9c75a93579c18fe912d62c7e..858d461bf38030317509fa8f9b88018d508d4b95 100644 --- a/src/geometry/LinePlotter.h +++ b/src/geometry/LinePlotter.h @@ -43,39 +43,38 @@ class vtkDataArray; class JPoint; -class LinePlotter -{ +class LinePlotter { public: - LinePlotter(); - ~LinePlotter(); + LinePlotter(); + ~LinePlotter(); - //void SetScalarRange(double minval=0.0, double maxval=1.0); - //void SetLookupTable(vtkLookupTable* table = 0); + //void SetScalarRange(double minval=0.0, double maxval=1.0); + //void SetLookupTable(vtkLookupTable* table = 0); - void PlotLine(JPoint* pt1, JPoint* pt2); - void PlotLine(double m[3], double n[3], unsigned char scalar[3]); - void PlotLine(double x, double y, double z, - double x2, double y2, double z2, unsigned char scalar[3]); - void addVertex(double vertex[3],double scalar[3]); - void addVertex(JPoint* pt1); - void SetNumberOfPoints(int nPoints); - void clear(); - static void setLineWidth(int width=1); - vtkActor* getActor(); + void PlotLine(JPoint* pt1, JPoint* pt2); + void PlotLine(double m[3], double n[3], unsigned char scalar[3]); + void PlotLine(double x, double y, double z, + double x2, double y2, double z2, unsigned char scalar[3]); + void addVertex(double vertex[3],double scalar[3]); + void addVertex(JPoint* pt1); + void SetNumberOfPoints(int nPoints); + void clear(); + static void setLineWidth(int width=1); + vtkActor* getActor(); private: - //double m_scalarMin, m_scalarMax ; - //vtkLookupTable* m_lookupTable ; - int m_curPointID ; - static int m_allLineWidth ; - //unsigned char colour[3]; + //double m_scalarMin, m_scalarMax ; + //vtkLookupTable* m_lookupTable ; + int m_curPointID ; + static int m_allLineWidth ; + //unsigned char colour[3]; - vtkPoints* m_points; - vtkActor* m_lineActors; - vtkCellArray* m_lines; - //vtkFloatArray* m_lineScalars ; - vtkDataArray* m_scalars ; + vtkPoints* m_points; + vtkActor* m_lineActors; + vtkCellArray* m_lines; + //vtkFloatArray* m_lineScalars ; + vtkDataArray* m_scalars ; }; diff --git a/src/geometry/LinePlotter2D.cpp b/src/geometry/LinePlotter2D.cpp index 0ea0de3ae5a5cd6346235640cd645923ec6fe606..b14c522aa42783f70120d55dd61a895ef3e0fdd8 100644 --- a/src/geometry/LinePlotter2D.cpp +++ b/src/geometry/LinePlotter2D.cpp @@ -97,50 +97,51 @@ LinePlotter2D::LinePlotter2D() } -LinePlotter2D::~LinePlotter2D(){ - - m_lookupTable->Delete(); - assembly->Delete(); - door_points->Delete(); - door_lines->Delete(); - door_lineScalars->Delete(); - door_mapper->Delete(); - door_actor->Delete(); - wall_points->Delete(); - wall_lines->Delete(); - wall_lineScalars->Delete(); - wall_mapper->Delete(); - wall_actor->Delete(); +LinePlotter2D::~LinePlotter2D() +{ + + m_lookupTable->Delete(); + assembly->Delete(); + door_points->Delete(); + door_lines->Delete(); + door_lineScalars->Delete(); + door_mapper->Delete(); + door_actor->Delete(); + wall_points->Delete(); + wall_lines->Delete(); + wall_lineScalars->Delete(); + wall_mapper->Delete(); + wall_actor->Delete(); } void LinePlotter2D::SetAllLineWidth(int width) { - //m_allLineWidth = width ; + //m_allLineWidth = width ; } void LinePlotter2D::PlotDoor(double m[3], double n[3], double scalar) { - door_points->InsertNextPoint(m); - door_lineScalars->InsertNextTuple1(scalar); - door_points->InsertNextPoint(n); - door_lineScalars->InsertNextTuple1(scalar); + door_points->InsertNextPoint(m); + door_lineScalars->InsertNextTuple1(scalar); + door_points->InsertNextPoint(n); + door_lineScalars->InsertNextTuple1(scalar); - door_lines->InsertNextCell(2); - door_lines->InsertCellPoint(door_curPointID); - door_lines->InsertCellPoint(door_curPointID+1); + door_lines->InsertNextCell(2); + door_lines->InsertCellPoint(door_curPointID); + door_lines->InsertCellPoint(door_curPointID+1); - door_curPointID+=2; + door_curPointID+=2; - if(scalar!=1.0){ - doorColorsToDefault=false; - } + if(scalar!=1.0) { + doorColorsToDefault=false; + } } void LinePlotter2D::changeWallsColor(double *col) { - //first switch off the automatic mapping - wall_mapper->SetScalarVisibility(0); - //then set the new color + //first switch off the automatic mapping + wall_mapper->SetScalarVisibility(0); + //then set the new color wall_actor->GetProperty()->SetColor(col); } @@ -168,24 +169,24 @@ void LinePlotter2D::changeNavLinesColor(double *col) void LinePlotter2D::changeDoorsColor(double *col) { - //first switch off the automatic mapping - door_mapper->SetScalarVisibility(0); - //then set the new color - door_actor->GetProperty()->SetColor(col); + //first switch off the automatic mapping + door_mapper->SetScalarVisibility(0); + //then set the new color + door_actor->GetProperty()->SetColor(col); } void LinePlotter2D::PlotWall(double m[3], double n[3], double scalar) { - wall_points->InsertNextPoint(m); - wall_lineScalars->InsertNextTuple1(scalar); - wall_points->InsertNextPoint(n); - wall_lineScalars->InsertNextTuple1(scalar); + wall_points->InsertNextPoint(m); + wall_lineScalars->InsertNextTuple1(scalar); + wall_points->InsertNextPoint(n); + wall_lineScalars->InsertNextTuple1(scalar); - wall_lines->InsertNextCell(2); - wall_lines->InsertCellPoint(wall_curPointID); - wall_lines->InsertCellPoint(wall_curPointID+1); + wall_lines->InsertNextCell(2); + wall_lines->InsertCellPoint(wall_curPointID); + wall_lines->InsertCellPoint(wall_curPointID+1); - wall_curPointID+=2; + wall_curPointID+=2; } //vtkPolyData* LinePlotter2D::CreatePolyData() @@ -246,8 +247,8 @@ vtkAssembly* LinePlotter2D::createAssembly() //if default, then hide all doors // fixme: not working - if(doorColorsToDefault){ - double col[3]={1.0,1.0,1.0}; + if(doorColorsToDefault) { + double col[3]= {1.0,1.0,1.0}; SystemSettings::getBackgroundColor(col); door_actor->GetProperty()->SetColor(col); door_actor->Modified(); @@ -301,10 +302,12 @@ vtkAssembly* LinePlotter2D::createAssembly() return assembly; } -void LinePlotter2D::showDoors(bool status){ - door_actor->SetVisibility(status); +void LinePlotter2D::showDoors(bool status) +{ + door_actor->SetVisibility(status); } -void LinePlotter2D::showWalls(bool status){ +void LinePlotter2D::showWalls(bool status) +{ wall_actor->SetVisibility(status); } diff --git a/src/geometry/LinePlotter2D.h b/src/geometry/LinePlotter2D.h index 46776870578a6294bb083f4bcfec5807c6006f98..2d4392b10a11f54061154845d40ed31ecdadeee6 100644 --- a/src/geometry/LinePlotter2D.h +++ b/src/geometry/LinePlotter2D.h @@ -43,55 +43,54 @@ class vtkPolyData; class vtkPolyDataMapper; -class LinePlotter2D -{ +class LinePlotter2D { public: - LinePlotter2D(); - ~LinePlotter2D(); + LinePlotter2D(); + ~LinePlotter2D(); - void SetAllLineWidth(int width = 1); - - void PlotDoor(double m[3], double n[3], double scalar); - void changeDoorsColor(double* col); + void SetAllLineWidth(int width = 1); - void PlotWall(double m[3], double n[3], double scalar); - void changeWallsColor(double *col); + void PlotDoor(double m[3], double n[3], double scalar); + void changeDoorsColor(double* col); + + void PlotWall(double m[3], double n[3], double scalar); + void changeWallsColor(double *col); void PlotNavLine(double m[3], double n[3], double scalar); void changeNavLinesColor(double *col); - void showDoors(bool status); - void showWalls(bool status); + void showDoors(bool status); + void showWalls(bool status); void showNavLines(bool status); - vtkAssembly* createAssembly(); - static bool doorColorsToDefault; + vtkAssembly* createAssembly(); + static bool doorColorsToDefault; private: - vtkLookupTable* m_lookupTable ; - vtkAssembly* assembly; + vtkLookupTable* m_lookupTable ; + vtkAssembly* assembly; - /// doors parameters - int door_curPointID ; + /// doors parameters + int door_curPointID ; double door_width; - vtkPoints* door_points; - vtkCellArray* door_lines; - vtkFloatArray* door_lineScalars ; - vtkPolyDataMapper* door_mapper; - vtkActor* door_actor; - - /// walls parameters - int wall_curPointID ; + vtkPoints* door_points; + vtkCellArray* door_lines; + vtkFloatArray* door_lineScalars ; + vtkPolyDataMapper* door_mapper; + vtkActor* door_actor; + + /// walls parameters + int wall_curPointID ; double wall_width; - vtkPoints* wall_points; - vtkCellArray* wall_lines; - vtkFloatArray* wall_lineScalars ; - vtkPolyDataMapper* wall_mapper; - vtkActor* wall_actor; + vtkPoints* wall_points; + vtkCellArray* wall_lines; + vtkFloatArray* wall_lineScalars ; + vtkPolyDataMapper* wall_mapper; + vtkActor* wall_actor; /// navigation lines parameters int navline_curPointID ; diff --git a/src/geometry/NavLine.cpp b/src/geometry/NavLine.cpp index ade179a33d520ace2144c3be73eb4e6cec455ee4..5f3cfc37aafc9b4e8b26c92ff51a3ad68f280b8d 100644 --- a/src/geometry/NavLine.cpp +++ b/src/geometry/NavLine.cpp @@ -30,15 +30,18 @@ -NavLine::NavLine() { +NavLine::NavLine() +{ } -NavLine::NavLine(Line l):Line(l) { +NavLine::NavLine(Line l):Line(l) +{ } -NavLine::~NavLine() { +NavLine::~NavLine() +{ } diff --git a/src/geometry/NavLine.h b/src/geometry/NavLine.h index 442ffa8b919d367945d78c01e6f55b8a292c6fda..8e82cc7aa7a7c93d93b135795fe89960602abe9a 100644 --- a/src/geometry/NavLine.h +++ b/src/geometry/NavLine.h @@ -33,9 +33,9 @@ class NavLine: public Line { public: - NavLine(); - NavLine(Line l); - virtual ~NavLine(); + NavLine(); + NavLine(Line l); + virtual ~NavLine(); }; diff --git a/src/geometry/Obstacle.cpp b/src/geometry/Obstacle.cpp index f36458d18613631538dc4917f6b98a2e66920f47..564527a31cc418b29822d35a19f20a95414f9585 100644 --- a/src/geometry/Obstacle.cpp +++ b/src/geometry/Obstacle.cpp @@ -44,204 +44,222 @@ using namespace std; -Obstacle::Obstacle() { - _isClosed=0.0; - _height=0.0; - _id=-1; - _caption="obstacle"; - _walls = vector<Wall > (); - _poly = vector<Point > (); +Obstacle::Obstacle() +{ + _isClosed=0.0; + _height=0.0; + _id=-1; + _caption="obstacle"; + _walls = vector<Wall > (); + _poly = vector<Point > (); } Obstacle::~Obstacle() {} -void Obstacle::AddWall(const Wall& w) { - _walls.push_back(w); +void Obstacle::AddWall(const Wall& w) +{ + _walls.push_back(w); } -string Obstacle::GetCaption() const { - return _caption; +string Obstacle::GetCaption() const +{ + return _caption; } -void Obstacle::SetCaption(string caption) { - _caption = caption; +void Obstacle::SetCaption(string caption) +{ + _caption = caption; } -double Obstacle::GetClosed() const { - return _isClosed; +double Obstacle::GetClosed() const +{ + return _isClosed; } -void Obstacle::SetClosed(double closed) { - _isClosed = closed; +void Obstacle::SetClosed(double closed) +{ + _isClosed = closed; } -double Obstacle::GetHeight() const { - return _height; +double Obstacle::GetHeight() const +{ + return _height; } -void Obstacle::SetHeight(double height) { - _height = height; +void Obstacle::SetHeight(double height) +{ + _height = height; } -int Obstacle::GetId() const { - return _id; +int Obstacle::GetId() const +{ + return _id; } -void Obstacle::SetId(int id) { - _id = id; +void Obstacle::SetId(int id) +{ + _id = id; } -const vector<Point>& Obstacle::GetPolygon() const { - return _poly; +const vector<Point>& Obstacle::GetPolygon() const +{ + return _poly; } -string Obstacle::Write() { - string s; - //Point pos; +string Obstacle::Write() +{ + string s; + //Point pos; - for (unsigned int j = 0; j < _walls.size(); j++) { - const Wall& w = _walls[j]; - s.append(w.Write()); - //pos = pos + w.GetPoint1() + w.GetPoint2(); - } - //pos = pos * (0.5 / _walls.size()); + for (unsigned int j = 0; j < _walls.size(); j++) { + const Wall& w = _walls[j]; + s.append(w.Write()); + //pos = pos + w.GetPoint1() + w.GetPoint2(); + } + //pos = pos * (0.5 / _walls.size()); - Point pos = GetCentroid(); + Point pos = GetCentroid(); - //add the obstacle caption - char tmp[CLENGTH]; - //sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%s\" color=\"100\" />\n" - // , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, _caption.c_str()); + //add the obstacle caption + char tmp[CLENGTH]; + //sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%s\" color=\"100\" />\n" + // , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, _caption.c_str()); - sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%d\" color=\"100\" />\n" - , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, _id); - s.append(tmp); + sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%d\" color=\"100\" />\n" + , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, _id); + s.append(tmp); - return s; + return s; } -const vector<Wall>& Obstacle::GetAllWalls() const { - return _walls; +const vector<Wall>& Obstacle::GetAllWalls() const +{ + return _walls; } -int Obstacle::WhichQuad(const Point& vertex, const Point& hitPos) const { - return (vertex.GetX() > hitPos.GetX()) ? ((vertex.GetY() > hitPos.GetY()) ? 1 : 4) : - ((vertex.GetY() > hitPos.GetY()) ? 2 : 3); +int Obstacle::WhichQuad(const Point& vertex, const Point& hitPos) const +{ + return (vertex.GetX() > hitPos.GetX()) ? ((vertex.GetY() > hitPos.GetY()) ? 1 : 4) : + ((vertex.GetY() > hitPos.GetY()) ? 2 : 3); } // x-Koordinate der Linie von einer Eccke zur nächsten -double Obstacle::Xintercept(const Point& point1, const Point& point2, double hitY) const { - return (point2.GetX() - (((point2.GetY() - hitY) * (point1.GetX() - point2.GetX())) / - (point1.GetY() - point2.GetY()))); +double Obstacle::Xintercept(const Point& point1, const Point& point2, double hitY) const +{ + return (point2.GetX() - (((point2.GetY() - hitY) * (point1.GetX() - point2.GetX())) / + (point1.GetY() - point2.GetY()))); } -bool Obstacle::Contains(const Point& ped) const { - - // in the case the obstacle is not a close surface, allow - // pedestrians distribution 'inside' - if(_isClosed==0.0) { - char tmp[CLENGTH]; - sprintf(tmp, "ERROR: \tObstacle::Contains(): the obstacle [%d] is open!!!\n", _id); - Log->Write(tmp); - exit(EXIT_FAILURE); - } - - short edge, first, next; - short quad, next_quad, delta, total; - - ///////////////////////////////////////////////////////////// - edge = first = 0; - quad = WhichQuad(_poly[edge], ped); - total = 0; // COUNT OF ABSOLUTE SECTORS CROSSED - /* LOOP THROUGH THE VERTICES IN A SECTOR */ - do { - next = (edge + 1) % _poly.size(); - next_quad = WhichQuad(_poly[next], ped); - delta = next_quad - quad; // HOW MANY QUADS HAVE I MOVED - - // SPECIAL CASES TO HANDLE CROSSINGS OF MORE THEN ONE - //QUAD - - switch (delta) { - case 2: // IF WE CROSSED THE MIDDLE, FIGURE OUT IF IT - //WAS CLOCKWISE OR COUNTER - case -2: // US THE X POSITION AT THE HIT POINT TO - // DETERMINE WHICH WAY AROUND - if (Xintercept(_poly[edge], _poly[next], ped.GetY()) > ped.GetX()) - delta = -(delta); - break; - case 3: // MOVING 3 QUADS IS LIKE MOVING BACK 1 - delta = -1; - break; - case -3: // MOVING BACK 3 IS LIKE MOVING FORWARD 1 - delta = 1; - break; - } - /* ADD IN THE DELTA */ - total += delta; - quad = next_quad; // RESET FOR NEXT STEP - edge = next; - } while (edge != first); - - /* AFTER ALL IS DONE IF THE TOTAL IS 4 THEN WE ARE INSIDE */ - if (abs(total) == 4) - return true; - else - return false; +bool Obstacle::Contains(const Point& ped) const +{ + + // in the case the obstacle is not a close surface, allow + // pedestrians distribution 'inside' + if(_isClosed==0.0) { + char tmp[CLENGTH]; + sprintf(tmp, "ERROR: \tObstacle::Contains(): the obstacle [%d] is open!!!\n", _id); + Log->Write(tmp); + exit(EXIT_FAILURE); + } + + short edge, first, next; + short quad, next_quad, delta, total; + + ///////////////////////////////////////////////////////////// + edge = first = 0; + quad = WhichQuad(_poly[edge], ped); + total = 0; // COUNT OF ABSOLUTE SECTORS CROSSED + /* LOOP THROUGH THE VERTICES IN A SECTOR */ + do { + next = (edge + 1) % _poly.size(); + next_quad = WhichQuad(_poly[next], ped); + delta = next_quad - quad; // HOW MANY QUADS HAVE I MOVED + + // SPECIAL CASES TO HANDLE CROSSINGS OF MORE THEN ONE + //QUAD + + switch (delta) { + case 2: // IF WE CROSSED THE MIDDLE, FIGURE OUT IF IT + //WAS CLOCKWISE OR COUNTER + case -2: // US THE X POSITION AT THE HIT POINT TO + // DETERMINE WHICH WAY AROUND + if (Xintercept(_poly[edge], _poly[next], ped.GetY()) > ped.GetX()) + delta = -(delta); + break; + case 3: // MOVING 3 QUADS IS LIKE MOVING BACK 1 + delta = -1; + break; + case -3: // MOVING BACK 3 IS LIKE MOVING FORWARD 1 + delta = 1; + break; + } + /* ADD IN THE DELTA */ + total += delta; + quad = next_quad; // RESET FOR NEXT STEP + edge = next; + } while (edge != first); + + /* AFTER ALL IS DONE IF THE TOTAL IS 4 THEN WE ARE INSIDE */ + if (abs(total) == 4) + return true; + else + return false; } -bool Obstacle::ConvertLineToPoly() { +bool Obstacle::ConvertLineToPoly() +{ - if(_isClosed==0.0){ - char tmp[CLENGTH]; - sprintf(tmp, "INFO: \tObstacle [%d] is not closed. Not converting to polyline.\n", _id); - Log->Write(tmp); + if(_isClosed==0.0) { + char tmp[CLENGTH]; + sprintf(tmp, "INFO: \tObstacle [%d] is not closed. Not converting to polyline.\n", _id); + Log->Write(tmp); return true; - } - vector<Line*> copy; - vector<Point> tmpPoly; - Point point; - Line* line; - // Alle Linienelemente in copy speichern - for (unsigned int i = 0; i < _walls.size(); i++) { - copy.push_back(&_walls[i]); - } - - line = copy[0]; - tmpPoly.push_back(line->GetPoint1()); - point = line->GetPoint2(); - copy.erase(copy.begin()); - // Polygon aus allen Linen erzeugen - for (int i = 0; i < (int) copy.size(); i++) { - line = copy[i]; - if ((point - line->GetPoint1()).Norm() < J_TOLERANZ) { - tmpPoly.push_back(line->GetPoint1()); - point = line->GetPoint2(); - copy.erase(copy.begin() + i); - // von vorne suchen - i = -1; - } else if ((point - line->GetPoint2()).Norm() < J_TOLERANZ) { - tmpPoly.push_back(line->GetPoint2()); - point = line->GetPoint1(); - copy.erase(copy.begin() + i); - // von vorne suchen - i = -1; - } - } - if ((tmpPoly[0] - point).Norm() > J_TOLERANZ) { - char tmp[CLENGTH]; - sprintf(tmp, "ERROR: \tObstacle::ConvertLineToPoly(): ID %d !!!\n", _id); - Log->Write(tmp); + } + vector<Line*> copy; + vector<Point> tmpPoly; + Point point; + Line* line; + // Alle Linienelemente in copy speichern + for (unsigned int i = 0; i < _walls.size(); i++) { + copy.push_back(&_walls[i]); + } + + line = copy[0]; + tmpPoly.push_back(line->GetPoint1()); + point = line->GetPoint2(); + copy.erase(copy.begin()); + // Polygon aus allen Linen erzeugen + for (int i = 0; i < (int) copy.size(); i++) { + line = copy[i]; + if ((point - line->GetPoint1()).Norm() < J_TOLERANZ) { + tmpPoly.push_back(line->GetPoint1()); + point = line->GetPoint2(); + copy.erase(copy.begin() + i); + // von vorne suchen + i = -1; + } else if ((point - line->GetPoint2()).Norm() < J_TOLERANZ) { + tmpPoly.push_back(line->GetPoint2()); + point = line->GetPoint1(); + copy.erase(copy.begin() + i); + // von vorne suchen + i = -1; + } + } + if ((tmpPoly[0] - point).Norm() > J_TOLERANZ) { + char tmp[CLENGTH]; + sprintf(tmp, "ERROR: \tObstacle::ConvertLineToPoly(): ID %d !!!\n", _id); + Log->Write(tmp); return false; - } - _poly = tmpPoly; + } + _poly = tmpPoly; return true; } -const Point Obstacle::GetCentroid() const{ +const Point Obstacle::GetCentroid() const +{ double px=0,py=0; double signedArea = 0.0; @@ -253,8 +271,7 @@ const Point Obstacle::GetCentroid() const{ // For all vertices except last unsigned int i=0; - for (i=0; i<_poly.size()-1; ++i) - { + for (i=0; i<_poly.size()-1; ++i) { x0 = _poly[i].GetX(); y0 = _poly[i].GetY(); x1 = _poly[i+1].GetX(); @@ -283,12 +300,13 @@ const Point Obstacle::GetCentroid() const{ } -bool Obstacle::IntersectWithLine(const Line& line) const { +bool Obstacle::IntersectWithLine(const Line& line) const +{ - for (unsigned int i=0;i<_walls.size();i++){ + for (unsigned int i=0; i<_walls.size(); i++) { - if(_walls[i].IntersectionWith(line)) return true; - } + if(_walls[i].IntersectionWith(line)) return true; + } - return false; + return false; } diff --git a/src/geometry/Obstacle.h b/src/geometry/Obstacle.h index 6456bd22cc43a29458ff85bf0ba086ed6c60b032..d682707977966a04fed7696f637936817325b547 100644 --- a/src/geometry/Obstacle.h +++ b/src/geometry/Obstacle.h @@ -39,107 +39,107 @@ class Obstacle { private: - double _isClosed; - double _height; - int _id; - std::string _caption; - std::vector<Wall> _walls; - std::vector<Point> _poly; + double _isClosed; + double _height; + int _id; + std::string _caption; + std::vector<Wall> _walls; + std::vector<Point> _poly; public: - Obstacle(); - virtual ~Obstacle(); - - /** - * Set/Get the obstacles' caption - */ - std::string GetCaption() const; - - /** - * Set/Get the obstacles' caption - */ - void SetCaption(std::string caption); - - /** - * Set/Get the close state of the obstacle - */ - double GetClosed() const; - - /** - * Set/Get the close state of the obstacle - */ - void SetClosed(double closed); - - /** - * Set/Get the height of the obstacle. - * Is used for computing visibility - */ - double GetHeight() const; - - /** - * Set/Get the height of the obstacle. - * Is used for computing visibility - */ - void SetHeight(double height); - - /** - * Set/Get the id of the obstacle - */ - int GetId() const; - - /** - * Set/Get the id of the obstacle - */ - void SetId(int id); - - /** - * construct the obstacle by adding more walls - */ - void AddWall(const Wall& w); - - /** - * @return All walls that constitute the obstacle - */ - const std::vector<Wall>& GetAllWalls() const; - - /** - * @return true if the point p is contained within the Closed Obstacle - * @see Setclose - */ - bool Contains(const Point& p) const; - - /** - * Create the obstacles polygonal structure from the walls - */ + Obstacle(); + virtual ~Obstacle(); + + /** + * Set/Get the obstacles' caption + */ + std::string GetCaption() const; + + /** + * Set/Get the obstacles' caption + */ + void SetCaption(std::string caption); + + /** + * Set/Get the close state of the obstacle + */ + double GetClosed() const; + + /** + * Set/Get the close state of the obstacle + */ + void SetClosed(double closed); + + /** + * Set/Get the height of the obstacle. + * Is used for computing visibility + */ + double GetHeight() const; + + /** + * Set/Get the height of the obstacle. + * Is used for computing visibility + */ + void SetHeight(double height); + + /** + * Set/Get the id of the obstacle + */ + int GetId() const; + + /** + * Set/Get the id of the obstacle + */ + void SetId(int id); + + /** + * construct the obstacle by adding more walls + */ + void AddWall(const Wall& w); + + /** + * @return All walls that constitute the obstacle + */ + const std::vector<Wall>& GetAllWalls() const; + + /** + * @return true if the point p is contained within the Closed Obstacle + * @see Setclose + */ + bool Contains(const Point& p) const; + + /** + * Create the obstacles polygonal structure from the walls + */ bool ConvertLineToPoly(); - /** - * @return the obstacle as a polygon - */ - const std::vector<Point>& GetPolygon() const; + /** + * @return the obstacle as a polygon + */ + const std::vector<Point>& GetPolygon() const; - /** - * @return the centroid of the obstacle - */ - const Point GetCentroid() const; + /** + * @return the centroid of the obstacle + */ + const Point GetCentroid() const; - /** - * return true if the given line intersects - * or share common vertex with the obstacle - */ - bool IntersectWithLine(const Line & line) const; + /** + * return true if the given line intersects + * or share common vertex with the obstacle + */ + bool IntersectWithLine(const Line & line) const; - /** - * @return a nicely formatted string representation of the obstacle - */ - std::string Write(); + /** + * @return a nicely formatted string representation of the obstacle + */ + std::string Write(); private: - int WhichQuad(const Point& vertex, const Point& hitPos) const; + int WhichQuad(const Point& vertex, const Point& hitPos) const; - // x-Koordinate der Linie von einer Eccke zur nächsten - double Xintercept(const Point& point1, const Point& point2, - double hitY) const; + // x-Koordinate der Linie von einer Eccke zur nächsten + double Xintercept(const Point& point1, const Point& point2, + double hitY) const; }; diff --git a/src/geometry/Point.cpp b/src/geometry/Point.cpp index 3f7256225da035635d0d774325461fce55fa8f0f..13821ba03c8107bd7efa8a5719965b22ad6977f7 100644 --- a/src/geometry/Point.cpp +++ b/src/geometry/Point.cpp @@ -1,6 +1,6 @@ /** * File: Point.cpp - * + * * Created on 30. September 2010, 09:21 * @section LICENSE * This file is part of JuPedSim. @@ -38,52 +38,63 @@ /************************************************************ Konstruktoren ************************************************************/ -Point::Point() { +Point::Point() +{ _x = 0.0; _y = 0.0; } -Point::Point(double x, double y) { +Point::Point(double x, double y) +{ _x = x; _y = y; } -Point::Point(const Point& orig) { +Point::Point(const Point& orig) +{ _x = orig.GetX(); _y = orig.GetY(); } -std::string Point::toString() const { - std::stringstream tmp; - tmp<<"( "<<_x<<" : " <<_y<<" )"; - return tmp.str(); +std::string Point::toString() const +{ + std::stringstream tmp; + tmp<<"( "<<_x<<" : " <<_y<<" )"; + return tmp.str(); }; -void Point::SetX(double x) { +void Point::SetX(double x) +{ _x = x; } -void Point::SetY(double y) { +void Point::SetY(double y) +{ _y = y; } -double Point::GetX() const { +double Point::GetX() const +{ return _x; } -double Point::GetY() const { +double Point::GetY() const +{ return _y; } -double Point::Norm() const { +double Point::Norm() const +{ return sqrt(_x * _x + _y * _y); } -double Point::NormSquare() const { +double Point::NormSquare() const +{ return (_x * _x + _y * _y); } -Point Point::Normalized() const { +Point Point::Normalized() const +{ double norm=Norm(); if (norm > J_EPS*J_EPS) return ( Point(_x, _y) / norm ); @@ -91,14 +102,16 @@ Point Point::Normalized() const { } // scalar product -double Point::ScalarP(const Point& v) const { +double Point::ScalarP(const Point& v) const +{ //return _x * v.GetX() + _y * v.GetY(); return _x * v._x + _y * v._y; } /// determinant of the square matrix formed by the vectors [ this, v] -double Point::Det(const Point& v) const { - return _x * v._y - _y * v._x; +double Point::Det(const Point& v) const +{ + return _x * v._y - _y * v._x; } /* Transformiert die "normalen" Koordinaten in Koordinaten der Ellipse @@ -110,13 +123,13 @@ double Point::Det(const Point& v) const { /*coordinate transformation of the point P(x,y) expressed in coord system S1 to a new coord. sys S2 - + A - * - | S_2 - \ | / - | \ | / - | \ | /^phi + * + | S_2 + \ | / + | \ | / + | \ | /^phi | yc___\ /_)_________ S_3 | O1 | | @@ -129,17 +142,17 @@ S_1 //////////////////////////////////// -S_1 is cartesian coordinate system!! +S_1 is cartesian coordinate system!! //////////////////////////////////// input: - (x,y) : coordinates of the point A in S_1 - (xc,yc) : coordinate of the center in the S_1 (Center of Ellipse) - phi : angle between the S_1 and S_2 - + output: - + (xnew,ynew) : new coordinate of the point A in the coord. sys S2 - + + (xnew,ynew) : new coordinate of the point A in the coord. sys S2 + OA = OO1 + O1A [x ; y] = [xc ; yc] + [x_3 ; y_3] : (1) ( with [x_i ; y_i] coordinats of P in S_i and i in {1,2,3} ) @@ -147,7 +160,7 @@ OA = OO1 + O1A [x_2 ; y_2] = M(phi) * [x_3 ; y_3] : (2) -(1) in (2)---> +(1) in (2)---> --> [x_2 ; y_2] = M(phi) * ([x ; y] - [xc ; yc]) @@ -158,22 +171,23 @@ OC = OO1 +O1C OC = -O1O +O1C xnew = -xc + x - + */ -Point Point::CoordTransToEllipse(const Point& center, double cphi, double sphi) const { +Point Point::CoordTransToEllipse(const Point& center, double cphi, double sphi) const +{ Point p = Point(_x, _y); return (p - center).Rotate(cphi, -sphi); } /* -This is the reverse funktion of CoordTransToEllipse(), +This is the reverse funktion of CoordTransToEllipse(), where the coord. of a point are transformated to cart. coord. input: - (x,y) : coordinates of the point P in S_2 - (xc,yc) : coordinate of the center in the S_1 (Center of Ellipse) - phi : angle between the S_1 and S_2 - + output: + (xnew,ynew) : new coordinate of the point P in the coord. sys S_1 @@ -184,7 +198,8 @@ where the coord. of a point are transformated to cart. coord. */ -Point Point::CoordTransToCart(const Point& center, double cphi, double sphi) const { +Point Point::CoordTransToCart(const Point& center, double cphi, double sphi) const +{ Point p = Point(_x, _y); return (p.Rotate(cphi, sphi) + center); } @@ -195,47 +210,53 @@ Rotation-matrix=[cos(theta) -sin(theta)] [ sin(theta) cos(theta)] */ -Point Point::Rotate(double ctheta, double stheta) const { +Point Point::Rotate(double ctheta, double stheta) const +{ return Point(_x * ctheta - _y*stheta, _x * stheta + _y * ctheta); } // sum -const Point Point::operator+(const Point& p) const { +const Point Point::operator+(const Point& p) const +{ //return Point(_x + p.GetX(), _y + p.GetY()); return Point(_x + p._x, _y + p._y); } // sub -const Point Point::operator-(const Point& p) const { +const Point Point::operator-(const Point& p) const +{ // return Point(_x - p.GetX(), _y - p.GetY()); return Point(_x - p._x, _y - p._y); } // equal -bool Point::operator==(const Point& p) const { +bool Point::operator==(const Point& p) const +{ // return (fabs(_x - p.GetX()) < J_EPS && fabs(_y - p.GetY()) < J_EPS); return (fabs(_x - p._x) < J_EPS && fabs(_y - p._y) < J_EPS); } // not equal -bool Point::operator!=(const Point& p) const { +bool Point::operator!=(const Point& p) const +{ //return (fabs(_x - p.GetX()) > J_EPS || fabs(_y - p.GetY()) > J_EPS); return (fabs(_x - p._x) > J_EPS || fabs(_y - p._y) > J_EPS); } // multiplication with scalar -const Point operator*(const Point& p, double f) { +const Point operator*(const Point& p, double f) +{ //return Point(p.GetX() * f, p.GetY() * f); return Point(p._x * f, p._y * f); } // divition with scalar -const Point operator/(const Point& p, double f) { +const Point operator/(const Point& p, double f) +{ if (f>J_EPS*J_EPS) return Point(p._x / f, p._y / f); - else - { + else { std::cout << "Warning: Point::/operator. dividand "<<f<< " is to small. Set it to 1 instead"<<std::endl; return Point(p._x, p._y); } diff --git a/src/geometry/Point.h b/src/geometry/Point.h index 46dcca7b19c4f4afc22d433b237c8f6461af361e..6064885fae63006240e8783c8dbb361d16b1af82 100644 --- a/src/geometry/Point.h +++ b/src/geometry/Point.h @@ -66,7 +66,7 @@ public: double Norm() const; /// Norm square double NormSquare() const; - /// normalized vector + /// normalized vector Point Normalized() const; /// dot product double ScalarP(const Point& v) const; diff --git a/src/geometry/PointPlotter.cpp b/src/geometry/PointPlotter.cpp index d4c8c7b04f58c7dc8ddbff010ae2f058a2ae7c51..e075c0d0acb3941eaa1af72a33d10a00686f8091 100644 --- a/src/geometry/PointPlotter.cpp +++ b/src/geometry/PointPlotter.cpp @@ -29,15 +29,15 @@ PointPlotter::PointPlotter() { - pts = vtkPoints::New(); - //pts->Allocate(30); - //pts->SetNumberOfPoints(30); - //pts->SetNumberOfPoints(MAX_POINTS); - SetPointRadius(2); - SetPointResolution(); - - scalars = vtkUnsignedCharArray::New(); - scalars->SetNumberOfComponents(3); + pts = vtkPoints::New(); + //pts->Allocate(30); + //pts->SetNumberOfPoints(30); + //pts->SetNumberOfPoints(MAX_POINTS); + SetPointRadius(2); + SetPointResolution(); + + scalars = vtkUnsignedCharArray::New(); + scalars->SetNumberOfComponents(3); colors=vtkFloatArray::New(); // VTK_CREATE(vtkDiskSource,src); @@ -51,13 +51,13 @@ PointPlotter::PointPlotter() src->SetNumberOfSides(5); - VTK_CREATE(vtkPolyData,polyData); - polyData->SetPoints(pts); + VTK_CREATE(vtkPolyData,polyData); + polyData->SetPoints(pts); //polyData->GetPointData()->SetScalars(scalars); polyData->GetPointData()->SetScalars(colors); - VTK_CREATE(vtkGlyph3D,glyph); - glyph->SetSourceConnection(src->GetOutputPort()); + VTK_CREATE(vtkGlyph3D,glyph); + glyph->SetSourceConnection(src->GetOutputPort()); #if VTK_MAJOR_VERSION <= 5 glyph->SetInput(polyData); @@ -66,35 +66,35 @@ PointPlotter::PointPlotter() #endif glyph->SetColorModeToColorByScalar(); - glyph->SetScaleModeToDataScalingOff() ; + glyph->SetScaleModeToDataScalingOff() ; - VTK_CREATE(vtkPolyDataMapper,mapper); + VTK_CREATE(vtkPolyDataMapper,mapper); mapper->SetInputConnection(glyph->GetOutputPort()); //borrow the lookup table from the peds glyphs if(extern_glyphs_pedestrians_actor_2D->GetMapper()) - mapper->SetLookupTable( - extern_glyphs_pedestrians_actor_2D->GetMapper()->GetLookupTable()); + mapper->SetLookupTable( + extern_glyphs_pedestrians_actor_2D->GetMapper()->GetLookupTable()); //vtkActor - pointActor = vtkActor::New(); - pointActor->SetMapper(mapper); + pointActor = vtkActor::New(); + pointActor->SetMapper(mapper); - /// initizliae the ID - nextPointID=0; + /// initizliae the ID + nextPointID=0; } PointPlotter::~PointPlotter() { - if (pts) - pts->Delete(); - if (scalars) - scalars->Delete(); + if (pts) + pts->Delete(); + if (scalars) + scalars->Delete(); if (colors) colors->Delete(); - if (pointActor) - pointActor->Delete(); + if (pointActor) + pointActor->Delete(); } @@ -102,26 +102,24 @@ PointPlotter::~PointPlotter() * add a point to the plot */ -void PointPlotter::PlotPoint(JPoint * point){ - double x=point->getX(); - double y=point->getY(); - double z=point->getZ(); - - unsigned char r=point->getR(); - unsigned char b=point->getB(); - unsigned char g=point->getG(); - PlotPoint( x, y, z, r, g, b); +void PointPlotter::PlotPoint(JPoint * point) +{ + double x=point->getX(); + double y=point->getY(); + double z=point->getZ(); + + unsigned char r=point->getR(); + unsigned char b=point->getB(); + unsigned char g=point->getG(); + PlotPoint( x, y, z, r, g, b); } void PointPlotter::PlotPoint(double pos[3], double col) { nextPointID++; - if(col==-1) - { + if(col==-1) { colors->InsertTuple1(nextPointID,NAN); - } - else - { + } else { colors->InsertTuple1(nextPointID,col/255.0); } @@ -131,29 +129,32 @@ void PointPlotter::PlotPoint(double pos[3], double col) } void PointPlotter::PlotPoint(double x, double y, double z, - unsigned char r, unsigned char g, unsigned char b) + unsigned char r, unsigned char g, unsigned char b) { - nextPointID++; - int PointsCount=1, dummy=0,dummy1;; + nextPointID++; + int PointsCount=1, dummy=0,dummy1;; - SystemSettings::getTrailsInfo(&PointsCount,&dummy,&dummy1); + SystemSettings::getTrailsInfo(&PointsCount,&dummy,&dummy1); //nextPointID=nextPointID%PointsCount; - pts->InsertPoint(nextPointID,x,y,z); + pts->InsertPoint(nextPointID,x,y,z); //pts->SetPoint(nextPointID,x,y,z); //scalars->SetTuple3(nextPointID,r,g,b); scalars->InsertTuple3(nextPointID,r,g,b); //scalars->InsertNextTuple3(r,g,b); - pts->Modified(); + pts->Modified(); scalars->Modified(); } void PointPlotter::SetVisibility(bool status) { - pointActor->SetVisibility(status); + pointActor->SetVisibility(status); } -vtkActor * PointPlotter::getActor(){ return pointActor;} +vtkActor * PointPlotter::getActor() +{ + return pointActor; +} diff --git a/src/geometry/PointPlotter.h b/src/geometry/PointPlotter.h index 341d82bbf7c03f362415aae094e917ec85906a87..4f1104a8ac89c5e9ff6682bd21ce9f0dd26dc672 100644 --- a/src/geometry/PointPlotter.h +++ b/src/geometry/PointPlotter.h @@ -45,40 +45,45 @@ class vtkFloatArray ; class JPoint; //for borrowing the lookup table -extern vtkSmartPointer<vtkActor> extern_glyphs_pedestrians_actor_2D; +extern vtkActor* extern_glyphs_pedestrians_actor_2D; -class PointPlotter -{ +class PointPlotter { public: - PointPlotter(); - ~PointPlotter(); + PointPlotter(); + ~PointPlotter(); - void PlotPoint(double x, double y, double z, - unsigned char r='a', unsigned char g='b', unsigned char b='c'); + void PlotPoint(double x, double y, double z, + unsigned char r='a', unsigned char g='b', unsigned char b='c'); void PlotPoint(JPoint* pt); void PlotPoint(double Position[3], double colour); - void SetPointRadius(double radius = 1.0) { pt_radius = radius ; } - void SetPointResolution(int res = 15) { pt_res = res ;} + void SetPointRadius(double radius = 1.0) + { + pt_radius = radius ; + } + void SetPointResolution(int res = 15) + { + pt_res = res ; + } - ///return the actors - vtkActor* getActor(); + ///return the actors + vtkActor* getActor(); void SetVisibility(bool status); private: - vtkActor* pointActor; - vtkPoints* pts ; - vtkDataArray* scalars ; + vtkActor* pointActor; + vtkPoints* pts ; + vtkDataArray* scalars ; vtkFloatArray* colors; - vtkIdType nextPointID; - int scalar_mode ; - double pt_radius ; - int pt_res ; + vtkIdType nextPointID; + int scalar_mode ; + double pt_radius ; + int pt_res ; }; #endif // POINT_PLOTTER_H diff --git a/src/geometry/PointPlotter2D.cpp b/src/geometry/PointPlotter2D.cpp index bd7c2859697e8c8180ccc5f361b3a30b1d6b26bd..da6ad451b5ff952c4f3da23eab195bfceda39b01 100644 --- a/src/geometry/PointPlotter2D.cpp +++ b/src/geometry/PointPlotter2D.cpp @@ -30,9 +30,9 @@ */ #include "PointPlotter2D.h" -#include "vtkPoints.h" -#include "vtkUnsignedCharArray.h" -#include "vtkPolyData.h" +#include "vtkPoints.h" +#include "vtkUnsignedCharArray.h" +#include "vtkPolyData.h" #include "vtkActor.h" #include "vtkDataArray.h" #include "vtkGlyph3D.h" @@ -42,82 +42,81 @@ PointPlotter2D::PointPlotter2D() { - pts = NULL ; - scalars = NULL ; + pts = NULL ; + scalars = NULL ; + + SetPointRadius(); + SetPointResolution(); - SetPointRadius(); - SetPointResolution(); - } PointPlotter2D::~PointPlotter2D() { - if (pts) - pts->Delete(); - if (scalars) - scalars->Delete(); + if (pts) + pts->Delete(); + if (scalars) + scalars->Delete(); } void PointPlotter2D::PlotPoint(double x, double y, double z, - unsigned char r, unsigned char g, unsigned char b) + unsigned char r, unsigned char g, unsigned char b) { - if (pts==NULL) - pts = vtkPoints::New(); - - if (scalars==NULL) - { - scalars = vtkUnsignedCharArray::New(); - scalars->SetNumberOfComponents(3); - } - - pts->InsertNextPoint(x,y,z); - scalars->InsertNextTuple3(r,g,b); - + if (pts==NULL) + pts = vtkPoints::New(); + + if (scalars==NULL) { + scalars = vtkUnsignedCharArray::New(); + scalars->SetNumberOfComponents(3); + } + + pts->InsertNextPoint(x,y,z); + scalars->InsertNextTuple3(r,g,b); + } vtkPolyData* PointPlotter2D::CreatePolyData() { - vtkDiskSource* src = vtkDiskSource::New(); - src->SetRadialResolution(1); - src->SetCircumferentialResolution(pt_res); + vtkDiskSource* src = vtkDiskSource::New(); + src->SetRadialResolution(1); + src->SetCircumferentialResolution(pt_res); - src->SetInnerRadius(0.0); - src->SetOuterRadius(pt_radius); + src->SetInnerRadius(0.0); + src->SetOuterRadius(pt_radius); - vtkPolyData* polyData = vtkPolyData::New(); - polyData->SetPoints(pts); - polyData->GetPointData()->SetScalars(scalars); + vtkPolyData* polyData = vtkPolyData::New(); + polyData->SetPoints(pts); + polyData->GetPointData()->SetScalars(scalars); - vtkGlyph3D* glyph = vtkGlyph3D::New(); - glyph->SetSourceConnection(src->GetOutputPort()); + vtkGlyph3D* glyph = vtkGlyph3D::New(); + glyph->SetSourceConnection(src->GetOutputPort()); #if VTK_MAJOR_VERSION <= 5 glyph->SetInput(polyData); #else glyph->SetInputData(polyData); #endif - glyph->SetColorModeToColorByScalar(); - glyph->SetScaleModeToDataScalingOff() ; + glyph->SetColorModeToColorByScalar(); + glyph->SetScaleModeToDataScalingOff() ; - vtkPolyData* output = glyph->GetOutput(); - return output ; + vtkPolyData* output = glyph->GetOutput(); + return output ; } vtkActor* PointPlotter2D::CreateActor() { - vtkPolyData* polyData = CreatePolyData(); + vtkPolyData* polyData = CreatePolyData(); - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); #if VTK_MAJOR_VERSION <= 5 mapper->SetInput(polyData); #else mapper->SetInputData(polyData); #endif - vtkActor* actor = vtkActor::New(); - actor->SetMapper(mapper); + vtkActor* actor = vtkActor::New(); + actor->SetMapper(mapper); - return actor ; + return actor ; } diff --git a/src/geometry/PointPlotter2D.h b/src/geometry/PointPlotter2D.h index d98d88700407ed3c60db55b1f84c5e02a15dcc9e..72e8f229aa526ff880450a26f5e758fdaa3b04fe 100644 --- a/src/geometry/PointPlotter2D.h +++ b/src/geometry/PointPlotter2D.h @@ -38,34 +38,39 @@ class vtkPolyData ; class vtkActor ; class vtkDataArray ; -class PointPlotter2D -{ +class PointPlotter2D { public: - - PointPlotter2D(); - ~PointPlotter2D(); + PointPlotter2D(); + ~PointPlotter2D(); - void PlotPoint(double x, double y, double z, - unsigned char r, unsigned char g, unsigned char b); - - void SetPointRadius(double radius = 1.0) { pt_radius = radius ; } - void SetPointResolution(int res = 15) { pt_res = res ;} + void PlotPoint(double x, double y, double z, + unsigned char r, unsigned char g, unsigned char b); + void SetPointRadius(double radius = 1.0) + { + pt_radius = radius ; + } + void SetPointResolution(int res = 15) + { + pt_res = res ; + } - vtkPolyData* CreatePolyData(); // call it after all points are plotted - vtkActor* CreateActor(); // call it after all points are plotted + + + vtkPolyData* CreatePolyData(); // call it after all points are plotted + vtkActor* CreateActor(); // call it after all points are plotted private: - vtkPoints* pts ; - vtkDataArray* scalars ; - int scalar_mode ; + vtkPoints* pts ; + vtkDataArray* scalars ; + int scalar_mode ; - double pt_radius ; - int pt_res ; + double pt_radius ; + int pt_res ; }; #endif // MY_VTK_POINT_PLOTTER_H diff --git a/src/geometry/Room.cpp b/src/geometry/Room.cpp index 5c256a071ba1f3f2be01d6153932258989f93014..f2838fc3c28a5c398858af92a7710945cd2df308 100644 --- a/src/geometry/Room.cpp +++ b/src/geometry/Room.cpp @@ -1,6 +1,6 @@ /** * File: Room.cpp - * + * * Created on 30. September 2010, 11:58 * @section LICENSE * This file is part of JuPedSim. @@ -34,7 +34,8 @@ using namespace std; Konstruktoren ************************************************************/ -Room::Room() { +Room::Room() +{ _id = -1; _state=ROOM_CLEAN; //smoke-free _caption = "no room caption"; @@ -43,7 +44,8 @@ Room::Room() { _outputFile=NULL; } -Room::Room(const Room& orig) { +Room::Room(const Room& orig) +{ _id = orig.GetID(); _caption = orig.GetCaption(); _zPos = orig.GetZPos(); @@ -52,7 +54,8 @@ Room::Room(const Room& orig) { _outputFile=orig.GetOutputHandler(); } -Room::~Room() { +Room::~Room() +{ for (unsigned int i = 0; i < _subRooms.size(); i++) delete _subRooms[i]; } @@ -60,19 +63,23 @@ Room::~Room() { /************************************************************* Setter-Funktionen ************************************************************/ -void Room::SetID(int ID) { +void Room::SetID(int ID) +{ _id = ID; } -void Room::SetCaption(string s) { +void Room::SetCaption(string s) +{ _caption = s; } -void Room::SetZPos(double z) { +void Room::SetZPos(double z) +{ _zPos = z; } -void Room::SetSubRoom(SubRoom* subroom, int index) { +void Room::SetSubRoom(SubRoom* subroom, int index) +{ if ((index >= 0) && (index < GetNumberOfSubRooms())) { _subRooms[index] = subroom; } else { @@ -81,40 +88,47 @@ void Room::SetSubRoom(SubRoom* subroom, int index) { } } -void Room::SetState(RoomState state) { - _state=state; +void Room::SetState(RoomState state) +{ + _state=state; } /************************************************************* Getter-Functions ************************************************************/ -int Room::GetID() const { +int Room::GetID() const +{ return _id; } -string Room::GetCaption() const { +string Room::GetCaption() const +{ return _caption; } -double Room::GetZPos() const { +double Room::GetZPos() const +{ //if(pCaption=="070") return pZPos+1.0; - return _zPos; + return _zPos; } -int Room::GetNumberOfSubRooms() const { +int Room::GetNumberOfSubRooms() const +{ return _subRooms.size(); } -const vector<SubRoom*>& Room::GetAllSubRooms() const { +const vector<SubRoom*>& Room::GetAllSubRooms() const +{ return _subRooms; } -SubRoom* Room::GetSubRoom(int index) const { +SubRoom* Room::GetSubRoom(int index) const +{ if ((index >= 0) && (index < (int) _subRooms.size())) return _subRooms[index]; else { - char tmp[CLENGTH]; + char tmp[CLENGTH]; sprintf(tmp,"ERROR: Room::GetSubRoom() Wrong subroom index [%d] for room index [%d] ",index,_id); Log->Write(tmp); exit(0); @@ -124,7 +138,8 @@ SubRoom* Room::GetSubRoom(int index) const { #ifdef _SIMULATOR -int Room::GetNumberOfPedestrians() const { +int Room::GetNumberOfPedestrians() const +{ int sum = 0; for (int i = 0; i < GetNumberOfSubRooms(); i++) { sum += GetSubRoom(i)->GetNumberOfPedestrians(); @@ -134,8 +149,9 @@ int Room::GetNumberOfPedestrians() const { #endif // _SIMULATOR -RoomState Room::GetState() const { - return _state; +RoomState Room::GetState() const +{ + return _state; } @@ -143,11 +159,13 @@ RoomState Room::GetState() const { /************************************************************* Sonstige Funktionen ************************************************************/ -void Room::AddSubRoom(SubRoom* r) { +void Room::AddSubRoom(SubRoom* r) +{ _subRooms.push_back(r); } -void Room::DeleteSubRoom(int index) { +void Room::DeleteSubRoom(int index) +{ if ((index >= 0) && (index < (int) _subRooms.size())) _subRooms.erase(_subRooms.begin() + index); else { @@ -161,7 +179,8 @@ void Room::DeleteSubRoom(int index) { ************************************************************/ -void Room::WriteToErrorLog() const { +void Room::WriteToErrorLog() const +{ char tmp[CLENGTH]; string s; sprintf(tmp, "\tRaum: %d [%s]:\n", _id, _caption.c_str()); @@ -175,18 +194,22 @@ void Room::WriteToErrorLog() const { } -const vector<int>& Room::GetAllTransitionsIDs() const { - return _transitionsIDs; +const vector<int>& Room::GetAllTransitionsIDs() const +{ + return _transitionsIDs; } -void Room::AddTransitionID(int ID){ - _transitionsIDs.push_back(ID); +void Room::AddTransitionID(int ID) +{ + _transitionsIDs.push_back(ID); } -void Room::SetOutputHandler(OutputHandler* oh){ - _outputFile=oh; +void Room::SetOutputHandler(OutputHandler* oh) +{ + _outputFile=oh; } -OutputHandler* Room::GetOutputHandler() const { - return _outputFile; +OutputHandler* Room::GetOutputHandler() const +{ + return _outputFile; } diff --git a/src/geometry/Room.h b/src/geometry/Room.h index 7917089bc9899b8a92036f9c140313c95fd31be5..d8420813d4cc46146a1deb21e7a5aa7d725acd05 100644 --- a/src/geometry/Room.h +++ b/src/geometry/Room.h @@ -35,8 +35,8 @@ class Room { private: - /// room ID and index - int _id; + /// room ID and index + int _id; /// room state RoomState _state; /// room caption @@ -109,11 +109,11 @@ public: /** * @return a vector containing all transitions Ids */ - const std::vector<int>& GetAllTransitionsIDs() const; + const std::vector<int>& GetAllTransitionsIDs() const; - /** - * @return the Subroom with the corresponding index - */ + /** + * @return the Subroom with the corresponding index + */ SubRoom* GetSubRoom(int index) const; /** @@ -139,7 +139,7 @@ public: /** * Add a new transition id */ - void AddTransitionID(int ID); + void AddTransitionID(int ID); /** diff --git a/src/geometry/SubRoom.cpp b/src/geometry/SubRoom.cpp index cab0d05a920c9375cfd11398d458c3f6412f3817..198f532a0c1a7dec5aaf85971bbea9db86efb283 100644 --- a/src/geometry/SubRoom.cpp +++ b/src/geometry/SubRoom.cpp @@ -46,598 +46,641 @@ using namespace std; int SubRoom::_static_uid=0; -SubRoom::SubRoom() { - _id = -1; - _roomID=-1; - _walls = vector<Wall > (); - _poly = vector<Point > (); - _obstacles=vector<Obstacle*> (); - - _crossings = vector<Crossing*>(); - _transitions = vector<Transition*>(); - _hlines = vector<Hline*>(); - - _planeEquation[0]=0.0; - _planeEquation[1]=0.0; - _planeEquation[2]=0.0; - _cosAngleWithHorizontalPlane=0; - - _goalIDs = vector<int> (); - _area = 0.0; - _closed=false; - _uid = _static_uid++; +SubRoom::SubRoom() +{ + _id = -1; + _roomID=-1; + _walls = vector<Wall > (); + _poly = vector<Point > (); + _obstacles=vector<Obstacle*> (); + + _crossings = vector<Crossing*>(); + _transitions = vector<Transition*>(); + _hlines = vector<Hline*>(); + + _planeEquation[0]=0.0; + _planeEquation[1]=0.0; + _planeEquation[2]=0.0; + _cosAngleWithHorizontalPlane=0; + + _goalIDs = vector<int> (); + _area = 0.0; + _closed=false; + _uid = _static_uid++; #ifdef _SIMULATOR - _peds = vector<Pedestrian* > (); + _peds = vector<Pedestrian* > (); #endif //_SIMULATOR } -SubRoom::SubRoom(const SubRoom& orig) { - _id = orig.GetSubRoomID(); - _walls = orig.GetAllWalls(); - _poly = orig.GetPolygon(); - _goalIDs = orig.GetAllGoalIDs(); - _area = orig.GetArea(); - _closed=orig.GetClosed(); - _roomID=orig.GetRoomID(); - _uid = orig.GetUID(); - _cosAngleWithHorizontalPlane=orig.GetCosAngleWithHorizontal(); +SubRoom::SubRoom(const SubRoom& orig) +{ + _id = orig.GetSubRoomID(); + _walls = orig.GetAllWalls(); + _poly = orig.GetPolygon(); + _goalIDs = orig.GetAllGoalIDs(); + _area = orig.GetArea(); + _closed=orig.GetClosed(); + _roomID=orig.GetRoomID(); + _uid = orig.GetUID(); + _cosAngleWithHorizontalPlane=orig.GetCosAngleWithHorizontal(); #ifdef _SIMULATOR - _peds = orig.GetAllPedestrians(); + _peds = orig.GetAllPedestrians(); #endif //_SIMULATOR } -SubRoom::~SubRoom() { - if (_walls.size() > 0) _walls.clear(); - if (_poly.size() > 0) _poly.clear(); - for (unsigned int i = 0; i < _obstacles.size(); i++) { - delete _obstacles[i]; - } - _obstacles.clear(); +SubRoom::~SubRoom() +{ + if (_walls.size() > 0) _walls.clear(); + if (_poly.size() > 0) _poly.clear(); + for (unsigned int i = 0; i < _obstacles.size(); i++) { + delete _obstacles[i]; + } + _obstacles.clear(); #ifdef _SIMULATOR - for (unsigned int i = 0; i < _peds.size(); i++) { - delete _peds[i]; - } + for (unsigned int i = 0; i < _peds.size(); i++) { + delete _peds[i]; + } #endif //_SIMULATOR } // Setter -Funktionen -void SubRoom::SetSubRoomID(int ID) { - _id = ID; +void SubRoom::SetSubRoomID(int ID) +{ + _id = ID; } -void SubRoom::SetClosed(double closed) { - _closed = closed; +void SubRoom::SetClosed(double closed) +{ + _closed = closed; } -void SubRoom::SetRoomID(int ID) { - _roomID = ID; +void SubRoom::SetRoomID(int ID) +{ + _roomID = ID; } -int SubRoom::GetSubRoomID() const { - return _id; +int SubRoom::GetSubRoomID() const +{ + return _id; } -double SubRoom::GetClosed() const { - return _closed; +double SubRoom::GetClosed() const +{ + return _closed; } // unique identifier for this subroom -int SubRoom::GetUID() const { - return _uid; - //return pRoomID * 1000 + pID; +int SubRoom::GetUID() const +{ + return _uid; + //return pRoomID * 1000 + pID; } -double SubRoom::GetArea() const { - return _area; +double SubRoom::GetArea() const +{ + return _area; } -int SubRoom::GetRoomID() const { - return _roomID; +int SubRoom::GetRoomID() const +{ + return _roomID; } -int SubRoom::GetNumberOfWalls() const { - return _walls.size(); +int SubRoom::GetNumberOfWalls() const +{ + return _walls.size(); } -const vector<Wall>& SubRoom::GetAllWalls() const { - return _walls; +const vector<Wall>& SubRoom::GetAllWalls() const +{ + return _walls; } -const Wall& SubRoom::GetWall(int index) const { - if ((index >= 0) && (index < GetNumberOfWalls())) - return _walls[index]; - else { - Log->Write("ERROR: Wrong 'index' in SubRoom::GetWall()"); - exit(0); - } +const Wall& SubRoom::GetWall(int index) const +{ + if ((index >= 0) && (index < GetNumberOfWalls())) + return _walls[index]; + else { + Log->Write("ERROR: Wrong 'index' in SubRoom::GetWall()"); + exit(0); + } } -const vector<Point>& SubRoom::GetPolygon() const { - return _poly; +const vector<Point>& SubRoom::GetPolygon() const +{ + return _poly; } -const vector<Obstacle*>& SubRoom::GetAllObstacles() const { - return _obstacles; +const vector<Obstacle*>& SubRoom::GetAllObstacles() const +{ + return _obstacles; } -int SubRoom::GetNumberOfGoalIDs() const { - return _goalIDs.size(); +int SubRoom::GetNumberOfGoalIDs() const +{ + return _goalIDs.size(); } -const vector<int>& SubRoom::GetAllGoalIDs() const { - return _goalIDs; +const vector<int>& SubRoom::GetAllGoalIDs() const +{ + return _goalIDs; } // Sonstiges -void SubRoom::AddWall(const Wall& w) { - _walls.push_back(w); +void SubRoom::AddWall(const Wall& w) +{ + _walls.push_back(w); } -void SubRoom::AddObstacle(Obstacle* obs){ - _obstacles.push_back(obs); - CheckObstacles(); +void SubRoom::AddObstacle(Obstacle* obs) +{ + _obstacles.push_back(obs); + CheckObstacles(); } -void SubRoom::AddGoalID(int ID) { - _goalIDs.push_back(ID); +void SubRoom::AddGoalID(int ID) +{ + _goalIDs.push_back(ID); } -void SubRoom::AddCrossing(Crossing* line){ - _crossings.push_back(line); - _goalIDs.push_back(line->GetUniqueID()); +void SubRoom::AddCrossing(Crossing* line) +{ + _crossings.push_back(line); + _goalIDs.push_back(line->GetUniqueID()); } -void SubRoom::AddTransition(Transition* line){ - _transitions.push_back(line); - _goalIDs.push_back(line->GetUniqueID()); +void SubRoom::AddTransition(Transition* line) +{ + _transitions.push_back(line); + _goalIDs.push_back(line->GetUniqueID()); } -void SubRoom::AddHline(Hline* line){ - _hlines.push_back(line); - _goalIDs.push_back(line->GetUniqueID()); +void SubRoom::AddHline(Hline* line) +{ + _hlines.push_back(line); + _goalIDs.push_back(line->GetUniqueID()); } -const vector<Crossing*>& SubRoom::GetAllCrossings() const{ - return _crossings; +const vector<Crossing*>& SubRoom::GetAllCrossings() const +{ + return _crossings; } -const vector<Transition*>& SubRoom::GetAllTransitions() const{ - return _transitions; +const vector<Transition*>& SubRoom::GetAllTransitions() const +{ + return _transitions; } -const vector<Hline*>& SubRoom::GetAllHlines() const{ - return _hlines; +const vector<Hline*>& SubRoom::GetAllHlines() const +{ + return _hlines; } -const Crossing* SubRoom::GetCrossing(int i) const { - return _crossings[i]; +const Crossing* SubRoom::GetCrossing(int i) const +{ + return _crossings[i]; } -const Transition* SubRoom::GetTransition(int i) const { - return _transitions[i]; +const Transition* SubRoom::GetTransition(int i) const +{ + return _transitions[i]; } -const Hline* SubRoom::GetHline(int i) const { - return _hlines[i]; +const Hline* SubRoom::GetHline(int i) const +{ + return _hlines[i]; } -void SubRoom::RemoveGoalID(int ID){ - for (unsigned int i=0;i<_goalIDs.size();i++){ - if(_goalIDs[i]==ID){ - Log->Write("Removing goal"); - _goalIDs.erase(_goalIDs.begin()+i); - return; - } - } - Log->Write("There is no goal with that id to remove"); +void SubRoom::RemoveGoalID(int ID) +{ + for (unsigned int i=0; i<_goalIDs.size(); i++) { + if(_goalIDs[i]==ID) { + Log->Write("Removing goal"); + _goalIDs.erase(_goalIDs.begin()+i); + return; + } + } + Log->Write("There is no goal with that id to remove"); } -void SubRoom::CalculateArea() { - double sum = 0; - int n = (int) _poly.size(); - for (int i = 0; i < n; i++) { - sum += (_poly[i].GetY() + _poly[(i + 1) % n].GetY())*(_poly[i].GetX() - _poly[(i + 1) % n].GetX()); - } - _area=(0.5 * fabs(sum)); +void SubRoom::CalculateArea() +{ + double sum = 0; + int n = (int) _poly.size(); + for (int i = 0; i < n; i++) { + sum += (_poly[i].GetY() + _poly[(i + 1) % n].GetY())*(_poly[i].GetX() - _poly[(i + 1) % n].GetX()); + } + _area=(0.5 * fabs(sum)); } -Point SubRoom::GetCentroid() const { - - double px=0,py=0; - double signedArea = 0.0; - double x0 = 0.0; // Current vertex X - double y0 = 0.0; // Current vertex Y - double x1 = 0.0; // Next vertex X - double y1 = 0.0; // Next vertex Y - double a = 0.0; // Partial signed area - - // For all vertices except last - unsigned int i=0; - for (i=0; i<_poly.size()-1; ++i) - { - x0 = _poly[i].GetX(); - y0 = _poly[i].GetY(); - x1 = _poly[i+1].GetX(); - y1 = _poly[i+1].GetY(); - a = x0*y1 - x1*y0; - signedArea += a; - px += (x0 + x1)*a; - py += (y0 + y1)*a; - } - - // Do last vertex - x0 = _poly[i].GetX(); - y0 = _poly[i].GetY(); - x1 = _poly[0].GetX(); - y1 = _poly[0].GetY(); - a = x0*y1 - x1*y0; - signedArea += a; - px += (x0 + x1)*a; - py += (y0 + y1)*a; - - signedArea *= 0.5; - px /= (6.0*signedArea); - py /= (6.0*signedArea); +Point SubRoom::GetCentroid() const +{ - return Point(px,py); + double px=0,py=0; + double signedArea = 0.0; + double x0 = 0.0; // Current vertex X + double y0 = 0.0; // Current vertex Y + double x1 = 0.0; // Next vertex X + double y1 = 0.0; // Next vertex Y + double a = 0.0; // Partial signed area + + // For all vertices except last + unsigned int i=0; + for (i=0; i<_poly.size()-1; ++i) { + x0 = _poly[i].GetX(); + y0 = _poly[i].GetY(); + x1 = _poly[i+1].GetX(); + y1 = _poly[i+1].GetY(); + a = x0*y1 - x1*y0; + signedArea += a; + px += (x0 + x1)*a; + py += (y0 + y1)*a; + } + + // Do last vertex + x0 = _poly[i].GetX(); + y0 = _poly[i].GetY(); + x1 = _poly[0].GetX(); + y1 = _poly[0].GetY(); + a = x0*y1 - x1*y0; + signedArea += a; + px += (x0 + x1)*a; + py += (y0 + y1)*a; + + signedArea *= 0.5; + px /= (6.0*signedArea); + py /= (6.0*signedArea); + + return Point(px,py); } bool SubRoom::IsVisible(const Point& p1, const Point& p2, bool considerHlines) { - // generate certain connection lines - // connecting p1 with p2 - Line cl = Line(p1,p2); - bool temp = true; - //check intersection with Walls - for(unsigned int i = 0; i < _walls.size(); i++) { - if(temp && cl.IntersectionWith(_walls[i])) - temp = false; - } + // generate certain connection lines + // connecting p1 with p2 + Line cl = Line(p1,p2); + bool temp = true; + //check intersection with Walls + for(unsigned int i = 0; i < _walls.size(); i++) { + if(temp && cl.IntersectionWith(_walls[i])) + temp = false; + } + + + //check intersection with obstacles + for(unsigned int i = 0; i < _obstacles.size(); i++) { + Obstacle * obs = _obstacles[i]; + for(unsigned int k = 0; k<obs->GetAllWalls().size(); k++) { + const Wall& w = obs->GetAllWalls()[k]; + if(temp && cl.IntersectionWith(w)) + temp = false; + } + } + + + // check intersection with other hlines in room + if(considerHlines) + for(unsigned int i = 0; i < _hlines.size(); i++) { + if(temp && cl.IntersectionWith(*(Line*)_hlines[i])) + temp = false; + } + + return temp; +} +bool SubRoom::IsVisible(Line* l1, Line* l2, bool considerHlines) +{ + // generate certain connection lines + // connecting p1 mit p1, p1 mit p2, p2 mit p1, p2 mit p2 und center mit center + Line cl[5]; + cl[0] = Line(l1->GetPoint1(), l2->GetPoint1()); + cl[1] = Line(l1->GetPoint1(), l2->GetPoint2()); + cl[2] = Line(l1->GetPoint2(), l2->GetPoint1()); + cl[3] = Line(l1->GetPoint2(), l2->GetPoint2()); + cl[4] = Line(l1->GetCentre(), l2->GetCentre()); + bool temp[5] = {true, true, true, true, true}; + //check intersection with Walls + for(unsigned int i = 0; i < GetAllWalls().size(); i++) { + for(int k = 0; k < 5; k++) { + if(temp[k] && cl[k].IntersectionWith(_walls[i]) && (cl[k].NormalVec() != _walls[i].NormalVec() || l1->NormalVec() != l2->NormalVec())) + temp[k] = false; + } + } + + //check intersection with obstacles + for(unsigned int i = 0; i < GetAllObstacles().size(); i++) { + Obstacle * obs = GetAllObstacles()[i]; + for(unsigned int k = 0; k<obs->GetAllWalls().size(); k++) { + const Wall& w = obs->GetAllWalls()[k]; + if((w.operator !=(*l1)) && (w.operator !=(*l2))) + for(int j = 0; j < 5; j++) { + if(temp[j] && cl[j].IntersectionWith(w)) + temp[j] = false; + } + } + } + + // check intersection with other hlines in room + if(considerHlines) + for(unsigned int i = 0; i < _hlines.size(); i++) { + if ( (l1->operator !=(*(Line*)_hlines[i])) && (l2->operator !=(*(Line*)_hlines[i])) ) { + for(int k = 0; k < 5; k++) { + if(temp[k] && cl[k].IntersectionWith(*(Line*)_hlines[i])) + temp[k] = false; + } + } + } + return temp[0] || temp[1] || temp[2] || temp[3] || temp[4]; +} - //check intersection with obstacles - for(unsigned int i = 0; i < _obstacles.size(); i++) { - Obstacle * obs = _obstacles[i]; - for(unsigned int k = 0; k<obs->GetAllWalls().size(); k++){ - const Wall& w = obs->GetAllWalls()[k]; - if(temp && cl.IntersectionWith(w)) - temp = false; - } - } - // check intersection with other hlines in room - if(considerHlines) - for(unsigned int i = 0; i < _hlines.size(); i++) { - if(temp && cl.IntersectionWith(*(Line*)_hlines[i])) - temp = false; - } - return temp; +// this is the case if they share a transition or crossing +bool SubRoom::IsDirectlyConnectedWith(const SubRoom* sub) const +{ + + //check the crossings + const vector<Crossing*>& crossings = sub->GetAllCrossings(); + for (unsigned int i = 0; i < crossings.size(); i++) { + for (unsigned int j = 0; j < _crossings.size(); j++) { + int uid1 = crossings[i]->GetUniqueID(); + int uid2 = _crossings[j]->GetUniqueID(); + // ignore my transition + if (uid1 == uid2) + return true; + } + } + + // and finally the transitions + const vector<Transition*>& transitions = sub->GetAllTransitions(); + for (unsigned int i = 0; i < transitions.size(); i++) { + for (unsigned int j = 0; j < _transitions.size(); j++) { + int uid1 = transitions[i]->GetUniqueID(); + int uid2 = _transitions[j]->GetUniqueID(); + // ignore my transition + if (uid1 == uid2) + return true; + } + } + + return false; +} + +void SubRoom::SetPlanEquation(double A, double B, double C) +{ + _planeEquation[0]=A; + _planeEquation[1]=B; + _planeEquation[2]=C; + //compute and cache the cosine of angle with the plane z=h + _cosAngleWithHorizontalPlane= (1.0/sqrt(A*A+B*B+1)); } -bool SubRoom::IsVisible(Line* l1, Line* l2, bool considerHlines) +const double* SubRoom::GetPlanEquation() const { - // generate certain connection lines - // connecting p1 mit p1, p1 mit p2, p2 mit p1, p2 mit p2 und center mit center - Line cl[5]; - cl[0] = Line(l1->GetPoint1(), l2->GetPoint1()); - cl[1] = Line(l1->GetPoint1(), l2->GetPoint2()); - cl[2] = Line(l1->GetPoint2(), l2->GetPoint1()); - cl[3] = Line(l1->GetPoint2(), l2->GetPoint2()); - cl[4] = Line(l1->GetCentre(), l2->GetCentre()); - bool temp[5] = {true, true, true, true, true}; - //check intersection with Walls - for(unsigned int i = 0; i < GetAllWalls().size(); i++) { - for(int k = 0; k < 5; k++) { - if(temp[k] && cl[k].IntersectionWith(_walls[i]) && (cl[k].NormalVec() != _walls[i].NormalVec() || l1->NormalVec() != l2->NormalVec())) - temp[k] = false; - } - } - - //check intersection with obstacles - for(unsigned int i = 0; i < GetAllObstacles().size(); i++) { - Obstacle * obs = GetAllObstacles()[i]; - for(unsigned int k = 0; k<obs->GetAllWalls().size(); k++){ - const Wall& w = obs->GetAllWalls()[k]; - if((w.operator !=(*l1)) && (w.operator !=(*l2))) - for(int j = 0; j < 5; j++) { - if(temp[j] && cl[j].IntersectionWith(w)) - temp[j] = false; - } - } - } - - // check intersection with other hlines in room - if(considerHlines) - for(unsigned int i = 0; i < _hlines.size(); i++) { - if ( (l1->operator !=(*(Line*)_hlines[i])) && (l2->operator !=(*(Line*)_hlines[i])) ) { - for(int k = 0; k < 5; k++) { - if(temp[k] && cl[k].IntersectionWith(*(Line*)_hlines[i])) - temp[k] = false; - } - } - } - return temp[0] || temp[1] || temp[2] || temp[3] || temp[4]; + return _planeEquation; } +double SubRoom::GetElevation(const Point& p) const +{ + return _planeEquation[0] * p._x + _planeEquation[1] * p._y + _planeEquation[2]; +} +double SubRoom::GetCosAngleWithHorizontal() const +{ + return _cosAngleWithHorizontalPlane; +} -// this is the case if they share a transition or crossing -bool SubRoom::IsDirectlyConnectedWith(const SubRoom* sub) const { - - //check the crossings - const vector<Crossing*>& crossings = sub->GetAllCrossings(); - for (unsigned int i = 0; i < crossings.size(); i++) { - for (unsigned int j = 0; j < _crossings.size(); j++) { - int uid1 = crossings[i]->GetUniqueID(); - int uid2 = _crossings[j]->GetUniqueID(); - // ignore my transition - if (uid1 == uid2) - return true; - } - } - - // and finally the transitions - const vector<Transition*>& transitions = sub->GetAllTransitions(); - for (unsigned int i = 0; i < transitions.size(); i++) { - for (unsigned int j = 0; j < _transitions.size(); j++) { - int uid1 = transitions[i]->GetUniqueID(); - int uid2 = _transitions[j]->GetUniqueID(); - // ignore my transition - if (uid1 == uid2) - return true; - } - } - - return false; -} - -void SubRoom::SetPlanEquation(double A, double B, double C) { - _planeEquation[0]=A; - _planeEquation[1]=B; - _planeEquation[2]=C; - //compute and cache the cosine of angle with the plane z=h - _cosAngleWithHorizontalPlane= (1.0/sqrt(A*A+B*B+1)); -} - -const double* SubRoom::GetPlanEquation() const { - return _planeEquation; -} - -double SubRoom::GetElevation(const Point& p) const { - return _planeEquation[0] * p._x + _planeEquation[1] * p._y + _planeEquation[2]; -} - -double SubRoom::GetCosAngleWithHorizontal() const { - return _cosAngleWithHorizontalPlane; - -} - -void SubRoom::CheckObstacles(){ - for(unsigned int i = 0; i<_walls.size();i++){ - for(unsigned int j = 0; j<_obstacles.size();j++){ - if(_obstacles[j]->IntersectWithLine(_walls[i])){ - Log->Write("INFO: \tthe obstacle id [%d] is intersection with subroom [%d]",_obstacles[j]->GetId(),_id); - Log->Write("INFO: \tthe triangulation will not work."); - exit(EXIT_FAILURE); - } - } - } -} - -void SubRoom::SanityCheck(){ - if(_obstacles.size()==0){ - if((IsConvex()==false) && (_hlines.size()==0)){ - Log->Write("WARNING:\t Room [%d] Subroom [%d] is not convex!",_roomID,_id); - Log->Write("\t\t you might consider adding extra hlines in your routing.xml file"); - } else { - // everything is fine - } - } else { - if(_hlines.size()==0){ - Log->Write("WARNING:\t you have obstacles in room [%d] Subroom [%d]!",_roomID,_id); - Log->Write("\t\t you might consider adding extra hlines in your routing.xml file"); - }else { - // everything is fine - } - } +void SubRoom::CheckObstacles() +{ + for(unsigned int i = 0; i<_walls.size(); i++) { + for(unsigned int j = 0; j<_obstacles.size(); j++) { + if(_obstacles[j]->IntersectWithLine(_walls[i])) { + Log->Write("INFO: \tthe obstacle id [%d] is intersection with subroom [%d]",_obstacles[j]->GetId(),_id); + Log->Write("INFO: \tthe triangulation will not work."); + exit(EXIT_FAILURE); + } + } + } +} + +void SubRoom::SanityCheck() +{ + if(_obstacles.size()==0) { + if((IsConvex()==false) && (_hlines.size()==0)) { + Log->Write("WARNING:\t Room [%d] Subroom [%d] is not convex!",_roomID,_id); + Log->Write("\t\t you might consider adding extra hlines in your routing.xml file"); + } else { + // everything is fine + } + } else { + if(_hlines.size()==0) { + Log->Write("WARNING:\t you have obstacles in room [%d] Subroom [%d]!",_roomID,_id); + Log->Write("\t\t you might consider adding extra hlines in your routing.xml file"); + } else { + // everything is fine + } + } } ///http://stackoverflow.com/questions/471962/how-do-determine-if-a-polygon-is-complex-convex-nonconvex -bool SubRoom::IsConvex(){ - unsigned int hsize=_poly.size(); - unsigned int pos=0; - unsigned int neg=0; - - if(hsize==0){ - Log->Write("WARNING:\t cannot check empty polygon for convexification"); - Log->Write("WARNING:\t Did you forget to tall ConvertLineToPoly() ?"); - return false; - } - - for(unsigned int i=0;i<hsize;i++) - { - Point vecAB= _poly[(i+1)%hsize]-_poly[i%hsize]; - Point vecBC= _poly[(i+2)%hsize]-_poly[(i+1)%hsize]; - double det= vecAB.Det(vecBC); - if(fabs(det)<J_EPS) det=0.0; - - if(det<0.0){ - neg++; - } - else if(det>0.0) - { - pos++; - } - else - { - pos++; - neg++; - } - - } - - if ( (pos==hsize ) || (neg==hsize) ) { - return true; - } - return false; +bool SubRoom::IsConvex() +{ + unsigned int hsize=_poly.size(); + unsigned int pos=0; + unsigned int neg=0; + + if(hsize==0) { + Log->Write("WARNING:\t cannot check empty polygon for convexification"); + Log->Write("WARNING:\t Did you forget to tall ConvertLineToPoly() ?"); + return false; + } + + for(unsigned int i=0; i<hsize; i++) { + Point vecAB= _poly[(i+1)%hsize]-_poly[i%hsize]; + Point vecBC= _poly[(i+2)%hsize]-_poly[(i+1)%hsize]; + double det= vecAB.Det(vecBC); + if(fabs(det)<J_EPS) det=0.0; + + if(det<0.0) { + neg++; + } else if(det>0.0) { + pos++; + } else { + pos++; + neg++; + } + + } + + if ( (pos==hsize ) || (neg==hsize) ) { + return true; + } + return false; } ///http://stackoverflow.com/questions/9473570/polygon-vertices-clockwise-or-counterclockwise/ -bool SubRoom::IsClockwise(){ - if(_poly.size()<3){ - Log->Write("ERROR:\tYou need at least 3 vertices to check for orientation. Subroom ID [%d]"); - return false; - //exit(EXIT_FAILURE); - } +bool SubRoom::IsClockwise() +{ + if(_poly.size()<3) { + Log->Write("ERROR:\tYou need at least 3 vertices to check for orientation. Subroom ID [%d]"); + return false; + //exit(EXIT_FAILURE); + } - Point vecAB= _poly[1]-_poly[0]; - Point vecBC= _poly[2]-_poly[1]; + Point vecAB= _poly[1]-_poly[0]; + Point vecBC= _poly[2]-_poly[1]; - double det=vecAB.Det(vecBC); - if(fabs(det)<J_EPS) det=0.0; + double det=vecAB.Det(vecBC); + if(fabs(det)<J_EPS) det=0.0; - return ( det<=0.0 ); + return ( det<=0.0 ); } /************************************************************ NormalSubRoom ************************************************************/ -NormalSubRoom::NormalSubRoom() : SubRoom() { - -} - -NormalSubRoom::NormalSubRoom(const NormalSubRoom& orig) : SubRoom(orig) { - -} - -NormalSubRoom::~NormalSubRoom() { -} - -string NormalSubRoom::WriteSubRoom() const { - string s; - for (int j = 0; j < GetNumberOfWalls(); j++) { - - const Wall& w = GetWall(j); - string geometry; - char wall[CLENGTH] = ""; - geometry.append("\t\t<wall>\n"); - sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", - (w.GetPoint1().GetX()) * FAKTOR, - (w.GetPoint1().GetY()) * FAKTOR, - GetElevation(w.GetPoint1())*FAKTOR); - geometry.append(wall); - sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", - (w.GetPoint2().GetX()) * FAKTOR, - (w.GetPoint2().GetY()) * FAKTOR, - GetElevation(w.GetPoint2())*FAKTOR); - geometry.append(wall); - geometry.append("\t\t</wall>\n"); - - s.append(geometry); - //s.append(GetWall(j).Write()); - } - //add the subroom caption - Point pos = GetCentroid(); - char tmp[CLENGTH]; - sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%d\" color=\"100\" />\n" - , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, GetSubRoomID()); - s.append(tmp); - - //write the obstacles - for( unsigned int j=0;j<GetAllObstacles().size(); j++) { - s.append(GetAllObstacles()[j]->Write()); - } - - return s; -} - -string NormalSubRoom::WritePolyLine() const { - - string s; - char tmp[CLENGTH]; - - s.append("\t<Obstacle closed=\"1\" boundingbox=\"0\" class=\"1\">\n"); - for (unsigned int j = 0; j < _poly.size(); j++) { - sprintf(tmp, "\t\t<Vertex p_x = \"%.2lf\" p_y = \"%.2lf\"/>\n",_poly[j].GetX(),_poly[j].GetY()); - s.append(tmp); - } - s.append("\t</Obstacle>\n"); - - //write the obstacles - for( unsigned int j=0;j<GetAllObstacles().size(); j++) { - s.append(GetAllObstacles()[j]->Write()); - } - - return s; -} - -void NormalSubRoom::WriteToErrorLog() const { - Log->Write("\t\tNormal SubRoom:\n"); - for (int i = 0; i < GetNumberOfWalls(); i++) { - Wall w = GetWall(i); - w.WriteToErrorLog(); - } -} - -bool NormalSubRoom::ConvertLineToPoly(vector<Line*> goals) { - vector<Line*> copy; - vector<Point> tmpPoly; - Point point; - Line* line; - // Alle Linienelemente in copy speichern - for (int i = 0; i < GetNumberOfWalls(); i++) { - copy.push_back(&_walls[i]); - } - // Transitions und Crossings sind in goal abgespeichert - copy.insert(copy.end(), goals.begin(), goals.end()); - - line = copy[0]; - tmpPoly.push_back(line->GetPoint1()); - point = line->GetPoint2(); - copy.erase(copy.begin()); - // Polygon aus allen Linen erzeugen - for (int i = 0; i < (int) copy.size(); i++) { - line = copy[i]; - if ((point - line->GetPoint1()).Norm() < J_TOLERANZ) { - tmpPoly.push_back(line->GetPoint1()); - point = line->GetPoint2(); - copy.erase(copy.begin() + i); - // von vorne suchen - i = -1; - } else if ((point - line->GetPoint2()).Norm() < J_TOLERANZ) { - tmpPoly.push_back(line->GetPoint2()); - point = line->GetPoint1(); - copy.erase(copy.begin() + i); - // von vorne suchen - i = -1; - } - } - if ((tmpPoly[0] - point).Norm() > J_TOLERANZ) { - char tmp[CLENGTH]; - sprintf(tmp, "ERROR: \tNormalSubRoom::ConvertLineToPoly(): SubRoom %d Room %d Anfangspunkt ungleich Endpunkt!!!\n" - "\t(%f, %f) != (%f, %f)\n", GetSubRoomID(), GetRoomID(), tmpPoly[0].GetX(), tmpPoly[0].GetY(), point.GetX(), - point.GetY()); - Log->Write(tmp); - sprintf(tmp, "ERROR: \tDistance between the points: %lf !!!\n", (tmpPoly[0] - point).Norm()); - Log->Write(tmp); +NormalSubRoom::NormalSubRoom() : SubRoom() +{ + +} + +NormalSubRoom::NormalSubRoom(const NormalSubRoom& orig) : SubRoom(orig) +{ + +} + +NormalSubRoom::~NormalSubRoom() +{ +} + +string NormalSubRoom::WriteSubRoom() const +{ + string s; + for (int j = 0; j < GetNumberOfWalls(); j++) { + + const Wall& w = GetWall(j); + string geometry; + char wall[CLENGTH] = ""; + geometry.append("\t\t<wall>\n"); + sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", + (w.GetPoint1().GetX()) * FAKTOR, + (w.GetPoint1().GetY()) * FAKTOR, + GetElevation(w.GetPoint1())*FAKTOR); + geometry.append(wall); + sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", + (w.GetPoint2().GetX()) * FAKTOR, + (w.GetPoint2().GetY()) * FAKTOR, + GetElevation(w.GetPoint2())*FAKTOR); + geometry.append(wall); + geometry.append("\t\t</wall>\n"); + + s.append(geometry); + //s.append(GetWall(j).Write()); + } + //add the subroom caption + Point pos = GetCentroid(); + char tmp[CLENGTH]; + sprintf(tmp, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"0\" text=\"%d\" color=\"100\" />\n" + , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR, GetSubRoomID()); + s.append(tmp); + + //write the obstacles + for( unsigned int j=0; j<GetAllObstacles().size(); j++) { + s.append(GetAllObstacles()[j]->Write()); + } + + return s; +} + +string NormalSubRoom::WritePolyLine() const +{ + + string s; + char tmp[CLENGTH]; + + s.append("\t<Obstacle closed=\"1\" boundingbox=\"0\" class=\"1\">\n"); + for (unsigned int j = 0; j < _poly.size(); j++) { + sprintf(tmp, "\t\t<Vertex p_x = \"%.2lf\" p_y = \"%.2lf\"/>\n",_poly[j].GetX(),_poly[j].GetY()); + s.append(tmp); + } + s.append("\t</Obstacle>\n"); + + //write the obstacles + for( unsigned int j=0; j<GetAllObstacles().size(); j++) { + s.append(GetAllObstacles()[j]->Write()); + } + + return s; +} + +void NormalSubRoom::WriteToErrorLog() const +{ + Log->Write("\t\tNormal SubRoom:\n"); + for (int i = 0; i < GetNumberOfWalls(); i++) { + Wall w = GetWall(i); + w.WriteToErrorLog(); + } +} + +bool NormalSubRoom::ConvertLineToPoly(vector<Line*> goals) +{ + vector<Line*> copy; + vector<Point> tmpPoly; + Point point; + Line* line; + // Alle Linienelemente in copy speichern + for (int i = 0; i < GetNumberOfWalls(); i++) { + copy.push_back(&_walls[i]); + } + // Transitions und Crossings sind in goal abgespeichert + copy.insert(copy.end(), goals.begin(), goals.end()); + + line = copy[0]; + tmpPoly.push_back(line->GetPoint1()); + point = line->GetPoint2(); + copy.erase(copy.begin()); + // Polygon aus allen Linen erzeugen + for (int i = 0; i < (int) copy.size(); i++) { + line = copy[i]; + if ((point - line->GetPoint1()).Norm() < J_TOLERANZ) { + tmpPoly.push_back(line->GetPoint1()); + point = line->GetPoint2(); + copy.erase(copy.begin() + i); + // von vorne suchen + i = -1; + } else if ((point - line->GetPoint2()).Norm() < J_TOLERANZ) { + tmpPoly.push_back(line->GetPoint2()); + point = line->GetPoint1(); + copy.erase(copy.begin() + i); + // von vorne suchen + i = -1; + } + } + if ((tmpPoly[0] - point).Norm() > J_TOLERANZ) { + char tmp[CLENGTH]; + sprintf(tmp, "ERROR: \tNormalSubRoom::ConvertLineToPoly(): SubRoom %d Room %d Anfangspunkt ungleich Endpunkt!!!\n" + "\t(%f, %f) != (%f, %f)\n", GetSubRoomID(), GetRoomID(), tmpPoly[0].GetX(), tmpPoly[0].GetY(), point.GetX(), + point.GetY()); + Log->Write(tmp); + sprintf(tmp, "ERROR: \tDistance between the points: %lf !!!\n", (tmpPoly[0] - point).Norm()); + Log->Write(tmp); return false; - } - _poly = tmpPoly; + } + _poly = tmpPoly; return true; } @@ -646,376 +689,402 @@ bool NormalSubRoom::ConvertLineToPoly(vector<Line*> goals) { // gibt zuruck in welchen Quadranten vertex liegt, wobei hitPos der Koordinatenursprung ist -int NormalSubRoom::WhichQuad(const Point& vertex, const Point& hitPos) const { - return (vertex.GetX() > hitPos.GetX()) ? ((vertex.GetY() > hitPos.GetY()) ? 1 : 4) : - ((vertex.GetY() > hitPos.GetY()) ? 2 : 3); +int NormalSubRoom::WhichQuad(const Point& vertex, const Point& hitPos) const +{ + return (vertex.GetX() > hitPos.GetX()) ? ((vertex.GetY() > hitPos.GetY()) ? 1 : 4) : + ((vertex.GetY() > hitPos.GetY()) ? 2 : 3); } // x-Koordinate der Linie von einer Eccke zur nächsten -double NormalSubRoom::Xintercept(const Point& point1, const Point& point2, double hitY) const { - return (point2.GetX() - (((point2.GetY() - hitY) * (point1.GetX() - point2.GetX())) / - (point1.GetY() - point2.GetY()))); +double NormalSubRoom::Xintercept(const Point& point1, const Point& point2, double hitY) const +{ + return (point2.GetX() - (((point2.GetY() - hitY) * (point1.GetX() - point2.GetX())) / + (point1.GetY() - point2.GetY()))); } // neue Version auch für konkave Polygone -bool NormalSubRoom::IsInSubRoom(const Point& ped) const { - short edge, first, next; - short quad, next_quad, delta, total; - - ///////////////////////////////////////////////////////////// - edge = first = 0; - quad = WhichQuad(_poly[edge], ped); - total = 0; // COUNT OF ABSOLUTE SECTORS CROSSED - /* LOOP THROUGH THE VERTICES IN A SECTOR */ - do { - next = (edge + 1) % _poly.size(); - next_quad = WhichQuad(_poly[next], ped); - delta = next_quad - quad; // HOW MANY QUADS HAVE I MOVED - - // SPECIAL CASES TO HANDLE CROSSINGS OF MORE THEN ONE - //QUAD - - switch (delta) { - case 2: // IF WE CROSSED THE MIDDLE, FIGURE OUT IF IT - //WAS CLOCKWISE OR COUNTER - case -2: // US THE X POSITION AT THE HIT POINT TO - // DETERMINE WHICH WAY AROUND - if (Xintercept(_poly[edge], _poly[next], ped._y) > ped._x) - delta = -(delta); - break; - case 3: // MOVING 3 QUADS IS LIKE MOVING BACK 1 - delta = -1; - break; - case -3: // MOVING BACK 3 IS LIKE MOVING FORWARD 1 - delta = 1; - break; - } - /* ADD IN THE DELTA */ - total += delta; - quad = next_quad; // RESET FOR NEXT STEP - edge = next; - } while (edge != first); - - /* AFTER ALL IS DONE IF THE TOTAL IS 4 THEN WE ARE INSIDE */ - if (abs(total) == 4) - return true; - else - return false; +bool NormalSubRoom::IsInSubRoom(const Point& ped) const +{ + short edge, first, next; + short quad, next_quad, delta, total; + + ///////////////////////////////////////////////////////////// + edge = first = 0; + quad = WhichQuad(_poly[edge], ped); + total = 0; // COUNT OF ABSOLUTE SECTORS CROSSED + /* LOOP THROUGH THE VERTICES IN A SECTOR */ + do { + next = (edge + 1) % _poly.size(); + next_quad = WhichQuad(_poly[next], ped); + delta = next_quad - quad; // HOW MANY QUADS HAVE I MOVED + + // SPECIAL CASES TO HANDLE CROSSINGS OF MORE THEN ONE + //QUAD + + switch (delta) { + case 2: // IF WE CROSSED THE MIDDLE, FIGURE OUT IF IT + //WAS CLOCKWISE OR COUNTER + case -2: // US THE X POSITION AT THE HIT POINT TO + // DETERMINE WHICH WAY AROUND + if (Xintercept(_poly[edge], _poly[next], ped._y) > ped._x) + delta = -(delta); + break; + case 3: // MOVING 3 QUADS IS LIKE MOVING BACK 1 + delta = -1; + break; + case -3: // MOVING BACK 3 IS LIKE MOVING FORWARD 1 + delta = 1; + break; + } + /* ADD IN THE DELTA */ + total += delta; + quad = next_quad; // RESET FOR NEXT STEP + edge = next; + } while (edge != first); + + /* AFTER ALL IS DONE IF THE TOTAL IS 4 THEN WE ARE INSIDE */ + if (abs(total) == 4) + return true; + else + return false; } /************************************************************ Stair ************************************************************/ -Stair::Stair() : NormalSubRoom() { - pUp = Point(); - pDown = Point(); +Stair::Stair() : NormalSubRoom() +{ + pUp = Point(); + pDown = Point(); } -Stair::Stair(const Stair & orig) : NormalSubRoom(orig) { - pUp = orig.GetUp(); - pDown = orig.GetDown(); +Stair::Stair(const Stair & orig) : NormalSubRoom(orig) +{ + pUp = orig.GetUp(); + pDown = orig.GetDown(); } -Stair::~Stair() { +Stair::~Stair() +{ } // Setter-Funktionen -void Stair::SetUp(const Point & p) { - pUp = p; +void Stair::SetUp(const Point & p) +{ + pUp = p; } -void Stair::SetDown(const Point & p) { - pDown = p; +void Stair::SetDown(const Point & p) +{ + pDown = p; } // Getter-Funktionen -const Point & Stair::GetUp() const { - return pUp; -} - -const Point & Stair::GetDown() const { - return pDown; +const Point & Stair::GetUp() const +{ + return pUp; } -string Stair::WriteSubRoom() const { - string s; - - for (int j = 0; j < GetNumberOfWalls(); j++) { - const Wall& w = GetWall(j); - - string geometry; - char wall[CLENGTH] = ""; - geometry.append("\t\t<wall>\n"); - sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", - (w.GetPoint1().GetX()) * FAKTOR, - (w.GetPoint1().GetY()) * FAKTOR, - GetElevation(w.GetPoint1())*FAKTOR); - geometry.append(wall); - sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", - (w.GetPoint2().GetX()) * FAKTOR, - (w.GetPoint2().GetY()) * FAKTOR, - GetElevation(w.GetPoint2())*FAKTOR); - geometry.append(wall); - geometry.append("\t\t</wall>\n"); - - s.append(geometry); - //s.append(w.Write()); - } - //Line tmp = Line(GetUp(), GetDown()); - // s.append(tmp.Write()); - Point pos = GetCentroid(); - char tmp_c[CLENGTH]; - sprintf(tmp_c, "\t\t<sphere centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"%.2f\" radius=\"20\" color=\"100\" />\n" - , GetUp().GetX() * FAKTOR, GetUp().GetY() * FAKTOR, GetElevation(GetUp())*FAKTOR); - s.append(tmp_c); - - //add the subroom caption - sprintf(tmp_c, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"%.2f\" text=\"%d\" color=\"100\" />\n" - , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR,GetElevation(pos)*FAKTOR ,GetSubRoomID()); - s.append(tmp_c); - - return s; +const Point & Stair::GetDown() const +{ + return pDown; } -string Stair::WritePolyLine() const { +string Stair::WriteSubRoom() const +{ + string s; + + for (int j = 0; j < GetNumberOfWalls(); j++) { + const Wall& w = GetWall(j); + + string geometry; + char wall[CLENGTH] = ""; + geometry.append("\t\t<wall>\n"); + sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", + (w.GetPoint1().GetX()) * FAKTOR, + (w.GetPoint1().GetY()) * FAKTOR, + GetElevation(w.GetPoint1())*FAKTOR); + geometry.append(wall); + sprintf(wall, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", + (w.GetPoint2().GetX()) * FAKTOR, + (w.GetPoint2().GetY()) * FAKTOR, + GetElevation(w.GetPoint2())*FAKTOR); + geometry.append(wall); + geometry.append("\t\t</wall>\n"); + + s.append(geometry); + //s.append(w.Write()); + } + //Line tmp = Line(GetUp(), GetDown()); + // s.append(tmp.Write()); + Point pos = GetCentroid(); + char tmp_c[CLENGTH]; + sprintf(tmp_c, "\t\t<sphere centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"%.2f\" radius=\"20\" color=\"100\" />\n" + , GetUp().GetX() * FAKTOR, GetUp().GetY() * FAKTOR, GetElevation(GetUp())*FAKTOR); + s.append(tmp_c); + + //add the subroom caption + sprintf(tmp_c, "\t\t<label centerX=\"%.2f\" centerY=\"%.2f\" centerZ=\"%.2f\" text=\"%d\" color=\"100\" />\n" + , pos.GetX() * FAKTOR, pos.GetY() * FAKTOR,GetElevation(pos)*FAKTOR ,GetSubRoomID()); + s.append(tmp_c); + + return s; +} + +string Stair::WritePolyLine() const +{ - string s; - char tmp[CLENGTH]; + string s; + char tmp[CLENGTH]; - s.append("\t<Obstacle closed=\"1\" boundingbox=\"0\" class=\"1\">\n"); - for (unsigned int j = 0; j < _poly.size(); j++) { - sprintf(tmp, "\t\t<Vertex p_x = \"%.2lf\" p_y = \"%.2lf\"/>\n",_poly[j].GetX(),_poly[j].GetY()); - s.append(tmp); - } - s.append("\t</Obstacle>\n"); + s.append("\t<Obstacle closed=\"1\" boundingbox=\"0\" class=\"1\">\n"); + for (unsigned int j = 0; j < _poly.size(); j++) { + sprintf(tmp, "\t\t<Vertex p_x = \"%.2lf\" p_y = \"%.2lf\"/>\n",_poly[j].GetX(),_poly[j].GetY()); + s.append(tmp); + } + s.append("\t</Obstacle>\n"); - //write the obstacles - for( unsigned int j=0;j<GetAllObstacles().size(); j++) { - s.append(GetAllObstacles()[j]->Write()); - } + //write the obstacles + for( unsigned int j=0; j<GetAllObstacles().size(); j++) { + s.append(GetAllObstacles()[j]->Write()); + } - return s; + return s; } -void Stair::WriteToErrorLog() const { - Log->Write("\t\tStair:\n"); - for (int i = 0; i < GetNumberOfWalls(); i++) { - Wall w = GetWall(i); - w.WriteToErrorLog(); - } +void Stair::WriteToErrorLog() const +{ + Log->Write("\t\tStair:\n"); + for (int i = 0; i < GetNumberOfWalls(); i++) { + Wall w = GetWall(i); + w.WriteToErrorLog(); + } } /* prüft ob die Punkte p1, p2 und p3 auf einer Linie liegen, oder eine Ecke bilden. * Dabei liegt p2 IMMER in der Mitte und entspricht aktPoint * */ -const Point* Stair::CheckCorner(const Point** otherPoint, const Point** aktPoint, const Point* nextPoint) { - - Point l1 = **otherPoint - **aktPoint; - Point l2 = *nextPoint - **aktPoint; - const Point* rueck = NULL; - // Punkte bilden eine Linie - if (fabs(fabs(l1.ScalarP(l2) / (l1.Norm() * l2.Norm())) - 1) < 0.1) { - *aktPoint = nextPoint; - } else // aktPoint/p2 ist eine Ecke - { - rueck = *aktPoint; - *otherPoint = *aktPoint; - *aktPoint = nextPoint; - } - return rueck; -} - -bool Stair::ConvertLineToPoly(vector<Line*> goals) { - - //return NormalSubRoom::ConvertLineToPoly(goals); - - vector<Line*> copy; - vector<Point> orgPoly = vector<Point > (); - const Point* aktPoint; - const Point* otherPoint; - const Point* nextPoint; - const Point* firstAktPoint; - const Point* firstOtherPoint; - Line *nextLine; - - // Alle Linienelemente in copy speichern - for (int i = 0; i < GetNumberOfWalls(); i++) { - copy.push_back(&_walls[i]); - } - // Transitions und Crossings sind in goal abgespeichert - copy.insert(copy.end(), goals.begin(), goals.end()); - - aktPoint = ©[0]->GetPoint1(); - firstAktPoint = aktPoint; - otherPoint = ©[0]->GetPoint2(); - firstOtherPoint = otherPoint; - copy.erase(copy.begin()); - - // Polygon aus allen Linen erzeugen - for (int i = 0; i < (int) copy.size(); i++) { - nextLine = copy[i]; - nextPoint = NULL; - if ((*aktPoint - nextLine->GetPoint1()).Norm() < J_TOLERANZ) { - nextPoint = &nextLine->GetPoint2(); - } else if ((*aktPoint - nextLine->GetPoint2()).Norm() < J_TOLERANZ) { - nextPoint = &nextLine->GetPoint1(); - } - if (nextPoint != NULL) { - const Point* rueck = CheckCorner(&otherPoint, &aktPoint, nextPoint); - if (rueck != NULL) - orgPoly.push_back(*rueck); - copy.erase(copy.begin() + i); - i = -1; // von vorne suchen - } - } - if ((*aktPoint - *firstOtherPoint).Norm() < J_TOLERANZ) { - const Point* rueck = CheckCorner(&otherPoint, &aktPoint, firstAktPoint); - if (rueck != NULL) - orgPoly.push_back(*rueck); - } else { - char tmp[CLENGTH]; - double x1, y1, x2, y2; - x1 = firstOtherPoint->GetX(); - y1 = firstOtherPoint->GetY(); - x2 = aktPoint->GetX(); - y2 = aktPoint->GetY(); - sprintf(tmp, "ERROR: \tStair::ConvertLineToPoly(): SubRoom %d Room %d Anfangspunkt ungleich Endpunkt!!!\n" - "\t(%f, %f) != (%f, %f)\n", GetSubRoomID(), GetRoomID(), x1, y1, x2, y2); - Log->Write(tmp); +const Point* Stair::CheckCorner(const Point** otherPoint, const Point** aktPoint, const Point* nextPoint) +{ + + Point l1 = **otherPoint - **aktPoint; + Point l2 = *nextPoint - **aktPoint; + const Point* rueck = NULL; + // Punkte bilden eine Linie + if (fabs(fabs(l1.ScalarP(l2) / (l1.Norm() * l2.Norm())) - 1) < 0.1) { + *aktPoint = nextPoint; + } else { // aktPoint/p2 ist eine Ecke + rueck = *aktPoint; + *otherPoint = *aktPoint; + *aktPoint = nextPoint; + } + return rueck; +} + +bool Stair::ConvertLineToPoly(vector<Line*> goals) +{ + + //return NormalSubRoom::ConvertLineToPoly(goals); + + vector<Line*> copy; + vector<Point> orgPoly = vector<Point > (); + const Point* aktPoint; + const Point* otherPoint; + const Point* nextPoint; + const Point* firstAktPoint; + const Point* firstOtherPoint; + Line *nextLine; + + // Alle Linienelemente in copy speichern + for (int i = 0; i < GetNumberOfWalls(); i++) { + copy.push_back(&_walls[i]); + } + // Transitions und Crossings sind in goal abgespeichert + copy.insert(copy.end(), goals.begin(), goals.end()); + + aktPoint = ©[0]->GetPoint1(); + firstAktPoint = aktPoint; + otherPoint = ©[0]->GetPoint2(); + firstOtherPoint = otherPoint; + copy.erase(copy.begin()); + + // Polygon aus allen Linen erzeugen + for (int i = 0; i < (int) copy.size(); i++) { + nextLine = copy[i]; + nextPoint = NULL; + if ((*aktPoint - nextLine->GetPoint1()).Norm() < J_TOLERANZ) { + nextPoint = &nextLine->GetPoint2(); + } else if ((*aktPoint - nextLine->GetPoint2()).Norm() < J_TOLERANZ) { + nextPoint = &nextLine->GetPoint1(); + } + if (nextPoint != NULL) { + const Point* rueck = CheckCorner(&otherPoint, &aktPoint, nextPoint); + if (rueck != NULL) + orgPoly.push_back(*rueck); + copy.erase(copy.begin() + i); + i = -1; // von vorne suchen + } + } + if ((*aktPoint - *firstOtherPoint).Norm() < J_TOLERANZ) { + const Point* rueck = CheckCorner(&otherPoint, &aktPoint, firstAktPoint); + if (rueck != NULL) + orgPoly.push_back(*rueck); + } else { + char tmp[CLENGTH]; + double x1, y1, x2, y2; + x1 = firstOtherPoint->GetX(); + y1 = firstOtherPoint->GetY(); + x2 = aktPoint->GetX(); + y2 = aktPoint->GetY(); + sprintf(tmp, "ERROR: \tStair::ConvertLineToPoly(): SubRoom %d Room %d Anfangspunkt ungleich Endpunkt!!!\n" + "\t(%f, %f) != (%f, %f)\n", GetSubRoomID(), GetRoomID(), x1, y1, x2, y2); + Log->Write(tmp); return false; - } + } - if (orgPoly.size() != 4) { - char tmp[CLENGTH]; - sprintf(tmp, "ERROR: \tStair::ConvertLineToPoly(): Stair %d Room %d ist kein Viereck!!!\n" - "Anzahl Ecken: %d\n", GetSubRoomID(), GetRoomID(), orgPoly.size()); - Log->Write(tmp); + if (orgPoly.size() != 4) { + char tmp[CLENGTH]; + sprintf(tmp, "ERROR: \tStair::ConvertLineToPoly(): Stair %d Room %d ist kein Viereck!!!\n" + "Anzahl Ecken: %d\n", GetSubRoomID(), GetRoomID(), orgPoly.size()); + Log->Write(tmp); return false; - } - vector<Point> neuPoly = (orgPoly); - // ganz kleine Treppen (nur eine Stufe) nicht - if ((neuPoly[0] - neuPoly[1]).Norm() > 0.9 && (neuPoly[1] - neuPoly[2]).Norm() > 0.9) { - for (int i1 = 0; i1 < (int) orgPoly.size(); i1++) { - int i2 = (i1 + 1) % orgPoly.size(); - int i3 = (i2 + 1) % orgPoly.size(); - int i4 = (i3 + 1) % orgPoly.size(); - Point p1 = neuPoly[i1]; - Point p2 = neuPoly[i2]; - Point p3 = neuPoly[i3]; - Point p4 = neuPoly[i4]; - - Point l1 = p2 - p1; - Point l2 = p3 - p2; - - if (l1.Norm() < l2.Norm()) { - neuPoly[i2] = neuPoly[i2] + l1.Normalized() * 2 * J_EPS_GOAL; - l2 = p3 - p4; - neuPoly[i3] = neuPoly[i3] + l2.Normalized() * 2 * J_EPS_GOAL; - } - } - } - _poly = neuPoly; + } + vector<Point> neuPoly = (orgPoly); + // ganz kleine Treppen (nur eine Stufe) nicht + if ((neuPoly[0] - neuPoly[1]).Norm() > 0.9 && (neuPoly[1] - neuPoly[2]).Norm() > 0.9) { + for (int i1 = 0; i1 < (int) orgPoly.size(); i1++) { + int i2 = (i1 + 1) % orgPoly.size(); + int i3 = (i2 + 1) % orgPoly.size(); + int i4 = (i3 + 1) % orgPoly.size(); + Point p1 = neuPoly[i1]; + Point p2 = neuPoly[i2]; + Point p3 = neuPoly[i3]; + Point p4 = neuPoly[i4]; + + Point l1 = p2 - p1; + Point l2 = p3 - p2; + + if (l1.Norm() < l2.Norm()) { + neuPoly[i2] = neuPoly[i2] + l1.Normalized() * 2 * J_EPS_GOAL; + l2 = p3 - p4; + neuPoly[i3] = neuPoly[i3] + l2.Normalized() * 2 * J_EPS_GOAL; + } + } + } + _poly = neuPoly; return true; } -bool Stair::IsInSubRoom(const Point& ped) const { - bool rueck = false; - int N = (int) _poly.size(); - int sum = 0; +bool Stair::IsInSubRoom(const Point& ped) const +{ + bool rueck = false; + int N = (int) _poly.size(); + int sum = 0; - for (int i = 0; i < N; i++) { - Line l = Line(_poly[i], _poly[(i + 1) % N]); - Point s = l.LotPoint(ped); - if (l.IsInLineSegment(s)) - sum++; - } - if (sum == 4) - rueck = true; + for (int i = 0; i < N; i++) { + Line l = Line(_poly[i], _poly[(i + 1) % N]); + Point s = l.LotPoint(ped); + if (l.IsInLineSegment(s)) + sum++; + } + if (sum == 4) + rueck = true; - return rueck; + return rueck; } -void SubRoom::SetType(const std::string& type) { - _type = type; +void SubRoom::SetType(const std::string& type) +{ + _type = type; } -const std::string& SubRoom::GetType() const { - return _type; +const std::string& SubRoom::GetType() const +{ + return _type; } #ifdef _SIMULATOR -void SubRoom::SetAllPedestrians(const vector<Pedestrian*>& peds) { - _peds = peds; +void SubRoom::SetAllPedestrians(const vector<Pedestrian*>& peds) +{ + _peds = peds; } -void SubRoom::SetPedestrian(Pedestrian* ped, int index) { - if ((index >= 0) && (index < GetNumberOfPedestrians())) { - _peds[index] = ped; - } else { - Log->Write("ERROR: Wrong Index in SubRoom::SetPedestrian()"); - exit(0); - } +void SubRoom::SetPedestrian(Pedestrian* ped, int index) +{ + if ((index >= 0) && (index < GetNumberOfPedestrians())) { + _peds[index] = ped; + } else { + Log->Write("ERROR: Wrong Index in SubRoom::SetPedestrian()"); + exit(0); + } } -bool SubRoom::IsInSubRoom(Pedestrian* ped) const { - //TODO: reference ? - Point pos = ped->GetPos(); - if (ped->GetExitLine()->DistTo(pos) <= J_EPS_GOAL) - return true; - else - return IsInSubRoom(pos); +bool SubRoom::IsInSubRoom(Pedestrian* ped) const +{ + //TODO: reference ? + Point pos = ped->GetPos(); + if (ped->GetExitLine()->DistTo(pos) <= J_EPS_GOAL) + return true; + else + return IsInSubRoom(pos); } -int SubRoom::GetNumberOfPedestrians() const { - return _peds.size(); +int SubRoom::GetNumberOfPedestrians() const +{ + return _peds.size(); } -const vector<Pedestrian*>& SubRoom::GetAllPedestrians() const { - return _peds; +const vector<Pedestrian*>& SubRoom::GetAllPedestrians() const +{ + return _peds; } -Pedestrian* SubRoom::GetPedestrian(int index) const { - if ((index >= 0) && (index < (int) GetNumberOfPedestrians())) - return _peds[index]; - else { - Log->Write("ERROR: Wrong 'index' in SubRoom::GetPedestrian()"); - exit(0); - } +Pedestrian* SubRoom::GetPedestrian(int index) const +{ + if ((index >= 0) && (index < (int) GetNumberOfPedestrians())) + return _peds[index]; + else { + Log->Write("ERROR: Wrong 'index' in SubRoom::GetPedestrian()"); + exit(0); + } } -void SubRoom::AddPedestrian(Pedestrian* ped) { - _peds.push_back(ped); +void SubRoom::AddPedestrian(Pedestrian* ped) +{ + _peds.push_back(ped); } -void SubRoom::DeletePedestrian(int index) { - if ((index >= 0) && (index < (int) GetNumberOfPedestrians())) { - _peds.erase(_peds.begin() + index); +void SubRoom::DeletePedestrian(int index) +{ + if ((index >= 0) && (index < (int) GetNumberOfPedestrians())) { + _peds.erase(_peds.begin() + index); - } else { - Log->Write("ERROR: Wrong Index in SubRoom::DeletePedestrian()"); - exit(0); - } + } else { + Log->Write("ERROR: Wrong Index in SubRoom::DeletePedestrian()"); + exit(0); + } } -void SubRoom::ClearAllPedestrians(){ - for(unsigned int p=0;p<_peds.size();p++){ - delete _peds[p]; - } - _peds.clear(); +void SubRoom::ClearAllPedestrians() +{ + for(unsigned int p=0; p<_peds.size(); p++) { + delete _peds[p]; + } + _peds.clear(); } #endif // _SIMULATOR diff --git a/src/geometry/SubRoom.h b/src/geometry/SubRoom.h index a73b90209630f80646caca43d7fd5a644b4923cb..e035453a1a3b0cd12601de3190d426f653b811a6 100644 --- a/src/geometry/SubRoom.h +++ b/src/geometry/SubRoom.h @@ -41,7 +41,7 @@ class Obstacle; class Crossing; #ifdef _SIMULATOR - class Pedestrian; +class Pedestrian; #endif @@ -51,283 +51,283 @@ class Crossing; class SubRoom { private: - /// the id set using the SetID method - int _id; - /// the unique id resulting from the count of all subrooms in the system - int _uid; - int _roomID; - std::vector<int> _goalIDs; // all navigation lines contained in this subroom - double _area; - double _closed; - //defined by: Z = Ax + By + C - double _planeEquation[3]; - double _cosAngleWithHorizontalPlane; - std::string _type; - - std::vector<Obstacle*> _obstacles; // obstacles - - //different types of navigation lines - std::vector<Crossing*> _crossings; - std::vector<Transition*> _transitions; - std::vector<Hline*> _hlines; - - /// storing and incrementing the total number of subrooms - static int _static_uid; + /// the id set using the SetID method + int _id; + /// the unique id resulting from the count of all subrooms in the system + int _uid; + int _roomID; + std::vector<int> _goalIDs; // all navigation lines contained in this subroom + double _area; + double _closed; + //defined by: Z = Ax + By + C + double _planeEquation[3]; + double _cosAngleWithHorizontalPlane; + std::string _type; + + std::vector<Obstacle*> _obstacles; // obstacles + + //different types of navigation lines + std::vector<Crossing*> _crossings; + std::vector<Transition*> _transitions; + std::vector<Hline*> _hlines; + + /// storing and incrementing the total number of subrooms + static int _static_uid; #ifdef _SIMULATOR - std::vector<Pedestrian*> _peds; // pedestrians container + std::vector<Pedestrian*> _peds; // pedestrians container #endif protected: - std::vector<Wall> _walls; - std::vector<Point> _poly; // Polygonal representation of the subroom + std::vector<Wall> _walls; + std::vector<Point> _poly; // Polygonal representation of the subroom public: - // constructors - SubRoom(); - SubRoom(const SubRoom& orig); - virtual ~SubRoom(); - - /** - * Set/Get the subroom id - */ - void SetSubRoomID(int ID); - - /** - * Set/Get the associated room id - */ - void SetRoomID(int ID); - //void SetAllWalls(const std::vector<Wall>& walls); - //void SetWall(const Wall& wall, int index); - //void SetPolygon(const std::vector<Point>& poly); - //void SetArea(double a); - - void SetClosed(double c); - - /** - * Set the plane equation for this subroom. - * defined by: Z = Ax + By + C - */ - void SetPlanEquation(double A, double B, double C); - - /** - * Set/Get the subroom id - */ - int GetSubRoomID() const; - - /** - * @return the number of walls forming this subroom - */ - int GetNumberOfWalls() const; - - /** - * @return all walls - */ - const std::vector<Wall>& GetAllWalls() const; - - /** - * @return a reference to the wall at position index - */ - const Wall& GetWall(int index) const; - - /** - * @return the polygonal representation of the subroom - * counterclockwise - */ - const std::vector<Point>& GetPolygon() const; - - /** - * @return a reference to all obstacles contained - */ - const std::vector<Obstacle*>& GetAllObstacles() const; - - /** - * @return the number of hlines+transitions+crossings - */ - int GetNumberOfGoalIDs() const; - - /** - * @return a vector containing all Ids - */ - const std::vector<int>& GetAllGoalIDs() const; - - /** - * @return the room containing this subroom - */ - int GetRoomID() const; - - /** - * @return the unique identifier for this subroom - */ - int GetUID() const; - - /** - * Set/Get the type of the subroom. - * Possible types are: stairs, room and floor. - * @return the type of the subroom. - */ - const std::string& GetType() const; - - /** - * Set/Get the type of the subroom. - * Possible types are: stairs, room and floor. - * @return the type of the subroom. - */ - void SetType(const std::string& type); - - - /** - * @return the status - */ - double GetClosed() const; - - /** - * @return the area - */ - double GetArea() const; - - /** - * @return the centroid of the subroom - * @see http://en.wikipedia.org/wiki/Centroid - */ - Point GetCentroid() const; - - /** - * @return the three coefficients of the plane equation. - * defined by: Z = Ax + By + C - */ - const double * GetPlanEquation () const; - - /** - * @return the elevation of a 2Dimensional point using the plane equation. - * @see GetPlanEquation - */ - double GetElevation(const Point & p1) const; - - - /** - * compute the cosine of the dihedral angle with the Horizontal plane Z=h - * @return the cosine of the angle - */ - double GetCosAngleWithHorizontal() const; - - /** - * Compute the area of the subroom. - * @see GetArea() - */ - void CalculateArea(); - - /** - * @return true if the polygon is convex - * @see http://stackoverflow.com/questions/471962/how-do-determine-if-a-polygon-is-complex-convex-nonconvex - */ - bool IsConvex(); - - /** - * @return true if the polygon is clockwise oriented - * @see http://stackoverflow.com/questions/9473570/polygon-vertices-clockwise-or-counterclockwise/ - */ - bool IsClockwise(); - - - /** - * check the subroom for some inconsistencies. - * e.g. simple polygons - * no intersection between the walls and the obstacles. - */ - void CheckObstacles(); - - /** - * Check the subroom for possible errors and - * output user specific informations. - */ - void SanityCheck(); - - //navigation - void AddCrossing(Crossing* line); - void AddTransition(Transition* line); - void AddHline(Hline* line); - - const std::vector<Crossing*>& GetAllCrossings() const; - const std::vector<Transition*>& GetAllTransitions() const; - const std::vector<Hline*>& GetAllHlines() const; - const Crossing* GetCrossing(int i) const; - const Transition* GetTransition(int i) const; - const Hline* GetHline(int i) const; - - - /** - * Add a wall to the subroom - */ - void AddWall(const Wall& w); - - /** - * Adds an obstacle to the subroom. - * They are used for the triangulation/convexifivation process - */ - void AddObstacle(Obstacle* obs); - - /** - * Remove the pedestrian from the subroom. - * @param index, the index of the peds in the vector (NOT THE ID !) - */ - void DeletePedestrian(int index); - //void DeletePedestrian(Pedestrian* ped); - void AddGoalID(int ID); - void RemoveGoalID(int ID); - - - - /** - * @return true if the two subrooms share a common walkable Edge (crossing or transition) - */ - bool IsDirectlyConnectedWith(const SubRoom* sub) const; - - /** - * @return true if the two segments are visible from each other. - * Alls walls and transitions and crossings are used in this check. - * The use of hlines is optional, because they are not real, can can be considered transparent - */ - bool IsVisible(Line* l1, Line* l2, bool considerHlines=false); - - /** - * @return true if the two points are visible from each other. - * Alls walls and transitions and crossings are used in this check. - * The use of hlines is optional, because they are not real, can be considered transparent - */ - bool IsVisible(const Point& p1, const Point& p2, bool considerHlines=false); - - - - // virtual functions - virtual std::string WriteSubRoom() const = 0; - virtual void WriteToErrorLog() const = 0; - virtual std::string WritePolyLine() const=0; - - /// convert all walls and transitions(doors) into a polygon representing the subroom + // constructors + SubRoom(); + SubRoom(const SubRoom& orig); + virtual ~SubRoom(); + + /** + * Set/Get the subroom id + */ + void SetSubRoomID(int ID); + + /** + * Set/Get the associated room id + */ + void SetRoomID(int ID); + //void SetAllWalls(const std::vector<Wall>& walls); + //void SetWall(const Wall& wall, int index); + //void SetPolygon(const std::vector<Point>& poly); + //void SetArea(double a); + + void SetClosed(double c); + + /** + * Set the plane equation for this subroom. + * defined by: Z = Ax + By + C + */ + void SetPlanEquation(double A, double B, double C); + + /** + * Set/Get the subroom id + */ + int GetSubRoomID() const; + + /** + * @return the number of walls forming this subroom + */ + int GetNumberOfWalls() const; + + /** + * @return all walls + */ + const std::vector<Wall>& GetAllWalls() const; + + /** + * @return a reference to the wall at position index + */ + const Wall& GetWall(int index) const; + + /** + * @return the polygonal representation of the subroom + * counterclockwise + */ + const std::vector<Point>& GetPolygon() const; + + /** + * @return a reference to all obstacles contained + */ + const std::vector<Obstacle*>& GetAllObstacles() const; + + /** + * @return the number of hlines+transitions+crossings + */ + int GetNumberOfGoalIDs() const; + + /** + * @return a vector containing all Ids + */ + const std::vector<int>& GetAllGoalIDs() const; + + /** + * @return the room containing this subroom + */ + int GetRoomID() const; + + /** + * @return the unique identifier for this subroom + */ + int GetUID() const; + + /** + * Set/Get the type of the subroom. + * Possible types are: stairs, room and floor. + * @return the type of the subroom. + */ + const std::string& GetType() const; + + /** + * Set/Get the type of the subroom. + * Possible types are: stairs, room and floor. + * @return the type of the subroom. + */ + void SetType(const std::string& type); + + + /** + * @return the status + */ + double GetClosed() const; + + /** + * @return the area + */ + double GetArea() const; + + /** + * @return the centroid of the subroom + * @see http://en.wikipedia.org/wiki/Centroid + */ + Point GetCentroid() const; + + /** + * @return the three coefficients of the plane equation. + * defined by: Z = Ax + By + C + */ + const double * GetPlanEquation () const; + + /** + * @return the elevation of a 2Dimensional point using the plane equation. + * @see GetPlanEquation + */ + double GetElevation(const Point & p1) const; + + + /** + * compute the cosine of the dihedral angle with the Horizontal plane Z=h + * @return the cosine of the angle + */ + double GetCosAngleWithHorizontal() const; + + /** + * Compute the area of the subroom. + * @see GetArea() + */ + void CalculateArea(); + + /** + * @return true if the polygon is convex + * @see http://stackoverflow.com/questions/471962/how-do-determine-if-a-polygon-is-complex-convex-nonconvex + */ + bool IsConvex(); + + /** + * @return true if the polygon is clockwise oriented + * @see http://stackoverflow.com/questions/9473570/polygon-vertices-clockwise-or-counterclockwise/ + */ + bool IsClockwise(); + + + /** + * check the subroom for some inconsistencies. + * e.g. simple polygons + * no intersection between the walls and the obstacles. + */ + void CheckObstacles(); + + /** + * Check the subroom for possible errors and + * output user specific informations. + */ + void SanityCheck(); + + //navigation + void AddCrossing(Crossing* line); + void AddTransition(Transition* line); + void AddHline(Hline* line); + + const std::vector<Crossing*>& GetAllCrossings() const; + const std::vector<Transition*>& GetAllTransitions() const; + const std::vector<Hline*>& GetAllHlines() const; + const Crossing* GetCrossing(int i) const; + const Transition* GetTransition(int i) const; + const Hline* GetHline(int i) const; + + + /** + * Add a wall to the subroom + */ + void AddWall(const Wall& w); + + /** + * Adds an obstacle to the subroom. + * They are used for the triangulation/convexifivation process + */ + void AddObstacle(Obstacle* obs); + + /** + * Remove the pedestrian from the subroom. + * @param index, the index of the peds in the vector (NOT THE ID !) + */ + void DeletePedestrian(int index); + //void DeletePedestrian(Pedestrian* ped); + void AddGoalID(int ID); + void RemoveGoalID(int ID); + + + + /** + * @return true if the two subrooms share a common walkable Edge (crossing or transition) + */ + bool IsDirectlyConnectedWith(const SubRoom* sub) const; + + /** + * @return true if the two segments are visible from each other. + * Alls walls and transitions and crossings are used in this check. + * The use of hlines is optional, because they are not real, can can be considered transparent + */ + bool IsVisible(Line* l1, Line* l2, bool considerHlines=false); + + /** + * @return true if the two points are visible from each other. + * Alls walls and transitions and crossings are used in this check. + * The use of hlines is optional, because they are not real, can be considered transparent + */ + bool IsVisible(const Point& p1, const Point& p2, bool considerHlines=false); + + + + // virtual functions + virtual std::string WriteSubRoom() const = 0; + virtual void WriteToErrorLog() const = 0; + virtual std::string WritePolyLine() const=0; + + /// convert all walls and transitions(doors) into a polygon representing the subroom virtual bool ConvertLineToPoly(std::vector<Line*> goals) = 0; - ///check whether the pedestrians is still in the subroom - virtual bool IsInSubRoom(const Point& ped) const = 0; + ///check whether the pedestrians is still in the subroom + virtual bool IsInSubRoom(const Point& ped) const = 0; - // MPI: - void ClearAllPedestrians(); + // MPI: + void ClearAllPedestrians(); #ifdef _SIMULATOR - /** - * @return the number of pedestrians in this subroom - */ - int GetNumberOfPedestrians() const; - void AddPedestrian(Pedestrian* ped); - virtual bool IsInSubRoom(Pedestrian* ped) const; - void SetAllPedestrians(const std::vector<Pedestrian*>& peds); - void SetPedestrian(Pedestrian* ped, int index); - const std::vector<Pedestrian*>& GetAllPedestrians() const; - Pedestrian* GetPedestrian(int index) const; + /** + * @return the number of pedestrians in this subroom + */ + int GetNumberOfPedestrians() const; + void AddPedestrian(Pedestrian* ped); + virtual bool IsInSubRoom(Pedestrian* ped) const; + void SetAllPedestrians(const std::vector<Pedestrian*>& peds); + void SetPedestrian(Pedestrian* ped, int index); + const std::vector<Pedestrian*>& GetAllPedestrians() const; + Pedestrian* GetPedestrian(int index) const; #endif @@ -340,21 +340,21 @@ public: class NormalSubRoom : public SubRoom { private: - ///@see IsInSubRoom - int WhichQuad(const Point& vertex, const Point& hitPos) const; - double Xintercept(const Point& point1, const Point& point2, double hitY) const; + ///@see IsInSubRoom + int WhichQuad(const Point& vertex, const Point& hitPos) const; + double Xintercept(const Point& point1, const Point& point2, double hitY) const; public: - NormalSubRoom(); - NormalSubRoom(const NormalSubRoom& orig); - virtual ~NormalSubRoom(); + NormalSubRoom(); + NormalSubRoom(const NormalSubRoom& orig); + virtual ~NormalSubRoom(); - std::string WriteSubRoom() const; - std::string WritePolyLine() const; + std::string WriteSubRoom() const; + std::string WritePolyLine() const; virtual void WriteToErrorLog() const; virtual bool ConvertLineToPoly(std::vector<Line*> goals); - bool IsInSubRoom(const Point& ped) const; + bool IsInSubRoom(const Point& ped) const; }; /************************************************************ @@ -363,33 +363,33 @@ public: class Stair : public NormalSubRoom { private: - Point pUp; /// Punkt der den oberen Bereich der Treppe markiert - Point pDown; /// Punkt der den unteren Bereich der Treppe markiert + Point pUp; /// Punkt der den oberen Bereich der Treppe markiert + Point pDown; /// Punkt der den unteren Bereich der Treppe markiert - const Point* CheckCorner(const Point** otherPoint, const Point** aktPoint, const Point* nextPoint); + const Point* CheckCorner(const Point** otherPoint, const Point** aktPoint, const Point* nextPoint); public: - Stair(); - Stair(const Stair& orig); - virtual ~Stair(); - - // Setter-Funktionen - void SetUp(const Point& p); - void SetDown(const Point& p); - - // Getter-Funktionen - const Point& GetUp() const; - const Point& GetDown() const; - - /// pedestrians are going the stairs downwards - bool IsUpStairs() const; - /// pedestrians are going the stairs upwards - bool IsDownStair() const; - - std::string WriteSubRoom() const; - std::string WritePolyLine() const; - virtual void WriteToErrorLog() const; + Stair(); + Stair(const Stair& orig); + virtual ~Stair(); + + // Setter-Funktionen + void SetUp(const Point& p); + void SetDown(const Point& p); + + // Getter-Funktionen + const Point& GetUp() const; + const Point& GetDown() const; + + /// pedestrians are going the stairs downwards + bool IsUpStairs() const; + /// pedestrians are going the stairs upwards + bool IsDownStair() const; + + std::string WriteSubRoom() const; + std::string WritePolyLine() const; + virtual void WriteToErrorLog() const; virtual bool ConvertLineToPoly(std::vector<Line*> goals); - bool IsInSubRoom(const Point& ped) const; + bool IsInSubRoom(const Point& ped) const; }; #endif /* _SUBROOM_H */ diff --git a/src/geometry/Transition.cpp b/src/geometry/Transition.cpp index 590a7ff7b45eaa64271687594662f06519c6c407..df12dffbc3f5fdafe1104ba77a248927db6a8ad6 100644 --- a/src/geometry/Transition.cpp +++ b/src/geometry/Transition.cpp @@ -35,148 +35,164 @@ using namespace std; Transition (abgeleitet von Crossing) ************************************************************/ -Transition::Transition() : Crossing() { - _isOpen = true; - _room2 = NULL; +Transition::Transition() : Crossing() +{ + _isOpen = true; + _room2 = NULL; } -Transition::~Transition() { +Transition::~Transition() +{ } // Setter-Funktionen -void Transition::Close() { - _isOpen = false; +void Transition::Close() +{ + _isOpen = false; } -void Transition::Open() { - _isOpen = true; +void Transition::Open() +{ + _isOpen = true; } -void Transition::SetType(string type){ - _type=type; +void Transition::SetType(string type) +{ + _type=type; } -void Transition::SetRoom2(Room* r) { - _room2 = r; +void Transition::SetRoom2(Room* r) +{ + _room2 = r; } // Getter-Funktionen -bool Transition::IsOpen() const { - return _isOpen; +bool Transition::IsOpen() const +{ + return _isOpen; } -Room* Transition::GetRoom2() const { - return _room2; +Room* Transition::GetRoom2() const +{ + return _room2; } -string Transition::GetType() const { - return _type; +string Transition::GetType() const +{ + return _type; } // Sonstiges // gibt den ANDEREN room != roomID zurück -Room* Transition::GetOtherRoom(int roomID) const { - if (GetRoom1()!=NULL && GetRoom1()->GetID() == roomID) { - return GetRoom2(); - } else if (GetRoom2()!=NULL && GetRoom2()->GetID() == roomID) { - return GetRoom1(); - } else { - char msg[CLENGTH]; - sprintf(msg,"ERROR: \tTransition::GetOtherRoom() wrong roomID [%d]",roomID); - Log->Write(msg); - exit(0); - } +Room* Transition::GetOtherRoom(int roomID) const +{ + if (GetRoom1()!=NULL && GetRoom1()->GetID() == roomID) { + return GetRoom2(); + } else if (GetRoom2()!=NULL && GetRoom2()->GetID() == roomID) { + return GetRoom1(); + } else { + char msg[CLENGTH]; + sprintf(msg,"ERROR: \tTransition::GetOtherRoom() wrong roomID [%d]",roomID); + Log->Write(msg); + exit(0); + } } // virtuelle Funktionen // prüft ob Ausgang nach draußen -bool Transition::IsExit() const { - if(GetRoom1()!=NULL && _room2!=NULL) - return false; - else - return true; +bool Transition::IsExit() const +{ + if(GetRoom1()!=NULL && _room2!=NULL) + return false; + else + return true; } // prüft, ob Transition in Raum mit roomID -bool Transition::IsInRoom(int roomID) const { - bool c1 = false; - bool c2 = false; - if (GetRoom1() != NULL && GetRoom1()->GetID() == roomID) - c1 = true; - if (GetRoom2() != NULL && GetRoom2()->GetID() == roomID) - c2 = true; - return c1 || c2; +bool Transition::IsInRoom(int roomID) const +{ + bool c1 = false; + bool c2 = false; + if (GetRoom1() != NULL && GetRoom1()->GetID() == roomID) + c1 = true; + if (GetRoom2() != NULL && GetRoom2()->GetID() == roomID) + c2 = true; + return c1 || c2; } -bool Transition::IsTransition() const { - return true; +bool Transition::IsTransition() const +{ + return true; } /* gibt den ANDEREN Subroom mit GetRoomID() != roomID zurück * subroomID wird hier nicht benötigt, aber in Crossings::GetOtherSubRoom() * (virtuelle Funktion) */ -SubRoom* Transition::GetOtherSubRoom(int roomID, int subroomID) const { - if ((GetRoom1() != NULL) && (GetRoom1()->GetID() == roomID)) - return GetSubRoom2(); - else if ((GetRoom2() != NULL) && (GetRoom2()->GetID() == roomID)) - return GetSubRoom1(); - else { - char tmp[CLENGTH]; - sprintf(tmp,"ERROR: \tTransition::GetOtherSubRoom No exit found " - "on the other side\n ID=%hd, roomID=%hd, subroomID=%hd\n",GetUniqueID(),roomID,subroomID); - Log->Write(tmp); - exit(0); - } +SubRoom* Transition::GetOtherSubRoom(int roomID, int subroomID) const +{ + if ((GetRoom1() != NULL) && (GetRoom1()->GetID() == roomID)) + return GetSubRoom2(); + else if ((GetRoom2() != NULL) && (GetRoom2()->GetID() == roomID)) + return GetSubRoom1(); + else { + char tmp[CLENGTH]; + sprintf(tmp,"ERROR: \tTransition::GetOtherSubRoom No exit found " + "on the other side\n ID=%hd, roomID=%hd, subroomID=%hd\n",GetUniqueID(),roomID,subroomID); + Log->Write(tmp); + exit(0); + } } // Ein-Ausgbae -void Transition::WriteToErrorLog() const { - string s; - char tmp[CLENGTH]; - sprintf(tmp, "\t\tTRANS: %d [%s] (%f, %f) -- (%f, %f)\n", GetID(), GetCaption().c_str(), - GetPoint1().GetX(), GetPoint1().GetY(), GetPoint2().GetX(), GetPoint2().GetY()); - s.append(tmp); - // erster Raum - if (GetRoom1() != NULL) { - sprintf(tmp, "\t\t\t\tRoom: %d [%s] SubRoom: %d", GetRoom1()->GetID(), - GetRoom1()->GetCaption().c_str(), GetSubRoom1()->GetSubRoomID()); - } else { - sprintf(tmp, "\t\t\t\tAusgang"); - } - s.append(tmp); - // zweiter Raum - if (GetRoom2() != NULL) { - sprintf(tmp, " <->\tRoom: %d [%s] SubRoom: %d\n", GetRoom2()->GetID(), - GetRoom2()->GetCaption().c_str(), GetSubRoom2()->GetSubRoomID()); - } else { - sprintf(tmp, " <->\tAusgang\n"); - } - s.append(tmp); - Log->Write(s); +void Transition::WriteToErrorLog() const +{ + string s; + char tmp[CLENGTH]; + sprintf(tmp, "\t\tTRANS: %d [%s] (%f, %f) -- (%f, %f)\n", GetID(), GetCaption().c_str(), + GetPoint1().GetX(), GetPoint1().GetY(), GetPoint2().GetX(), GetPoint2().GetY()); + s.append(tmp); + // erster Raum + if (GetRoom1() != NULL) { + sprintf(tmp, "\t\t\t\tRoom: %d [%s] SubRoom: %d", GetRoom1()->GetID(), + GetRoom1()->GetCaption().c_str(), GetSubRoom1()->GetSubRoomID()); + } else { + sprintf(tmp, "\t\t\t\tAusgang"); + } + s.append(tmp); + // zweiter Raum + if (GetRoom2() != NULL) { + sprintf(tmp, " <->\tRoom: %d [%s] SubRoom: %d\n", GetRoom2()->GetID(), + GetRoom2()->GetCaption().c_str(), GetSubRoom2()->GetSubRoomID()); + } else { + sprintf(tmp, " <->\tAusgang\n"); + } + s.append(tmp); + Log->Write(s); } // TraVisTo Ausgabe -string Transition::WriteElement() const { - string geometry; - char tmp[CLENGTH] = ""; - - sprintf(tmp,"\t\t<door ID=\"%d\" color=\"180\" caption=\"%d_%d_%s\">\n",GetUniqueID(),GetID(),GetUniqueID(),GetCaption().c_str()); - geometry.append(tmp); - sprintf(tmp, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", - (GetPoint1().GetX()) * FAKTOR, - (GetPoint1().GetY()) * FAKTOR, - GetSubRoom1()->GetElevation(GetPoint1())*FAKTOR); - geometry.append(tmp); - sprintf(tmp, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", - (GetPoint2().GetX()) * FAKTOR, - (GetPoint2().GetY()) * FAKTOR, - GetSubRoom1()->GetElevation(GetPoint2())*FAKTOR); - geometry.append(tmp); - geometry.append("\t\t</door>\n"); - return geometry; +string Transition::WriteElement() const +{ + string geometry; + char tmp[CLENGTH] = ""; + + sprintf(tmp,"\t\t<door ID=\"%d\" color=\"180\" caption=\"%d_%d_%s\">\n",GetUniqueID(),GetID(),GetUniqueID(),GetCaption().c_str()); + geometry.append(tmp); + sprintf(tmp, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", + (GetPoint1().GetX()) * FAKTOR, + (GetPoint1().GetY()) * FAKTOR, + GetSubRoom1()->GetElevation(GetPoint1())*FAKTOR); + geometry.append(tmp); + sprintf(tmp, "\t\t\t<point xPos=\"%.2f\" yPos=\"%.2f\" zPos=\"%.2f\"/>\n", + (GetPoint2().GetX()) * FAKTOR, + (GetPoint2().GetY()) * FAKTOR, + GetSubRoom1()->GetElevation(GetPoint2())*FAKTOR); + geometry.append(tmp); + geometry.append("\t\t</door>\n"); + return geometry; } diff --git a/src/geometry/Wall.cpp b/src/geometry/Wall.cpp index c0a56433941d45c26b6f52df15aca248152eab50..e3c02f4675e04b874c4e694905c2207ef51ebde4 100644 --- a/src/geometry/Wall.cpp +++ b/src/geometry/Wall.cpp @@ -32,24 +32,29 @@ using namespace std; Wall ************************************************************/ -Wall::Wall() : Line() { +Wall::Wall() : Line() +{ } -Wall::Wall(const Point& p1, const Point& p2) : Line(p1, p2) { +Wall::Wall(const Point& p1, const Point& p2) : Line(p1, p2) +{ } -Wall::Wall(const Wall& orig) : Line(orig) { +Wall::Wall(const Wall& orig) : Line(orig) +{ } -void Wall::WriteToErrorLog() const { +void Wall::WriteToErrorLog() const +{ char tmp[CLENGTH]; sprintf(tmp, "\t\tWALL: (%f, %f) -- (%f, %f)\n", GetPoint1().GetX(), GetPoint1().GetY(), GetPoint2().GetX(), GetPoint2().GetY()); Log->Write(tmp); } -string Wall::Write() const { +string Wall::Write() const +{ string geometry; char wall[500] = ""; geometry.append("\t\t<wall>\n"); diff --git a/src/main.cpp b/src/main.cpp index 5cb9a4dc85a2b8dc4b3b6803dea0e24d8e30824b..1bb6b7b5d661675cfa2cd8bb1631032dbed8038f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -59,13 +59,13 @@ int main(int argc, char *argv[]) { - QApplication a(argc, argv); - // To ensure that decimal numbers use a "point" instead of "colon" on some systems + QApplication a(argc, argv); + // To ensure that decimal numbers use a "point" instead of "colon" on some systems //setlocale(LC_NUMERIC, "en_US" ); setlocale(LC_NUMERIC,"C"); MainWindow w; - w.show(); + w.show(); - return a.exec(); + return a.exec(); } diff --git a/src/network/TraVisToServer.cpp b/src/network/TraVisToServer.cpp index 1dd0a52dbeb2c2c74a757d1890e405d98a9585e8..9d9b782d4e1e4b6206653210b3d7d88c37866a4b 100644 --- a/src/network/TraVisToServer.cpp +++ b/src/network/TraVisToServer.cpp @@ -38,265 +38,274 @@ using namespace std; -TraVisToServer::TraVisToServer(quint16 port) { - this->port=port; - isConnected=false; - listening=false; - //QObject(0); - qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError"); - createConnection(); +TraVisToServer::TraVisToServer(quint16 port) +{ + this->port=port; + isConnected=false; + listening=false; + //QObject(0); + qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError"); + createConnection(); } -TraVisToServer::~TraVisToServer() { - if(tcpServer->isListening()){ - tcpServer->close(); - } - delete tcpServer; - -} +TraVisToServer::~TraVisToServer() +{ + if(tcpServer->isListening()) { + tcpServer->close(); + } + delete tcpServer; -void TraVisToServer::close(){ - tcpServer->close(); } -void TraVisToServer::slotHandleConnection(){ - - // cerr<<"handling new connection"<<endl; - // - //// while(tcpServer->waitForNewConnection(-1)){ - //// cerr<<"uuuu"<<endl; - //// } - // QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); - // connect(clientConnection, SIGNAL(disconnected()), - // clientConnection, SLOT(deleteLater())); - // - // if(clientConnection->waitForReadyRead(-1)){ - // cerr<<"could somehow not read from the device"<<endl; - // } - // - // // while(1){ - //receive data until disconnected - - // cerr<<"juhuuuu"<<endl; - - //receive geometry - - // // receive trajectories - // QDataStream in(clientConnection); - // in.setVersion(QDataStream::Qt_4_0); - // - // if (blockSize == 0) { - // if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) - // return; - // in >> blockSize; - // } - // - // if (clientConnection->bytesAvailable() < blockSize) - // return; - // - // QString nextFortune; - // in >> nextFortune; - // - // cerr<<nextFortune.toStdString()<<endl; - - // } - +void TraVisToServer::close() +{ + tcpServer->close(); } +void TraVisToServer::slotHandleConnection() +{ -void TraVisToServer::createConnection(){ - - tcpServer = new QTcpServer(); - tcpServer->setMaxPendingConnections(2); + // cerr<<"handling new connection"<<endl; + // + //// while(tcpServer->waitForNewConnection(-1)){ + //// cerr<<"uuuu"<<endl; + //// } + // QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); + // connect(clientConnection, SIGNAL(disconnected()), + // clientConnection, SLOT(deleteLater())); + // + // if(clientConnection->waitForReadyRead(-1)){ + // cerr<<"could somehow not read from the device"<<endl; + // } + // + // // while(1){ + //receive data until disconnected + + // cerr<<"juhuuuu"<<endl; + + //receive geometry + + // // receive trajectories + // QDataStream in(clientConnection); + // in.setVersion(QDataStream::Qt_4_0); + // + // if (blockSize == 0) { + // if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) + // return; + // in >> blockSize; + // } + // + // if (clientConnection->bytesAvailable() < blockSize) + // return; + // + // QString nextFortune; + // in >> nextFortune; + // + // cerr<<nextFortune.toStdString()<<endl; + + // } - if (!tcpServer->listen(QHostAddress::Any,port)) { - cerr<<"I cant listen to ALL interfaces, sorry"<<endl; - cerr<<"I will try to listen only the LocalHost (127.0.0.1)"<<endl; +} - if (!tcpServer->listen(QHostAddress::LocalHost,port)) { - cerr<<"I cant listen to LocalHost either, sorry"<<endl; - //QMessageBox::critical(0, tr("TraVisTo Server"), - // tr("Unable to start the server: %1.").arg(tcpServer->errorString())); - // close(); - return; - } - } - if(!connect(tcpServer, SIGNAL(newConnection()), this, SLOT(slotHandleConnection()))){ - cerr<<"could not create connection newconnection"<<endl; - } +void TraVisToServer::createConnection() +{ - if(tcpServer->isListening ()){ - listening=true; - cerr<<"\nTraVisTo is listening on port "<< tcpServer->serverPort()<<endl; - } - //slotHandleConnection(); + tcpServer = new QTcpServer(); + tcpServer->setMaxPendingConnections(2); + + if (!tcpServer->listen(QHostAddress::Any,port)) { + cerr<<"I cant listen to ALL interfaces, sorry"<<endl; + cerr<<"I will try to listen only the LocalHost (127.0.0.1)"<<endl; + + if (!tcpServer->listen(QHostAddress::LocalHost,port)) { + cerr<<"I cant listen to LocalHost either, sorry"<<endl; + + //QMessageBox::critical(0, tr("TraVisTo Server"), + // tr("Unable to start the server: %1.").arg(tcpServer->errorString())); + // close(); + return; + } + } + if(!connect(tcpServer, SIGNAL(newConnection()), this, SLOT(slotHandleConnection()))) { + cerr<<"could not create connection newconnection"<<endl; + } + + if(tcpServer->isListening ()) { + listening=true; + cerr<<"\nTraVisTo is listening on port "<< tcpServer->serverPort()<<endl; + } + //slotHandleConnection(); } -void TraVisToServer::receiveMessage(/*char* result*/ QString & result){ +void TraVisToServer::receiveMessage(/*char* result*/ QString & result) +{ - result.clear(); + result.clear(); - if(!isConnected){ - // pool each 1000 ms. bad idea i Know ! - if(!tcpServer->waitForNewConnection(1000)){ + if(!isConnected) { + // pool each 1000 ms. bad idea i Know ! + if(!tcpServer->waitForNewConnection(1000)) { // cerr<<"something went wrong, with the server"<<endl; // cerr <<" 200 ms passed !"<<endl; - return; - } - - clientConnection = tcpServer->nextPendingConnection(); - connect(clientConnection, SIGNAL(disconnected()), - clientConnection, SLOT(deleteLater())); - - // if(!clientConnection->waitForReadyRead()){ - // cerr<<"could somehow not read from the device"<<endl; - // return; - // } - if(!connect(clientConnection, SIGNAL(readyRead()), this, SLOT(slotReadMessage()))){ - cerr<<"can't connect ready read slot"<<endl; - } - - qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError"); - if(!connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(slotDisplayError(QAbstractSocket::SocketError)))){ - cerr<<"cant connect error slot"<<endl; - } - - isConnected=true; - } - - if(!clientConnection->waitForReadyRead()){ - clientConnection->disconnectFromHost(); - clientConnection->abort(); - isConnected=false; // the connection is lost - cerr<<"Connection was closed"<<endl; - return; - } - - while (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { - if (!clientConnection->waitForReadyRead(-1)) { - // emit error(socket.error(), socket.errorString()); - cout << "o000ooh la lalala"<<endl; - return; - } - } - // quint16 blockSize; - // QDataStream in(clientConnection); - // in.setVersion(QDataStream::Qt_4_0); - // in >> blockSize; - - //first the size of the data - char tell[10]; - clientConnection->readLine(tell,10); - // cout<<"line: "<<tell<<endl; - - blockSize = atoi(tell); - - while (clientConnection->bytesAvailable() < blockSize) { - if (!clientConnection->waitForReadyRead(-1)) { - //emit error(clientConnection->error(), clientConnection->errorString()); - cout << "ouh la lalala"<<endl; - return; - } - } - - - // QString fortune; - // in >> result; - //clientConnection->flush(); - - // blockSize =clientConnection->read(sizeof(quint16)).toUShort(); - // quint16 toRead=0; - // QString mesg; - - // while (toRead < blockSize) { - // toRead+=clientConnection->bytesAvailable(); - // QByteArray fr =clientConnection->read(toRead); - // clientConnection->flush(); - // mesg.append(fr); - // cout<<toRead <<":"<<blockSize<<endl; - // } - // cout <<"data size:"<<clientConnection->bytesAvailable() <<":" << blockSize<<endl; - QByteArray fr =clientConnection->read(blockSize); - // char *data = (char*)malloc(blockSize*sizeof(char));; - // cout<<data<<endl; - // cout<< clientConnection->read(data,blockSize)<<" read"<<endl; - // cout<<data<<endl; - result = QString(fr); - // in >> result; - // cout <<"size: "<<result.length()<<endl; - //cout <<"size: "<<result.toStdString()<<endl; - // cout <<"size: "<<fr.size()<<endl; - // QString msg(fr); - - // result=msg; - // cout << "data: "<< count++<< msg.toStdString()<<endl; - // cout << "data: "<< count++<<":" << blockSize<<endl; - // cout << "data: "<< count++<<":" << data<<endl; - // cout << "data: "<< count++<< size<<endl; - - - // //get all data - // QByteArray data = clientConnection->readAll(); - // - // //result= new char[data.size()]; - // result=data.data(); - - // //if(!data.isEmpty()) - // cout <<" size>>"<< blockSize<<endl; - // cout <<" >>"<<result.toStdString()<<endl; - // system("pause"); - // //cout <<" >>"<<result.t<<endl; - - //cout <<result.toStdString()<<endl; + return; + } + + clientConnection = tcpServer->nextPendingConnection(); + connect(clientConnection, SIGNAL(disconnected()), + clientConnection, SLOT(deleteLater())); + + // if(!clientConnection->waitForReadyRead()){ + // cerr<<"could somehow not read from the device"<<endl; + // return; + // } + if(!connect(clientConnection, SIGNAL(readyRead()), this, SLOT(slotReadMessage()))) { + cerr<<"can't connect ready read slot"<<endl; + } + + qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError"); + if(!connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), + this, SLOT(slotDisplayError(QAbstractSocket::SocketError)))) { + cerr<<"cant connect error slot"<<endl; + } + + isConnected=true; + } + + if(!clientConnection->waitForReadyRead()) { + clientConnection->disconnectFromHost(); + clientConnection->abort(); + isConnected=false; // the connection is lost + cerr<<"Connection was closed"<<endl; + return; + } + + while (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { + if (!clientConnection->waitForReadyRead(-1)) { + // emit error(socket.error(), socket.errorString()); + cout << "o000ooh la lalala"<<endl; + return; + } + } + // quint16 blockSize; + // QDataStream in(clientConnection); + // in.setVersion(QDataStream::Qt_4_0); + // in >> blockSize; + + //first the size of the data + char tell[10]; + clientConnection->readLine(tell,10); + // cout<<"line: "<<tell<<endl; + + blockSize = atoi(tell); + + while (clientConnection->bytesAvailable() < blockSize) { + if (!clientConnection->waitForReadyRead(-1)) { + //emit error(clientConnection->error(), clientConnection->errorString()); + cout << "ouh la lalala"<<endl; + return; + } + } + + + // QString fortune; + // in >> result; + //clientConnection->flush(); + + // blockSize =clientConnection->read(sizeof(quint16)).toUShort(); + // quint16 toRead=0; + // QString mesg; + + // while (toRead < blockSize) { + // toRead+=clientConnection->bytesAvailable(); + // QByteArray fr =clientConnection->read(toRead); + // clientConnection->flush(); + // mesg.append(fr); + // cout<<toRead <<":"<<blockSize<<endl; + // } + // cout <<"data size:"<<clientConnection->bytesAvailable() <<":" << blockSize<<endl; + QByteArray fr =clientConnection->read(blockSize); + // char *data = (char*)malloc(blockSize*sizeof(char));; + // cout<<data<<endl; + // cout<< clientConnection->read(data,blockSize)<<" read"<<endl; + // cout<<data<<endl; + result = QString(fr); + // in >> result; + // cout <<"size: "<<result.length()<<endl; + //cout <<"size: "<<result.toStdString()<<endl; + // cout <<"size: "<<fr.size()<<endl; + // QString msg(fr); + + // result=msg; + // cout << "data: "<< count++<< msg.toStdString()<<endl; + // cout << "data: "<< count++<<":" << blockSize<<endl; + // cout << "data: "<< count++<<":" << data<<endl; + // cout << "data: "<< count++<< size<<endl; + + + // //get all data + // QByteArray data = clientConnection->readAll(); + // + // //result= new char[data.size()]; + // result=data.data(); + + // //if(!data.isEmpty()) + // cout <<" size>>"<< blockSize<<endl; + // cout <<" >>"<<result.toStdString()<<endl; + // system("pause"); + // //cout <<" >>"<<result.t<<endl; + + //cout <<result.toStdString()<<endl; } -void TraVisToServer::sendMessage(char* data){ +void TraVisToServer::sendMessage(char* data) +{ } void TraVisToServer::slotDisplayError(QAbstractSocket::SocketError socketError) { - switch (socketError) { - - case QAbstractSocket::RemoteHostClosedError: - cerr<< "The host closed the connection "<<endl; - break; - - case QAbstractSocket::HostNotFoundError: - cerr<< "The host was not found. Please check the "<<endl; - cerr<< "host name and port settings."<<endl; - break; - - case QAbstractSocket::ConnectionRefusedError: - cerr<<"The connection was refused by the peer. "<<endl; - cerr<< "Make sure the fortune server is running, "<<endl; - cerr<<"and check that the host name and port "<<endl; - cerr<<"settings are correct."<<endl; - break; - - default: - cerr<<"TraVisTo Client:"<<endl; - cerr<<"The following error occurred: "<<endl; - //cerr<< clientConnection->errorString().toStdString()<<endl; - break; - } + switch (socketError) { + + case QAbstractSocket::RemoteHostClosedError: + cerr<< "The host closed the connection "<<endl; + break; + + case QAbstractSocket::HostNotFoundError: + cerr<< "The host was not found. Please check the "<<endl; + cerr<< "host name and port settings."<<endl; + break; + + case QAbstractSocket::ConnectionRefusedError: + cerr<<"The connection was refused by the peer. "<<endl; + cerr<< "Make sure the fortune server is running, "<<endl; + cerr<<"and check that the host name and port "<<endl; + cerr<<"settings are correct."<<endl; + break; + + default: + cerr<<"TraVisTo Client:"<<endl; + cerr<<"The following error occurred: "<<endl; + //cerr<< clientConnection->errorString().toStdString()<<endl; + break; + } } -void TraVisToServer::slotConnectionClosed(){ - //clientConnection->deleteLater(); - isConnected=false; - //cerr<< "connection lost"<<endl; +void TraVisToServer::slotConnectionClosed() +{ + //clientConnection->deleteLater(); + isConnected=false; + //cerr<< "connection lost"<<endl; } -void TraVisToServer::slotReadMessage(){ - //clientConnection->deleteLater(); - //isConnected=false; - // cerr<< "you have a post"<<endl; +void TraVisToServer::slotReadMessage() +{ + //clientConnection->deleteLater(); + //isConnected=false; + // cerr<< "you have a post"<<endl; } diff --git a/src/network/TraVisToServer.h b/src/network/TraVisToServer.h index b96939378515866edd32c00e14b058b30c3eb346..a2181718891c1fb9ce50af67520e11dcf687b57f 100644 --- a/src/network/TraVisToServer.h +++ b/src/network/TraVisToServer.h @@ -41,37 +41,40 @@ class TraVisToServer:public QObject { - Q_OBJECT + Q_OBJECT public: - TraVisToServer(quint16 port=PORT); - virtual ~TraVisToServer(); + TraVisToServer(quint16 port=PORT); + virtual ~TraVisToServer(); - //void receiveMessage(char* data); - void receiveMessage(QString& msg); - void sendMessage(char* data); - bool isListening(){return listening;} - void close(); + //void receiveMessage(char* data); + void receiveMessage(QString& msg); + void sendMessage(char* data); + bool isListening() + { + return listening; + } + void close(); private: - void createConnection(); - void closeConnection(); + void createConnection(); + void closeConnection(); private Q_SLOTS: - void slotHandleConnection(); - void slotReadMessage(); - void slotConnectionClosed(); - void slotDisplayError(QAbstractSocket::SocketError socketError); - //void slotConnected(); - //void slotDisconnected(); + void slotHandleConnection(); + void slotReadMessage(); + void slotConnectionClosed(); + void slotDisplayError(QAbstractSocket::SocketError socketError); + //void slotConnected(); + //void slotDisconnected(); private: - bool isConnected; - bool listening; - //QTcpSocket *tcpSocket; - //QTcpSocket *clientConnection; - QTcpSocket *clientConnection; + bool isConnected; + bool listening; + //QTcpSocket *tcpSocket; + //QTcpSocket *clientConnection; + QTcpSocket *clientConnection; QTcpServer *tcpServer; QString currentFortune; int blockSize; diff --git a/src/tinyxml/tinystr.cpp b/src/tinyxml/tinystr.cpp index 066576820516de3bae97b08f9258468f9cc136f4..90b030e6fbe326a19969a6759221614de66f35d9 100644 --- a/src/tinyxml/tinystr.cpp +++ b/src/tinyxml/tinystr.cpp @@ -36,75 +36,70 @@ TiXmlString::Rep TiXmlString::nullrep_ = { 0, 0, { '\0' } }; void TiXmlString::reserve (size_type cap) { - if (cap > capacity()) - { - TiXmlString tmp; - tmp.init(length(), cap); - memcpy(tmp.start(), data(), length()); - swap(tmp); - } + if (cap > capacity()) { + TiXmlString tmp; + tmp.init(length(), cap); + memcpy(tmp.start(), data(), length()); + swap(tmp); + } } TiXmlString& TiXmlString::assign(const char* str, size_type len) { - size_type cap = capacity(); - if (len > cap || cap > 3*(len + 8)) - { - TiXmlString tmp; - tmp.init(len); - memcpy(tmp.start(), str, len); - swap(tmp); - } - else - { - memmove(start(), str, len); - set_size(len); - } - return *this; + size_type cap = capacity(); + if (len > cap || cap > 3*(len + 8)) { + TiXmlString tmp; + tmp.init(len); + memcpy(tmp.start(), str, len); + swap(tmp); + } else { + memmove(start(), str, len); + set_size(len); + } + return *this; } TiXmlString& TiXmlString::append(const char* str, size_type len) { - size_type newsize = length() + len; - if (newsize > capacity()) - { - reserve (newsize + capacity()); - } - memmove(finish(), str, len); - set_size(newsize); - return *this; + size_type newsize = length() + len; + if (newsize > capacity()) { + reserve (newsize + capacity()); + } + memmove(finish(), str, len); + set_size(newsize); + return *this; } TiXmlString operator + (const TiXmlString & a, const TiXmlString & b) { - TiXmlString tmp; - tmp.reserve(a.length() + b.length()); - tmp += a; - tmp += b; - return tmp; + TiXmlString tmp; + tmp.reserve(a.length() + b.length()); + tmp += a; + tmp += b; + return tmp; } TiXmlString operator + (const TiXmlString & a, const char* b) { - TiXmlString tmp; - TiXmlString::size_type b_len = static_cast<TiXmlString::size_type>( strlen(b) ); - tmp.reserve(a.length() + b_len); - tmp += a; - tmp.append(b, b_len); - return tmp; + TiXmlString tmp; + TiXmlString::size_type b_len = static_cast<TiXmlString::size_type>( strlen(b) ); + tmp.reserve(a.length() + b_len); + tmp += a; + tmp.append(b, b_len); + return tmp; } TiXmlString operator + (const char* a, const TiXmlString & b) { - TiXmlString tmp; - TiXmlString::size_type a_len = static_cast<TiXmlString::size_type>( strlen(a) ); - tmp.reserve(a_len + b.length()); - tmp.append(a, a_len); - tmp += b; - return tmp; + TiXmlString tmp; + TiXmlString::size_type a_len = static_cast<TiXmlString::size_type>( strlen(a) ); + tmp.reserve(a_len + b.length()); + tmp.append(a, a_len); + tmp += b; + return tmp; } diff --git a/src/tinyxml/tinystr.h b/src/tinyxml/tinystr.h index 89cca3341564c0337e3e940bfa4ae053e84e656c..779ed89992b307579a54409b69b400a5dba7de90 100644 --- a/src/tinyxml/tinystr.h +++ b/src/tinyxml/tinystr.h @@ -35,13 +35,13 @@ distribution. used. Be nice to old compilers and macro it here: */ #if defined(_MSC_VER) && (_MSC_VER >= 1200 ) - // Microsoft visual studio, version 6 and higher. - #define TIXML_EXPLICIT explicit +// Microsoft visual studio, version 6 and higher. +#define TIXML_EXPLICIT explicit #elif defined(__GNUC__) && (__GNUC__ >= 3 ) - // GCC version 3 and higher.s - #define TIXML_EXPLICIT explicit +// GCC version 3 and higher.s +#define TIXML_EXPLICIT explicit #else - #define TIXML_EXPLICIT +#define TIXML_EXPLICIT #endif @@ -52,225 +52,272 @@ distribution. The buffer allocation is made by a simplistic power of 2 like mechanism : if we increase a string and there's no more room, we allocate a buffer twice as big as we need. */ -class TiXmlString -{ - public : - // The size type used - typedef size_t size_type; - - // Error value for find primitive - static const size_type npos; // = -1; - - - // TiXmlString empty constructor - TiXmlString () : rep_(&nullrep_) - { - } - - // TiXmlString copy constructor - TiXmlString ( const TiXmlString & copy) : rep_(0) - { - init(copy.length()); - memcpy(start(), copy.data(), length()); - } - - // TiXmlString constructor, based on a string - TIXML_EXPLICIT TiXmlString ( const char * copy) : rep_(0) - { - init( static_cast<size_type>( strlen(copy) )); - memcpy(start(), copy, length()); - } - - // TiXmlString constructor, based on a string - TIXML_EXPLICIT TiXmlString ( const char * str, size_type len) : rep_(0) - { - init(len); - memcpy(start(), str, len); - } - - // TiXmlString destructor - ~TiXmlString () - { - quit(); - } - - TiXmlString& operator = (const char * copy) - { - return assign( copy, (size_type)strlen(copy)); - } - - TiXmlString& operator = (const TiXmlString & copy) - { - return assign(copy.start(), copy.length()); - } - - - // += operator. Maps to append - TiXmlString& operator += (const char * suffix) - { - return append(suffix, static_cast<size_type>( strlen(suffix) )); - } - - // += operator. Maps to append - TiXmlString& operator += (char single) - { - return append(&single, 1); - } - - // += operator. Maps to append - TiXmlString& operator += (const TiXmlString & suffix) - { - return append(suffix.data(), suffix.length()); - } - - - // Convert a TiXmlString into a null-terminated char * - const char * c_str () const { return rep_->str; } - - // Convert a TiXmlString into a char * (need not be null terminated). - const char * data () const { return rep_->str; } - - // Return the length of a TiXmlString - size_type length () const { return rep_->size; } - - // Alias for length() - size_type size () const { return rep_->size; } - - // Checks if a TiXmlString is empty - bool empty () const { return rep_->size == 0; } - - // Return capacity of string - size_type capacity () const { return rep_->capacity; } - - - // single char extraction - const char& at (size_type index) const - { - assert( index < length() ); - return rep_->str[ index ]; - } - - // [] operator - char& operator [] (size_type index) const - { - assert( index < length() ); - return rep_->str[ index ]; - } - - // find a char in a string. Return TiXmlString::npos if not found - size_type find (char lookup) const - { - return find(lookup, 0); - } - - // find a char in a string from an offset. Return TiXmlString::npos if not found - size_type find (char tofind, size_type offset) const - { - if (offset >= length()) return npos; - - for (const char* p = c_str() + offset; *p != '\0'; ++p) - { - if (*p == tofind) return static_cast< size_type >( p - c_str() ); - } - return npos; - } - - void clear () - { - //Lee: - //The original was just too strange, though correct: - // TiXmlString().swap(*this); - //Instead use the quit & re-init: - quit(); - init(0,0); - } - - /* Function to reserve a big amount of data when we know we'll need it. Be aware that this - function DOES NOT clear the content of the TiXmlString if any exists. - */ - void reserve (size_type cap); - - TiXmlString& assign (const char* str, size_type len); - - TiXmlString& append (const char* str, size_type len); - - void swap (TiXmlString& other) - { - Rep* r = rep_; - rep_ = other.rep_; - other.rep_ = r; - } - - private: - - void init(size_type sz) { init(sz, sz); } - void set_size(size_type sz) { rep_->str[ rep_->size = sz ] = '\0'; } - char* start() const { return rep_->str; } - char* finish() const { return rep_->str + rep_->size; } - - struct Rep - { - size_type size, capacity; - char str[1]; - }; - - void init(size_type sz, size_type cap) - { - if (cap) - { - // Lee: the original form: - // rep_ = static_cast<Rep*>(operator new(sizeof(Rep) + cap)); - // doesn't work in some cases of new being overloaded. Switching - // to the normal allocation, although use an 'int' for systems - // that are overly picky about structure alignment. - const size_type bytesNeeded = sizeof(Rep) + cap; - const size_type intsNeeded = ( bytesNeeded + sizeof(int) - 1 ) / sizeof( int ); - rep_ = reinterpret_cast<Rep*>( new int[ intsNeeded ] ); - - rep_->str[ rep_->size = sz ] = '\0'; - rep_->capacity = cap; - } - else - { - rep_ = &nullrep_; - } - } - - void quit() - { - if (rep_ != &nullrep_) - { - // The rep_ is really an array of ints. (see the allocator, above). - // Cast it back before delete, so the compiler won't incorrectly call destructors. - delete [] ( reinterpret_cast<int*>( rep_ ) ); - } - } - - Rep * rep_; - static Rep nullrep_; +class TiXmlString { +public : + // The size type used + typedef size_t size_type; + + // Error value for find primitive + static const size_type npos; // = -1; + + + // TiXmlString empty constructor + TiXmlString () : rep_(&nullrep_) + { + } + + // TiXmlString copy constructor + TiXmlString ( const TiXmlString & copy) : rep_(0) + { + init(copy.length()); + memcpy(start(), copy.data(), length()); + } + + // TiXmlString constructor, based on a string + TIXML_EXPLICIT TiXmlString ( const char * copy) : rep_(0) + { + init( static_cast<size_type>( strlen(copy) )); + memcpy(start(), copy, length()); + } + + // TiXmlString constructor, based on a string + TIXML_EXPLICIT TiXmlString ( const char * str, size_type len) : rep_(0) + { + init(len); + memcpy(start(), str, len); + } + + // TiXmlString destructor + ~TiXmlString () + { + quit(); + } + + TiXmlString& operator = (const char * copy) + { + return assign( copy, (size_type)strlen(copy)); + } + + TiXmlString& operator = (const TiXmlString & copy) + { + return assign(copy.start(), copy.length()); + } + + + // += operator. Maps to append + TiXmlString& operator += (const char * suffix) + { + return append(suffix, static_cast<size_type>( strlen(suffix) )); + } + + // += operator. Maps to append + TiXmlString& operator += (char single) + { + return append(&single, 1); + } + + // += operator. Maps to append + TiXmlString& operator += (const TiXmlString & suffix) + { + return append(suffix.data(), suffix.length()); + } + + + // Convert a TiXmlString into a null-terminated char * + const char * c_str () const + { + return rep_->str; + } + + // Convert a TiXmlString into a char * (need not be null terminated). + const char * data () const + { + return rep_->str; + } + + // Return the length of a TiXmlString + size_type length () const + { + return rep_->size; + } + + // Alias for length() + size_type size () const + { + return rep_->size; + } + + // Checks if a TiXmlString is empty + bool empty () const + { + return rep_->size == 0; + } + + // Return capacity of string + size_type capacity () const + { + return rep_->capacity; + } + + + // single char extraction + const char& at (size_type index) const + { + assert( index < length() ); + return rep_->str[ index ]; + } + + // [] operator + char& operator [] (size_type index) const + { + assert( index < length() ); + return rep_->str[ index ]; + } + + // find a char in a string. Return TiXmlString::npos if not found + size_type find (char lookup) const + { + return find(lookup, 0); + } + + // find a char in a string from an offset. Return TiXmlString::npos if not found + size_type find (char tofind, size_type offset) const + { + if (offset >= length()) return npos; + + for (const char* p = c_str() + offset; *p != '\0'; ++p) { + if (*p == tofind) return static_cast< size_type >( p - c_str() ); + } + return npos; + } + + void clear () + { + //Lee: + //The original was just too strange, though correct: + // TiXmlString().swap(*this); + //Instead use the quit & re-init: + quit(); + init(0,0); + } + + /* Function to reserve a big amount of data when we know we'll need it. Be aware that this + function DOES NOT clear the content of the TiXmlString if any exists. + */ + void reserve (size_type cap); + + TiXmlString& assign (const char* str, size_type len); + + TiXmlString& append (const char* str, size_type len); + + void swap (TiXmlString& other) + { + Rep* r = rep_; + rep_ = other.rep_; + other.rep_ = r; + } + +private: + + void init(size_type sz) + { + init(sz, sz); + } + void set_size(size_type sz) + { + rep_->str[ rep_->size = sz ] = '\0'; + } + char* start() const + { + return rep_->str; + } + char* finish() const + { + return rep_->str + rep_->size; + } + + struct Rep { + size_type size, capacity; + char str[1]; + }; + + void init(size_type sz, size_type cap) + { + if (cap) { + // Lee: the original form: + // rep_ = static_cast<Rep*>(operator new(sizeof(Rep) + cap)); + // doesn't work in some cases of new being overloaded. Switching + // to the normal allocation, although use an 'int' for systems + // that are overly picky about structure alignment. + const size_type bytesNeeded = sizeof(Rep) + cap; + const size_type intsNeeded = ( bytesNeeded + sizeof(int) - 1 ) / sizeof( int ); + rep_ = reinterpret_cast<Rep*>( new int[ intsNeeded ] ); + + rep_->str[ rep_->size = sz ] = '\0'; + rep_->capacity = cap; + } else { + rep_ = &nullrep_; + } + } + + void quit() + { + if (rep_ != &nullrep_) { + // The rep_ is really an array of ints. (see the allocator, above). + // Cast it back before delete, so the compiler won't incorrectly call destructors. + delete [] ( reinterpret_cast<int*>( rep_ ) ); + } + } + + Rep * rep_; + static Rep nullrep_; } ; inline bool operator == (const TiXmlString & a, const TiXmlString & b) { - return ( a.length() == b.length() ) // optimization on some platforms - && ( strcmp(a.c_str(), b.c_str()) == 0 ); // actual compare + return ( a.length() == b.length() ) // optimization on some platforms + && ( strcmp(a.c_str(), b.c_str()) == 0 ); // actual compare } inline bool operator < (const TiXmlString & a, const TiXmlString & b) { - return strcmp(a.c_str(), b.c_str()) < 0; + return strcmp(a.c_str(), b.c_str()) < 0; } -inline bool operator != (const TiXmlString & a, const TiXmlString & b) { return !(a == b); } -inline bool operator > (const TiXmlString & a, const TiXmlString & b) { return b < a; } -inline bool operator <= (const TiXmlString & a, const TiXmlString & b) { return !(b < a); } -inline bool operator >= (const TiXmlString & a, const TiXmlString & b) { return !(a < b); } +inline bool operator != (const TiXmlString & a, const TiXmlString & b) +{ + return !(a == b); +} +inline bool operator > (const TiXmlString & a, const TiXmlString & b) +{ + return b < a; +} +inline bool operator <= (const TiXmlString & a, const TiXmlString & b) +{ + return !(b < a); +} +inline bool operator >= (const TiXmlString & a, const TiXmlString & b) +{ + return !(a < b); +} -inline bool operator == (const TiXmlString & a, const char* b) { return strcmp(a.c_str(), b) == 0; } -inline bool operator == (const char* a, const TiXmlString & b) { return b == a; } -inline bool operator != (const TiXmlString & a, const char* b) { return !(a == b); } -inline bool operator != (const char* a, const TiXmlString & b) { return !(b == a); } +inline bool operator == (const TiXmlString & a, const char* b) +{ + return strcmp(a.c_str(), b) == 0; +} +inline bool operator == (const char* a, const TiXmlString & b) +{ + return b == a; +} +inline bool operator != (const TiXmlString & a, const char* b) +{ + return !(a == b); +} +inline bool operator != (const char* a, const TiXmlString & b) +{ + return !(b == a); +} TiXmlString operator + (const TiXmlString & a, const TiXmlString & b); TiXmlString operator + (const TiXmlString & a, const char* b); @@ -281,23 +328,22 @@ TiXmlString operator + (const char* a, const TiXmlString & b); TiXmlOutStream is an emulation of std::ostream. It is based on TiXmlString. Only the operators that we need for TinyXML have been developped. */ -class TiXmlOutStream : public TiXmlString -{ +class TiXmlOutStream : public TiXmlString { public : - // TiXmlOutStream << operator. - TiXmlOutStream & operator << (const TiXmlString & in) - { - *this += in; - return *this; - } - - // TiXmlOutStream << operator. - TiXmlOutStream & operator << (const char * in) - { - *this += in; - return *this; - } + // TiXmlOutStream << operator. + TiXmlOutStream & operator << (const TiXmlString & in) + { + *this += in; + return *this; + } + + // TiXmlOutStream << operator. + TiXmlOutStream & operator << (const char * in) + { + *this += in; + return *this; + } } ; diff --git a/src/tinyxml/tinyxml.cpp b/src/tinyxml/tinyxml.cpp index 9c161dfcb934e855ff679998c34669bfdd66aa21..84f55fd83a9e65f131cf2e5212240fbd9b2914a1 100644 --- a/src/tinyxml/tinyxml.cpp +++ b/src/tinyxml/tinyxml.cpp @@ -38,670 +38,620 @@ bool TiXmlBase::condenseWhiteSpace = true; // Microsoft compiler security FILE* TiXmlFOpen( const char* filename, const char* mode ) { - #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - FILE* fp = 0; - errno_t err = fopen_s( &fp, filename, mode ); - if ( !err && fp ) - return fp; - return 0; - #else - return fopen( filename, mode ); - #endif +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) + FILE* fp = 0; + errno_t err = fopen_s( &fp, filename, mode ); + if ( !err && fp ) + return fp; + return 0; +#else + return fopen( filename, mode ); +#endif } void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) { - int i=0; - - while( i<(int)str.length() ) - { - unsigned char c = (unsigned char) str[i]; - - if ( c == '&' - && i < ( (int)str.length() - 2 ) - && str[i+1] == '#' - && str[i+2] == 'x' ) - { - // Hexadecimal character reference. - // Pass through unchanged. - // © -- copyright symbol, for example. - // - // The -1 is a bug fix from Rob Laveaux. It keeps - // an overflow from happening if there is no ';'. - // There are actually 2 ways to exit this loop - - // while fails (error case) and break (semicolon found). - // However, there is no mechanism (currently) for - // this function to return an error. - while ( i<(int)str.length()-1 ) - { - outString->append( str.c_str() + i, 1 ); - ++i; - if ( str[i] == ';' ) - break; - } - } - else if ( c == '&' ) - { - outString->append( entity[0].str, entity[0].strLength ); - ++i; - } - else if ( c == '<' ) - { - outString->append( entity[1].str, entity[1].strLength ); - ++i; - } - else if ( c == '>' ) - { - outString->append( entity[2].str, entity[2].strLength ); - ++i; - } - else if ( c == '\"' ) - { - outString->append( entity[3].str, entity[3].strLength ); - ++i; - } - else if ( c == '\'' ) - { - outString->append( entity[4].str, entity[4].strLength ); - ++i; - } - else if ( c < 32 ) - { - // Easy pass at non-alpha/numeric/symbol - // Below 32 is symbolic. - char buf[ 32 ]; - - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); - #else - sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); - #endif - - //*ME: warning C4267: convert 'size_t' to 'int' - //*ME: Int-Cast to make compiler happy ... - outString->append( buf, (int)strlen( buf ) ); - ++i; - } - else - { - //char realc = (char) c; - //outString->append( &realc, 1 ); - *outString += (char) c; // somewhat more efficient function call. - ++i; - } - } + int i=0; + + while( i<(int)str.length() ) { + unsigned char c = (unsigned char) str[i]; + + if ( c == '&' + && i < ( (int)str.length() - 2 ) + && str[i+1] == '#' + && str[i+2] == 'x' ) { + // Hexadecimal character reference. + // Pass through unchanged. + // © -- copyright symbol, for example. + // + // The -1 is a bug fix from Rob Laveaux. It keeps + // an overflow from happening if there is no ';'. + // There are actually 2 ways to exit this loop - + // while fails (error case) and break (semicolon found). + // However, there is no mechanism (currently) for + // this function to return an error. + while ( i<(int)str.length()-1 ) { + outString->append( str.c_str() + i, 1 ); + ++i; + if ( str[i] == ';' ) + break; + } + } else if ( c == '&' ) { + outString->append( entity[0].str, entity[0].strLength ); + ++i; + } else if ( c == '<' ) { + outString->append( entity[1].str, entity[1].strLength ); + ++i; + } else if ( c == '>' ) { + outString->append( entity[2].str, entity[2].strLength ); + ++i; + } else if ( c == '\"' ) { + outString->append( entity[3].str, entity[3].strLength ); + ++i; + } else if ( c == '\'' ) { + outString->append( entity[4].str, entity[4].strLength ); + ++i; + } else if ( c < 32 ) { + // Easy pass at non-alpha/numeric/symbol + // Below 32 is symbolic. + char buf[ 32 ]; + +#if defined(TIXML_SNPRINTF) + TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); +#else + sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); +#endif + + //*ME: warning C4267: convert 'size_t' to 'int' + //*ME: Int-Cast to make compiler happy ... + outString->append( buf, (int)strlen( buf ) ); + ++i; + } else { + //char realc = (char) c; + //outString->append( &realc, 1 ); + *outString += (char) c; // somewhat more efficient function call. + ++i; + } + } } TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { - parent = 0; - type = _type; - firstChild = 0; - lastChild = 0; - prev = 0; - next = 0; + parent = 0; + type = _type; + firstChild = 0; + lastChild = 0; + prev = 0; + next = 0; } TiXmlNode::~TiXmlNode() { - TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; + TiXmlNode* node = firstChild; + TiXmlNode* temp = 0; - while ( node ) - { - temp = node; - node = node->next; - delete temp; - } + while ( node ) { + temp = node; + node = node->next; + delete temp; + } } void TiXmlNode::CopyTo( TiXmlNode* target ) const { - target->SetValue (value.c_str() ); - target->userData = userData; - target->location = location; + target->SetValue (value.c_str() ); + target->userData = userData; + target->location = location; } void TiXmlNode::Clear() { - TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; + TiXmlNode* node = firstChild; + TiXmlNode* temp = 0; - while ( node ) - { - temp = node; - node = node->next; - delete temp; - } + while ( node ) { + temp = node; + node = node->next; + delete temp; + } - firstChild = 0; - lastChild = 0; + firstChild = 0; + lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { - assert( node->parent == 0 || node->parent == this ); - assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); + assert( node->parent == 0 || node->parent == this ); + assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); - if ( node->Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - delete node; - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } + if ( node->Type() == TiXmlNode::TINYXML_DOCUMENT ) { + delete node; + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - node->parent = this; + node->parent = this; - node->prev = lastChild; - node->next = 0; + node->prev = lastChild; + node->next = 0; - if ( lastChild ) - lastChild->next = node; - else - firstChild = node; // it was an empty list. + if ( lastChild ) + lastChild->next = node; + else + firstChild = node; // it was an empty list. - lastChild = node; - return node; + lastChild = node; + return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; + if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } + TiXmlNode* node = addThis.Clone(); + if ( !node ) + return 0; - return LinkEndChild( node ); + return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) -{ - if ( !beforeThis || beforeThis->parent != this ) { - return 0; - } - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; - node->parent = this; - - node->next = beforeThis; - node->prev = beforeThis->prev; - if ( beforeThis->prev ) - { - beforeThis->prev->next = node; - } - else - { - assert( firstChild == beforeThis ); - firstChild = node; - } - beforeThis->prev = node; - return node; +{ + if ( !beforeThis || beforeThis->parent != this ) { + return 0; + } + if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } + + TiXmlNode* node = addThis.Clone(); + if ( !node ) + return 0; + node->parent = this; + + node->next = beforeThis; + node->prev = beforeThis->prev; + if ( beforeThis->prev ) { + beforeThis->prev->next = node; + } else { + assert( firstChild == beforeThis ); + firstChild = node; + } + beforeThis->prev = node; + return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { - if ( !afterThis || afterThis->parent != this ) { - return 0; - } - if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) - { - if ( GetDocument() ) - GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - TiXmlNode* node = addThis.Clone(); - if ( !node ) - return 0; - node->parent = this; - - node->prev = afterThis; - node->next = afterThis->next; - if ( afterThis->next ) - { - afterThis->next->prev = node; - } - else - { - assert( lastChild == afterThis ); - lastChild = node; - } - afterThis->next = node; - return node; + if ( !afterThis || afterThis->parent != this ) { + return 0; + } + if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { + if ( GetDocument() ) + GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } + + TiXmlNode* node = addThis.Clone(); + if ( !node ) + return 0; + node->parent = this; + + node->prev = afterThis; + node->next = afterThis->next; + if ( afterThis->next ) { + afterThis->next->prev = node; + } else { + assert( lastChild == afterThis ); + lastChild = node; + } + afterThis->next = node; + return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { - if ( !replaceThis ) - return 0; + if ( !replaceThis ) + return 0; - if ( replaceThis->parent != this ) - return 0; + if ( replaceThis->parent != this ) + return 0; - if ( withThis.ToDocument() ) { - // A document can never be a child. Thanks to Noam. - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } + if ( withThis.ToDocument() ) { + // A document can never be a child. Thanks to Noam. + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } - TiXmlNode* node = withThis.Clone(); - if ( !node ) - return 0; + TiXmlNode* node = withThis.Clone(); + if ( !node ) + return 0; - node->next = replaceThis->next; - node->prev = replaceThis->prev; + node->next = replaceThis->next; + node->prev = replaceThis->prev; - if ( replaceThis->next ) - replaceThis->next->prev = node; - else - lastChild = node; + if ( replaceThis->next ) + replaceThis->next->prev = node; + else + lastChild = node; - if ( replaceThis->prev ) - replaceThis->prev->next = node; - else - firstChild = node; + if ( replaceThis->prev ) + replaceThis->prev->next = node; + else + firstChild = node; - delete replaceThis; - node->parent = this; - return node; + delete replaceThis; + node->parent = this; + return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { - if ( !removeThis ) { - return false; - } + if ( !removeThis ) { + return false; + } - if ( removeThis->parent != this ) - { - assert( 0 ); - return false; - } + if ( removeThis->parent != this ) { + assert( 0 ); + return false; + } - if ( removeThis->next ) - removeThis->next->prev = removeThis->prev; - else - lastChild = removeThis->prev; + if ( removeThis->next ) + removeThis->next->prev = removeThis->prev; + else + lastChild = removeThis->prev; - if ( removeThis->prev ) - removeThis->prev->next = removeThis->next; - else - firstChild = removeThis->next; + if ( removeThis->prev ) + removeThis->prev->next = removeThis->next; + else + firstChild = removeThis->next; - delete removeThis; - return true; + delete removeThis; + return true; } const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { - const TiXmlNode* node; - for ( node = firstChild; node; node = node->next ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; + const TiXmlNode* node; + for ( node = firstChild; node; node = node->next ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { - const TiXmlNode* node; - for ( node = lastChild; node; node = node->prev ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; + const TiXmlNode* node; + for ( node = lastChild; node; node = node->prev ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const { - if ( !previous ) - { - return FirstChild(); - } - else - { - assert( previous->parent == this ); - return previous->NextSibling(); - } + if ( !previous ) { + return FirstChild(); + } else { + assert( previous->parent == this ); + return previous->NextSibling(); + } } const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const { - if ( !previous ) - { - return FirstChild( val ); - } - else - { - assert( previous->parent == this ); - return previous->NextSibling( val ); - } + if ( !previous ) { + return FirstChild( val ); + } else { + assert( previous->parent == this ); + return previous->NextSibling( val ); + } } -const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const +const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { - const TiXmlNode* node; - for ( node = next; node; node = node->next ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; + const TiXmlNode* node; + for ( node = next; node; node = node->next ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { - const TiXmlNode* node; - for ( node = prev; node; node = node->prev ) - { - if ( strcmp( node->Value(), _value ) == 0 ) - return node; - } - return 0; + const TiXmlNode* node; + for ( node = prev; node; node = node->prev ) { + if ( strcmp( node->Value(), _value ) == 0 ) + return node; + } + return 0; } void TiXmlElement::RemoveAttribute( const char * name ) { - #ifdef TIXML_USE_STL - TIXML_STRING str( name ); - TiXmlAttribute* node = attributeSet.Find( str ); - #else - TiXmlAttribute* node = attributeSet.Find( name ); - #endif - if ( node ) - { - attributeSet.Remove( node ); - delete node; - } +#ifdef TIXML_USE_STL + TIXML_STRING str( name ); + TiXmlAttribute* node = attributeSet.Find( str ); +#else + TiXmlAttribute* node = attributeSet.Find( name ); +#endif + if ( node ) { + attributeSet.Remove( node ); + delete node; + } } const TiXmlElement* TiXmlNode::FirstChildElement() const { - const TiXmlNode* node; + const TiXmlNode* node; - for ( node = FirstChild(); - node; - node = node->NextSibling() ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = FirstChild(); + node; + node = node->NextSibling() ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { - const TiXmlNode* node; + const TiXmlNode* node; - for ( node = FirstChild( _value ); - node; - node = node->NextSibling( _value ) ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = FirstChild( _value ); + node; + node = node->NextSibling( _value ) ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement() const { - const TiXmlNode* node; + const TiXmlNode* node; - for ( node = NextSibling(); - node; - node = node->NextSibling() ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = NextSibling(); + node; + node = node->NextSibling() ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { - const TiXmlNode* node; + const TiXmlNode* node; - for ( node = NextSibling( _value ); - node; - node = node->NextSibling( _value ) ) - { - if ( node->ToElement() ) - return node->ToElement(); - } - return 0; + for ( node = NextSibling( _value ); + node; + node = node->NextSibling( _value ) ) { + if ( node->ToElement() ) + return node->ToElement(); + } + return 0; } const TiXmlDocument* TiXmlNode::GetDocument() const { - const TiXmlNode* node; + const TiXmlNode* node; - for( node = this; node; node = node->parent ) - { - if ( node->ToDocument() ) - return node->ToDocument(); - } - return 0; + for( node = this; node; node = node->parent ) { + if ( node->ToDocument() ) + return node->ToDocument(); + } + return 0; } TiXmlElement::TiXmlElement (const char * _value) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) + : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { - firstChild = lastChild = 0; - value = _value; + firstChild = lastChild = 0; + value = _value; } #ifdef TIXML_USE_STL -TiXmlElement::TiXmlElement( const std::string& _value ) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) +TiXmlElement::TiXmlElement( const std::string& _value ) + : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { - firstChild = lastChild = 0; - value = _value; + firstChild = lastChild = 0; + value = _value; } #endif TiXmlElement::TiXmlElement( const TiXmlElement& copy) - : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) + : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { - firstChild = lastChild = 0; - copy.CopyTo( this ); + firstChild = lastChild = 0; + copy.CopyTo( this ); } TiXmlElement& TiXmlElement::operator=( const TiXmlElement& base ) { - ClearThis(); - base.CopyTo( this ); - return *this; + ClearThis(); + base.CopyTo( this ); + return *this; } TiXmlElement::~TiXmlElement() { - ClearThis(); + ClearThis(); } void TiXmlElement::ClearThis() { - Clear(); - while( attributeSet.First() ) - { - TiXmlAttribute* node = attributeSet.First(); - attributeSet.Remove( node ); - delete node; - } + Clear(); + while( attributeSet.First() ) { + TiXmlAttribute* node = attributeSet.First(); + attributeSet.Remove( node ); + delete node; + } } const char* TiXmlElement::Attribute( const char* name ) const { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( node ) - return node->Value(); - return 0; + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( node ) + return node->Value(); + return 0; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( attrib ) - return &attrib->ValueStr(); - return 0; + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( attrib ) + return &attrib->ValueStr(); + return 0; } #endif const char* TiXmlElement::Attribute( const char* name, int* i ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const char* result = 0; - if ( attrib ) { - result = attrib->Value(); - if ( i ) { - attrib->QueryIntValue( i ); - } - } - return result; + if ( attrib ) { + result = attrib->Value(); + if ( i ) { + attrib->QueryIntValue( i ); + } + } + return result; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const std::string* result = 0; - if ( attrib ) { - result = &attrib->ValueStr(); - if ( i ) { - attrib->QueryIntValue( i ); - } - } - return result; + if ( attrib ) { + result = &attrib->ValueStr(); + if ( i ) { + attrib->QueryIntValue( i ); + } + } + return result; } #endif const char* TiXmlElement::Attribute( const char* name, double* d ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const char* result = 0; - if ( attrib ) { - result = attrib->Value(); - if ( d ) { - attrib->QueryDoubleValue( d ); - } - } - return result; + if ( attrib ) { + result = attrib->Value(); + if ( d ) { + attrib->QueryDoubleValue( d ); + } + } + return result; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; + const TiXmlAttribute* attrib = attributeSet.Find( name ); + const std::string* result = 0; - if ( attrib ) { - result = &attrib->ValueStr(); - if ( d ) { - attrib->QueryDoubleValue( d ); - } - } - return result; + if ( attrib ) { + result = &attrib->ValueStr(); + if ( d ) { + attrib->QueryDoubleValue( d ); + } + } + return result; } #endif int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryIntValue( ival ); + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryIntValue( ival ); } int TiXmlElement::QueryUnsignedAttribute( const char* name, unsigned* value ) const { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; - int ival = 0; - int result = node->QueryIntValue( &ival ); - *value = (unsigned)ival; - return result; + int ival = 0; + int result = node->QueryIntValue( &ival ); + *value = (unsigned)ival; + return result; } int TiXmlElement::QueryBoolAttribute( const char* name, bool* bval ) const { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; - - int result = TIXML_WRONG_TYPE; - if ( StringEqual( node->Value(), "true", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "yes", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "1", true, TIXML_ENCODING_UNKNOWN ) ) - { - *bval = true; - result = TIXML_SUCCESS; - } - else if ( StringEqual( node->Value(), "false", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "no", true, TIXML_ENCODING_UNKNOWN ) - || StringEqual( node->Value(), "0", true, TIXML_ENCODING_UNKNOWN ) ) - { - *bval = false; - result = TIXML_SUCCESS; - } - return result; + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; + + int result = TIXML_WRONG_TYPE; + if ( StringEqual( node->Value(), "true", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "yes", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "1", true, TIXML_ENCODING_UNKNOWN ) ) { + *bval = true; + result = TIXML_SUCCESS; + } else if ( StringEqual( node->Value(), "false", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "no", true, TIXML_ENCODING_UNKNOWN ) + || StringEqual( node->Value(), "0", true, TIXML_ENCODING_UNKNOWN ) ) { + *bval = false; + result = TIXML_SUCCESS; + } + return result; } @@ -709,471 +659,447 @@ int TiXmlElement::QueryBoolAttribute( const char* name, bool* bval ) const #ifdef TIXML_USE_STL int TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryIntValue( ival ); + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryIntValue( ival ); } #endif int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryDoubleValue( dval ); + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryDoubleValue( dval ); } #ifdef TIXML_USE_STL int TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const { - const TiXmlAttribute* attrib = attributeSet.Find( name ); - if ( !attrib ) - return TIXML_NO_ATTRIBUTE; - return attrib->QueryDoubleValue( dval ); + const TiXmlAttribute* attrib = attributeSet.Find( name ); + if ( !attrib ) + return TIXML_NO_ATTRIBUTE; + return attrib->QueryDoubleValue( dval ); } #endif void TiXmlElement::SetAttribute( const char * name, int val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetIntValue( val ); - } +{ + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetIntValue( val ); + } } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& name, int val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetIntValue( val ); - } +{ + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetIntValue( val ); + } } #endif void TiXmlElement::SetDoubleAttribute( const char * name, double val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetDoubleValue( val ); - } +{ + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetDoubleValue( val ); + } } #ifdef TIXML_USE_STL void TiXmlElement::SetDoubleAttribute( const std::string& name, double val ) -{ - TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); - if ( attrib ) { - attrib->SetDoubleValue( val ); - } +{ + TiXmlAttribute* attrib = attributeSet.FindOrCreate( name ); + if ( attrib ) { + attrib->SetDoubleValue( val ); + } } -#endif +#endif void TiXmlElement::SetAttribute( const char * cname, const char * cvalue ) { - TiXmlAttribute* attrib = attributeSet.FindOrCreate( cname ); - if ( attrib ) { - attrib->SetValue( cvalue ); - } + TiXmlAttribute* attrib = attributeSet.FindOrCreate( cname ); + if ( attrib ) { + attrib->SetValue( cvalue ); + } } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& _name, const std::string& _value ) { - TiXmlAttribute* attrib = attributeSet.FindOrCreate( _name ); - if ( attrib ) { - attrib->SetValue( _value ); - } + TiXmlAttribute* attrib = attributeSet.FindOrCreate( _name ); + if ( attrib ) { + attrib->SetValue( _value ); + } } #endif void TiXmlElement::Print( FILE* cfile, int depth ) const { - int i; - assert( cfile ); - for ( i=0; i<depth; i++ ) { - fprintf( cfile, " " ); - } - - fprintf( cfile, "<%s", value.c_str() ); - - const TiXmlAttribute* attrib; - for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) - { - fprintf( cfile, " " ); - attrib->Print( cfile, depth ); - } - - // There are 3 different formatting approaches: - // 1) An element without children is printed as a <foo /> node - // 2) An element with only a text child is printed as <foo> text </foo> - // 3) An element with children is printed on multiple lines. - TiXmlNode* node; - if ( !firstChild ) - { - fprintf( cfile, " />" ); - } - else if ( firstChild == lastChild && firstChild->ToText() ) - { - fprintf( cfile, ">" ); - firstChild->Print( cfile, depth + 1 ); - fprintf( cfile, "</%s>", value.c_str() ); - } - else - { - fprintf( cfile, ">" ); - - for ( node = firstChild; node; node=node->NextSibling() ) - { - if ( !node->ToText() ) - { - fprintf( cfile, "\n" ); - } - node->Print( cfile, depth+1 ); - } - fprintf( cfile, "\n" ); - for( i=0; i<depth; ++i ) { - fprintf( cfile, " " ); - } - fprintf( cfile, "</%s>", value.c_str() ); - } + int i; + assert( cfile ); + for ( i=0; i<depth; i++ ) { + fprintf( cfile, " " ); + } + + fprintf( cfile, "<%s", value.c_str() ); + + const TiXmlAttribute* attrib; + for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { + fprintf( cfile, " " ); + attrib->Print( cfile, depth ); + } + + // There are 3 different formatting approaches: + // 1) An element without children is printed as a <foo /> node + // 2) An element with only a text child is printed as <foo> text </foo> + // 3) An element with children is printed on multiple lines. + TiXmlNode* node; + if ( !firstChild ) { + fprintf( cfile, " />" ); + } else if ( firstChild == lastChild && firstChild->ToText() ) { + fprintf( cfile, ">" ); + firstChild->Print( cfile, depth + 1 ); + fprintf( cfile, "</%s>", value.c_str() ); + } else { + fprintf( cfile, ">" ); + + for ( node = firstChild; node; node=node->NextSibling() ) { + if ( !node->ToText() ) { + fprintf( cfile, "\n" ); + } + node->Print( cfile, depth+1 ); + } + fprintf( cfile, "\n" ); + for( i=0; i<depth; ++i ) { + fprintf( cfile, " " ); + } + fprintf( cfile, "</%s>", value.c_str() ); + } } void TiXmlElement::CopyTo( TiXmlElement* target ) const { - // superclass: - TiXmlNode::CopyTo( target ); + // superclass: + TiXmlNode::CopyTo( target ); - // Element class: - // Clone the attributes, then clone the children. - const TiXmlAttribute* attribute = 0; - for( attribute = attributeSet.First(); - attribute; - attribute = attribute->Next() ) - { - target->SetAttribute( attribute->Name(), attribute->Value() ); - } + // Element class: + // Clone the attributes, then clone the children. + const TiXmlAttribute* attribute = 0; + for( attribute = attributeSet.First(); + attribute; + attribute = attribute->Next() ) { + target->SetAttribute( attribute->Name(), attribute->Value() ); + } - TiXmlNode* node = 0; - for ( node = firstChild; node; node = node->NextSibling() ) - { - target->LinkEndChild( node->Clone() ); - } + TiXmlNode* node = 0; + for ( node = firstChild; node; node = node->NextSibling() ) { + target->LinkEndChild( node->Clone() ); + } } bool TiXmlElement::Accept( TiXmlVisitor* visitor ) const { - if ( visitor->VisitEnter( *this, attributeSet.First() ) ) - { - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - if ( !node->Accept( visitor ) ) - break; - } - } - return visitor->VisitExit( *this ); + if ( visitor->VisitEnter( *this, attributeSet.First() ) ) { + for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) + break; + } + } + return visitor->VisitExit( *this ); } TiXmlNode* TiXmlElement::Clone() const { - TiXmlElement* clone = new TiXmlElement( Value() ); - if ( !clone ) - return 0; + TiXmlElement* clone = new TiXmlElement( Value() ); + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } const char* TiXmlElement::GetText() const { - const TiXmlNode* child = this->FirstChild(); - if ( child ) { - const TiXmlText* childText = child->ToText(); - if ( childText ) { - return childText->Value(); - } - } - return 0; + const TiXmlNode* child = this->FirstChild(); + if ( child ) { + const TiXmlText* childText = child->ToText(); + if ( childText ) { + return childText->Value(); + } + } + return 0; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { - tabsize = 4; - useMicrosoftBOM = false; - ClearError(); + tabsize = 4; + useMicrosoftBOM = false; + ClearError(); } TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { - tabsize = 4; - useMicrosoftBOM = false; - value = documentName; - ClearError(); + tabsize = 4; + useMicrosoftBOM = false; + value = documentName; + ClearError(); } #ifdef TIXML_USE_STL TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { - tabsize = 4; - useMicrosoftBOM = false; + tabsize = 4; + useMicrosoftBOM = false; value = documentName; - ClearError(); + ClearError(); } #endif TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::TINYXML_DOCUMENT ) { - copy.CopyTo( this ); + copy.CopyTo( this ); } TiXmlDocument& TiXmlDocument::operator=( const TiXmlDocument& copy ) { - Clear(); - copy.CopyTo( this ); - return *this; + Clear(); + copy.CopyTo( this ); + return *this; } bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) { - return LoadFile( Value(), encoding ); + return LoadFile( Value(), encoding ); } bool TiXmlDocument::SaveFile() const { - return SaveFile( Value() ); + return SaveFile( Value() ); } bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) { - TIXML_STRING filename( _filename ); - value = filename; + TIXML_STRING filename( _filename ); + value = filename; - // reading in binary mode so that tinyxml can normalize the EOL - FILE* file = TiXmlFOpen( value.c_str (), "rb" ); + // reading in binary mode so that tinyxml can normalize the EOL + FILE* file = TiXmlFOpen( value.c_str (), "rb" ); - if ( file ) - { - bool result = LoadFile( file, encoding ); - fclose( file ); - return result; - } - else - { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } + if ( file ) { + bool result = LoadFile( file, encoding ); + fclose( file ); + return result; + } else { + SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } } bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) { - if ( !file ) - { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } - - // Delete the existing data: - Clear(); - location.Clear(); - - // Get the file size, so we can pre-allocate the string. HUGE speed impact. - long length = 0; - fseek( file, 0, SEEK_END ); - length = ftell( file ); - fseek( file, 0, SEEK_SET ); - - // Strange case, but good to handle up front. - if ( length <= 0 ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } - - // Subtle bug here. TinyXml did use fgets. But from the XML spec: - // 2.11 End-of-Line Handling - // <snip> - // <quote> - // ...the XML processor MUST behave as if it normalized all line breaks in external - // parsed entities (including the document entity) on input, before parsing, by translating - // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to - // a single #xA character. - // </quote> - // - // It is not clear fgets does that, and certainly isn't clear it works cross platform. - // Generally, you expect fgets to translate from the convention of the OS to the c/unix - // convention, and not work generally. - - /* - while( fgets( buf, sizeof(buf), file ) ) - { - data += buf; - } - */ - - char* buf = new char[ length+1 ]; - buf[0] = 0; - - if ( fread( buf, length, 1, file ) != 1 ) { - delete [] buf; - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); - return false; - } - - // Process the buffer in place to normalize new lines. (See comment above.) - // Copies from the 'p' to 'q' pointer, where p can advance faster if - // a newline-carriage return is hit. - // - // Wikipedia: - // Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or - // CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)... - // * LF: Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others + if ( !file ) { + SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } + + // Delete the existing data: + Clear(); + location.Clear(); + + // Get the file size, so we can pre-allocate the string. HUGE speed impact. + long length = 0; + fseek( file, 0, SEEK_END ); + length = ftell( file ); + fseek( file, 0, SEEK_SET ); + + // Strange case, but good to handle up front. + if ( length <= 0 ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } + + // Subtle bug here. TinyXml did use fgets. But from the XML spec: + // 2.11 End-of-Line Handling + // <snip> + // <quote> + // ...the XML processor MUST behave as if it normalized all line breaks in external + // parsed entities (including the document entity) on input, before parsing, by translating + // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to + // a single #xA character. + // </quote> + // + // It is not clear fgets does that, and certainly isn't clear it works cross platform. + // Generally, you expect fgets to translate from the convention of the OS to the c/unix + // convention, and not work generally. + + /* + while( fgets( buf, sizeof(buf), file ) ) + { + data += buf; + } + */ + + char* buf = new char[ length+1 ]; + buf[0] = 0; + + if ( fread( buf, length, 1, file ) != 1 ) { + delete [] buf; + SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + return false; + } + + // Process the buffer in place to normalize new lines. (See comment above.) + // Copies from the 'p' to 'q' pointer, where p can advance faster if + // a newline-carriage return is hit. + // + // Wikipedia: + // Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or + // CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)... + // * LF: Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others // * CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS // * CR: Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9 - const char* p = buf; // the read head - char* q = buf; // the write head - const char CR = 0x0d; - const char LF = 0x0a; + const char* p = buf; // the read head + char* q = buf; // the write head + const char CR = 0x0d; + const char LF = 0x0a; - buf[length] = 0; - while( *p ) { - assert( p < (buf+length) ); - assert( q <= (buf+length) ); - assert( q <= p ); + buf[length] = 0; + while( *p ) { + assert( p < (buf+length) ); + assert( q <= (buf+length) ); + assert( q <= p ); - if ( *p == CR ) { - *q++ = LF; - p++; - if ( *p == LF ) { // check for CR+LF (and skip LF) - p++; - } - } - else { - *q++ = *p++; - } - } - assert( q <= (buf+length) ); - *q = 0; + if ( *p == CR ) { + *q++ = LF; + p++; + if ( *p == LF ) { // check for CR+LF (and skip LF) + p++; + } + } else { + *q++ = *p++; + } + } + assert( q <= (buf+length) ); + *q = 0; - Parse( buf, 0, encoding ); + Parse( buf, 0, encoding ); - delete [] buf; - return !Error(); + delete [] buf; + return !Error(); } bool TiXmlDocument::SaveFile( const char * filename ) const { - // The old c stuff lives on... - FILE* fp = TiXmlFOpen( filename, "w" ); - if ( fp ) - { - bool result = SaveFile( fp ); - fclose( fp ); - return result; - } - return false; + // The old c stuff lives on... + FILE* fp = TiXmlFOpen( filename, "w" ); + if ( fp ) { + bool result = SaveFile( fp ); + fclose( fp ); + return result; + } + return false; } bool TiXmlDocument::SaveFile( FILE* fp ) const { - if ( useMicrosoftBOM ) - { - const unsigned char TIXML_UTF_LEAD_0 = 0xefU; - const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; - const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; + if ( useMicrosoftBOM ) { + const unsigned char TIXML_UTF_LEAD_0 = 0xefU; + const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; + const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; - fputc( TIXML_UTF_LEAD_0, fp ); - fputc( TIXML_UTF_LEAD_1, fp ); - fputc( TIXML_UTF_LEAD_2, fp ); - } - Print( fp, 0 ); - return (ferror(fp) == 0); + fputc( TIXML_UTF_LEAD_0, fp ); + fputc( TIXML_UTF_LEAD_1, fp ); + fputc( TIXML_UTF_LEAD_2, fp ); + } + Print( fp, 0 ); + return (ferror(fp) == 0); } void TiXmlDocument::CopyTo( TiXmlDocument* target ) const { - TiXmlNode::CopyTo( target ); + TiXmlNode::CopyTo( target ); - target->error = error; - target->errorId = errorId; - target->errorDesc = errorDesc; - target->tabsize = tabsize; - target->errorLocation = errorLocation; - target->useMicrosoftBOM = useMicrosoftBOM; + target->error = error; + target->errorId = errorId; + target->errorDesc = errorDesc; + target->tabsize = tabsize; + target->errorLocation = errorLocation; + target->useMicrosoftBOM = useMicrosoftBOM; - TiXmlNode* node = 0; - for ( node = firstChild; node; node = node->NextSibling() ) - { - target->LinkEndChild( node->Clone() ); - } + TiXmlNode* node = 0; + for ( node = firstChild; node; node = node->NextSibling() ) { + target->LinkEndChild( node->Clone() ); + } } TiXmlNode* TiXmlDocument::Clone() const { - TiXmlDocument* clone = new TiXmlDocument(); - if ( !clone ) - return 0; + TiXmlDocument* clone = new TiXmlDocument(); + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } void TiXmlDocument::Print( FILE* cfile, int depth ) const { - assert( cfile ); - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - node->Print( cfile, depth ); - fprintf( cfile, "\n" ); - } + assert( cfile ); + for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { + node->Print( cfile, depth ); + fprintf( cfile, "\n" ); + } } bool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const { - if ( visitor->VisitEnter( *this ) ) - { - for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) - { - if ( !node->Accept( visitor ) ) - break; - } - } - return visitor->VisitExit( *this ); + if ( visitor->VisitEnter( *this ) ) { + for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) + break; + } + } + return visitor->VisitExit( *this ); } const TiXmlAttribute* TiXmlAttribute::Next() const { - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( next->value.empty() && next->name.empty() ) - return 0; - return next; + // We are using knowledge of the sentinel. The sentinel + // have a value or name. + if ( next->value.empty() && next->name.empty() ) + return 0; + return next; } /* @@ -1189,11 +1115,11 @@ TiXmlAttribute* TiXmlAttribute::Next() const TiXmlAttribute* TiXmlAttribute::Previous() const { - // We are using knowledge of the sentinel. The sentinel - // have a value or name. - if ( prev->value.empty() && prev->name.empty() ) - return 0; - return prev; + // We are using knowledge of the sentinel. The sentinel + // have a value or name. + if ( prev->value.empty() && prev->name.empty() ) + return 0; + return prev; } /* @@ -1209,678 +1135,657 @@ TiXmlAttribute* TiXmlAttribute::Previous() void TiXmlAttribute::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { - TIXML_STRING n, v; - - EncodeString( name, &n ); - EncodeString( value, &v ); - - if (value.find ('\"') == TIXML_STRING::npos) { - if ( cfile ) { - fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); - } - if ( str ) { - (*str) += n; (*str) += "=\""; (*str) += v; (*str) += "\""; - } - } - else { - if ( cfile ) { - fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); - } - if ( str ) { - (*str) += n; (*str) += "='"; (*str) += v; (*str) += "'"; - } - } + TIXML_STRING n, v; + + EncodeString( name, &n ); + EncodeString( value, &v ); + + if (value.find ('\"') == TIXML_STRING::npos) { + if ( cfile ) { + fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); + } + if ( str ) { + (*str) += n; + (*str) += "=\""; + (*str) += v; + (*str) += "\""; + } + } else { + if ( cfile ) { + fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); + } + if ( str ) { + (*str) += n; + (*str) += "='"; + (*str) += v; + (*str) += "'"; + } + } } int TiXmlAttribute::QueryIntValue( int* ival ) const { - if ( TIXML_SSCANF( value.c_str(), "%d", ival ) == 1 ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; + if ( TIXML_SSCANF( value.c_str(), "%d", ival ) == 1 ) + return TIXML_SUCCESS; + return TIXML_WRONG_TYPE; } int TiXmlAttribute::QueryDoubleValue( double* dval ) const { - if ( TIXML_SSCANF( value.c_str(), "%lf", dval ) == 1 ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; + if ( TIXML_SSCANF( value.c_str(), "%lf", dval ) == 1 ) + return TIXML_SUCCESS; + return TIXML_WRONG_TYPE; } void TiXmlAttribute::SetIntValue( int _value ) { - char buf [64]; - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); - #else - sprintf (buf, "%d", _value); - #endif - SetValue (buf); + char buf [64]; +#if defined(TIXML_SNPRINTF) + TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); +#else + sprintf (buf, "%d", _value); +#endif + SetValue (buf); } void TiXmlAttribute::SetDoubleValue( double _value ) { - char buf [256]; - #if defined(TIXML_SNPRINTF) - TIXML_SNPRINTF( buf, sizeof(buf), "%g", _value); - #else - sprintf (buf, "%g", _value); - #endif - SetValue (buf); + char buf [256]; +#if defined(TIXML_SNPRINTF) + TIXML_SNPRINTF( buf, sizeof(buf), "%g", _value); +#else + sprintf (buf, "%g", _value); +#endif + SetValue (buf); } int TiXmlAttribute::IntValue() const { - return atoi (value.c_str ()); + return atoi (value.c_str ()); } double TiXmlAttribute::DoubleValue() const { - return atof (value.c_str ()); + return atof (value.c_str ()); } TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) { - copy.CopyTo( this ); + copy.CopyTo( this ); } TiXmlComment& TiXmlComment::operator=( const TiXmlComment& base ) { - Clear(); - base.CopyTo( this ); - return *this; + Clear(); + base.CopyTo( this ); + return *this; } void TiXmlComment::Print( FILE* cfile, int depth ) const { - assert( cfile ); - for ( int i=0; i<depth; i++ ) - { - fprintf( cfile, " " ); - } - fprintf( cfile, "<!--%s-->", value.c_str() ); + assert( cfile ); + for ( int i=0; i<depth; i++ ) { + fprintf( cfile, " " ); + } + fprintf( cfile, "<!--%s-->", value.c_str() ); } void TiXmlComment::CopyTo( TiXmlComment* target ) const { - TiXmlNode::CopyTo( target ); + TiXmlNode::CopyTo( target ); } bool TiXmlComment::Accept( TiXmlVisitor* visitor ) const { - return visitor->Visit( *this ); + return visitor->Visit( *this ); } TiXmlNode* TiXmlComment::Clone() const { - TiXmlComment* clone = new TiXmlComment(); + TiXmlComment* clone = new TiXmlComment(); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } void TiXmlText::Print( FILE* cfile, int depth ) const { - assert( cfile ); - if ( cdata ) - { - int i; - fprintf( cfile, "\n" ); - for ( i=0; i<depth; i++ ) { - fprintf( cfile, " " ); - } - fprintf( cfile, "<![CDATA[%s]]>\n", value.c_str() ); // unformatted output - } - else - { - TIXML_STRING buffer; - EncodeString( value, &buffer ); - fprintf( cfile, "%s", buffer.c_str() ); - } + assert( cfile ); + if ( cdata ) { + int i; + fprintf( cfile, "\n" ); + for ( i=0; i<depth; i++ ) { + fprintf( cfile, " " ); + } + fprintf( cfile, "<![CDATA[%s]]>\n", value.c_str() ); // unformatted output + } else { + TIXML_STRING buffer; + EncodeString( value, &buffer ); + fprintf( cfile, "%s", buffer.c_str() ); + } } void TiXmlText::CopyTo( TiXmlText* target ) const { - TiXmlNode::CopyTo( target ); - target->cdata = cdata; + TiXmlNode::CopyTo( target ); + target->cdata = cdata; } bool TiXmlText::Accept( TiXmlVisitor* visitor ) const { - return visitor->Visit( *this ); + return visitor->Visit( *this ); } TiXmlNode* TiXmlText::Clone() const -{ - TiXmlText* clone = 0; - clone = new TiXmlText( "" ); +{ + TiXmlText* clone = 0; + clone = new TiXmlText( "" ); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, - const char * _encoding, - const char * _standalone ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) + const char * _encoding, + const char * _standalone ) + : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) { - version = _version; - encoding = _encoding; - standalone = _standalone; + version = _version; + encoding = _encoding; + standalone = _standalone; } #ifdef TIXML_USE_STL TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, - const std::string& _encoding, - const std::string& _standalone ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) + const std::string& _encoding, + const std::string& _standalone ) + : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) { - version = _version; - encoding = _encoding; - standalone = _standalone; + version = _version; + encoding = _encoding; + standalone = _standalone; } #endif TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) - : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) + : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) { - copy.CopyTo( this ); + copy.CopyTo( this ); } TiXmlDeclaration& TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) { - Clear(); - copy.CopyTo( this ); - return *this; + Clear(); + copy.CopyTo( this ); + return *this; } void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { - if ( cfile ) fprintf( cfile, "<?xml " ); - if ( str ) (*str) += "<?xml "; - - if ( !version.empty() ) { - if ( cfile ) fprintf (cfile, "version=\"%s\" ", version.c_str ()); - if ( str ) { (*str) += "version=\""; (*str) += version; (*str) += "\" "; } - } - if ( !encoding.empty() ) { - if ( cfile ) fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); - if ( str ) { (*str) += "encoding=\""; (*str) += encoding; (*str) += "\" "; } - } - if ( !standalone.empty() ) { - if ( cfile ) fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); - if ( str ) { (*str) += "standalone=\""; (*str) += standalone; (*str) += "\" "; } - } - if ( cfile ) fprintf( cfile, "?>" ); - if ( str ) (*str) += "?>"; + if ( cfile ) fprintf( cfile, "<?xml " ); + if ( str ) (*str) += "<?xml "; + + if ( !version.empty() ) { + if ( cfile ) fprintf (cfile, "version=\"%s\" ", version.c_str ()); + if ( str ) { + (*str) += "version=\""; + (*str) += version; + (*str) += "\" "; + } + } + if ( !encoding.empty() ) { + if ( cfile ) fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); + if ( str ) { + (*str) += "encoding=\""; + (*str) += encoding; + (*str) += "\" "; + } + } + if ( !standalone.empty() ) { + if ( cfile ) fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); + if ( str ) { + (*str) += "standalone=\""; + (*str) += standalone; + (*str) += "\" "; + } + } + if ( cfile ) fprintf( cfile, "?>" ); + if ( str ) (*str) += "?>"; } void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const { - TiXmlNode::CopyTo( target ); + TiXmlNode::CopyTo( target ); - target->version = version; - target->encoding = encoding; - target->standalone = standalone; + target->version = version; + target->encoding = encoding; + target->standalone = standalone; } bool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const { - return visitor->Visit( *this ); + return visitor->Visit( *this ); } TiXmlNode* TiXmlDeclaration::Clone() const -{ - TiXmlDeclaration* clone = new TiXmlDeclaration(); +{ + TiXmlDeclaration* clone = new TiXmlDeclaration(); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } void TiXmlUnknown::Print( FILE* cfile, int depth ) const { - for ( int i=0; i<depth; i++ ) - fprintf( cfile, " " ); - fprintf( cfile, "<%s>", value.c_str() ); + for ( int i=0; i<depth; i++ ) + fprintf( cfile, " " ); + fprintf( cfile, "<%s>", value.c_str() ); } void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const { - TiXmlNode::CopyTo( target ); + TiXmlNode::CopyTo( target ); } bool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const { - return visitor->Visit( *this ); + return visitor->Visit( *this ); } TiXmlNode* TiXmlUnknown::Clone() const { - TiXmlUnknown* clone = new TiXmlUnknown(); + TiXmlUnknown* clone = new TiXmlUnknown(); - if ( !clone ) - return 0; + if ( !clone ) + return 0; - CopyTo( clone ); - return clone; + CopyTo( clone ); + return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { - sentinel.next = &sentinel; - sentinel.prev = &sentinel; + sentinel.next = &sentinel; + sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { - assert( sentinel.next == &sentinel ); - assert( sentinel.prev == &sentinel ); + assert( sentinel.next == &sentinel ); + assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { - #ifdef TIXML_USE_STL - assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. - #else - assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. - #endif +#ifdef TIXML_USE_STL + assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. +#else + assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. +#endif - addMe->next = &sentinel; - addMe->prev = sentinel.prev; + addMe->next = &sentinel; + addMe->prev = sentinel.prev; - sentinel.prev->next = addMe; - sentinel.prev = addMe; + sentinel.prev->next = addMe; + sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { - TiXmlAttribute* node; + TiXmlAttribute* node; - for( node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( node == removeMe ) - { - node->prev->next = node->next; - node->next->prev = node->prev; - node->next = 0; - node->prev = 0; - return; - } - } - assert( 0 ); // we tried to remove a non-linked attribute. + for( node = sentinel.next; node != &sentinel; node = node->next ) { + if ( node == removeMe ) { + node->prev->next = node->next; + node->next->prev = node->prev; + node->next = 0; + node->prev = 0; + return; + } + } + assert( 0 ); // we tried to remove a non-linked attribute. } #ifdef TIXML_USE_STL TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const { - for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( node->name == name ) - return node; - } - return 0; + for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { + if ( node->name == name ) + return node; + } + return 0; } TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const std::string& _name ) { - TiXmlAttribute* attrib = Find( _name ); - if ( !attrib ) { - attrib = new TiXmlAttribute(); - Add( attrib ); - attrib->SetName( _name ); - } - return attrib; + TiXmlAttribute* attrib = Find( _name ); + if ( !attrib ) { + attrib = new TiXmlAttribute(); + Add( attrib ); + attrib->SetName( _name ); + } + return attrib; } #endif TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const { - for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) - { - if ( strcmp( node->name.c_str(), name ) == 0 ) - return node; - } - return 0; + for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { + if ( strcmp( node->name.c_str(), name ) == 0 ) + return node; + } + return 0; } TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const char* _name ) { - TiXmlAttribute* attrib = Find( _name ); - if ( !attrib ) { - attrib = new TiXmlAttribute(); - Add( attrib ); - attrib->SetName( _name ); - } - return attrib; + TiXmlAttribute* attrib = Find( _name ); + if ( !attrib ) { + attrib = new TiXmlAttribute(); + Add( attrib ); + attrib->SetName( _name ); + } + return attrib; } -#ifdef TIXML_USE_STL +#ifdef TIXML_USE_STL std::istream& operator>> (std::istream & in, TiXmlNode & base) { - TIXML_STRING tag; - tag.reserve( 8 * 1000 ); - base.StreamIn( &in, &tag ); + TIXML_STRING tag; + tag.reserve( 8 * 1000 ); + base.StreamIn( &in, &tag ); - base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); - return in; + base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); + return in; } #endif -#ifdef TIXML_USE_STL +#ifdef TIXML_USE_STL std::ostream& operator<< (std::ostream & out, const TiXmlNode & base) { - TiXmlPrinter printer; - printer.SetStreamPrinting(); - base.Accept( &printer ); - out << printer.Str(); + TiXmlPrinter printer; + printer.SetStreamPrinting(); + base.Accept( &printer ); + out << printer.Str(); - return out; + return out; } std::string& operator<< (std::string& out, const TiXmlNode& base ) { - TiXmlPrinter printer; - printer.SetStreamPrinting(); - base.Accept( &printer ); - out.append( printer.Str() ); + TiXmlPrinter printer; + printer.SetStreamPrinting(); + base.Accept( &printer ); + out.append( printer.Str() ); - return out; + return out; } #endif TiXmlHandle TiXmlHandle::FirstChild() const { - if ( node ) - { - TiXmlNode* child = node->FirstChild(); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + TiXmlNode* child = node->FirstChild(); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { - if ( node ) - { - TiXmlNode* child = node->FirstChild( value ); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + TiXmlNode* child = node->FirstChild( value ); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement() const { - if ( node ) - { - TiXmlElement* child = node->FirstChildElement(); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + TiXmlElement* child = node->FirstChildElement(); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { - if ( node ) - { - TiXmlElement* child = node->FirstChildElement( value ); - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + TiXmlElement* child = node->FirstChildElement( value ); + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( int count ) const { - if ( node ) - { - int i; - TiXmlNode* child = node->FirstChild(); - for ( i=0; - child && i<count; - child = child->NextSibling(), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + int i; + TiXmlNode* child = node->FirstChild(); + for ( i=0; + child && i<count; + child = child->NextSibling(), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { - if ( node ) - { - int i; - TiXmlNode* child = node->FirstChild( value ); - for ( i=0; - child && i<count; - child = child->NextSibling( value ), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + int i; + TiXmlNode* child = node->FirstChild( value ); + for ( i=0; + child && i<count; + child = child->NextSibling( value ), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( int count ) const { - if ( node ) - { - int i; - TiXmlElement* child = node->FirstChildElement(); - for ( i=0; - child && i<count; - child = child->NextSiblingElement(), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + int i; + TiXmlElement* child = node->FirstChildElement(); + for ( i=0; + child && i<count; + child = child->NextSiblingElement(), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { - if ( node ) - { - int i; - TiXmlElement* child = node->FirstChildElement( value ); - for ( i=0; - child && i<count; - child = child->NextSiblingElement( value ), ++i ) - { - // nothing - } - if ( child ) - return TiXmlHandle( child ); - } - return TiXmlHandle( 0 ); + if ( node ) { + int i; + TiXmlElement* child = node->FirstChildElement( value ); + for ( i=0; + child && i<count; + child = child->NextSiblingElement( value ), ++i ) { + // nothing + } + if ( child ) + return TiXmlHandle( child ); + } + return TiXmlHandle( 0 ); } bool TiXmlPrinter::VisitEnter( const TiXmlDocument& ) { - return true; + return true; } bool TiXmlPrinter::VisitExit( const TiXmlDocument& ) { - return true; + return true; } bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) { - DoIndent(); - buffer += "<"; - buffer += element.Value(); - - for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) - { - buffer += " "; - attrib->Print( 0, 0, &buffer ); - } - - if ( !element.FirstChild() ) - { - buffer += " />"; - DoLineBreak(); - } - else - { - buffer += ">"; - if ( element.FirstChild()->ToText() - && element.LastChild() == element.FirstChild() - && element.FirstChild()->ToText()->CDATA() == false ) - { - simpleTextPrint = true; - // no DoLineBreak()! - } - else - { - DoLineBreak(); - } - } - ++depth; - return true; + DoIndent(); + buffer += "<"; + buffer += element.Value(); + + for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) { + buffer += " "; + attrib->Print( 0, 0, &buffer ); + } + + if ( !element.FirstChild() ) { + buffer += " />"; + DoLineBreak(); + } else { + buffer += ">"; + if ( element.FirstChild()->ToText() + && element.LastChild() == element.FirstChild() + && element.FirstChild()->ToText()->CDATA() == false ) { + simpleTextPrint = true; + // no DoLineBreak()! + } else { + DoLineBreak(); + } + } + ++depth; + return true; } bool TiXmlPrinter::VisitExit( const TiXmlElement& element ) { - --depth; - if ( !element.FirstChild() ) - { - // nothing. - } - else - { - if ( simpleTextPrint ) - { - simpleTextPrint = false; - } - else - { - DoIndent(); - } - buffer += "</"; - buffer += element.Value(); - buffer += ">"; - DoLineBreak(); - } - return true; + --depth; + if ( !element.FirstChild() ) { + // nothing. + } else { + if ( simpleTextPrint ) { + simpleTextPrint = false; + } else { + DoIndent(); + } + buffer += "</"; + buffer += element.Value(); + buffer += ">"; + DoLineBreak(); + } + return true; } bool TiXmlPrinter::Visit( const TiXmlText& text ) { - if ( text.CDATA() ) - { - DoIndent(); - buffer += "<![CDATA["; - buffer += text.Value(); - buffer += "]]>"; - DoLineBreak(); - } - else if ( simpleTextPrint ) - { - TIXML_STRING str; - TiXmlBase::EncodeString( text.ValueTStr(), &str ); - buffer += str; - } - else - { - DoIndent(); - TIXML_STRING str; - TiXmlBase::EncodeString( text.ValueTStr(), &str ); - buffer += str; - DoLineBreak(); - } - return true; + if ( text.CDATA() ) { + DoIndent(); + buffer += "<![CDATA["; + buffer += text.Value(); + buffer += "]]>"; + DoLineBreak(); + } else if ( simpleTextPrint ) { + TIXML_STRING str; + TiXmlBase::EncodeString( text.ValueTStr(), &str ); + buffer += str; + } else { + DoIndent(); + TIXML_STRING str; + TiXmlBase::EncodeString( text.ValueTStr(), &str ); + buffer += str; + DoLineBreak(); + } + return true; } bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) { - DoIndent(); - declaration.Print( 0, 0, &buffer ); - DoLineBreak(); - return true; + DoIndent(); + declaration.Print( 0, 0, &buffer ); + DoLineBreak(); + return true; } bool TiXmlPrinter::Visit( const TiXmlComment& comment ) { - DoIndent(); - buffer += "<!--"; - buffer += comment.Value(); - buffer += "-->"; - DoLineBreak(); - return true; + DoIndent(); + buffer += "<!--"; + buffer += comment.Value(); + buffer += "-->"; + DoLineBreak(); + return true; } bool TiXmlPrinter::Visit( const TiXmlUnknown& unknown ) { - DoIndent(); - buffer += "<"; - buffer += unknown.Value(); - buffer += ">"; - DoLineBreak(); - return true; + DoIndent(); + buffer += "<"; + buffer += unknown.Value(); + buffer += ">"; + DoLineBreak(); + return true; } diff --git a/src/tinyxml/tinyxml.h b/src/tinyxml/tinyxml.h index b3f08d658abb934b968d4ff57c97b7686b3ef207..2a9fb61738293502a701a092c8f3fe6b8e134203 100644 --- a/src/tinyxml/tinyxml.h +++ b/src/tinyxml/tinyxml.h @@ -46,13 +46,13 @@ distribution. #endif #ifdef TIXML_USE_STL - #include <string> - #include <iostream> - #include <sstream> - #define TIXML_STRING std::string +#include <string> +#include <iostream> +#include <sstream> +#define TIXML_STRING std::string #else - #include "tinystr.h" - #define TIXML_STRING TiXmlString +#include "tinystr.h" +#define TIXML_STRING TiXmlString #endif // Deprecated library function hell. Compilers want to use the @@ -62,25 +62,25 @@ distribution. #define TIXML_SAFE #ifdef TIXML_SAFE - #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - // Microsoft visual studio, version 2005 and higher. - #define TIXML_SNPRINTF _snprintf_s - #define TIXML_SSCANF sscanf_s - #elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) - // Microsoft visual studio, version 6 and higher. - //#pragma message( "Using _sn* functions." ) - #define TIXML_SNPRINTF _snprintf - #define TIXML_SSCANF sscanf - #elif defined(__GNUC__) && (__GNUC__ >= 3 ) - // GCC version 3 and higher.s - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_SSCANF sscanf - #else - #define TIXML_SNPRINTF snprintf - #define TIXML_SSCANF sscanf - #endif -#endif +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) +// Microsoft visual studio, version 2005 and higher. +#define TIXML_SNPRINTF _snprintf_s +#define TIXML_SSCANF sscanf_s +#elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) +// Microsoft visual studio, version 6 and higher. +//#pragma message( "Using _sn* functions." ) +#define TIXML_SNPRINTF _snprintf +#define TIXML_SSCANF sscanf +#elif defined(__GNUC__) && (__GNUC__ >= 3 ) +// GCC version 3 and higher.s +//#warning( "Using sn* functions." ) +#define TIXML_SNPRINTF snprintf +#define TIXML_SSCANF sscanf +#else +#define TIXML_SNPRINTF snprintf +#define TIXML_SSCANF sscanf +#endif +#endif class TiXmlDocument; class TiXmlElement; @@ -95,16 +95,21 @@ const int TIXML_MAJOR_VERSION = 2; const int TIXML_MINOR_VERSION = 6; const int TIXML_PATCH_VERSION = 2; -/* Internal structure for tracking location of items +/* Internal structure for tracking location of items in the XML file. */ -struct TiXmlCursor -{ - TiXmlCursor() { Clear(); } - void Clear() { row = col = -1; } - - int row; // 0 based. - int col; // 0 based. +struct TiXmlCursor { + TiXmlCursor() + { + Clear(); + } + void Clear() + { + row = col = -1; + } + + int row; // 0 based. + int col; // 0 based. }; @@ -118,7 +123,7 @@ struct TiXmlCursor If you return 'true' from a Visit method, recursive parsing will continue. If you return false, <b>no children of this node or its sibilings</b> will be Visited. - All flavors of Visit methods have a default implementation that returns 'true' (continue + All flavors of Visit methods have a default implementation that returns 'true' (continue visiting). You need to only override methods that are interesting to you. Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting. @@ -127,46 +132,67 @@ struct TiXmlCursor @sa TiXmlNode::Accept() */ -class TiXmlVisitor -{ +class TiXmlVisitor { public: - virtual ~TiXmlVisitor() {} - - /// Visit a document. - virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) { return true; } - /// Visit a document. - virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) { return true; } - - /// Visit an element. - virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) { return true; } - /// Visit an element. - virtual bool VisitExit( const TiXmlElement& /*element*/ ) { return true; } - - /// Visit a declaration - virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; } - /// Visit a text node - virtual bool Visit( const TiXmlText& /*text*/ ) { return true; } - /// Visit a comment node - virtual bool Visit( const TiXmlComment& /*comment*/ ) { return true; } - /// Visit an unknown node - virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; } + virtual ~TiXmlVisitor() {} + + /// Visit a document. + virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) + { + return true; + } + /// Visit a document. + virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) + { + return true; + } + + /// Visit an element. + virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) + { + return true; + } + /// Visit an element. + virtual bool VisitExit( const TiXmlElement& /*element*/ ) + { + return true; + } + + /// Visit a declaration + virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) + { + return true; + } + /// Visit a text node + virtual bool Visit( const TiXmlText& /*text*/ ) + { + return true; + } + /// Visit a comment node + virtual bool Visit( const TiXmlComment& /*comment*/ ) + { + return true; + } + /// Visit an unknown node + virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) + { + return true; + } }; // Only used by Attribute::Query functions -enum -{ - TIXML_SUCCESS, - TIXML_NO_ATTRIBUTE, - TIXML_WRONG_TYPE +enum { + TIXML_SUCCESS, + TIXML_NO_ATTRIBUTE, + TIXML_WRONG_TYPE }; // Used by the parsing routines. -enum TiXmlEncoding -{ - TIXML_ENCODING_UNKNOWN, - TIXML_ENCODING_UTF8, - TIXML_ENCODING_LEGACY +enum TiXmlEncoding { + TIXML_ENCODING_UNKNOWN, + TIXML_ENCODING_UTF8, + TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; @@ -193,226 +219,232 @@ const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; A Decleration contains: Attributes (not on tree) @endverbatim */ -class TiXmlBase -{ - friend class TiXmlNode; - friend class TiXmlElement; - friend class TiXmlDocument; +class TiXmlBase { + friend class TiXmlNode; + friend class TiXmlElement; + friend class TiXmlDocument; public: - TiXmlBase() : userData(0) {} - virtual ~TiXmlBase() {} - - /** All TinyXml classes can print themselves to a filestream - or the string class (TiXmlString in non-STL mode, std::string - in STL mode.) Either or both cfile and str can be null. - - This is a formatted print, and will insert - tabs and newlines. - - (For an unformatted stream, use the << operator.) - */ - virtual void Print( FILE* cfile, int depth ) const = 0; - - /** The world does not agree on whether white space should be kept or - not. In order to make everyone happy, these global, static functions - are provided to set whether or not TinyXml will condense all white space - into a single space or not. The default is to condense. Note changing this - value is not thread safe. - */ - static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } - - /// Return the current white space setting. - static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } - - /** Return the position, in the original source file, of this node or attribute. - The row and column are 1-based. (That is the first row and first column is - 1,1). If the returns values are 0 or less, then the parser does not have - a row and column value. - - Generally, the row and column value will be set when the TiXmlDocument::Load(), - TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set - when the DOM was created from operator>>. - - The values reflect the initial load. Once the DOM is modified programmatically - (by adding or changing nodes and attributes) the new values will NOT update to - reflect changes in the document. - - There is a minor performance cost to computing the row and column. Computation - can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. - - @sa TiXmlDocument::SetTabSize() - */ - int Row() const { return location.row + 1; } - int Column() const { return location.col + 1; } ///< See Row() - - void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data. - void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data. - const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data. - - // Table that returs, for a given lead byte, the total number of bytes - // in the UTF-8 sequence. - static const int utf8ByteTable[256]; - - virtual const char* Parse( const char* p, - TiXmlParsingData* data, - TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; - - /** Expands entities in a string. Note this should not contian the tag's '<', '>', etc, - or they will be transformed into entities! - */ - static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out ); - - enum - { - TIXML_NO_ERROR = 0, - TIXML_ERROR, - TIXML_ERROR_OPENING_FILE, - TIXML_ERROR_PARSING_ELEMENT, - TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, - TIXML_ERROR_READING_ELEMENT_VALUE, - TIXML_ERROR_READING_ATTRIBUTES, - TIXML_ERROR_PARSING_EMPTY, - TIXML_ERROR_READING_END_TAG, - TIXML_ERROR_PARSING_UNKNOWN, - TIXML_ERROR_PARSING_COMMENT, - TIXML_ERROR_PARSING_DECLARATION, - TIXML_ERROR_DOCUMENT_EMPTY, - TIXML_ERROR_EMBEDDED_NULL, - TIXML_ERROR_PARSING_CDATA, - TIXML_ERROR_DOCUMENT_TOP_ONLY, - - TIXML_ERROR_STRING_COUNT - }; + TiXmlBase() : userData(0) {} + virtual ~TiXmlBase() {} + + /** All TinyXml classes can print themselves to a filestream + or the string class (TiXmlString in non-STL mode, std::string + in STL mode.) Either or both cfile and str can be null. + + This is a formatted print, and will insert + tabs and newlines. + + (For an unformatted stream, use the << operator.) + */ + virtual void Print( FILE* cfile, int depth ) const = 0; + + /** The world does not agree on whether white space should be kept or + not. In order to make everyone happy, these global, static functions + are provided to set whether or not TinyXml will condense all white space + into a single space or not. The default is to condense. Note changing this + value is not thread safe. + */ + static void SetCondenseWhiteSpace( bool condense ) + { + condenseWhiteSpace = condense; + } + + /// Return the current white space setting. + static bool IsWhiteSpaceCondensed() + { + return condenseWhiteSpace; + } + + /** Return the position, in the original source file, of this node or attribute. + The row and column are 1-based. (That is the first row and first column is + 1,1). If the returns values are 0 or less, then the parser does not have + a row and column value. + + Generally, the row and column value will be set when the TiXmlDocument::Load(), + TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set + when the DOM was created from operator>>. + + The values reflect the initial load. Once the DOM is modified programmatically + (by adding or changing nodes and attributes) the new values will NOT update to + reflect changes in the document. + + There is a minor performance cost to computing the row and column. Computation + can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. + + @sa TiXmlDocument::SetTabSize() + */ + int Row() const + { + return location.row + 1; + } + int Column() const + { + return location.col + 1; ///< See Row() + } + + void SetUserData( void* user ) + { + userData = user; ///< Set a pointer to arbitrary user data. + } + void* GetUserData() + { + return userData; ///< Get a pointer to arbitrary user data. + } + const void* GetUserData() const + { + return userData; ///< Get a pointer to arbitrary user data. + } + + // Table that returs, for a given lead byte, the total number of bytes + // in the UTF-8 sequence. + static const int utf8ByteTable[256]; + + virtual const char* Parse( const char* p, + TiXmlParsingData* data, + TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; + + /** Expands entities in a string. Note this should not contian the tag's '<', '>', etc, + or they will be transformed into entities! + */ + static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out ); + + enum { + TIXML_NO_ERROR = 0, + TIXML_ERROR, + TIXML_ERROR_OPENING_FILE, + TIXML_ERROR_PARSING_ELEMENT, + TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, + TIXML_ERROR_READING_ELEMENT_VALUE, + TIXML_ERROR_READING_ATTRIBUTES, + TIXML_ERROR_PARSING_EMPTY, + TIXML_ERROR_READING_END_TAG, + TIXML_ERROR_PARSING_UNKNOWN, + TIXML_ERROR_PARSING_COMMENT, + TIXML_ERROR_PARSING_DECLARATION, + TIXML_ERROR_DOCUMENT_EMPTY, + TIXML_ERROR_EMBEDDED_NULL, + TIXML_ERROR_PARSING_CDATA, + TIXML_ERROR_DOCUMENT_TOP_ONLY, + + TIXML_ERROR_STRING_COUNT + }; protected: - static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); + static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); - inline static bool IsWhiteSpace( char c ) - { - return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); - } - inline static bool IsWhiteSpace( int c ) - { - if ( c < 256 ) - return IsWhiteSpace( (char) c ); - return false; // Again, only truly correct for English/Latin...but usually works. - } + inline static bool IsWhiteSpace( char c ) + { + return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); + } + inline static bool IsWhiteSpace( int c ) + { + if ( c < 256 ) + return IsWhiteSpace( (char) c ); + return false; // Again, only truly correct for English/Latin...but usually works. + } - #ifdef TIXML_USE_STL - static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ); - static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag ); - #endif - - /* Reads an XML name into the string provided. Returns - a pointer just past the last character of the name, - or 0 if the function has an error. - */ - static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); - - /* Reads text. Returns a pointer past the given end tag. - Wickedly complex options, but it keeps the (sensitive) code in one place. - */ - static const char* ReadText( const char* in, // where to start - TIXML_STRING* text, // the string read - bool ignoreWhiteSpace, // whether to keep the white space - const char* endTag, // what ends this text - bool ignoreCase, // whether to ignore case in the end tag - TiXmlEncoding encoding ); // the current encoding - - // If an entity has been found, transform it into a character. - static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); - - // Get a character, while interpreting entities. - // The length can be from 0 to 4 bytes. - inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) - { - assert( p ); - if ( encoding == TIXML_ENCODING_UTF8 ) - { - *length = utf8ByteTable[ *((const unsigned char*)p) ]; - assert( *length >= 0 && *length < 5 ); - } - else - { - *length = 1; - } - - if ( *length == 1 ) - { - if ( *p == '&' ) - return GetEntity( p, _value, length, encoding ); - *_value = *p; - return p+1; - } - else if ( *length ) - { - //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), - // and the null terminator isn't needed - for( int i=0; p[i] && i<*length; ++i ) { - _value[i] = p[i]; - } - return p + (*length); - } - else - { - // Not valid text. - return 0; - } - } - - // Return true if the next characters in the stream are any of the endTag sequences. - // Ignore case only works for english, and should only be relied on when comparing - // to English words: StringEqual( p, "version", true ) is fine. - static bool StringEqual( const char* p, - const char* endTag, - bool ignoreCase, - TiXmlEncoding encoding ); - - static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; +#ifdef TIXML_USE_STL + static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ); + static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag ); +#endif - TiXmlCursor location; + /* Reads an XML name into the string provided. Returns + a pointer just past the last character of the name, + or 0 if the function has an error. + */ + static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); + + /* Reads text. Returns a pointer past the given end tag. + Wickedly complex options, but it keeps the (sensitive) code in one place. + */ + static const char* ReadText( const char* in, // where to start + TIXML_STRING* text, // the string read + bool ignoreWhiteSpace, // whether to keep the white space + const char* endTag, // what ends this text + bool ignoreCase, // whether to ignore case in the end tag + TiXmlEncoding encoding ); // the current encoding + + // If an entity has been found, transform it into a character. + static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); + + // Get a character, while interpreting entities. + // The length can be from 0 to 4 bytes. + inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) + { + assert( p ); + if ( encoding == TIXML_ENCODING_UTF8 ) { + *length = utf8ByteTable[ *((const unsigned char*)p) ]; + assert( *length >= 0 && *length < 5 ); + } else { + *length = 1; + } + + if ( *length == 1 ) { + if ( *p == '&' ) + return GetEntity( p, _value, length, encoding ); + *_value = *p; + return p+1; + } else if ( *length ) { + //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), + // and the null terminator isn't needed + for( int i=0; p[i] && i<*length; ++i ) { + _value[i] = p[i]; + } + return p + (*length); + } else { + // Not valid text. + return 0; + } + } + + // Return true if the next characters in the stream are any of the endTag sequences. + // Ignore case only works for english, and should only be relied on when comparing + // to English words: StringEqual( p, "version", true ) is fine. + static bool StringEqual( const char* p, + const char* endTag, + bool ignoreCase, + TiXmlEncoding encoding ); + + static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; + + TiXmlCursor location; /// Field containing a generic user pointer - void* userData; - - // None of these methods are reliable for any language except English. - // Good for approximation, not great for accuracy. - static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); - static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); - inline static int ToLower( int v, TiXmlEncoding encoding ) - { - if ( encoding == TIXML_ENCODING_UTF8 ) - { - if ( v < 128 ) return tolower( v ); - return v; - } - else - { - return tolower( v ); - } - } - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); + void* userData; + + // None of these methods are reliable for any language except English. + // Good for approximation, not great for accuracy. + static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); + static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); + inline static int ToLower( int v, TiXmlEncoding encoding ) + { + if ( encoding == TIXML_ENCODING_UTF8 ) { + if ( v < 128 ) return tolower( v ); + return v; + } else { + return tolower( v ); + } + } + static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); private: - TiXmlBase( const TiXmlBase& ); // not implemented. - void operator=( const TiXmlBase& base ); // not allowed. - - struct Entity - { - const char* str; - unsigned int strLength; - char chr; - }; - enum - { - NUM_ENTITY = 5, - MAX_ENTITY_LENGTH = 6 - - }; - static Entity entity[ NUM_ENTITY ]; - static bool condenseWhiteSpace; + TiXmlBase( const TiXmlBase& ); // not implemented. + void operator=( const TiXmlBase& base ); // not allowed. + + struct Entity { + const char* str; + unsigned int strLength; + char chr; + }; + enum { + NUM_ENTITY = 5, + MAX_ENTITY_LENGTH = 6 + + }; + static Entity entity[ NUM_ENTITY ]; + static bool condenseWhiteSpace; }; @@ -422,352 +454,490 @@ private: in a document, or stand on its own. The type of a TiXmlNode can be queried, and it can be cast to its more defined type. */ -class TiXmlNode : public TiXmlBase -{ - friend class TiXmlDocument; - friend class TiXmlElement; +class TiXmlNode : public TiXmlBase { + friend class TiXmlDocument; + friend class TiXmlElement; public: - #ifdef TIXML_USE_STL - - /** An input stream operator, for every class. Tolerant of newlines and - formatting, but doesn't expect them. - */ - friend std::istream& operator >> (std::istream& in, TiXmlNode& base); - - /** An output stream operator, for every class. Note that this outputs - without any newlines or formatting, as opposed to Print(), which - includes tabs and new lines. - - The operator<< and operator>> are not completely symmetric. Writing - a node to a stream is very well defined. You'll get a nice stream - of output, without any extra whitespace or newlines. - - But reading is not as well defined. (As it always is.) If you create - a TiXmlElement (for example) and read that from an input stream, - the text needs to define an element or junk will result. This is - true of all input streams, but it's worth keeping in mind. - - A TiXmlDocument will read nodes until it reads a root element, and - all the children of that root element. - */ - friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); - - /// Appends the XML node or attribute to a std::string. - friend std::string& operator<< (std::string& out, const TiXmlNode& base ); - - #endif - - /** The types of XML nodes supported by TinyXml. (All the - unsupported types are picked up by UNKNOWN.) - */ - enum NodeType - { - TINYXML_DOCUMENT, - TINYXML_ELEMENT, - TINYXML_COMMENT, - TINYXML_UNKNOWN, - TINYXML_TEXT, - TINYXML_DECLARATION, - TINYXML_TYPECOUNT - }; - - virtual ~TiXmlNode(); - - /** The meaning of 'value' changes for the specific type of - TiXmlNode. - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - - The subclasses will wrap this function. - */ - const char *Value() const { return value.c_str (); } - - #ifdef TIXML_USE_STL - /** Return Value() as a std::string. If you only use STL, - this is more efficient than calling Value(). - Only available in STL mode. - */ - const std::string& ValueStr() const { return value; } - #endif - - const TIXML_STRING& ValueTStr() const { return value; } - - /** Changes the value of the node. Defined as: - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - */ - void SetValue(const char * _value) { value = _value;} - - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif - - /// Delete all the children of this node. Does not affect 'this'. - void Clear(); - - /// One step up the DOM. - TiXmlNode* Parent() { return parent; } - const TiXmlNode* Parent() const { return parent; } - - const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. - TiXmlNode* FirstChild() { return firstChild; } - const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. - /// The first child of this node with the matching 'value'. Will be null if none found. - TiXmlNode* FirstChild( const char * _value ) { - // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) - // call the method, cast the return back to non-const. - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value )); - } - const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. - TiXmlNode* LastChild() { return lastChild; } - - const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. - TiXmlNode* LastChild( const char * _value ) { - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value )); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form. - #endif - - /** An alternate way to walk the children of a node. - One way to iterate over nodes is: - @verbatim - for( child = parent->FirstChild(); child; child = child->NextSibling() ) - @endverbatim - - IterateChildren does the same thing with the syntax: - @verbatim - child = 0; - while( child = parent->IterateChildren( child ) ) - @endverbatim - - IterateChildren takes the previous child as input and finds - the next one. If the previous child is null, it returns the - first. IterateChildren will return null when done. - */ - const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) ); - } - - /// This flavor of IterateChildren searches for children with a particular 'value' - const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - #endif - - /** Add a new node related to this. Adds a child past the LastChild. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); - - - /** Add a new node related to this. Adds a child past the LastChild. - - NOTE: the node to be added is passed by pointer, and will be - henceforth owned (and deleted) by tinyXml. This method is efficient - and avoids an extra copy, but should be used with care as it - uses a different memory model than the other insert functions. - - @sa InsertEndChild - */ - TiXmlNode* LinkEndChild( TiXmlNode* addThis ); +#ifdef TIXML_USE_STL - /** Add a new node related to this. Adds a child before the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); + /** An input stream operator, for every class. Tolerant of newlines and + formatting, but doesn't expect them. + */ + friend std::istream& operator >> (std::istream& in, TiXmlNode& base); - /** Add a new node related to this. Adds a child after the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); + /** An output stream operator, for every class. Note that this outputs + without any newlines or formatting, as opposed to Print(), which + includes tabs and new lines. - /** Replace a child of this node. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); + The operator<< and operator>> are not completely symmetric. Writing + a node to a stream is very well defined. You'll get a nice stream + of output, without any extra whitespace or newlines. - /// Delete a child of this node. - bool RemoveChild( TiXmlNode* removeThis ); + But reading is not as well defined. (As it always is.) If you create + a TiXmlElement (for example) and read that from an input stream, + the text needs to define an element or junk will result. This is + true of all input streams, but it's worth keeping in mind. - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling() const { return prev; } - TiXmlNode* PreviousSibling() { return prev; } + A TiXmlDocument will read nodes until it reads a root element, and + all the children of that root element. + */ + friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling( const char * ) const; - TiXmlNode* PreviousSibling( const char *_prev ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) ); - } + /// Appends the XML node or attribute to a std::string. + friend std::string& operator<< (std::string& out, const TiXmlNode& base ); - #ifdef TIXML_USE_STL - const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. - #endif - - /// Navigate to a sibling node. - const TiXmlNode* NextSibling() const { return next; } - TiXmlNode* NextSibling() { return next; } - - /// Navigate to a sibling node with the given 'value'. - const TiXmlNode* NextSibling( const char * ) const; - TiXmlNode* NextSibling( const char* _next ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) ); - } +#endif - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement() const; - TiXmlElement* NextSiblingElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() ); - } + /** The types of XML nodes supported by TinyXml. (All the + unsupported types are picked up by UNKNOWN.) + */ + enum NodeType { + TINYXML_DOCUMENT, + TINYXML_ELEMENT, + TINYXML_COMMENT, + TINYXML_UNKNOWN, + TINYXML_TEXT, + TINYXML_DECLARATION, + TINYXML_TYPECOUNT + }; + + virtual ~TiXmlNode(); + + /** The meaning of 'value' changes for the specific type of + TiXmlNode. + @verbatim + Document: filename of the xml file + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + + The subclasses will wrap this function. + */ + const char *Value() const + { + return value.c_str (); + } - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement( const char * ) const; - TiXmlElement* NextSiblingElement( const char *_next ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) ); - } +#ifdef TIXML_USE_STL + /** Return Value() as a std::string. If you only use STL, + this is more efficient than calling Value(). + Only available in STL mode. + */ + const std::string& ValueStr() const + { + return value; + } +#endif - #ifdef TIXML_USE_STL - const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - #endif + const TIXML_STRING& ValueTStr() const + { + return value; + } + + /** Changes the value of the node. Defined as: + @verbatim + Document: filename of the xml file + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + */ + void SetValue(const char * _value) + { + value = _value; + } - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement() const; - TiXmlElement* FirstChildElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() ); - } +#ifdef TIXML_USE_STL + /// STL std::string form. + void SetValue( const std::string& _value ) + { + value = _value; + } +#endif - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement( const char * _value ) const; - TiXmlElement* FirstChildElement( const char * _value ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) ); - } + /// Delete all the children of this node. Does not affect 'this'. + void Clear(); + + /// One step up the DOM. + TiXmlNode* Parent() + { + return parent; + } + const TiXmlNode* Parent() const + { + return parent; + } + + const TiXmlNode* FirstChild() const + { + return firstChild; ///< The first child of this node. Will be null if there are no children. + } + TiXmlNode* FirstChild() + { + return firstChild; + } + const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. + /// The first child of this node with the matching 'value'. Will be null if none found. + TiXmlNode* FirstChild( const char * _value ) + { + // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) + // call the method, cast the return back to non-const. + return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value )); + } + const TiXmlNode* LastChild() const + { + return lastChild; /// The last child of this node. Will be null if there are no children. + } + TiXmlNode* LastChild() + { + return lastChild; + } + + const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. + TiXmlNode* LastChild( const char * _value ) + { + return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value )); + } - #ifdef TIXML_USE_STL - const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - #endif - - /** Query the type (as an enumerated value, above) of this node. - The possible types are: TINYXML_DOCUMENT, TINYXML_ELEMENT, TINYXML_COMMENT, - TINYXML_UNKNOWN, TINYXML_TEXT, and TINYXML_DECLARATION. - */ - int Type() const { return type; } - - /** Return a pointer to the Document this node lives in. - Returns null if not in a document. - */ - const TiXmlDocument* GetDocument() const; - TiXmlDocument* GetDocument() { - return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() ); - } +#ifdef TIXML_USE_STL + const TiXmlNode* FirstChild( const std::string& _value ) const + { + return FirstChild (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* FirstChild( const std::string& _value ) + { + return FirstChild (_value.c_str ()); ///< STL std::string form. + } + const TiXmlNode* LastChild( const std::string& _value ) const + { + return LastChild (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* LastChild( const std::string& _value ) + { + return LastChild (_value.c_str ()); ///< STL std::string form. + } +#endif - /// Returns true if this node has no children. - bool NoChildren() const { return !firstChild; } + /** An alternate way to walk the children of a node. + One way to iterate over nodes is: + @verbatim + for( child = parent->FirstChild(); child; child = child->NextSibling() ) + @endverbatim + + IterateChildren does the same thing with the syntax: + @verbatim + child = 0; + while( child = parent->IterateChildren( child ) ) + @endverbatim + + IterateChildren takes the previous child as input and finds + the next one. If the previous child is null, it returns the + first. IterateChildren will return null when done. + */ + const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; + TiXmlNode* IterateChildren( const TiXmlNode* previous ) + { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) ); + } + + /// This flavor of IterateChildren searches for children with a particular 'value' + const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; + TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) + { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) ); + } - virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. +#ifdef TIXML_USE_STL + const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const + { + return IterateChildren (_value.c_str (), previous); ///< STL std::string form. + } + TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) + { + return IterateChildren (_value.c_str (), previous); ///< STL std::string form. + } +#endif - virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. + /** Add a new node related to this. Adds a child past the LastChild. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); + + + /** Add a new node related to this. Adds a child past the LastChild. + + NOTE: the node to be added is passed by pointer, and will be + henceforth owned (and deleted) by tinyXml. This method is efficient + and avoids an extra copy, but should be used with care as it + uses a different memory model than the other insert functions. + + @sa InsertEndChild + */ + TiXmlNode* LinkEndChild( TiXmlNode* addThis ); + + /** Add a new node related to this. Adds a child before the specified child. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); + + /** Add a new node related to this. Adds a child after the specified child. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); + + /** Replace a child of this node. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); + + /// Delete a child of this node. + bool RemoveChild( TiXmlNode* removeThis ); + + /// Navigate to a sibling node. + const TiXmlNode* PreviousSibling() const + { + return prev; + } + TiXmlNode* PreviousSibling() + { + return prev; + } + + /// Navigate to a sibling node. + const TiXmlNode* PreviousSibling( const char * ) const; + TiXmlNode* PreviousSibling( const char *_prev ) + { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) ); + } - /** Create an exact duplicate of this node and return it. The memory must be deleted - by the caller. - */ - virtual TiXmlNode* Clone() const = 0; +#ifdef TIXML_USE_STL + const TiXmlNode* PreviousSibling( const std::string& _value ) const + { + return PreviousSibling (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* PreviousSibling( const std::string& _value ) + { + return PreviousSibling (_value.c_str ()); ///< STL std::string form. + } + const TiXmlNode* NextSibling( const std::string& _value) const + { + return NextSibling (_value.c_str ()); ///< STL std::string form. + } + TiXmlNode* NextSibling( const std::string& _value) + { + return NextSibling (_value.c_str ()); ///< STL std::string form. + } +#endif - /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the TiXmlVisitor interface. + /// Navigate to a sibling node. + const TiXmlNode* NextSibling() const + { + return next; + } + TiXmlNode* NextSibling() + { + return next; + } + + /// Navigate to a sibling node with the given 'value'. + const TiXmlNode* NextSibling( const char * ) const; + TiXmlNode* NextSibling( const char* _next ) + { + return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) ); + } + + /** Convenience function to get through elements. + Calls NextSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* NextSiblingElement() const; + TiXmlElement* NextSiblingElement() + { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() ); + } + + /** Convenience function to get through elements. + Calls NextSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* NextSiblingElement( const char * ) const; + TiXmlElement* NextSiblingElement( const char *_next ) + { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) ); + } - This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML is unchanged by using this - interface versus any other.) +#ifdef TIXML_USE_STL + const TiXmlElement* NextSiblingElement( const std::string& _value) const + { + return NextSiblingElement (_value.c_str ()); ///< STL std::string form. + } + TiXmlElement* NextSiblingElement( const std::string& _value) + { + return NextSiblingElement (_value.c_str ()); ///< STL std::string form. + } +#endif - The interface has been based on ideas from: + /// Convenience function to get through elements. + const TiXmlElement* FirstChildElement() const; + TiXmlElement* FirstChildElement() + { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() ); + } - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + /// Convenience function to get through elements. + const TiXmlElement* FirstChildElement( const char * _value ) const; + TiXmlElement* FirstChildElement( const char * _value ) + { + return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) ); + } - Which are both good references for "visiting". +#ifdef TIXML_USE_STL + const TiXmlElement* FirstChildElement( const std::string& _value ) const + { + return FirstChildElement (_value.c_str ()); ///< STL std::string form. + } + TiXmlElement* FirstChildElement( const std::string& _value ) + { + return FirstChildElement (_value.c_str ()); ///< STL std::string form. + } +#endif - An example of using Accept(): - @verbatim - TiXmlPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( TiXmlVisitor* visitor ) const = 0; + /** Query the type (as an enumerated value, above) of this node. + The possible types are: TINYXML_DOCUMENT, TINYXML_ELEMENT, TINYXML_COMMENT, + TINYXML_UNKNOWN, TINYXML_TEXT, and TINYXML_DECLARATION. + */ + int Type() const + { + return type; + } + + /** Return a pointer to the Document this node lives in. + Returns null if not in a document. + */ + const TiXmlDocument* GetDocument() const; + TiXmlDocument* GetDocument() + { + return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() ); + } + + /// Returns true if this node has no children. + bool NoChildren() const + { + return !firstChild; + } + + virtual const TiXmlDocument* ToDocument() const + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlElement* ToElement() const + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlComment* ToComment() const + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlUnknown* ToUnknown() const + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlText* ToText() const + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual const TiXmlDeclaration* ToDeclaration() const + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + + virtual TiXmlDocument* ToDocument() + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlElement* ToElement() + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlComment* ToComment() + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlUnknown* ToUnknown() + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlText* ToText() + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + virtual TiXmlDeclaration* ToDeclaration() + { + return 0; ///< Cast to a more defined type. Will return null if not of the requested type. + } + + /** Create an exact duplicate of this node and return it. The memory must be deleted + by the caller. + */ + virtual TiXmlNode* Clone() const = 0; + + /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the TiXmlVisitor interface. + + This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML is unchanged by using this + interface versus any other.) + + The interface has been based on ideas from: + + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + + Which are both good references for "visiting". + + An example of using Accept(): + @verbatim + TiXmlPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept( TiXmlVisitor* visitor ) const = 0; protected: - TiXmlNode( NodeType _type ); + TiXmlNode( NodeType _type ); - // Copy to the allocated object. Shared functionality between Clone, Copy constructor, - // and the assignment operator. - void CopyTo( TiXmlNode* target ) const; + // Copy to the allocated object. Shared functionality between Clone, Copy constructor, + // and the assignment operator. + void CopyTo( TiXmlNode* target ) const; - #ifdef TIXML_USE_STL - // The real work of the input operator. - virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0; - #endif +#ifdef TIXML_USE_STL + // The real work of the input operator. + virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0; +#endif - // Figure out what is at *p, and parse it. Returns null if it is not an xml node. - TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); + // Figure out what is at *p, and parse it. Returns null if it is not an xml node. + TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); - TiXmlNode* parent; - NodeType type; + TiXmlNode* parent; + NodeType type; - TiXmlNode* firstChild; - TiXmlNode* lastChild; + TiXmlNode* firstChild; + TiXmlNode* lastChild; - TIXML_STRING value; + TIXML_STRING value; - TiXmlNode* prev; - TiXmlNode* next; + TiXmlNode* prev; + TiXmlNode* next; private: - TiXmlNode( const TiXmlNode& ); // not implemented. - void operator=( const TiXmlNode& base ); // not allowed. + TiXmlNode( const TiXmlNode& ); // not implemented. + void operator=( const TiXmlNode& base ); // not allowed. }; @@ -778,121 +948,159 @@ private: part of the tinyXML document object model. There are other suggested ways to look at this problem. */ -class TiXmlAttribute : public TiXmlBase -{ - friend class TiXmlAttributeSet; +class TiXmlAttribute : public TiXmlBase { + friend class TiXmlAttributeSet; public: - /// Construct an empty attribute. - TiXmlAttribute() : TiXmlBase() - { - document = 0; - prev = next = 0; - } - - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlAttribute( const std::string& _name, const std::string& _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } - #endif - - /// Construct an attribute with a name and value. - TiXmlAttribute( const char * _name, const char * _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } + /// Construct an empty attribute. + TiXmlAttribute() : TiXmlBase() + { + document = 0; + prev = next = 0; + } - const char* Name() const { return name.c_str(); } ///< Return the name of this attribute. - const char* Value() const { return value.c_str(); } ///< Return the value of this attribute. - #ifdef TIXML_USE_STL - const std::string& ValueStr() const { return value; } ///< Return the value of this attribute. - #endif - int IntValue() const; ///< Return the value of this attribute, converted to an integer. - double DoubleValue() const; ///< Return the value of this attribute, converted to a double. - - // Get the tinyxml string representation - const TIXML_STRING& NameTStr() const { return name; } - - /** QueryIntValue examines the value string. It is an alternative to the - IntValue() method with richer error checking. - If the value is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. - - A specialized but useful call. Note that for success it returns 0, - which is the opposite of almost all other TinyXml calls. - */ - int QueryIntValue( int* _value ) const; - /// QueryDoubleValue examines the value string. See QueryIntValue(). - int QueryDoubleValue( double* _value ) const; - - void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. - void SetValue( const char* _value ) { value = _value; } ///< Set the value. - - void SetIntValue( int _value ); ///< Set the value from an integer. - void SetDoubleValue( double _value ); ///< Set the value from a double. - - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetName( const std::string& _name ) { name = _name; } - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif - - /// Get the next sibling attribute in the DOM. Returns null at end. - const TiXmlAttribute* Next() const; - TiXmlAttribute* Next() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() ); - } - - /// Get the previous sibling attribute in the DOM. Returns null at beginning. - const TiXmlAttribute* Previous() const; - TiXmlAttribute* Previous() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() ); - } - - bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } - bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } - bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } +#ifdef TIXML_USE_STL + /// std::string constructor. + TiXmlAttribute( const std::string& _name, const std::string& _value ) + { + name = _name; + value = _value; + document = 0; + prev = next = 0; + } +#endif - /* Attribute parsing starts: first letter of the name - returns: the next char after the value end quote - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + /// Construct an attribute with a name and value. + TiXmlAttribute( const char * _name, const char * _value ) + { + name = _name; + value = _value; + document = 0; + prev = next = 0; + } + + const char* Name() const + { + return name.c_str(); ///< Return the name of this attribute. + } + const char* Value() const + { + return value.c_str(); ///< Return the value of this attribute. + } +#ifdef TIXML_USE_STL + const std::string& ValueStr() const + { + return value; ///< Return the value of this attribute. + } +#endif + int IntValue() const; ///< Return the value of this attribute, converted to an integer. + double DoubleValue() const; ///< Return the value of this attribute, converted to a double. + + // Get the tinyxml string representation + const TIXML_STRING& NameTStr() const + { + return name; + } + + /** QueryIntValue examines the value string. It is an alternative to the + IntValue() method with richer error checking. + If the value is an integer, it is stored in 'value' and + the call returns TIXML_SUCCESS. If it is not + an integer, it returns TIXML_WRONG_TYPE. + + A specialized but useful call. Note that for success it returns 0, + which is the opposite of almost all other TinyXml calls. + */ + int QueryIntValue( int* _value ) const; + /// QueryDoubleValue examines the value string. See QueryIntValue(). + int QueryDoubleValue( double* _value ) const; + + void SetName( const char* _name ) + { + name = _name; ///< Set the name of this attribute. + } + void SetValue( const char* _value ) + { + value = _value; ///< Set the value. + } + + void SetIntValue( int _value ); ///< Set the value from an integer. + void SetDoubleValue( double _value ); ///< Set the value from a double. - // Prints this Attribute to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } - void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; +#ifdef TIXML_USE_STL + /// STL std::string form. + void SetName( const std::string& _name ) + { + name = _name; + } + /// STL std::string form. + void SetValue( const std::string& _value ) + { + value = _value; + } +#endif - // [internal use] - // Set the document pointer so the attribute can report errors. - void SetDocument( TiXmlDocument* doc ) { document = doc; } + /// Get the next sibling attribute in the DOM. Returns null at end. + const TiXmlAttribute* Next() const; + TiXmlAttribute* Next() + { + return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() ); + } + + /// Get the previous sibling attribute in the DOM. Returns null at beginning. + const TiXmlAttribute* Previous() const; + TiXmlAttribute* Previous() + { + return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() ); + } + + bool operator==( const TiXmlAttribute& rhs ) const + { + return rhs.name == name; + } + bool operator<( const TiXmlAttribute& rhs ) const + { + return name < rhs.name; + } + bool operator>( const TiXmlAttribute& rhs ) const + { + return name > rhs.name; + } + + /* Attribute parsing starts: first letter of the name + returns: the next char after the value end quote + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + + // Prints this Attribute to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const + { + Print( cfile, depth, 0 ); + } + void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; + + // [internal use] + // Set the document pointer so the attribute can report errors. + void SetDocument( TiXmlDocument* doc ) + { + document = doc; + } private: - TiXmlAttribute( const TiXmlAttribute& ); // not implemented. - void operator=( const TiXmlAttribute& base ); // not allowed. - - TiXmlDocument* document; // A pointer back to a document, for error reporting. - TIXML_STRING name; - TIXML_STRING value; - TiXmlAttribute* prev; - TiXmlAttribute* next; + TiXmlAttribute( const TiXmlAttribute& ); // not implemented. + void operator=( const TiXmlAttribute& base ); // not allowed. + + TiXmlDocument* document; // A pointer back to a document, for error reporting. + TIXML_STRING name; + TIXML_STRING value; + TiXmlAttribute* prev; + TiXmlAttribute* next; }; /* A class used to manage a group of attributes. It is only used internally, both by the ELEMENT and the DECLARATION. - + The set can be changed transparent to the Element and Declaration classes that use it, but NOT transparent to the Attribute which has to implement a next() and previous() method. Which makes @@ -902,36 +1110,47 @@ private: - I like circular lists - it demonstrates some independence from the (typical) doubly linked list. */ -class TiXmlAttributeSet -{ +class TiXmlAttributeSet { public: - TiXmlAttributeSet(); - ~TiXmlAttributeSet(); - - void Add( TiXmlAttribute* attribute ); - void Remove( TiXmlAttribute* attribute ); - - const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } - TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } - - TiXmlAttribute* Find( const char* _name ) const; - TiXmlAttribute* FindOrCreate( const char* _name ); + TiXmlAttributeSet(); + ~TiXmlAttributeSet(); + + void Add( TiXmlAttribute* attribute ); + void Remove( TiXmlAttribute* attribute ); + + const TiXmlAttribute* First() const + { + return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; + } + TiXmlAttribute* First() + { + return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; + } + const TiXmlAttribute* Last() const + { + return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; + } + TiXmlAttribute* Last() + { + return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; + } + + TiXmlAttribute* Find( const char* _name ) const; + TiXmlAttribute* FindOrCreate( const char* _name ); # ifdef TIXML_USE_STL - TiXmlAttribute* Find( const std::string& _name ) const; - TiXmlAttribute* FindOrCreate( const std::string& _name ); + TiXmlAttribute* Find( const std::string& _name ) const; + TiXmlAttribute* FindOrCreate( const std::string& _name ); # endif private: - //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), - //*ME: this class must be also use a hidden/disabled copy-constructor !!! - TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed - void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) + //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), + //*ME: this class must be also use a hidden/disabled copy-constructor !!! + TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed + void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) - TiXmlAttribute sentinel; + TiXmlAttribute sentinel; }; @@ -939,266 +1158,294 @@ private: and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ -class TiXmlElement : public TiXmlNode -{ +class TiXmlElement : public TiXmlNode { public: - /// Construct an element. - TiXmlElement (const char * in_value); - - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlElement( const std::string& _value ); - #endif - - TiXmlElement( const TiXmlElement& ); - - TiXmlElement& operator=( const TiXmlElement& base ); - - virtual ~TiXmlElement(); - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - */ - const char* Attribute( const char* name ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an integer, - the integer value will be put in the return 'i', if 'i' - is non-null. - */ - const char* Attribute( const char* name, int* i ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an double, - the double value will be put in the return 'd', if 'd' - is non-null. - */ - const char* Attribute( const char* name, double* d ) const; - - /** QueryIntAttribute examines the attribute - it is an alternative to the - Attribute() method with richer error checking. - If the attribute is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. If the attribute - does not exist, then TIXML_NO_ATTRIBUTE is returned. - */ - int QueryIntAttribute( const char* name, int* _value ) const; - /// QueryUnsignedAttribute examines the attribute - see QueryIntAttribute(). - int QueryUnsignedAttribute( const char* name, unsigned* _value ) const; - /** QueryBoolAttribute examines the attribute - see QueryIntAttribute(). - Note that '1', 'true', or 'yes' are considered true, while '0', 'false' - and 'no' are considered false. - */ - int QueryBoolAttribute( const char* name, bool* _value ) const; - /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). - int QueryDoubleAttribute( const char* name, double* _value ) const; - /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). - int QueryFloatAttribute( const char* name, float* _value ) const { - double d; - int result = QueryDoubleAttribute( name, &d ); - if ( result == TIXML_SUCCESS ) { - *_value = (float)d; - } - return result; - } + /// Construct an element. + TiXmlElement (const char * in_value); - #ifdef TIXML_USE_STL - /// QueryStringAttribute examines the attribute - see QueryIntAttribute(). - int QueryStringAttribute( const char* name, std::string* _value ) const { - const char* cstr = Attribute( name ); - if ( cstr ) { - *_value = std::string( cstr ); - return TIXML_SUCCESS; - } - return TIXML_NO_ATTRIBUTE; - } +#ifdef TIXML_USE_STL + /// std::string constructor. + TiXmlElement( const std::string& _value ); +#endif - /** Template form of the attribute query which will try to read the - attribute into the specified type. Very easy, very powerful, but - be careful to make sure to call this with the correct type. - - NOTE: This method doesn't work correctly for 'string' types that contain spaces. + TiXmlElement( const TiXmlElement& ); + + TiXmlElement& operator=( const TiXmlElement& base ); + + virtual ~TiXmlElement(); + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + */ + const char* Attribute( const char* name ) const; + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + If the attribute exists and can be converted to an integer, + the integer value will be put in the return 'i', if 'i' + is non-null. + */ + const char* Attribute( const char* name, int* i ) const; + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + If the attribute exists and can be converted to an double, + the double value will be put in the return 'd', if 'd' + is non-null. + */ + const char* Attribute( const char* name, double* d ) const; + + /** QueryIntAttribute examines the attribute - it is an alternative to the + Attribute() method with richer error checking. + If the attribute is an integer, it is stored in 'value' and + the call returns TIXML_SUCCESS. If it is not + an integer, it returns TIXML_WRONG_TYPE. If the attribute + does not exist, then TIXML_NO_ATTRIBUTE is returned. + */ + int QueryIntAttribute( const char* name, int* _value ) const; + /// QueryUnsignedAttribute examines the attribute - see QueryIntAttribute(). + int QueryUnsignedAttribute( const char* name, unsigned* _value ) const; + /** QueryBoolAttribute examines the attribute - see QueryIntAttribute(). + Note that '1', 'true', or 'yes' are considered true, while '0', 'false' + and 'no' are considered false. + */ + int QueryBoolAttribute( const char* name, bool* _value ) const; + /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). + int QueryDoubleAttribute( const char* name, double* _value ) const; + /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). + int QueryFloatAttribute( const char* name, float* _value ) const + { + double d; + int result = QueryDoubleAttribute( name, &d ); + if ( result == TIXML_SUCCESS ) { + *_value = (float)d; + } + return result; + } - @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE - */ - template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const - { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; - - std::stringstream sstream( node->ValueStr() ); - sstream >> *outValue; - if ( !sstream.fail() ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; - } +#ifdef TIXML_USE_STL + /// QueryStringAttribute examines the attribute - see QueryIntAttribute(). + int QueryStringAttribute( const char* name, std::string* _value ) const + { + const char* cstr = Attribute( name ); + if ( cstr ) { + *_value = std::string( cstr ); + return TIXML_SUCCESS; + } + return TIXML_NO_ATTRIBUTE; + } + + /** Template form of the attribute query which will try to read the + attribute into the specified type. Very easy, very powerful, but + be careful to make sure to call this with the correct type. + + NOTE: This method doesn't work correctly for 'string' types that contain spaces. + + @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE + */ + template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const + { + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; + + std::stringstream sstream( node->ValueStr() ); + sstream >> *outValue; + if ( !sstream.fail() ) + return TIXML_SUCCESS; + return TIXML_WRONG_TYPE; + } + + int QueryValueAttribute( const std::string& name, std::string* outValue ) const + { + const TiXmlAttribute* node = attributeSet.Find( name ); + if ( !node ) + return TIXML_NO_ATTRIBUTE; + *outValue = node->ValueStr(); + return TIXML_SUCCESS; + } +#endif - int QueryValueAttribute( const std::string& name, std::string* outValue ) const - { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; - *outValue = node->ValueStr(); - return TIXML_SUCCESS; - } - #endif - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char* name, const char * _value ); - - #ifdef TIXML_USE_STL - const std::string* Attribute( const std::string& name ) const; - const std::string* Attribute( const std::string& name, int* i ) const; - const std::string* Attribute( const std::string& name, double* d ) const; - int QueryIntAttribute( const std::string& name, int* _value ) const; - int QueryDoubleAttribute( const std::string& name, double* _value ) const; - - /// STL std::string form. - void SetAttribute( const std::string& name, const std::string& _value ); - ///< STL std::string form. - void SetAttribute( const std::string& name, int _value ); - ///< STL std::string form. - void SetDoubleAttribute( const std::string& name, double value ); - #endif - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char * name, int value ); - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetDoubleAttribute( const char * name, double value ); - - /** Deletes an attribute with the given name. - */ - void RemoveAttribute( const char * name ); - #ifdef TIXML_USE_STL - void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. - #endif - - const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. - TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } - const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. - TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the TiXmlText child - and accessing it directly. - - If the first child of 'this' is a TiXmlText, the GetText() - returns the character string of the Text node, else null is returned. - - This is a convenient method for getting the text of simple contained text: - @verbatim - <foo>This is text</foo> - const char* str = fooElement->GetText(); - @endverbatim - - 'str' will be a pointer to "This is text". - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - <foo><b>This is text</b></foo> - @endverbatim - - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - <foo>This is <b>text</b></foo> - @endverbatim - GetText() will return "This is ". - - WARNING: GetText() accesses a child node - don't become confused with the - similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are - safe type casts on the referenced node. - */ - const char* GetText() const; - - /// Creates a new Element and returns it - the returned element is a copy. - virtual TiXmlNode* Clone() const; - // Print the Element to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /* Attribtue parsing starts: next char past '<' - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetAttribute( const char* name, const char * _value ); + +#ifdef TIXML_USE_STL + const std::string* Attribute( const std::string& name ) const; + const std::string* Attribute( const std::string& name, int* i ) const; + const std::string* Attribute( const std::string& name, double* d ) const; + int QueryIntAttribute( const std::string& name, int* _value ) const; + int QueryDoubleAttribute( const std::string& name, double* _value ) const; + + /// STL std::string form. + void SetAttribute( const std::string& name, const std::string& _value ); + ///< STL std::string form. + void SetAttribute( const std::string& name, int _value ); + ///< STL std::string form. + void SetDoubleAttribute( const std::string& name, double value ); +#endif + + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetAttribute( const char * name, int value ); + + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetDoubleAttribute( const char * name, double value ); + + /** Deletes an attribute with the given name. + */ + void RemoveAttribute( const char * name ); +#ifdef TIXML_USE_STL + void RemoveAttribute( const std::string& name ) + { + RemoveAttribute (name.c_str ()); ///< STL std::string form. + } +#endif + + const TiXmlAttribute* FirstAttribute() const + { + return attributeSet.First(); ///< Access the first attribute in this element. + } + TiXmlAttribute* FirstAttribute() + { + return attributeSet.First(); + } + const TiXmlAttribute* LastAttribute() const + { + return attributeSet.Last(); ///< Access the last attribute in this element. + } + TiXmlAttribute* LastAttribute() + { + return attributeSet.Last(); + } + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the TiXmlText child + and accessing it directly. + + If the first child of 'this' is a TiXmlText, the GetText() + returns the character string of the Text node, else null is returned. + + This is a convenient method for getting the text of simple contained text: + @verbatim + <foo>This is text</foo> + const char* str = fooElement->GetText(); + @endverbatim + + 'str' will be a pointer to "This is text". + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + <foo><b>This is text</b></foo> + @endverbatim + + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + <foo>This is <b>text</b></foo> + @endverbatim + GetText() will return "This is ". + + WARNING: GetText() accesses a child node - don't become confused with the + similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are + safe type casts on the referenced node. + */ + const char* GetText() const; + + /// Creates a new Element and returns it - the returned element is a copy. + virtual TiXmlNode* Clone() const; + // Print the Element to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; + + /* Attribtue parsing starts: next char past '<' + returns: next char past '>' + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + + virtual const TiXmlElement* ToElement() const + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlElement* ToElement() + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* visitor ) const; protected: - void CopyTo( TiXmlElement* target ) const; - void ClearThis(); // like clear, but initializes 'this' object as well + void CopyTo( TiXmlElement* target ) const; + void ClearThis(); // like clear, but initializes 'this' object as well - // Used to be public [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - /* [internal use] - Reads the "value" of the element -- another element, or text. - This should terminate with the current end tag. - */ - const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); + // Used to be public [internal use] +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif + /* [internal use] + Reads the "value" of the element -- another element, or text. + This should terminate with the current end tag. + */ + const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); private: - TiXmlAttributeSet attributeSet; + TiXmlAttributeSet attributeSet; }; /** An XML comment. */ -class TiXmlComment : public TiXmlNode -{ +class TiXmlComment : public TiXmlNode { public: - /// Constructs an empty comment. - TiXmlComment() : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {} - /// Construct a comment from text. - TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) { - SetValue( _value ); - } - TiXmlComment( const TiXmlComment& ); - TiXmlComment& operator=( const TiXmlComment& base ); - - virtual ~TiXmlComment() {} - - /// Returns a copy of this Comment. - virtual TiXmlNode* Clone() const; - // Write this Comment to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /* Attribtue parsing starts: at the ! of the !-- - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /// Constructs an empty comment. + TiXmlComment() : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {} + /// Construct a comment from text. + TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) + { + SetValue( _value ); + } + TiXmlComment( const TiXmlComment& ); + TiXmlComment& operator=( const TiXmlComment& base ); + + virtual ~TiXmlComment() {} + + /// Returns a copy of this Comment. + virtual TiXmlNode* Clone() const; + // Write this Comment to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; + + /* Attribtue parsing starts: at the ! of the !-- + returns: next char past '>' + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + + virtual const TiXmlComment* ToComment() const + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlComment* ToComment() + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* visitor ) const; protected: - void CopyTo( TiXmlComment* target ) const; + void CopyTo( TiXmlComment* target ) const; - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + // used to be public +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif // virtual void StreamOut( TIXML_OSTREAM * out ) const; private: @@ -1206,68 +1453,86 @@ private: }; -/** XML text. A text node can have 2 ways to output the next. "normal" output +/** XML text. A text node can have 2 ways to output the next. "normal" output and CDATA. It will default to the mode it was parsed from the XML file and - you generally want to leave it alone, but you can change the output mode with + you generally want to leave it alone, but you can change the output mode with SetCDATA() and query it with CDATA(). */ -class TiXmlText : public TiXmlNode -{ - friend class TiXmlElement; +class TiXmlText : public TiXmlNode { + friend class TiXmlElement; public: - /** Constructor for text element. By default, it is treated as - normal, encoded text. If you want it be output as a CDATA text - element, set the parameter _cdata to 'true' - */ - TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) - { - SetValue( initValue ); - cdata = false; - } - virtual ~TiXmlText() {} - - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) - { - SetValue( initValue ); - cdata = false; - } - #endif - - TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TINYXML_TEXT ) { copy.CopyTo( this ); } - TiXmlText& operator=( const TiXmlText& base ) { base.CopyTo( this ); return *this; } - - // Write this text object to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /// Queries whether this represents text using a CDATA section. - bool CDATA() const { return cdata; } - /// Turns on or off a CDATA representation of text. - void SetCDATA( bool _cdata ) { cdata = _cdata; } + /** Constructor for text element. By default, it is treated as + normal, encoded text. If you want it be output as a CDATA text + element, set the parameter _cdata to 'true' + */ + TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) + { + SetValue( initValue ); + cdata = false; + } + virtual ~TiXmlText() {} - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. +#ifdef TIXML_USE_STL + /// Constructor. + TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) + { + SetValue( initValue ); + cdata = false; + } +#endif - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; + TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TINYXML_TEXT ) + { + copy.CopyTo( this ); + } + TiXmlText& operator=( const TiXmlText& base ) + { + base.CopyTo( this ); + return *this; + } + + // Write this text object to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; + + /// Queries whether this represents text using a CDATA section. + bool CDATA() const + { + return cdata; + } + /// Turns on or off a CDATA representation of text. + void SetCDATA( bool _cdata ) + { + cdata = _cdata; + } + + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + + virtual const TiXmlText* ToText() const + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlText* ToText() + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* content ) const; protected : - /// [internal use] Creates a new Element and returns it. - virtual TiXmlNode* Clone() const; - void CopyTo( TiXmlText* target ) const; + /// [internal use] Creates a new Element and returns it. + virtual TiXmlNode* Clone() const; + void CopyTo( TiXmlText* target ) const; - bool Blank() const; // returns true if all white space and new lines - // [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + bool Blank() const; // returns true if all white space and new lines + // [internal use] +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: - bool cdata; // true if this should be input and output as a CDATA style text element + bool cdata; // true if this should be input and output as a CDATA style text element }; @@ -1284,65 +1549,80 @@ private: handled as special cases, not generic attributes, simply because there can only be at most 3 and they are always the same. */ -class TiXmlDeclaration : public TiXmlNode -{ +class TiXmlDeclaration : public TiXmlNode { public: - /// Construct an empty declaration. - TiXmlDeclaration() : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) {} + /// Construct an empty declaration. + TiXmlDeclaration() : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) {} #ifdef TIXML_USE_STL - /// Constructor. - TiXmlDeclaration( const std::string& _version, - const std::string& _encoding, - const std::string& _standalone ); + /// Constructor. + TiXmlDeclaration( const std::string& _version, + const std::string& _encoding, + const std::string& _standalone ); #endif - /// Construct. - TiXmlDeclaration( const char* _version, - const char* _encoding, - const char* _standalone ); - - TiXmlDeclaration( const TiXmlDeclaration& copy ); - TiXmlDeclaration& operator=( const TiXmlDeclaration& copy ); - - virtual ~TiXmlDeclaration() {} - - /// Version. Will return an empty string if none was found. - const char *Version() const { return version.c_str (); } - /// Encoding. Will return an empty string if none was found. - const char *Encoding() const { return encoding.c_str (); } - /// Is this a standalone document? - const char *Standalone() const { return standalone.c_str (); } - - /// Creates a copy of this Declaration and returns it. - virtual TiXmlNode* Clone() const; - // Print this declaration to a FILE stream. - virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } - - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /// Construct. + TiXmlDeclaration( const char* _version, + const char* _encoding, + const char* _standalone ); + + TiXmlDeclaration( const TiXmlDeclaration& copy ); + TiXmlDeclaration& operator=( const TiXmlDeclaration& copy ); + + virtual ~TiXmlDeclaration() {} + + /// Version. Will return an empty string if none was found. + const char *Version() const + { + return version.c_str (); + } + /// Encoding. Will return an empty string if none was found. + const char *Encoding() const + { + return encoding.c_str (); + } + /// Is this a standalone document? + const char *Standalone() const + { + return standalone.c_str (); + } + + /// Creates a copy of this Declaration and returns it. + virtual TiXmlNode* Clone() const; + // Print this declaration to a FILE stream. + virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; + virtual void Print( FILE* cfile, int depth ) const + { + Print( cfile, depth, 0 ); + } + + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + + virtual const TiXmlDeclaration* ToDeclaration() const + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlDeclaration* ToDeclaration() + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* visitor ) const; protected: - void CopyTo( TiXmlDeclaration* target ) const; - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + void CopyTo( TiXmlDeclaration* target ) const; + // used to be public +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: - TIXML_STRING version; - TIXML_STRING encoding; - TIXML_STRING standalone; + TIXML_STRING version; + TIXML_STRING encoding; + TIXML_STRING standalone; }; @@ -1353,35 +1633,47 @@ private: DTD tags get thrown into TiXmlUnknowns. */ -class TiXmlUnknown : public TiXmlNode -{ +class TiXmlUnknown : public TiXmlNode { public: - TiXmlUnknown() : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) {} - virtual ~TiXmlUnknown() {} - - TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) { copy.CopyTo( this ); } - TiXmlUnknown& operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); return *this; } - - /// Creates a copy of this Unknown and returns it. - virtual TiXmlNode* Clone() const; - // Print this Unknown to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; + TiXmlUnknown() : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) {} + virtual ~TiXmlUnknown() {} + + TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) + { + copy.CopyTo( this ); + } + TiXmlUnknown& operator=( const TiXmlUnknown& copy ) + { + copy.CopyTo( this ); + return *this; + } + + /// Creates a copy of this Unknown and returns it. + virtual TiXmlNode* Clone() const; + // Print this Unknown to a FILE stream. + virtual void Print( FILE* cfile, int depth ) const; + + virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + + virtual const TiXmlUnknown* ToUnknown() const + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlUnknown* ToUnknown() + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* content ) const; protected: - void CopyTo( TiXmlUnknown* target ) const; + void CopyTo( TiXmlUnknown* target ) const; - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: @@ -1392,168 +1684,205 @@ private: XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name. */ -class TiXmlDocument : public TiXmlNode -{ +class TiXmlDocument : public TiXmlNode { public: - /// Create an empty document, that has no name. - TiXmlDocument(); - /// Create a document with a name. The name of the document is also the filename of the xml. - TiXmlDocument( const char * documentName ); - - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlDocument( const std::string& documentName ); - #endif - - TiXmlDocument( const TiXmlDocument& copy ); - TiXmlDocument& operator=( const TiXmlDocument& copy ); - - virtual ~TiXmlDocument() {} - - /** Load a file using the current document value. - Returns true if successful. Will delete any existing - document data before loading. - */ - bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the current document value. Returns true if successful. - bool SaveFile() const; - /// Load a file using the given filename. Returns true if successful. - bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given filename. Returns true if successful. - bool SaveFile( const char * filename ) const; - /** Load a file using the given FILE*. Returns true if successful. Note that this method - doesn't stream - the entire object pointed at by the FILE* - will be interpreted as an XML file. TinyXML doesn't stream in XML from the current - file location. Streaming may be added in the future. - */ - bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given FILE*. Returns true if successful. - bool SaveFile( FILE* ) const; - - #ifdef TIXML_USE_STL - bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. - { - return LoadFile( filename.c_str(), encoding ); - } - bool SaveFile( const std::string& filename ) const ///< STL std::string version. - { - return SaveFile( filename.c_str() ); - } - #endif - - /** Parse the given null terminated block of xml data. Passing in an encoding to this - method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml - to use that encoding, regardless of what TinyXml might otherwise try to detect. - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - - /** Get the root element -- the only top level element -- of the document. - In well formed XML, there should only be one. TinyXml is tolerant of - multiple elements at the document level. - */ - const TiXmlElement* RootElement() const { return FirstChildElement(); } - TiXmlElement* RootElement() { return FirstChildElement(); } - - /** If an error occurs, Error will be set to true. Also, - - The ErrorId() will contain the integer identifier of the error (not generally useful) - - The ErrorDesc() method will return the name of the error. (very useful) - - The ErrorRow() and ErrorCol() will return the location of the error (if known) - */ - bool Error() const { return error; } - - /// Contains a textual (english) description of the error if one occurs. - const char * ErrorDesc() const { return errorDesc.c_str (); } - - /** Generally, you probably want the error string ( ErrorDesc() ). But if you - prefer the ErrorId, this function will fetch it. - */ - int ErrorId() const { return errorId; } - - /** Returns the location (if known) of the error. The first column is column 1, - and the first row is row 1. A value of 0 means the row and column wasn't applicable - (memory errors, for example, have no row/column) or the parser lost the error. (An - error in the error reporting, in that case.) - - @sa SetTabSize, Row, Column - */ - int ErrorRow() const { return errorLocation.row+1; } - int ErrorCol() const { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() - - /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) - to report the correct values for row and column. It does not change the output - or input in any way. - - By calling this method, with a tab size - greater than 0, the row and column of each node and attribute is stored - when the file is loaded. Very useful for tracking the DOM back in to - the source file. - - The tab size is required for calculating the location of nodes. If not - set, the default of 4 is used. The tabsize is set per document. Setting - the tabsize to 0 disables row/column tracking. - - Note that row and column tracking is not supported when using operator>>. - - The tab size needs to be enabled before the parse or load. Correct usage: - @verbatim - TiXmlDocument doc; - doc.SetTabSize( 8 ); - doc.Load( "myfile.xml" ); - @endverbatim - - @sa Row, Column - */ - void SetTabSize( int _tabsize ) { tabsize = _tabsize; } - - int TabSize() const { return tabsize; } - - /** If you have handled the error, it can be reset with this call. The error - state is automatically cleared if you Parse a new XML block. - */ - void ClearError() { error = false; - errorId = 0; - errorDesc = ""; - errorLocation.row = errorLocation.col = 0; - //errorLocation.last = 0; - } - - /** Write the document to standard out using formatted printing ("pretty print"). */ - void Print() const { Print( stdout, 0 ); } - - /* Write the document to a string using formatted printing ("pretty print"). This - will allocate a character array (new char[]) and return it as a pointer. The - calling code pust call delete[] on the return char* to avoid a memory leak. - */ - //char* PrintToMemory() const; - - /// Print this Document to a FILE stream. - virtual void Print( FILE* cfile, int depth = 0 ) const; - // [internal use] - void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); - - virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; + /// Create an empty document, that has no name. + TiXmlDocument(); + /// Create a document with a name. The name of the document is also the filename of the xml. + TiXmlDocument( const char * documentName ); + +#ifdef TIXML_USE_STL + /// Constructor. + TiXmlDocument( const std::string& documentName ); +#endif + + TiXmlDocument( const TiXmlDocument& copy ); + TiXmlDocument& operator=( const TiXmlDocument& copy ); + + virtual ~TiXmlDocument() {} + + /** Load a file using the current document value. + Returns true if successful. Will delete any existing + document data before loading. + */ + bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + /// Save a file using the current document value. Returns true if successful. + bool SaveFile() const; + /// Load a file using the given filename. Returns true if successful. + bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + /// Save a file using the given filename. Returns true if successful. + bool SaveFile( const char * filename ) const; + /** Load a file using the given FILE*. Returns true if successful. Note that this method + doesn't stream - the entire object pointed at by the FILE* + will be interpreted as an XML file. TinyXML doesn't stream in XML from the current + file location. Streaming may be added in the future. + */ + bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + /// Save a file using the given FILE*. Returns true if successful. + bool SaveFile( FILE* ) const; + +#ifdef TIXML_USE_STL + bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. + { + return LoadFile( filename.c_str(), encoding ); + } + bool SaveFile( const std::string& filename ) const ///< STL std::string version. + { + return SaveFile( filename.c_str() ); + } +#endif + + /** Parse the given null terminated block of xml data. Passing in an encoding to this + method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml + to use that encoding, regardless of what TinyXml might otherwise try to detect. + */ + virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); + + /** Get the root element -- the only top level element -- of the document. + In well formed XML, there should only be one. TinyXml is tolerant of + multiple elements at the document level. + */ + const TiXmlElement* RootElement() const + { + return FirstChildElement(); + } + TiXmlElement* RootElement() + { + return FirstChildElement(); + } + + /** If an error occurs, Error will be set to true. Also, + - The ErrorId() will contain the integer identifier of the error (not generally useful) + - The ErrorDesc() method will return the name of the error. (very useful) + - The ErrorRow() and ErrorCol() will return the location of the error (if known) + */ + bool Error() const + { + return error; + } + + /// Contains a textual (english) description of the error if one occurs. + const char * ErrorDesc() const + { + return errorDesc.c_str (); + } + + /** Generally, you probably want the error string ( ErrorDesc() ). But if you + prefer the ErrorId, this function will fetch it. + */ + int ErrorId() const + { + return errorId; + } + + /** Returns the location (if known) of the error. The first column is column 1, + and the first row is row 1. A value of 0 means the row and column wasn't applicable + (memory errors, for example, have no row/column) or the parser lost the error. (An + error in the error reporting, in that case.) + + @sa SetTabSize, Row, Column + */ + int ErrorRow() const + { + return errorLocation.row+1; + } + int ErrorCol() const + { + return errorLocation.col+1; ///< The column where the error occured. See ErrorRow() + } + + /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) + to report the correct values for row and column. It does not change the output + or input in any way. + + By calling this method, with a tab size + greater than 0, the row and column of each node and attribute is stored + when the file is loaded. Very useful for tracking the DOM back in to + the source file. + + The tab size is required for calculating the location of nodes. If not + set, the default of 4 is used. The tabsize is set per document. Setting + the tabsize to 0 disables row/column tracking. + + Note that row and column tracking is not supported when using operator>>. + + The tab size needs to be enabled before the parse or load. Correct usage: + @verbatim + TiXmlDocument doc; + doc.SetTabSize( 8 ); + doc.Load( "myfile.xml" ); + @endverbatim + + @sa Row, Column + */ + void SetTabSize( int _tabsize ) + { + tabsize = _tabsize; + } + + int TabSize() const + { + return tabsize; + } + + /** If you have handled the error, it can be reset with this call. The error + state is automatically cleared if you Parse a new XML block. + */ + void ClearError() + { + error = false; + errorId = 0; + errorDesc = ""; + errorLocation.row = errorLocation.col = 0; + //errorLocation.last = 0; + } + + /** Write the document to standard out using formatted printing ("pretty print"). */ + void Print() const + { + Print( stdout, 0 ); + } + + /* Write the document to a string using formatted printing ("pretty print"). This + will allocate a character array (new char[]) and return it as a pointer. The + calling code pust call delete[] on the return char* to avoid a memory leak. + */ + //char* PrintToMemory() const; + + /// Print this Document to a FILE stream. + virtual void Print( FILE* cfile, int depth = 0 ) const; + // [internal use] + void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); + + virtual const TiXmlDocument* ToDocument() const + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + virtual TiXmlDocument* ToDocument() + { + return this; ///< Cast to a more defined type. Will return null not of the requested type. + } + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept( TiXmlVisitor* content ) const; protected : - // [internal use] - virtual TiXmlNode* Clone() const; - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + // [internal use] + virtual TiXmlNode* Clone() const; +#ifdef TIXML_USE_STL + virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); +#endif private: - void CopyTo( TiXmlDocument* target ) const; - - bool error; - int errorId; - TIXML_STRING errorDesc; - int tabsize; - TiXmlCursor errorLocation; - bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. + void CopyTo( TiXmlDocument* target ) const; + + bool error; + int errorId; + TIXML_STRING errorDesc; + int tabsize; + TiXmlCursor errorLocation; + bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. }; @@ -1572,7 +1901,7 @@ private: <Document> @endverbatim - Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very + Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like: @verbatim @@ -1592,7 +1921,7 @@ private: @endverbatim And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity - of such code. A TiXmlHandle checks for null pointers so it is perfectly safe + of such code. A TiXmlHandle checks for null pointers so it is perfectly safe and correct to use: @verbatim @@ -1613,7 +1942,7 @@ private: What they should not be used for is iteration: @verbatim - int i=0; + int i=0; while ( true ) { TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement(); @@ -1624,8 +1953,8 @@ private: } @endverbatim - It seems reasonable, but it is in fact two embedded while loops. The Child method is - a linear walk to find the element, so this code would iterate much more than it needs + It seems reasonable, but it is in fact two embedded while loops. The Child method is + a linear walk to find the element, so this code would iterate much more than it needs to. Instead, prefer: @verbatim @@ -1637,83 +1966,128 @@ private: } @endverbatim */ -class TiXmlHandle -{ +class TiXmlHandle { public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - TiXmlHandle( TiXmlNode* _node ) { this->node = _node; } - /// Copy constructor - TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } - TiXmlHandle operator=( const TiXmlHandle& ref ) { if ( &ref != this ) this->node = ref.node; return *this; } - - /// Return a handle to the first child node. - TiXmlHandle FirstChild() const; - /// Return a handle to the first child node with the given name. - TiXmlHandle FirstChild( const char * value ) const; - /// Return a handle to the first child element. - TiXmlHandle FirstChildElement() const; - /// Return a handle to the first child element with the given name. - TiXmlHandle FirstChildElement( const char * value ) const; - - /** Return a handle to the "index" child with the given name. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( const char* value, int index ) const; - /** Return a handle to the "index" child. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( int index ) const; - /** Return a handle to the "index" child element with the given name. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( const char* value, int index ) const; - /** Return a handle to the "index" child element. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( int index ) const; - - #ifdef TIXML_USE_STL - TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } - TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } - - TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } - TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } - #endif - - /** Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* ToNode() const { return node; } - /** Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } - /** Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } - /** Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } - - /** @deprecated use ToNode. - Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* Node() const { return ToNode(); } - /** @deprecated use ToElement. - Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* Element() const { return ToElement(); } - /** @deprecated use ToText() - Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* Text() const { return ToText(); } - /** @deprecated use ToUnknown() - Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* Unknown() const { return ToUnknown(); } + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + TiXmlHandle( TiXmlNode* _node ) + { + this->node = _node; + } + /// Copy constructor + TiXmlHandle( const TiXmlHandle& ref ) + { + this->node = ref.node; + } + TiXmlHandle operator=( const TiXmlHandle& ref ) + { + if ( &ref != this ) this->node = ref.node; + return *this; + } + + /// Return a handle to the first child node. + TiXmlHandle FirstChild() const; + /// Return a handle to the first child node with the given name. + TiXmlHandle FirstChild( const char * value ) const; + /// Return a handle to the first child element. + TiXmlHandle FirstChildElement() const; + /// Return a handle to the first child element with the given name. + TiXmlHandle FirstChildElement( const char * value ) const; + + /** Return a handle to the "index" child with the given name. + The first child is 0, the second 1, etc. + */ + TiXmlHandle Child( const char* value, int index ) const; + /** Return a handle to the "index" child. + The first child is 0, the second 1, etc. + */ + TiXmlHandle Child( int index ) const; + /** Return a handle to the "index" child element with the given name. + The first child element is 0, the second 1, etc. Note that only TiXmlElements + are indexed: other types are not counted. + */ + TiXmlHandle ChildElement( const char* value, int index ) const; + /** Return a handle to the "index" child element. + The first child element is 0, the second 1, etc. Note that only TiXmlElements + are indexed: other types are not counted. + */ + TiXmlHandle ChildElement( int index ) const; + +#ifdef TIXML_USE_STL + TiXmlHandle FirstChild( const std::string& _value ) const + { + return FirstChild( _value.c_str() ); + } + TiXmlHandle FirstChildElement( const std::string& _value ) const + { + return FirstChildElement( _value.c_str() ); + } + + TiXmlHandle Child( const std::string& _value, int index ) const + { + return Child( _value.c_str(), index ); + } + TiXmlHandle ChildElement( const std::string& _value, int index ) const + { + return ChildElement( _value.c_str(), index ); + } +#endif + + /** Return the handle as a TiXmlNode. This may return null. + */ + TiXmlNode* ToNode() const + { + return node; + } + /** Return the handle as a TiXmlElement. This may return null. + */ + TiXmlElement* ToElement() const + { + return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); + } + /** Return the handle as a TiXmlText. This may return null. + */ + TiXmlText* ToText() const + { + return ( ( node && node->ToText() ) ? node->ToText() : 0 ); + } + /** Return the handle as a TiXmlUnknown. This may return null. + */ + TiXmlUnknown* ToUnknown() const + { + return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); + } + + /** @deprecated use ToNode. + Return the handle as a TiXmlNode. This may return null. + */ + TiXmlNode* Node() const + { + return ToNode(); + } + /** @deprecated use ToElement. + Return the handle as a TiXmlElement. This may return null. + */ + TiXmlElement* Element() const + { + return ToElement(); + } + /** @deprecated use ToText() + Return the handle as a TiXmlText. This may return null. + */ + TiXmlText* Text() const + { + return ToText(); + } + /** @deprecated use ToUnknown() + Return the handle as a TiXmlUnknown. This may return null. + */ + TiXmlUnknown* Unknown() const + { + return ToUnknown(); + } private: - TiXmlNode* node; + TiXmlNode* node; }; @@ -1736,67 +2110,91 @@ private: fprintf( stdout, "%s", printer.CStr() ); @endverbatim */ -class TiXmlPrinter : public TiXmlVisitor -{ +class TiXmlPrinter : public TiXmlVisitor { public: - TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ), - buffer(), indent( " " ), lineBreak( "\n" ) {} - - virtual bool VisitEnter( const TiXmlDocument& doc ); - virtual bool VisitExit( const TiXmlDocument& doc ); - - virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ); - virtual bool VisitExit( const TiXmlElement& element ); - - virtual bool Visit( const TiXmlDeclaration& declaration ); - virtual bool Visit( const TiXmlText& text ); - virtual bool Visit( const TiXmlComment& comment ); - virtual bool Visit( const TiXmlUnknown& unknown ); - - /** Set the indent characters for printing. By default 4 spaces - but tab (\t) is also useful, or null/empty string for no indentation. - */ - void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; } - /// Query the indention string. - const char* Indent() { return indent.c_str(); } - /** Set the line breaking string. By default set to newline (\n). - Some operating systems prefer other characters, or can be - set to the null/empty string for no indenation. - */ - void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; } - /// Query the current line breaking string. - const char* LineBreak() { return lineBreak.c_str(); } - - /** Switch over to "stream printing" which is the most dense formatting without - linebreaks. Common when the XML is needed for network transmission. - */ - void SetStreamPrinting() { indent = ""; - lineBreak = ""; - } - /// Return the result. - const char* CStr() { return buffer.c_str(); } - /// Return the length of the result string. - size_t Size() { return buffer.size(); } - - #ifdef TIXML_USE_STL - /// Return the result. - const std::string& Str() { return buffer; } - #endif + TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ), + buffer(), indent( " " ), lineBreak( "\n" ) {} + + virtual bool VisitEnter( const TiXmlDocument& doc ); + virtual bool VisitExit( const TiXmlDocument& doc ); + + virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ); + virtual bool VisitExit( const TiXmlElement& element ); + + virtual bool Visit( const TiXmlDeclaration& declaration ); + virtual bool Visit( const TiXmlText& text ); + virtual bool Visit( const TiXmlComment& comment ); + virtual bool Visit( const TiXmlUnknown& unknown ); + + /** Set the indent characters for printing. By default 4 spaces + but tab (\t) is also useful, or null/empty string for no indentation. + */ + void SetIndent( const char* _indent ) + { + indent = _indent ? _indent : "" ; + } + /// Query the indention string. + const char* Indent() + { + return indent.c_str(); + } + /** Set the line breaking string. By default set to newline (\n). + Some operating systems prefer other characters, or can be + set to the null/empty string for no indenation. + */ + void SetLineBreak( const char* _lineBreak ) + { + lineBreak = _lineBreak ? _lineBreak : ""; + } + /// Query the current line breaking string. + const char* LineBreak() + { + return lineBreak.c_str(); + } + + /** Switch over to "stream printing" which is the most dense formatting without + linebreaks. Common when the XML is needed for network transmission. + */ + void SetStreamPrinting() + { + indent = ""; + lineBreak = ""; + } + /// Return the result. + const char* CStr() + { + return buffer.c_str(); + } + /// Return the length of the result string. + size_t Size() + { + return buffer.size(); + } -private: - void DoIndent() { - for( int i=0; i<depth; ++i ) - buffer += indent; - } - void DoLineBreak() { - buffer += lineBreak; - } +#ifdef TIXML_USE_STL + /// Return the result. + const std::string& Str() + { + return buffer; + } +#endif - int depth; - bool simpleTextPrint; - TIXML_STRING buffer; - TIXML_STRING indent; - TIXML_STRING lineBreak; +private: + void DoIndent() + { + for( int i=0; i<depth; ++i ) + buffer += indent; + } + void DoLineBreak() + { + buffer += lineBreak; + } + + int depth; + bool simpleTextPrint; + TIXML_STRING buffer; + TIXML_STRING indent; + TIXML_STRING lineBreak; }; diff --git a/src/tinyxml/tinyxmlerror.cpp b/src/tinyxml/tinyxmlerror.cpp index 538c21d0bd95fb114e70636bc1a776937975a912..2eec2b5bd19ed65f4207c1128f5a0a4ec916f433 100644 --- a/src/tinyxml/tinyxmlerror.cpp +++ b/src/tinyxml/tinyxmlerror.cpp @@ -2,12 +2,12 @@ www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must @@ -31,22 +31,21 @@ distribution. // It also cleans up the code a bit. // -const char* TiXmlBase::errorString[ TiXmlBase::TIXML_ERROR_STRING_COUNT ] = -{ - "No error", - "Error", - "Failed to open file", - "Error parsing Element.", - "Failed to read Element name", - "Error reading Element value.", - "Error reading Attributes.", - "Error: empty tag.", - "Error reading end tag.", - "Error parsing Unknown.", - "Error parsing Comment.", - "Error parsing Declaration.", - "Error document empty.", - "Error null (0) or unexpected EOF found in input stream.", - "Error parsing CDATA.", - "Error when TiXmlDocument added to document, because TiXmlDocument can only be at the root.", +const char* TiXmlBase::errorString[ TiXmlBase::TIXML_ERROR_STRING_COUNT ] = { + "No error", + "Error", + "Failed to open file", + "Error parsing Element.", + "Failed to read Element name", + "Error reading Element value.", + "Error reading Attributes.", + "Error: empty tag.", + "Error reading end tag.", + "Error parsing Unknown.", + "Error parsing Comment.", + "Error parsing Declaration.", + "Error document empty.", + "Error null (0) or unexpected EOF found in input stream.", + "Error parsing CDATA.", + "Error when TiXmlDocument added to document, because TiXmlDocument can only be at the root.", }; diff --git a/src/tinyxml/tinyxmlparser.cpp b/src/tinyxml/tinyxmlparser.cpp index a7e0137264ed4da6c19a6e75f34477c9761e8f3d..cde79f012b5f2fde0aeb1ffbcc36dd4a9c7cd433 100644 --- a/src/tinyxml/tinyxmlparser.cpp +++ b/src/tinyxml/tinyxmlparser.cpp @@ -2,23 +2,23 @@ www.sourceforge.net/projects/tinyxml Original code by Lee Thomason (www.grinninglizard.com) -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: -1. The origin of this software must not be misrepresented; you must +1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and +2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source +3. This notice may not be removed or altered from any source distribution. */ @@ -40,14 +40,13 @@ distribution. // Note tha "PutString" hardcodes the same list. This // is less flexible than it appears. Changing the entries -// or order will break putstring. -TiXmlBase::Entity TiXmlBase::entity[ TiXmlBase::NUM_ENTITY ] = -{ - { "&", 5, '&' }, - { "<", 4, '<' }, - { ">", 4, '>' }, - { """, 6, '\"' }, - { "'", 6, '\'' } +// or order will break putstring. +TiXmlBase::Entity TiXmlBase::entity[ TiXmlBase::NUM_ENTITY ] = { + { "&", 5, '&' }, + { "<", 4, '<' }, + { ">", 4, '>' }, + { """, 6, '\"' }, + { "'", 6, '\'' } }; // Bunch of unicode info at: @@ -55,91 +54,91 @@ TiXmlBase::Entity TiXmlBase::entity[ TiXmlBase::NUM_ENTITY ] = // Including the basic of this table, which determines the #bytes in the // sequence from the lead byte. 1 placed for invalid sequences -- // although the result will be junk, pass it through as much as possible. -// Beware of the non-characters in UTF-8: +// Beware of the non-characters in UTF-8: // ef bb bf (Microsoft "lead bytes") // ef bf be -// ef bf bf +// ef bf bf const unsigned char TIXML_UTF_LEAD_0 = 0xefU; const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; -const int TiXmlBase::utf8ByteTable[256] = -{ - // 0 1 2 3 4 5 6 7 8 9 a b c d e f - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 - 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0 - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte - 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid +const int TiXmlBase::utf8ByteTable[256] = { + // 0 1 2 3 4 5 6 7 8 9 a b c d e f + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 + 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0 + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte + 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid }; void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) { - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - - if (input < 0x80) - *length = 1; - else if ( input < 0x800 ) - *length = 2; - else if ( input < 0x10000 ) - *length = 3; - else if ( input < 0x200000 ) - *length = 4; - else - { *length = 0; return; } // This code won't covert this correctly anyway. - - output += *length; - - // Scary scary fall throughs. - switch (*length) - { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - } + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + + if (input < 0x80) + *length = 1; + else if ( input < 0x800 ) + *length = 2; + else if ( input < 0x10000 ) + *length = 3; + else if ( input < 0x200000 ) + *length = 4; + else { + *length = 0; // This code won't covert this correctly anyway. + return; + } + + output += *length; + + // Scary scary fall throughs. + switch (*length) { + case 4: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 3: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 2: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 1: + --output; + *output = (char)(input | FIRST_BYTE_MARK[*length]); + } } /*static*/ int TiXmlBase::IsAlpha( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) { - // This will only work for low-ascii, everything else is assumed to be a valid - // letter. I'm not sure this is the best approach, but it is quite tricky trying - // to figure out alhabetical vs. not across encoding. So take a very - // conservative approach. + // This will only work for low-ascii, everything else is assumed to be a valid + // letter. I'm not sure this is the best approach, but it is quite tricky trying + // to figure out alhabetical vs. not across encoding. So take a very + // conservative approach. // if ( encoding == TIXML_ENCODING_UTF8 ) // { - if ( anyByte < 127 ) - return isalpha( anyByte ); - else - return 1; // What else to do? The unicode set is huge...get the english ones right. + if ( anyByte < 127 ) + return isalpha( anyByte ); + else + return 1; // What else to do? The unicode set is huge...get the english ones right. // } // else // { @@ -150,17 +149,17 @@ void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* leng /*static*/ int TiXmlBase::IsAlphaNum( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) { - // This will only work for low-ascii, everything else is assumed to be a valid - // letter. I'm not sure this is the best approach, but it is quite tricky trying - // to figure out alhabetical vs. not across encoding. So take a very - // conservative approach. + // This will only work for low-ascii, everything else is assumed to be a valid + // letter. I'm not sure this is the best approach, but it is quite tricky trying + // to figure out alhabetical vs. not across encoding. So take a very + // conservative approach. // if ( encoding == TIXML_ENCODING_UTF8 ) // { - if ( anyByte < 127 ) - return isalnum( anyByte ); - else - return 1; // What else to do? The unicode set is huge...get the english ones right. + if ( anyByte < 127 ) + return isalnum( anyByte ); + else + return 1; // What else to do? The unicode set is huge...get the english ones right. // } // else // { @@ -169,230 +168,213 @@ void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* leng } -class TiXmlParsingData -{ - friend class TiXmlDocument; - public: - void Stamp( const char* now, TiXmlEncoding encoding ); - - const TiXmlCursor& Cursor() const { return cursor; } - - private: - // Only used by the document! - TiXmlParsingData( const char* start, int _tabsize, int row, int col ) - { - assert( start ); - stamp = start; - tabsize = _tabsize; - cursor.row = row; - cursor.col = col; - } - - TiXmlCursor cursor; - const char* stamp; - int tabsize; +class TiXmlParsingData { + friend class TiXmlDocument; +public: + void Stamp( const char* now, TiXmlEncoding encoding ); + + const TiXmlCursor& Cursor() const + { + return cursor; + } + +private: + // Only used by the document! + TiXmlParsingData( const char* start, int _tabsize, int row, int col ) + { + assert( start ); + stamp = start; + tabsize = _tabsize; + cursor.row = row; + cursor.col = col; + } + + TiXmlCursor cursor; + const char* stamp; + int tabsize; }; void TiXmlParsingData::Stamp( const char* now, TiXmlEncoding encoding ) { - assert( now ); - - // Do nothing if the tabsize is 0. - if ( tabsize < 1 ) - { - return; - } - - // Get the current row, column. - int row = cursor.row; - int col = cursor.col; - const char* p = stamp; - assert( p ); - - while ( p < now ) - { - // Treat p as unsigned, so we have a happy compiler. - const unsigned char* pU = (const unsigned char*)p; - - // Code contributed by Fletcher Dunn: (modified by lee) - switch (*pU) { - case 0: - // We *should* never get here, but in case we do, don't - // advance past the terminating null character, ever - return; - - case '\r': - // bump down to the next line - ++row; - col = 0; - // Eat the character - ++p; - - // Check for \r\n sequence, and treat this as a single character - if (*p == '\n') { - ++p; - } - break; - - case '\n': - // bump down to the next line - ++row; - col = 0; - - // Eat the character - ++p; - - // Check for \n\r sequence, and treat this as a single - // character. (Yes, this bizarre thing does occur still - // on some arcane platforms...) - if (*p == '\r') { - ++p; - } - break; - - case '\t': - // Eat the character - ++p; - - // Skip to next tab stop - col = (col / tabsize + 1) * tabsize; - break; - - case TIXML_UTF_LEAD_0: - if ( encoding == TIXML_ENCODING_UTF8 ) - { - if ( *(p+1) && *(p+2) ) - { - // In these cases, don't advance the column. These are - // 0-width spaces. - if ( *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 ) - p += 3; - else if ( *(pU+1)==0xbfU && *(pU+2)==0xbeU ) - p += 3; - else if ( *(pU+1)==0xbfU && *(pU+2)==0xbfU ) - p += 3; - else - { p +=3; ++col; } // A normal character. - } - } - else - { - ++p; - ++col; - } - break; - - default: - if ( encoding == TIXML_ENCODING_UTF8 ) - { - // Eat the 1 to 4 byte utf8 character. - int step = TiXmlBase::utf8ByteTable[*((const unsigned char*)p)]; - if ( step == 0 ) - step = 1; // Error case from bad encoding, but handle gracefully. - p += step; - - // Just advance one column, of course. - ++col; - } - else - { - ++p; - ++col; - } - break; - } - } - cursor.row = row; - cursor.col = col; - assert( cursor.row >= -1 ); - assert( cursor.col >= -1 ); - stamp = p; - assert( stamp ); + assert( now ); + + // Do nothing if the tabsize is 0. + if ( tabsize < 1 ) { + return; + } + + // Get the current row, column. + int row = cursor.row; + int col = cursor.col; + const char* p = stamp; + assert( p ); + + while ( p < now ) { + // Treat p as unsigned, so we have a happy compiler. + const unsigned char* pU = (const unsigned char*)p; + + // Code contributed by Fletcher Dunn: (modified by lee) + switch (*pU) { + case 0: + // We *should* never get here, but in case we do, don't + // advance past the terminating null character, ever + return; + + case '\r': + // bump down to the next line + ++row; + col = 0; + // Eat the character + ++p; + + // Check for \r\n sequence, and treat this as a single character + if (*p == '\n') { + ++p; + } + break; + + case '\n': + // bump down to the next line + ++row; + col = 0; + + // Eat the character + ++p; + + // Check for \n\r sequence, and treat this as a single + // character. (Yes, this bizarre thing does occur still + // on some arcane platforms...) + if (*p == '\r') { + ++p; + } + break; + + case '\t': + // Eat the character + ++p; + + // Skip to next tab stop + col = (col / tabsize + 1) * tabsize; + break; + + case TIXML_UTF_LEAD_0: + if ( encoding == TIXML_ENCODING_UTF8 ) { + if ( *(p+1) && *(p+2) ) { + // In these cases, don't advance the column. These are + // 0-width spaces. + if ( *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 ) + p += 3; + else if ( *(pU+1)==0xbfU && *(pU+2)==0xbeU ) + p += 3; + else if ( *(pU+1)==0xbfU && *(pU+2)==0xbfU ) + p += 3; + else { + p +=3; // A normal character. + ++col; + } + } + } else { + ++p; + ++col; + } + break; + + default: + if ( encoding == TIXML_ENCODING_UTF8 ) { + // Eat the 1 to 4 byte utf8 character. + int step = TiXmlBase::utf8ByteTable[*((const unsigned char*)p)]; + if ( step == 0 ) + step = 1; // Error case from bad encoding, but handle gracefully. + p += step; + + // Just advance one column, of course. + ++col; + } else { + ++p; + ++col; + } + break; + } + } + cursor.row = row; + cursor.col = col; + assert( cursor.row >= -1 ); + assert( cursor.col >= -1 ); + stamp = p; + assert( stamp ); } const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding ) { - if ( !p || !*p ) - { - return 0; - } - if ( encoding == TIXML_ENCODING_UTF8 ) - { - while ( *p ) - { - const unsigned char* pU = (const unsigned char*)p; - - // Skip the stupid Microsoft UTF-8 Byte order marks - if ( *(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==TIXML_UTF_LEAD_1 - && *(pU+2)==TIXML_UTF_LEAD_2 ) - { - p += 3; - continue; - } - else if(*(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==0xbfU - && *(pU+2)==0xbeU ) - { - p += 3; - continue; - } - else if(*(pU+0)==TIXML_UTF_LEAD_0 - && *(pU+1)==0xbfU - && *(pU+2)==0xbfU ) - { - p += 3; - continue; - } - - if ( IsWhiteSpace( *p ) ) // Still using old rules for white space. - ++p; - else - break; - } - } - else - { - while ( *p && IsWhiteSpace( *p ) ) - ++p; - } - - return p; + if ( !p || !*p ) { + return 0; + } + if ( encoding == TIXML_ENCODING_UTF8 ) { + while ( *p ) { + const unsigned char* pU = (const unsigned char*)p; + + // Skip the stupid Microsoft UTF-8 Byte order marks + if ( *(pU+0)==TIXML_UTF_LEAD_0 + && *(pU+1)==TIXML_UTF_LEAD_1 + && *(pU+2)==TIXML_UTF_LEAD_2 ) { + p += 3; + continue; + } else if(*(pU+0)==TIXML_UTF_LEAD_0 + && *(pU+1)==0xbfU + && *(pU+2)==0xbeU ) { + p += 3; + continue; + } else if(*(pU+0)==TIXML_UTF_LEAD_0 + && *(pU+1)==0xbfU + && *(pU+2)==0xbfU ) { + p += 3; + continue; + } + + if ( IsWhiteSpace( *p ) ) // Still using old rules for white space. + ++p; + else + break; + } + } else { + while ( *p && IsWhiteSpace( *p ) ) + ++p; + } + + return p; } #ifdef TIXML_USE_STL /*static*/ bool TiXmlBase::StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ) { - for( ;; ) - { - if ( !in->good() ) return false; + for( ;; ) { + if ( !in->good() ) return false; - int c = in->peek(); - // At this scope, we can't get to a document. So fail silently. - if ( !IsWhiteSpace( c ) || c <= 0 ) - return true; + int c = in->peek(); + // At this scope, we can't get to a document. So fail silently. + if ( !IsWhiteSpace( c ) || c <= 0 ) + return true; - *tag += (char) in->get(); - } + *tag += (char) in->get(); + } } /*static*/ bool TiXmlBase::StreamTo( std::istream * in, int character, TIXML_STRING * tag ) { - //assert( character > 0 && character < 128 ); // else it won't work in utf-8 - while ( in->good() ) - { - int c = in->peek(); - if ( c == character ) - return true; - if ( c <= 0 ) // Silent failure: can't get document at this scope - return false; - - in->get(); - *tag += (char) c; - } - return false; + //assert( character > 0 && character < 128 ); // else it won't work in utf-8 + while ( in->good() ) { + int c = in->peek(); + if ( c == character ) + return true; + if ( c <= 0 ) // Silent failure: can't get document at this scope + return false; + + in->get(); + *tag += (char) c; + } + return false; } #endif @@ -401,1239 +383,1079 @@ const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding ) // const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name, TiXmlEncoding encoding ) { - // Oddly, not supported on some comilers, - //name->clear(); - // So use this: - *name = ""; - assert( p ); - - // Names start with letters or underscores. - // Of course, in unicode, tinyxml has no idea what a letter *is*. The - // algorithm is generous. - // - // After that, they can be letters, underscores, numbers, - // hyphens, or colons. (Colons are valid ony for namespaces, - // but tinyxml can't tell namespaces from names.) - if ( p && *p - && ( IsAlpha( (unsigned char) *p, encoding ) || *p == '_' ) ) - { - const char* start = p; - while( p && *p - && ( IsAlphaNum( (unsigned char ) *p, encoding ) - || *p == '_' - || *p == '-' - || *p == '.' - || *p == ':' ) ) - { - //(*name) += *p; // expensive - ++p; - } - if ( p-start > 0 ) { - name->assign( start, p-start ); - } - return p; - } - return 0; + // Oddly, not supported on some comilers, + //name->clear(); + // So use this: + *name = ""; + assert( p ); + + // Names start with letters or underscores. + // Of course, in unicode, tinyxml has no idea what a letter *is*. The + // algorithm is generous. + // + // After that, they can be letters, underscores, numbers, + // hyphens, or colons. (Colons are valid ony for namespaces, + // but tinyxml can't tell namespaces from names.) + if ( p && *p + && ( IsAlpha( (unsigned char) *p, encoding ) || *p == '_' ) ) { + const char* start = p; + while( p && *p + && ( IsAlphaNum( (unsigned char ) *p, encoding ) + || *p == '_' + || *p == '-' + || *p == '.' + || *p == ':' ) ) { + //(*name) += *p; // expensive + ++p; + } + if ( p-start > 0 ) { + name->assign( start, p-start ); + } + return p; + } + return 0; } const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXmlEncoding encoding ) { - // Presume an entity, and pull it out. + // Presume an entity, and pull it out. TIXML_STRING ent; - int i; - *length = 0; - - if ( *(p+1) && *(p+1) == '#' && *(p+2) ) - { - unsigned long ucs = 0; - ptrdiff_t delta = 0; - unsigned mult = 1; - - if ( *(p+2) == 'x' ) - { - // Hexadecimal. - if ( !*(p+3) ) return 0; - - const char* q = p+3; - q = strchr( q, ';' ); - - if ( !q || !*q ) return 0; - - delta = q-p; - --q; - - while ( *q != 'x' ) - { - if ( *q >= '0' && *q <= '9' ) - ucs += mult * (*q - '0'); - else if ( *q >= 'a' && *q <= 'f' ) - ucs += mult * (*q - 'a' + 10); - else if ( *q >= 'A' && *q <= 'F' ) - ucs += mult * (*q - 'A' + 10 ); - else - return 0; - mult *= 16; - --q; - } - } - else - { - // Decimal. - if ( !*(p+2) ) return 0; - - const char* q = p+2; - q = strchr( q, ';' ); - - if ( !q || !*q ) return 0; - - delta = q-p; - --q; - - while ( *q != '#' ) - { - if ( *q >= '0' && *q <= '9' ) - ucs += mult * (*q - '0'); - else - return 0; - mult *= 10; - --q; - } - } - if ( encoding == TIXML_ENCODING_UTF8 ) - { - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - } - else - { - *value = (char)ucs; - *length = 1; - } - return p + delta + 1; - } - - // Now try to match it. - for( i=0; i<NUM_ENTITY; ++i ) - { - if ( strncmp( entity[i].str, p, entity[i].strLength ) == 0 ) - { - assert( strlen( entity[i].str ) == entity[i].strLength ); - *value = entity[i].chr; - *length = 1; - return ( p + entity[i].strLength ); - } - } - - // So it wasn't an entity, its unrecognized, or something like that. - *value = *p; // Don't put back the last one, since we return it! - //*length = 1; // Leave unrecognized entities - this doesn't really work. - // Just writes strange XML. - return p+1; + int i; + *length = 0; + + if ( *(p+1) && *(p+1) == '#' && *(p+2) ) { + unsigned long ucs = 0; + ptrdiff_t delta = 0; + unsigned mult = 1; + + if ( *(p+2) == 'x' ) { + // Hexadecimal. + if ( !*(p+3) ) return 0; + + const char* q = p+3; + q = strchr( q, ';' ); + + if ( !q || !*q ) return 0; + + delta = q-p; + --q; + + while ( *q != 'x' ) { + if ( *q >= '0' && *q <= '9' ) + ucs += mult * (*q - '0'); + else if ( *q >= 'a' && *q <= 'f' ) + ucs += mult * (*q - 'a' + 10); + else if ( *q >= 'A' && *q <= 'F' ) + ucs += mult * (*q - 'A' + 10 ); + else + return 0; + mult *= 16; + --q; + } + } else { + // Decimal. + if ( !*(p+2) ) return 0; + + const char* q = p+2; + q = strchr( q, ';' ); + + if ( !q || !*q ) return 0; + + delta = q-p; + --q; + + while ( *q != '#' ) { + if ( *q >= '0' && *q <= '9' ) + ucs += mult * (*q - '0'); + else + return 0; + mult *= 10; + --q; + } + } + if ( encoding == TIXML_ENCODING_UTF8 ) { + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8( ucs, value, length ); + } else { + *value = (char)ucs; + *length = 1; + } + return p + delta + 1; + } + + // Now try to match it. + for( i=0; i<NUM_ENTITY; ++i ) { + if ( strncmp( entity[i].str, p, entity[i].strLength ) == 0 ) { + assert( strlen( entity[i].str ) == entity[i].strLength ); + *value = entity[i].chr; + *length = 1; + return ( p + entity[i].strLength ); + } + } + + // So it wasn't an entity, its unrecognized, or something like that. + *value = *p; // Don't put back the last one, since we return it! + //*length = 1; // Leave unrecognized entities - this doesn't really work. + // Just writes strange XML. + return p+1; } bool TiXmlBase::StringEqual( const char* p, - const char* tag, - bool ignoreCase, - TiXmlEncoding encoding ) + const char* tag, + bool ignoreCase, + TiXmlEncoding encoding ) { - assert( p ); - assert( tag ); - if ( !p || !*p ) - { - assert( 0 ); - return false; - } - - const char* q = p; - - if ( ignoreCase ) - { - while ( *q && *tag && ToLower( *q, encoding ) == ToLower( *tag, encoding ) ) - { - ++q; - ++tag; - } - - if ( *tag == 0 ) - return true; - } - else - { - while ( *q && *tag && *q == *tag ) - { - ++q; - ++tag; - } - - if ( *tag == 0 ) // Have we found the end of the tag, and everything equal? - return true; - } - return false; + assert( p ); + assert( tag ); + if ( !p || !*p ) { + assert( 0 ); + return false; + } + + const char* q = p; + + if ( ignoreCase ) { + while ( *q && *tag && ToLower( *q, encoding ) == ToLower( *tag, encoding ) ) { + ++q; + ++tag; + } + + if ( *tag == 0 ) + return true; + } else { + while ( *q && *tag && *q == *tag ) { + ++q; + ++tag; + } + + if ( *tag == 0 ) // Have we found the end of the tag, and everything equal? + return true; + } + return false; } -const char* TiXmlBase::ReadText( const char* p, - TIXML_STRING * text, - bool trimWhiteSpace, - const char* endTag, - bool caseInsensitive, - TiXmlEncoding encoding ) +const char* TiXmlBase::ReadText( const char* p, + TIXML_STRING * text, + bool trimWhiteSpace, + const char* endTag, + bool caseInsensitive, + TiXmlEncoding encoding ) { *text = ""; - if ( !trimWhiteSpace // certain tags always keep whitespace - || !condenseWhiteSpace ) // if true, whitespace is always kept - { - // Keep all the white space. - while ( p && *p - && !StringEqual( p, endTag, caseInsensitive, encoding ) - ) - { - int len; - char cArr[4] = { 0, 0, 0, 0 }; - p = GetChar( p, cArr, &len, encoding ); - text->append( cArr, len ); - } - } - else - { - bool whitespace = false; - - // Remove leading white space: - p = SkipWhiteSpace( p, encoding ); - while ( p && *p - && !StringEqual( p, endTag, caseInsensitive, encoding ) ) - { - if ( *p == '\r' || *p == '\n' ) - { - whitespace = true; - ++p; - } - else if ( IsWhiteSpace( *p ) ) - { - whitespace = true; - ++p; - } - else - { - // If we've found whitespace, add it before the - // new character. Any whitespace just becomes a space. - if ( whitespace ) - { - (*text) += ' '; - whitespace = false; - } - int len; - char cArr[4] = { 0, 0, 0, 0 }; - p = GetChar( p, cArr, &len, encoding ); - if ( len == 1 ) - (*text) += cArr[0]; // more efficient - else - text->append( cArr, len ); - } - } - } - if ( p && *p ) - p += strlen( endTag ); - return ( p && *p ) ? p : 0; + if ( !trimWhiteSpace // certain tags always keep whitespace + || !condenseWhiteSpace ) { // if true, whitespace is always kept + // Keep all the white space. + while ( p && *p + && !StringEqual( p, endTag, caseInsensitive, encoding ) + ) { + int len; + char cArr[4] = { 0, 0, 0, 0 }; + p = GetChar( p, cArr, &len, encoding ); + text->append( cArr, len ); + } + } else { + bool whitespace = false; + + // Remove leading white space: + p = SkipWhiteSpace( p, encoding ); + while ( p && *p + && !StringEqual( p, endTag, caseInsensitive, encoding ) ) { + if ( *p == '\r' || *p == '\n' ) { + whitespace = true; + ++p; + } else if ( IsWhiteSpace( *p ) ) { + whitespace = true; + ++p; + } else { + // If we've found whitespace, add it before the + // new character. Any whitespace just becomes a space. + if ( whitespace ) { + (*text) += ' '; + whitespace = false; + } + int len; + char cArr[4] = { 0, 0, 0, 0 }; + p = GetChar( p, cArr, &len, encoding ); + if ( len == 1 ) + (*text) += cArr[0]; // more efficient + else + text->append( cArr, len ); + } + } + } + if ( p && *p ) + p += strlen( endTag ); + return ( p && *p ) ? p : 0; } #ifdef TIXML_USE_STL void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) { - // The basic issue with a document is that we don't know what we're - // streaming. Read something presumed to be a tag (and hope), then - // identify it, and call the appropriate stream method on the tag. - // - // This "pre-streaming" will never read the closing ">" so the - // sub-tag can orient itself. - - if ( !StreamTo( in, '<', tag ) ) - { - SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - - while ( in->good() ) - { - int tagIndex = (int) tag->length(); - while ( in->good() && in->peek() != '>' ) - { - int c = in->get(); - if ( c <= 0 ) - { - SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - break; - } - (*tag) += (char) c; - } - - if ( in->good() ) - { - // We now have something we presume to be a node of - // some sort. Identify it, and call the node to - // continue streaming. - TiXmlNode* node = Identify( tag->c_str() + tagIndex, TIXML_DEFAULT_ENCODING ); - - if ( node ) - { - node->StreamIn( in, tag ); - bool isElement = node->ToElement() != 0; - delete node; - node = 0; - - // If this is the root element, we're done. Parsing will be - // done by the >> operator. - if ( isElement ) - { - return; - } - } - else - { - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - } - } - // We should have returned sooner. - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); + // The basic issue with a document is that we don't know what we're + // streaming. Read something presumed to be a tag (and hope), then + // identify it, and call the appropriate stream method on the tag. + // + // This "pre-streaming" will never read the closing ">" so the + // sub-tag can orient itself. + + if ( !StreamTo( in, '<', tag ) ) { + SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + + while ( in->good() ) { + int tagIndex = (int) tag->length(); + while ( in->good() && in->peek() != '>' ) { + int c = in->get(); + if ( c <= 0 ) { + SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + break; + } + (*tag) += (char) c; + } + + if ( in->good() ) { + // We now have something we presume to be a node of + // some sort. Identify it, and call the node to + // continue streaming. + TiXmlNode* node = Identify( tag->c_str() + tagIndex, TIXML_DEFAULT_ENCODING ); + + if ( node ) { + node->StreamIn( in, tag ); + bool isElement = node->ToElement() != 0; + delete node; + node = 0; + + // If this is the root element, we're done. Parsing will be + // done by the >> operator. + if ( isElement ) { + return; + } + } else { + SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + } + } + // We should have returned sooner. + SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); } #endif const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding ) { - ClearError(); - - // Parse away, at the document level. Since a document - // contains nothing but other tags, most of what happens - // here is skipping white space. - if ( !p || !*p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - // Note that, for a document, this needs to come - // before the while space skip, so that parsing - // starts from the pointer we are given. - location.Clear(); - if ( prevData ) - { - location.row = prevData->cursor.row; - location.col = prevData->cursor.col; - } - else - { - location.row = 0; - location.col = 0; - } - TiXmlParsingData data( p, TabSize(), location.row, location.col ); - location = data.Cursor(); - - if ( encoding == TIXML_ENCODING_UNKNOWN ) - { - // Check for the Microsoft UTF-8 lead bytes. - const unsigned char* pU = (const unsigned char*)p; - if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0 - && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1 - && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 ) - { - encoding = TIXML_ENCODING_UTF8; - useMicrosoftBOM = true; - } - } + ClearError(); + + // Parse away, at the document level. Since a document + // contains nothing but other tags, most of what happens + // here is skipping white space. + if ( !p || !*p ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } + + // Note that, for a document, this needs to come + // before the while space skip, so that parsing + // starts from the pointer we are given. + location.Clear(); + if ( prevData ) { + location.row = prevData->cursor.row; + location.col = prevData->cursor.col; + } else { + location.row = 0; + location.col = 0; + } + TiXmlParsingData data( p, TabSize(), location.row, location.col ); + location = data.Cursor(); + + if ( encoding == TIXML_ENCODING_UNKNOWN ) { + // Check for the Microsoft UTF-8 lead bytes. + const unsigned char* pU = (const unsigned char*)p; + if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0 + && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1 + && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 ) { + encoding = TIXML_ENCODING_UTF8; + useMicrosoftBOM = true; + } + } p = SkipWhiteSpace( p, encoding ); - if ( !p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; - } - - while ( p && *p ) - { - TiXmlNode* node = Identify( p, encoding ); - if ( node ) - { - p = node->Parse( p, &data, encoding ); - LinkEndChild( node ); - } - else - { - break; - } - - // Did we get encoding info? - if ( encoding == TIXML_ENCODING_UNKNOWN - && node->ToDeclaration() ) - { - TiXmlDeclaration* dec = node->ToDeclaration(); - const char* enc = dec->Encoding(); - assert( enc ); - - if ( *enc == 0 ) - encoding = TIXML_ENCODING_UTF8; - else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) ) - encoding = TIXML_ENCODING_UTF8; - else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) ) - encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice - else - encoding = TIXML_ENCODING_LEGACY; - } - - p = SkipWhiteSpace( p, encoding ); - } - - // Was this empty? - if ( !firstChild ) { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); - return 0; - } - - // All is well. - return p; + if ( !p ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + return 0; + } + + while ( p && *p ) { + TiXmlNode* node = Identify( p, encoding ); + if ( node ) { + p = node->Parse( p, &data, encoding ); + LinkEndChild( node ); + } else { + break; + } + + // Did we get encoding info? + if ( encoding == TIXML_ENCODING_UNKNOWN + && node->ToDeclaration() ) { + TiXmlDeclaration* dec = node->ToDeclaration(); + const char* enc = dec->Encoding(); + assert( enc ); + + if ( *enc == 0 ) + encoding = TIXML_ENCODING_UTF8; + else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) ) + encoding = TIXML_ENCODING_UTF8; + else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) ) + encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice + else + encoding = TIXML_ENCODING_LEGACY; + } + + p = SkipWhiteSpace( p, encoding ); + } + + // Was this empty? + if ( !firstChild ) { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); + return 0; + } + + // All is well. + return p; } void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* data, TiXmlEncoding encoding ) -{ - // The first error in a chain is more accurate - don't set again! - if ( error ) - return; - - assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); - error = true; - errorId = err; - errorDesc = errorString[ errorId ]; - - errorLocation.Clear(); - if ( pError && data ) - { - data->Stamp( pError, encoding ); - errorLocation = data->Cursor(); - } +{ + // The first error in a chain is more accurate - don't set again! + if ( error ) + return; + + assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); + error = true; + errorId = err; + errorDesc = errorString[ errorId ]; + + errorLocation.Clear(); + if ( pError && data ) { + data->Stamp( pError, encoding ); + errorLocation = data->Cursor(); + } } TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) { - TiXmlNode* returnNode = 0; - - p = SkipWhiteSpace( p, encoding ); - if( !p || !*p || *p != '<' ) - { - return 0; - } - - p = SkipWhiteSpace( p, encoding ); - - if ( !p || !*p ) - { - return 0; - } - - // What is this thing? - // - Elements start with a letter or underscore, but xml is reserved. - // - Comments: <!-- - // - Decleration: <?xml - // - Everthing else is unknown to tinyxml. - // - - const char* xmlHeader = { "<?xml" }; - const char* commentHeader = { "<!--" }; - const char* dtdHeader = { "<!" }; - const char* cdataHeader = { "<![CDATA[" }; - - if ( StringEqual( p, xmlHeader, true, encoding ) ) - { - #ifdef DEBUG_PARSER - TIXML_LOG( "XML parsing Declaration\n" ); - #endif - returnNode = new TiXmlDeclaration(); - } - else if ( StringEqual( p, commentHeader, false, encoding ) ) - { - #ifdef DEBUG_PARSER - TIXML_LOG( "XML parsing Comment\n" ); - #endif - returnNode = new TiXmlComment(); - } - else if ( StringEqual( p, cdataHeader, false, encoding ) ) - { - #ifdef DEBUG_PARSER - TIXML_LOG( "XML parsing CDATA\n" ); - #endif - TiXmlText* text = new TiXmlText( "" ); - text->SetCDATA( true ); - returnNode = text; - } - else if ( StringEqual( p, dtdHeader, false, encoding ) ) - { - #ifdef DEBUG_PARSER - TIXML_LOG( "XML parsing Unknown(1)\n" ); - #endif - returnNode = new TiXmlUnknown(); - } - else if ( IsAlpha( *(p+1), encoding ) - || *(p+1) == '_' ) - { - #ifdef DEBUG_PARSER - TIXML_LOG( "XML parsing Element\n" ); - #endif - returnNode = new TiXmlElement( "" ); - } - else - { - #ifdef DEBUG_PARSER - TIXML_LOG( "XML parsing Unknown(2)\n" ); - #endif - returnNode = new TiXmlUnknown(); - } - - if ( returnNode ) - { - // Set the parent, so it can report errors - returnNode->parent = this; - } - return returnNode; + TiXmlNode* returnNode = 0; + + p = SkipWhiteSpace( p, encoding ); + if( !p || !*p || *p != '<' ) { + return 0; + } + + p = SkipWhiteSpace( p, encoding ); + + if ( !p || !*p ) { + return 0; + } + + // What is this thing? + // - Elements start with a letter or underscore, but xml is reserved. + // - Comments: <!-- + // - Decleration: <?xml + // - Everthing else is unknown to tinyxml. + // + + const char* xmlHeader = { "<?xml" }; + const char* commentHeader = { "<!--" }; + const char* dtdHeader = { "<!" }; + const char* cdataHeader = { "<![CDATA[" }; + + if ( StringEqual( p, xmlHeader, true, encoding ) ) { +#ifdef DEBUG_PARSER + TIXML_LOG( "XML parsing Declaration\n" ); +#endif + returnNode = new TiXmlDeclaration(); + } else if ( StringEqual( p, commentHeader, false, encoding ) ) { +#ifdef DEBUG_PARSER + TIXML_LOG( "XML parsing Comment\n" ); +#endif + returnNode = new TiXmlComment(); + } else if ( StringEqual( p, cdataHeader, false, encoding ) ) { +#ifdef DEBUG_PARSER + TIXML_LOG( "XML parsing CDATA\n" ); +#endif + TiXmlText* text = new TiXmlText( "" ); + text->SetCDATA( true ); + returnNode = text; + } else if ( StringEqual( p, dtdHeader, false, encoding ) ) { +#ifdef DEBUG_PARSER + TIXML_LOG( "XML parsing Unknown(1)\n" ); +#endif + returnNode = new TiXmlUnknown(); + } else if ( IsAlpha( *(p+1), encoding ) + || *(p+1) == '_' ) { +#ifdef DEBUG_PARSER + TIXML_LOG( "XML parsing Element\n" ); +#endif + returnNode = new TiXmlElement( "" ); + } else { +#ifdef DEBUG_PARSER + TIXML_LOG( "XML parsing Unknown(2)\n" ); +#endif + returnNode = new TiXmlUnknown(); + } + + if ( returnNode ) { + // Set the parent, so it can report errors + returnNode->parent = this; + } + return returnNode; } #ifdef TIXML_USE_STL void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag) { - // We're called with some amount of pre-parsing. That is, some of "this" - // element is in "tag". Go ahead and stream to the closing ">" - while( in->good() ) - { - int c = in->get(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - (*tag) += (char) c ; - - if ( c == '>' ) - break; - } - - if ( tag->length() < 3 ) return; - - // Okay...if we are a "/>" tag, then we're done. We've read a complete tag. - // If not, identify and stream. - - if ( tag->at( tag->length() - 1 ) == '>' - && tag->at( tag->length() - 2 ) == '/' ) - { - // All good! - return; - } - else if ( tag->at( tag->length() - 1 ) == '>' ) - { - // There is more. Could be: - // text - // cdata text (which looks like another node) - // closing tag - // another node. - for ( ;; ) - { - StreamWhiteSpace( in, tag ); - - // Do we have text? - if ( in->good() && in->peek() != '<' ) - { - // Yep, text. - TiXmlText text( "" ); - text.StreamIn( in, tag ); - - // What follows text is a closing tag or another node. - // Go around again and figure it out. - continue; - } - - // We now have either a closing tag...or another node. - // We should be at a "<", regardless. - if ( !in->good() ) return; - assert( in->peek() == '<' ); - int tagIndex = (int) tag->length(); - - bool closingTag = false; - bool firstCharFound = false; - - for( ;; ) - { - if ( !in->good() ) - return; - - int c = in->peek(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - - if ( c == '>' ) - break; - - *tag += (char) c; - in->get(); - - // Early out if we find the CDATA id. - if ( c == '[' && tag->size() >= 9 ) - { - size_t len = tag->size(); - const char* start = tag->c_str() + len - 9; - if ( strcmp( start, "<![CDATA[" ) == 0 ) { - assert( !closingTag ); - break; - } - } - - if ( !firstCharFound && c != '<' && !IsWhiteSpace( c ) ) - { - firstCharFound = true; - if ( c == '/' ) - closingTag = true; - } - } - // If it was a closing tag, then read in the closing '>' to clean up the input stream. - // If it was not, the streaming will be done by the tag. - if ( closingTag ) - { - if ( !in->good() ) - return; - - int c = in->get(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - assert( c == '>' ); - *tag += (char) c; - - // We are done, once we've found our closing tag. - return; - } - else - { - // If not a closing tag, id it, and stream. - const char* tagloc = tag->c_str() + tagIndex; - TiXmlNode* node = Identify( tagloc, TIXML_DEFAULT_ENCODING ); - if ( !node ) - return; - node->StreamIn( in, tag ); - delete node; - node = 0; - - // No return: go around from the beginning: text, closing tag, or node. - } - } - } + // We're called with some amount of pre-parsing. That is, some of "this" + // element is in "tag". Go ahead and stream to the closing ">" + while( in->good() ) { + int c = in->get(); + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + (*tag) += (char) c ; + + if ( c == '>' ) + break; + } + + if ( tag->length() < 3 ) return; + + // Okay...if we are a "/>" tag, then we're done. We've read a complete tag. + // If not, identify and stream. + + if ( tag->at( tag->length() - 1 ) == '>' + && tag->at( tag->length() - 2 ) == '/' ) { + // All good! + return; + } else if ( tag->at( tag->length() - 1 ) == '>' ) { + // There is more. Could be: + // text + // cdata text (which looks like another node) + // closing tag + // another node. + for ( ;; ) { + StreamWhiteSpace( in, tag ); + + // Do we have text? + if ( in->good() && in->peek() != '<' ) { + // Yep, text. + TiXmlText text( "" ); + text.StreamIn( in, tag ); + + // What follows text is a closing tag or another node. + // Go around again and figure it out. + continue; + } + + // We now have either a closing tag...or another node. + // We should be at a "<", regardless. + if ( !in->good() ) return; + assert( in->peek() == '<' ); + int tagIndex = (int) tag->length(); + + bool closingTag = false; + bool firstCharFound = false; + + for( ;; ) { + if ( !in->good() ) + return; + + int c = in->peek(); + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + + if ( c == '>' ) + break; + + *tag += (char) c; + in->get(); + + // Early out if we find the CDATA id. + if ( c == '[' && tag->size() >= 9 ) { + size_t len = tag->size(); + const char* start = tag->c_str() + len - 9; + if ( strcmp( start, "<![CDATA[" ) == 0 ) { + assert( !closingTag ); + break; + } + } + + if ( !firstCharFound && c != '<' && !IsWhiteSpace( c ) ) { + firstCharFound = true; + if ( c == '/' ) + closingTag = true; + } + } + // If it was a closing tag, then read in the closing '>' to clean up the input stream. + // If it was not, the streaming will be done by the tag. + if ( closingTag ) { + if ( !in->good() ) + return; + + int c = in->get(); + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + assert( c == '>' ); + *tag += (char) c; + + // We are done, once we've found our closing tag. + return; + } else { + // If not a closing tag, id it, and stream. + const char* tagloc = tag->c_str() + tagIndex; + TiXmlNode* node = Identify( tagloc, TIXML_DEFAULT_ENCODING ); + if ( !node ) + return; + node->StreamIn( in, tag ); + delete node; + node = 0; + + // No return: go around from the beginning: text, closing tag, or node. + } + } + } } #endif const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { - p = SkipWhiteSpace( p, encoding ); - TiXmlDocument* document = GetDocument(); + p = SkipWhiteSpace( p, encoding ); + TiXmlDocument* document = GetDocument(); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, 0, 0, encoding ); - return 0; - } + if ( !p || !*p ) { + if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, 0, 0, encoding ); + return 0; + } - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } - if ( *p != '<' ) - { - if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, p, data, encoding ); - return 0; - } + if ( *p != '<' ) { + if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, p, data, encoding ); + return 0; + } - p = SkipWhiteSpace( p+1, encoding ); + p = SkipWhiteSpace( p+1, encoding ); - // Read the name. - const char* pErr = p; + // Read the name. + const char* pErr = p; p = ReadName( p, &value, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, pErr, data, encoding ); - return 0; - } + if ( !p || !*p ) { + if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, pErr, data, encoding ); + return 0; + } TIXML_STRING endTag ("</"); - endTag += value; - - // Check for and read attributes. Also look for an empty - // tag or an end tag. - while ( p && *p ) - { - pErr = p; - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); - return 0; - } - if ( *p == '/' ) - { - ++p; - // Empty tag. - if ( *p != '>' ) - { - if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY, p, data, encoding ); - return 0; - } - return (p+1); - } - else if ( *p == '>' ) - { - // Done with attributes (if there were any.) - // Read the value -- which can include other - // elements -- read the end tag, and return. - ++p; - p = ReadValue( p, data, encoding ); // Note this is an Element method, and will set the error if one happens. - if ( !p || !*p ) { - // We were looking for the end tag, but found nothing. - // Fix for [ 1663758 ] Failure to report error on bad XML - if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); - return 0; - } - - // We should find the end tag now - // note that: - // </foo > and - // </foo> - // are both valid end tags. - if ( StringEqual( p, endTag.c_str(), false, encoding ) ) - { - p += endTag.length(); - p = SkipWhiteSpace( p, encoding ); - if ( p && *p && *p == '>' ) { - ++p; - return p; - } - if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); - return 0; - } - else - { - if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); - return 0; - } - } - else - { - // Try to read an attribute: - TiXmlAttribute* attrib = new TiXmlAttribute(); - if ( !attrib ) - { - return 0; - } - - attrib->SetDocument( document ); - pErr = p; - p = attrib->Parse( p, data, encoding ); - - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding ); - delete attrib; - return 0; - } - - // Handle the strange case of double attributes: - #ifdef TIXML_USE_STL - TiXmlAttribute* node = attributeSet.Find( attrib->NameTStr() ); - #else - TiXmlAttribute* node = attributeSet.Find( attrib->Name() ); - #endif - if ( node ) - { - if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding ); - delete attrib; - return 0; - } - - attributeSet.Add( attrib ); - } - } - return p; + endTag += value; + + // Check for and read attributes. Also look for an empty + // tag or an end tag. + while ( p && *p ) { + pErr = p; + p = SkipWhiteSpace( p, encoding ); + if ( !p || !*p ) { + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); + return 0; + } + if ( *p == '/' ) { + ++p; + // Empty tag. + if ( *p != '>' ) { + if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY, p, data, encoding ); + return 0; + } + return (p+1); + } else if ( *p == '>' ) { + // Done with attributes (if there were any.) + // Read the value -- which can include other + // elements -- read the end tag, and return. + ++p; + p = ReadValue( p, data, encoding ); // Note this is an Element method, and will set the error if one happens. + if ( !p || !*p ) { + // We were looking for the end tag, but found nothing. + // Fix for [ 1663758 ] Failure to report error on bad XML + if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); + return 0; + } + + // We should find the end tag now + // note that: + // </foo > and + // </foo> + // are both valid end tags. + if ( StringEqual( p, endTag.c_str(), false, encoding ) ) { + p += endTag.length(); + p = SkipWhiteSpace( p, encoding ); + if ( p && *p && *p == '>' ) { + ++p; + return p; + } + if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); + return 0; + } else { + if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); + return 0; + } + } else { + // Try to read an attribute: + TiXmlAttribute* attrib = new TiXmlAttribute(); + if ( !attrib ) { + return 0; + } + + attrib->SetDocument( document ); + pErr = p; + p = attrib->Parse( p, data, encoding ); + + if ( !p || !*p ) { + if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding ); + delete attrib; + return 0; + } + + // Handle the strange case of double attributes: +#ifdef TIXML_USE_STL + TiXmlAttribute* node = attributeSet.Find( attrib->NameTStr() ); +#else + TiXmlAttribute* node = attributeSet.Find( attrib->Name() ); +#endif + if ( node ) { + if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding ); + delete attrib; + return 0; + } + + attributeSet.Add( attrib ); + } + } + return p; } const char* TiXmlElement::ReadValue( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { - TiXmlDocument* document = GetDocument(); - - // Read in text and elements in any order. - const char* pWithWhiteSpace = p; - p = SkipWhiteSpace( p, encoding ); - - while ( p && *p ) - { - if ( *p != '<' ) - { - // Take what we have, make a text element. - TiXmlText* textNode = new TiXmlText( "" ); - - if ( !textNode ) - { - return 0; - } - - if ( TiXmlBase::IsWhiteSpaceCondensed() ) - { - p = textNode->Parse( p, data, encoding ); - } - else - { - // Special case: we want to keep the white space - // so that leading spaces aren't removed. - p = textNode->Parse( pWithWhiteSpace, data, encoding ); - } - - if ( !textNode->Blank() ) - LinkEndChild( textNode ); - else - delete textNode; - } - else - { - // We hit a '<' - // Have we hit a new element or an end tag? This could also be - // a TiXmlText in the "CDATA" style. - if ( StringEqual( p, "</", false, encoding ) ) - { - return p; - } - else - { - TiXmlNode* node = Identify( p, encoding ); - if ( node ) - { - p = node->Parse( p, data, encoding ); - LinkEndChild( node ); - } - else - { - return 0; - } - } - } - pWithWhiteSpace = p; - p = SkipWhiteSpace( p, encoding ); - } - - if ( !p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, 0, 0, encoding ); - } - return p; + TiXmlDocument* document = GetDocument(); + + // Read in text and elements in any order. + const char* pWithWhiteSpace = p; + p = SkipWhiteSpace( p, encoding ); + + while ( p && *p ) { + if ( *p != '<' ) { + // Take what we have, make a text element. + TiXmlText* textNode = new TiXmlText( "" ); + + if ( !textNode ) { + return 0; + } + + if ( TiXmlBase::IsWhiteSpaceCondensed() ) { + p = textNode->Parse( p, data, encoding ); + } else { + // Special case: we want to keep the white space + // so that leading spaces aren't removed. + p = textNode->Parse( pWithWhiteSpace, data, encoding ); + } + + if ( !textNode->Blank() ) + LinkEndChild( textNode ); + else + delete textNode; + } else { + // We hit a '<' + // Have we hit a new element or an end tag? This could also be + // a TiXmlText in the "CDATA" style. + if ( StringEqual( p, "</", false, encoding ) ) { + return p; + } else { + TiXmlNode* node = Identify( p, encoding ); + if ( node ) { + p = node->Parse( p, data, encoding ); + LinkEndChild( node ); + } else { + return 0; + } + } + } + pWithWhiteSpace = p; + p = SkipWhiteSpace( p, encoding ); + } + + if ( !p ) { + if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, 0, 0, encoding ); + } + return p; } #ifdef TIXML_USE_STL void TiXmlUnknown::StreamIn( std::istream * in, TIXML_STRING * tag ) { - while ( in->good() ) - { - int c = in->get(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - (*tag) += (char) c; - - if ( c == '>' ) - { - // All is well. - return; - } - } + while ( in->good() ) { + int c = in->get(); + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + (*tag) += (char) c; + + if ( c == '>' ) { + // All is well. + return; + } + } } #endif const char* TiXmlUnknown::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { - TiXmlDocument* document = GetDocument(); - p = SkipWhiteSpace( p, encoding ); - - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } - if ( !p || !*p || *p != '<' ) - { - if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN, p, data, encoding ); - return 0; - } - ++p; + TiXmlDocument* document = GetDocument(); + p = SkipWhiteSpace( p, encoding ); + + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } + if ( !p || !*p || *p != '<' ) { + if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN, p, data, encoding ); + return 0; + } + ++p; value = ""; - while ( p && *p && *p != '>' ) - { - value += *p; - ++p; - } - - if ( !p ) - { - if ( document ) - document->SetError( TIXML_ERROR_PARSING_UNKNOWN, 0, 0, encoding ); - } - if ( p && *p == '>' ) - return p+1; - return p; + while ( p && *p && *p != '>' ) { + value += *p; + ++p; + } + + if ( !p ) { + if ( document ) + document->SetError( TIXML_ERROR_PARSING_UNKNOWN, 0, 0, encoding ); + } + if ( p && *p == '>' ) + return p+1; + return p; } #ifdef TIXML_USE_STL void TiXmlComment::StreamIn( std::istream * in, TIXML_STRING * tag ) { - while ( in->good() ) - { - int c = in->get(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - - (*tag) += (char) c; - - if ( c == '>' - && tag->at( tag->length() - 2 ) == '-' - && tag->at( tag->length() - 3 ) == '-' ) - { - // All is well. - return; - } - } + while ( in->good() ) { + int c = in->get(); + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + + (*tag) += (char) c; + + if ( c == '>' + && tag->at( tag->length() - 2 ) == '-' + && tag->at( tag->length() - 3 ) == '-' ) { + // All is well. + return; + } + } } #endif const char* TiXmlComment::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { - TiXmlDocument* document = GetDocument(); - value = ""; - - p = SkipWhiteSpace( p, encoding ); - - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } - const char* startTag = "<!--"; - const char* endTag = "-->"; - - if ( !StringEqual( p, startTag, false, encoding ) ) - { - if ( document ) - document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding ); - return 0; - } - p += strlen( startTag ); - - // [ 1475201 ] TinyXML parses entities in comments - // Oops - ReadText doesn't work, because we don't want to parse the entities. - // p = ReadText( p, &value, false, endTag, false, encoding ); - // - // from the XML spec: - /* - [Definition: Comments may appear anywhere in a document outside other markup; in addition, - they may appear within the document type declaration at places allowed by the grammar. - They are not part of the document's character data; an XML processor MAY, but need not, - make it possible for an application to retrieve the text of comments. For compatibility, - the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity - references MUST NOT be recognized within comments. - - An example of a comment: - - <!-- declarations for <head> & <body> --> - */ + TiXmlDocument* document = GetDocument(); + value = ""; + + p = SkipWhiteSpace( p, encoding ); + + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } + const char* startTag = "<!--"; + const char* endTag = "-->"; + + if ( !StringEqual( p, startTag, false, encoding ) ) { + if ( document ) + document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding ); + return 0; + } + p += strlen( startTag ); + + // [ 1475201 ] TinyXML parses entities in comments + // Oops - ReadText doesn't work, because we don't want to parse the entities. + // p = ReadText( p, &value, false, endTag, false, encoding ); + // + // from the XML spec: + /* + [Definition: Comments may appear anywhere in a document outside other markup; in addition, + they may appear within the document type declaration at places allowed by the grammar. + They are not part of the document's character data; an XML processor MAY, but need not, + make it possible for an application to retrieve the text of comments. For compatibility, + the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity + references MUST NOT be recognized within comments. + + An example of a comment: + + <!-- declarations for <head> & <body> --> + */ value = ""; - // Keep all the white space. - while ( p && *p && !StringEqual( p, endTag, false, encoding ) ) - { - value.append( p, 1 ); - ++p; - } - if ( p && *p ) - p += strlen( endTag ); - - return p; + // Keep all the white space. + while ( p && *p && !StringEqual( p, endTag, false, encoding ) ) { + value.append( p, 1 ); + ++p; + } + if ( p && *p ) + p += strlen( endTag ); + + return p; } const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) return 0; - - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } - // Read the name, the '=' and the value. - const char* pErr = p; - p = ReadName( p, &name, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); - return 0; - } - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p || *p != '=' ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } - - ++p; // skip '=' - p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } - - const char* end; - const char SINGLE_QUOTE = '\''; - const char DOUBLE_QUOTE = '\"'; - - if ( *p == SINGLE_QUOTE ) - { - ++p; - end = "\'"; // single quote in string - p = ReadText( p, &value, false, end, false, encoding ); - } - else if ( *p == DOUBLE_QUOTE ) - { - ++p; - end = "\""; // double quote in string - p = ReadText( p, &value, false, end, false, encoding ); - } - else - { - // All attribute values should be in single or double quotes. - // But this is such a common error that the parser will try - // its best, even without them. - value = ""; - while ( p && *p // existence - && !IsWhiteSpace( *p ) // whitespace - && *p != '/' && *p != '>' ) // tag end - { - if ( *p == SINGLE_QUOTE || *p == DOUBLE_QUOTE ) { - // [ 1451649 ] Attribute values with trailing quotes not handled correctly - // We did not have an opening quote but seem to have a - // closing one. Give up and throw an error. - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; - } - value += *p; - ++p; - } - } - return p; + p = SkipWhiteSpace( p, encoding ); + if ( !p || !*p ) return 0; + + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } + // Read the name, the '=' and the value. + const char* pErr = p; + p = ReadName( p, &name, encoding ); + if ( !p || !*p ) { + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); + return 0; + } + p = SkipWhiteSpace( p, encoding ); + if ( !p || !*p || *p != '=' ) { + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); + return 0; + } + + ++p; // skip '=' + p = SkipWhiteSpace( p, encoding ); + if ( !p || !*p ) { + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); + return 0; + } + + const char* end; + const char SINGLE_QUOTE = '\''; + const char DOUBLE_QUOTE = '\"'; + + if ( *p == SINGLE_QUOTE ) { + ++p; + end = "\'"; // single quote in string + p = ReadText( p, &value, false, end, false, encoding ); + } else if ( *p == DOUBLE_QUOTE ) { + ++p; + end = "\""; // double quote in string + p = ReadText( p, &value, false, end, false, encoding ); + } else { + // All attribute values should be in single or double quotes. + // But this is such a common error that the parser will try + // its best, even without them. + value = ""; + while ( p && *p // existence + && !IsWhiteSpace( *p ) // whitespace + && *p != '/' && *p != '>' ) { // tag end + if ( *p == SINGLE_QUOTE || *p == DOUBLE_QUOTE ) { + // [ 1451649 ] Attribute values with trailing quotes not handled correctly + // We did not have an opening quote but seem to have a + // closing one. Give up and throw an error. + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); + return 0; + } + value += *p; + ++p; + } + } + return p; } #ifdef TIXML_USE_STL void TiXmlText::StreamIn( std::istream * in, TIXML_STRING * tag ) { - while ( in->good() ) - { - int c = in->peek(); - if ( !cdata && (c == '<' ) ) - { - return; - } - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - - (*tag) += (char) c; - in->get(); // "commits" the peek made above - - if ( cdata && c == '>' && tag->size() >= 3 ) { - size_t len = tag->size(); - if ( (*tag)[len-2] == ']' && (*tag)[len-3] == ']' ) { - // terminator of cdata. - return; - } - } - } + while ( in->good() ) { + int c = in->peek(); + if ( !cdata && (c == '<' ) ) { + return; + } + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + + (*tag) += (char) c; + in->get(); // "commits" the peek made above + + if ( cdata && c == '>' && tag->size() >= 3 ) { + size_t len = tag->size(); + if ( (*tag)[len-2] == ']' && (*tag)[len-3] == ']' ) { + // terminator of cdata. + return; + } + } + } } #endif const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { - value = ""; - TiXmlDocument* document = GetDocument(); - - if ( data ) - { - data->Stamp( p, encoding ); - location = data->Cursor(); - } - - const char* const startTag = "<![CDATA["; - const char* const endTag = "]]>"; - - if ( cdata || StringEqual( p, startTag, false, encoding ) ) - { - cdata = true; - - if ( !StringEqual( p, startTag, false, encoding ) ) - { - if ( document ) - document->SetError( TIXML_ERROR_PARSING_CDATA, p, data, encoding ); - return 0; - } - p += strlen( startTag ); - - // Keep all the white space, ignore the encoding, etc. - while ( p && *p - && !StringEqual( p, endTag, false, encoding ) - ) - { - value += *p; - ++p; - } - - TIXML_STRING dummy; - p = ReadText( p, &dummy, false, endTag, false, encoding ); - return p; - } - else - { - bool ignoreWhite = true; - - const char* end = "<"; - p = ReadText( p, &value, ignoreWhite, end, false, encoding ); - if ( p && *p ) - return p-1; // don't truncate the '<' - return 0; - } + value = ""; + TiXmlDocument* document = GetDocument(); + + if ( data ) { + data->Stamp( p, encoding ); + location = data->Cursor(); + } + + const char* const startTag = "<![CDATA["; + const char* const endTag = "]]>"; + + if ( cdata || StringEqual( p, startTag, false, encoding ) ) { + cdata = true; + + if ( !StringEqual( p, startTag, false, encoding ) ) { + if ( document ) + document->SetError( TIXML_ERROR_PARSING_CDATA, p, data, encoding ); + return 0; + } + p += strlen( startTag ); + + // Keep all the white space, ignore the encoding, etc. + while ( p && *p + && !StringEqual( p, endTag, false, encoding ) + ) { + value += *p; + ++p; + } + + TIXML_STRING dummy; + p = ReadText( p, &dummy, false, endTag, false, encoding ); + return p; + } else { + bool ignoreWhite = true; + + const char* end = "<"; + p = ReadText( p, &value, ignoreWhite, end, false, encoding ); + if ( p && *p ) + return p-1; // don't truncate the '<' + return 0; + } } #ifdef TIXML_USE_STL void TiXmlDeclaration::StreamIn( std::istream * in, TIXML_STRING * tag ) { - while ( in->good() ) - { - int c = in->get(); - if ( c <= 0 ) - { - TiXmlDocument* document = GetDocument(); - if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); - return; - } - (*tag) += (char) c; - - if ( c == '>' ) - { - // All is well. - return; - } - } + while ( in->good() ) { + int c = in->get(); + if ( c <= 0 ) { + TiXmlDocument* document = GetDocument(); + if ( document ) + document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + return; + } + (*tag) += (char) c; + + if ( c == '>' ) { + // All is well. + return; + } + } } #endif const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding _encoding ) { - p = SkipWhiteSpace( p, _encoding ); - // Find the beginning, find the end, and look for - // the stuff in-between. - TiXmlDocument* document = GetDocument(); - if ( !p || !*p || !StringEqual( p, "<?xml", true, _encoding ) ) - { - if ( document ) document->SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding ); - return 0; - } - if ( data ) - { - data->Stamp( p, _encoding ); - location = data->Cursor(); - } - p += 5; - - version = ""; - encoding = ""; - standalone = ""; - - while ( p && *p ) - { - if ( *p == '>' ) - { - ++p; - return p; - } - - p = SkipWhiteSpace( p, _encoding ); - if ( StringEqual( p, "version", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - version = attrib.Value(); - } - else if ( StringEqual( p, "encoding", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - encoding = attrib.Value(); - } - else if ( StringEqual( p, "standalone", true, _encoding ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data, _encoding ); - standalone = attrib.Value(); - } - else - { - // Read over whatever it is. - while( p && *p && *p != '>' && !IsWhiteSpace( *p ) ) - ++p; - } - } - return 0; + p = SkipWhiteSpace( p, _encoding ); + // Find the beginning, find the end, and look for + // the stuff in-between. + TiXmlDocument* document = GetDocument(); + if ( !p || !*p || !StringEqual( p, "<?xml", true, _encoding ) ) { + if ( document ) document->SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding ); + return 0; + } + if ( data ) { + data->Stamp( p, _encoding ); + location = data->Cursor(); + } + p += 5; + + version = ""; + encoding = ""; + standalone = ""; + + while ( p && *p ) { + if ( *p == '>' ) { + ++p; + return p; + } + + p = SkipWhiteSpace( p, _encoding ); + if ( StringEqual( p, "version", true, _encoding ) ) { + TiXmlAttribute attrib; + p = attrib.Parse( p, data, _encoding ); + version = attrib.Value(); + } else if ( StringEqual( p, "encoding", true, _encoding ) ) { + TiXmlAttribute attrib; + p = attrib.Parse( p, data, _encoding ); + encoding = attrib.Value(); + } else if ( StringEqual( p, "standalone", true, _encoding ) ) { + TiXmlAttribute attrib; + p = attrib.Parse( p, data, _encoding ); + standalone = attrib.Value(); + } else { + // Read over whatever it is. + while( p && *p && *p != '>' && !IsWhiteSpace( *p ) ) + ++p; + } + } + return 0; } bool TiXmlText::Blank() const { - for ( unsigned i=0; i<value.length(); i++ ) - if ( !IsWhiteSpace( value[i] ) ) - return false; - return true; + for ( unsigned i=0; i<value.length(); i++ ) + if ( !IsWhiteSpace( value[i] ) ) + return false; + return true; }