Biomechanical Joint Model
 Author: Anderson Maciel

comexml.cpp

Go to the documentation of this file.
00001 /***************************************************************************
00002  *   Copyright (C) 2002 by Anderson Maciel                                 *
00003  *   andi.maciel@gmail.com                                                 *
00004  *                                                                         *
00005  *   This program is free software; you can redistribute it and/or modify  *
00006  *   it under the terms of the GNU General Public License as published by  *
00007  *   the Free Software Foundation; either version 2 of the License, or     *
00008  *   (at your option) any later version.                                   *
00009  *                                                                         *
00010  *   This program is distributed in the hope that it will be useful,       *
00011  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
00012  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
00013  *   GNU General Public License for more details.                          *
00014  *                                                                         *
00015  *   You should have received a copy of the GNU General Public License     *
00016  *   along with this program; if not, write to the                         *
00017  *   Free Software Foundation, Inc.,                                       *
00018  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
00019  **************************************************************************/
00020 
00022 //
00023 //  PROJECT.....: CO-ME
00024 //  RESPONSIBLE.: 
00025 //
00026 //  AUTHOR......: Anderson Maciel
00027 //  DATE........: September/03/2002
00028 //  DESCRIPTION.: COME_Xml class methods definition.
00029 //
00031 
00032 
00033 #include        <general/come.h>
00034 #include        <general/comexml.h>
00035 #include        <general/comesimulator.h>
00036 #include        <general/comescenario.h>
00037 #include        <bio/comemolecule.h>
00038 #include        <bio/comemoleculescartilage.h>
00039 #include        <bio/comemoleculesbone.h>
00040 #include        <physics/cometimeforce.h>
00041 #include        <kinematics/comepolyaxialjoint.h>
00042 #include        <kinematics/comedof.h>
00043 #include        <kinematics/comemodifier.h>
00044 #include        <kinematics/comemovement.h>
00045 
00046 #include        <xercesc/dom/DOM.hpp>
00047 #include        <xercesc/util/XercesDefs.hpp>
00048 #include        <xercesc/util/PlatformUtils.hpp>
00049 
00050 #ifndef _WIN32
00051 #include        <xercesc/util/Platforms/Linux/LinuxDefs.hpp>
00052 else
00053 #include        <xercesc/util/Platforms/Win32/Win32Defs.hpp>
00054 #endif
00055 
00056 #include        <xercesc/util/XMLString.hpp>
00057 #include        <xercesc/sax/SAXException.hpp>
00058 #include        <xercesc/sax/SAXParseException.hpp>
00059 #include        <xercesc/parsers/XercesDOMParser.hpp>
00060 #include        <xercesc/dom/DOMException.hpp>
00061 #include        <xercesc/framework/LocalFileFormatTarget.hpp>
00062 
00063 #include        <string.h>
00064 #include        <stdlib.h>
00065 #include        <stdio.h>
00066 #include        <math.h>
00067 
00068 using namespace XERCES_CPP_NAMESPACE;
00069 
00070 // Header to avoid multiple definition of ostream
00071 ostream& operator<<(ostream& target, const StrX& toDump);
00072 
00074 COME_Xml::COME_Xml(){
00075 
00076         // Never free this vector because it will be used by molecules
00077         materials = new vector<COME_Material*>;
00078 
00079 }
00080 
00081 COME_Xml::COME_Xml( vector<COME_Material*>* existentMaterials ){
00082 
00083         materials = existentMaterials;
00084 
00085 }
00086 
00088 COME_Xml::~COME_Xml(){
00089 
00090 }
00091 
00092 vector<COME_Material*>*
00093 COME_Xml::getAllMaterials(){
00094 
00095         return materials;
00096 }
00097 
00098 void
00099 COME_Xml::loadMaterialsFile( string fileName, list<COME_Patient*> &patientL, COME_Simulator *simulator, COME_Scenario *parentScene ){
00100 
00101 
00102     // Initialize the XML4C system
00103     try
00104     {
00105         XMLPlatformUtils::Initialize();
00106     }
00107 
00108     catch (const XMLException& toCatch)
00109     {
00110          printf( "Error during initialization! : %s\n", toCatch.getMessage() );
00111          return;
00112     }
00113 
00114     XercesDOMParser::ValSchemes    valScheme = XercesDOMParser::Val_Auto; //Val_Never Val_Always
00115     bool                     doNamespaces    = false;
00116 
00117     // Instantiate the DOM parser.
00118     XercesDOMParser parser;
00119     parser.setValidationScheme(valScheme);
00120     parser.setDoNamespaces(doNamespaces);
00121 
00122     // And create our error handler and install it
00123     DOMCountErrorHandler errorHandler;
00124     parser.setErrorHandler(&errorHandler);
00125 
00126     //
00127     //  Get the starting time and kick off the parse of the indicated
00128     //  file. Catch any exceptions that might propogate out of it.
00129     //
00130     unsigned long duration;
00131     try
00132     {
00133         const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
00134         parser.parse( fileName.c_str() );
00135         const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
00136         duration = endMillis - startMillis;
00137     }
00138 
00139     catch (const XMLException& toCatch)
00140     {
00141         cerr << "\nError during parsing: '" << fileName << "'\n"
00142              << "Exception message is:  \n"
00143              << StrX(toCatch.getMessage()) << "\n" << endl;
00144         return;
00145     }
00146     catch (const DOMException& toCatch)
00147     {
00148         cerr << "\nError during parsing: '" << fileName << "'\n"
00149              << "Exception message is:  \n"
00150              << toCatch.msg << "\n" << endl;
00151         XMLPlatformUtils::Terminate();
00152         return;
00153     }
00154     catch (...)
00155     {
00156        cerr << "\nUnexpected exception during parsing: '" << fileName << "'\n";
00157         XMLPlatformUtils::Terminate();
00158         return;
00159     }
00160 
00161     //
00162     //  Extract the DOM tree, get the list of all the elements and report the
00163     //  length as the count of elements.
00164     //
00165     if (errorHandler.getSawErrors())
00166     {
00167         printf( "\nErrors occured, no output available\n" );
00168     }
00169      else
00170     {
00172         DOMDocument *doc = parser.getDocument();
00173         unsigned int elementCount = doc->getElementsByTagName(XMLString::transcode("*"))->getLength();
00174                         
00176         root = doc->getDocumentElement();
00177         if( strcmp( XMLString::transcode(root->getTagName()), "come" ) ){
00178                 printf( "Invalid XML file.\n" );
00179                 exit(0);
00180         }
00181 
00182         simulatorXml = simulator;
00183 
00184         DOMNodeList *materialNodes = root->getElementsByTagName( XMLString::transcode("material") );
00185 
00186         loadMaterials( materialNodes );
00187     }
00188     return;
00189 }
00190 
00191 COME_BioStructure*
00192 COME_Xml::loadOrganFile( string fileName, list<COME_Patient*> &patientL, COME_Simulator *simulator, COME_Scenario *parentScene ){
00193 
00194 
00195     // Initialize the XML4C system
00196     try
00197     {
00198         XMLPlatformUtils::Initialize();
00199     }
00200 
00201     catch (const XMLException& toCatch)
00202     {
00203          printf( "Error during initialization! : %s\n", toCatch.getMessage() );
00204          return NULL;
00205     }
00206 
00207     XercesDOMParser::ValSchemes    valScheme = XercesDOMParser::Val_Auto; //Val_Never Val_Always
00208     bool                     doNamespaces    = false;
00209 
00210     // Instantiate the DOM parser.
00211     XercesDOMParser parser;
00212     parser.setValidationScheme(valScheme);
00213     parser.setDoNamespaces(doNamespaces);
00214 
00215     // And create our error handler and install it
00216     DOMCountErrorHandler errorHandler;
00217     parser.setErrorHandler(&errorHandler);
00218 
00219     //
00220     //  Get the starting time and kick off the parse of the indicated
00221     //  file. Catch any exceptions that might propogate out of it.
00222     //
00223     unsigned long duration;
00224     try
00225     {
00226         const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
00227         parser.parse( fileName.c_str() );
00228         const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
00229         duration = endMillis - startMillis;
00230     }
00231 
00232     catch (const XMLException& toCatch)
00233     {
00234         cerr << "\nError during parsing: '" << fileName << "'\n"
00235              << "Exception message is:  \n"
00236              << StrX(toCatch.getMessage()) << "\n" << endl;
00237         return NULL;
00238     }
00239     catch (const DOMException& toCatch)
00240     {
00241         cerr << "\nError during parsing: '" << fileName << "'\n"
00242              << "Exception message is:  \n"
00243              << toCatch.msg << "\n" << endl;
00244         XMLPlatformUtils::Terminate();
00245         return NULL;
00246     }
00247     catch (...)
00248     {
00249        cerr << "\nUnexpected exception during parsing: '" << fileName << "'\n";
00250         XMLPlatformUtils::Terminate();
00251         return NULL;
00252     }
00253 
00254     //
00255     //  Extract the DOM tree, get the list of all the elements and report the
00256     //  length as the count of elements.
00257     //
00258     if (errorHandler.getSawErrors())
00259     {
00260         printf( "\nErrors occured, no output available\n" );
00261     }
00262      else
00263     {
00265         DOMDocument *doc = parser.getDocument();
00266         unsigned int elementCount = doc->getElementsByTagName(XMLString::transcode("*"))->getLength();
00267                         
00269         root = doc->getDocumentElement();
00270         if( strcmp( XMLString::transcode(root->getTagName()), "come" ) ){
00271                 printf( "Invalid XML file.\n" );
00272                 exit(0);
00273         }
00274 
00275         simulatorXml = simulator;
00276 
00277         DOMNodeList *organs = root->getElementsByTagName( XMLString::transcode("molecule_organ") );
00278 
00279         return loadShapes( organs )[0];
00280     }
00281     return NULL;
00282 }       
00283 
00284 void
00285 COME_Xml::loadSceneFile( string fileName, list<COME_Patient*> &patientL, COME_Simulator *simulator, COME_Scenario *parentScene ){
00286 
00287 
00288     // Initialize the XML4C systemvoid
00289     try
00290     {
00291         XMLPlatformUtils::Initialize();
00292     }
00293 
00294     catch (const XMLException& toCatch)
00295     {
00296          printf( "Error during initialization! : %s\n", toCatch.getMessage() );
00297          return;
00298     }
00299 
00300     XercesDOMParser::ValSchemes    valScheme = XercesDOMParser::Val_Auto; //Val_Never Val_Always
00301     bool                     doNamespaces    = false;
00302 
00303     // Instantiate the DOM parser.
00304     XercesDOMParser parser;
00305     parser.setValidationScheme(valScheme);
00306     parser.setDoNamespaces(doNamespaces);
00307 
00308     // And create our error handler and install it
00309     DOMCountErrorHandler errorHandler;
00310     parser.setErrorHandler(&errorHandler);
00311 
00312     //
00313     //  Get the starting time and kick off the parse of the indicated
00314     //  file. Catch any exceptions that might propogate out of it.
00315     //
00316     unsigned long duration;
00317     try
00318     {
00319         const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
00320         parser.parse( fileName.c_str() );
00321         const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
00322         duration = endMillis - startMillis;
00323     }
00324 
00325     catch (const XMLException& toCatch)
00326     {
00327         cerr << "\nError during parsing: '" << fileName << "'\n"
00328              << "Exception message is:  \n"
00329              << StrX(toCatch.getMessage()) << "\n" << endl;
00330         return;
00331     }
00332     catch (const DOMException& toCatch)
00333     {
00334         cerr << "\nError during parsing: '" << fileName << "'\n"
00335              << "Exception message is:  \n"
00336              << toCatch.msg << "\n" << endl;
00337         XMLPlatformUtils::Terminate();
00338         return;
00339     }
00340     catch (...)
00341     {
00342        cerr << "\nUnexpected exception during parsing: '" << fileName << "'\n";
00343         XMLPlatformUtils::Terminate();
00344         return;
00345     }
00346 
00347     //
00348     //  Extract the DOM tree, get the list of all the elements and report the
00349     //  length as the count of elements.
00350     //
00351     if (errorHandler.getSawErrors())
00352     {
00353         printf( "\nErrors occured, no output available\n" );
00354     }
00355      else
00356     {
00358         DOMDocument *doc = parser.getDocument();
00359         unsigned int elementCount = doc->getElementsByTagName(XMLString::transcode("*"))->getLength();
00360                         
00362         root = doc->getDocumentElement();
00363         if( strcmp( XMLString::transcode(root->getTagName()), "come" ) ){
00364                 printf( "Invalid XML file.\n" );
00365                 exit(0);
00366         }
00367 
00368         simulatorXml = simulator;
00369 
00370         DOMNodeList *scene = root->getElementsByTagName( XMLString::transcode("scene") );
00371 
00372         for( int s = 0; s < scene->getLength(); s++ ){
00373         
00374                 if( !XMLString::compareString( scene->item(s)->getNodeName(), XMLString::transcode("scene" ) ) ){
00375                         DOMNamedNodeMap *attr = scene->item(s)->getAttributes();
00376                         double x = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("gX") )->getNodeValue() ) );
00377                         double y = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("gY") )->getNodeValue() ) );
00378                         double z = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("gZ") )->getNodeValue() ) );
00379                         parentScene->setGravity( COME_Vector3D( x, y, z ) );
00380                 }
00381         }
00382 
00383         DOMNodeList *simulation = root->getElementsByTagName( XMLString::transcode("simulation") );
00384 
00385         for( int sim = 0; sim < simulation->getLength(); sim++ ){
00386         
00387                 if( !XMLString::compareString( simulation->item(sim)->getNodeName(), XMLString::transcode("simulation" ) ) ){
00388                         DOMNamedNodeMap *attr = simulation->item(sim)->getAttributes();
00389                         simulator->setFPS( atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("fps") )->getNodeValue() ) ) );
00390                         simulator->setDuration( atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("duration") )->getNodeValue() ) ) );
00391                 }
00392         }
00393 
00394                 
00397         DOMNodeList *patients_forces = scene->item(0)->getChildNodes();
00398                         
00399         for( int i = 0; i < patients_forces->getLength(); i++ ){
00400                 
00401                 // Load patient attributes
00402                 if( !XMLString::compareString( patients_forces->item(i)->getNodeName(), XMLString::transcode("patient" ) ) ){
00403                         DOMNamedNodeMap *attr = patients_forces->item(i)->getAttributes();
00404                         string name = XMLString::transcode( attr->getNamedItem( XMLString::transcode("name") )->getNodeValue());
00405                         bool gender;
00406                         if( !XMLString::compareString(attr->getNamedItem( XMLString::transcode("gender") )->getNodeValue(), XMLString::transcode("M") ) ) {
00407                                 gender = true;
00408                         } else {
00409                                 gender = false;
00410                         }
00411                         float weight = (float)atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("weight") )->getNodeValue() ) );
00412                         float height = (float)atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("height") )->getNodeValue() ) );
00413                         short age = (short)atoi( XMLString::transcode( attr->getNamedItem( XMLString::transcode("age") )->getNodeValue() ) );
00414 
00415                         // Load patient materials
00416                         DOMNodeList *materialNodes = patients_forces->item(i)->getChildNodes();
00417                                                         
00418                         for( int io = 0; io < materialNodes->getLength(); io++ ){
00419 
00420                                 if( !XMLString::compareString( materialNodes->item(io)->getNodeName(), XMLString::transcode("materials" ) ) ){
00421 
00422                                         // Load patient materials
00423                                         DOMNodeList *materials_list = materialNodes->item(io)->getChildNodes();
00424                                         loadMaterials( materials_list );
00425                                 }
00426                         }
00427 
00429                         list<COME_BioStructure*> organList;
00430 
00432                         DOMNodeList *joints = root->getElementsByTagName(XMLString::transcode("joint"));
00433                         COME_Joint *rootJoint;
00434 
00435                         for( int ij = 0; ij < joints->getLength(); ij++ ){
00436                                 DOMNamedNodeMap *attr = joints->item(ij)->getAttributes();
00437                                 if( !XMLString::compareString( attr->getNamedItem( XMLString::transcode("description" ) )->getNodeValue(), XMLString::transcode("root") ) ){
00438                                         auxVec = new COME_Dof*[joints->getLength()*6];
00439                                         iIndDofAux = 0;
00440                                         rootJoint = loadJoint( joints->item(ij), NULL, organList );
00441                                         loadModifiers( joints );
00442                                         delete [] auxVec;
00443                                         break;
00444                                 }
00445                         }
00446 
00447                         // Build patient
00448                         COME_Patient* patientN = new COME_Patient( name, age, gender, weight, height, rootJoint, organList, parentScene );
00449 
00450                         // Add patient to the list
00451                         patientL.clear();
00452                         patientL.push_back( patientN );
00453                                                 
00454                 } 
00455                         // FUTURE IMPLEMENTATION
00456                         // Load global forces (gravity, etc.)           
00457                         //DOMNodeList *gForces = scene->getElementsByTagName("global_forces");
00458                                                                 
00459         }
00460 
00462         // Print out the stats that we collected and time taken.
00463         cout << fileName << ": " << duration << " ms ("
00464              << elementCount << " elems)." << endl;
00465     }
00466     // And call the termination method
00467     //XMLPlatformUtils::Terminate();
00468 
00469     return;
00470 }
00471 
00472 COME_Joint*
00473 COME_Xml::loadJoint( DOMNode *node, COME_Joint *parent, list<COME_BioStructure*> &patientOrganList ){
00474 
00476         DOMNamedNodeMap *attrNode = node->getAttributes();
00477         DOMNodeList *dofs_shapes = node->getChildNodes();
00478         COME_Dof *dofAux = loadDofs( dofs_shapes );
00479         COME_Joint *newJoint = NULL;
00480         
00481         if( !XMLString::compareString( attrNode->getNamedItem( XMLString::transcode("type") )->getNodeValue() , XMLString::transcode("plane") ) ){
00482                 //newJoint = new COME_PlaneJoint( parent, &(dofAux[0]), &(dofAux[1]), &(dofAux[2]), &(dofAux[3]), &(dofAux[4]), &(dofAux[5]) );
00483         } else if( !XMLString::compareString( attrNode->getNamedItem( XMLString::transcode("type") )->getNodeValue() , XMLString::transcode("uniaxial") ) ){
00484                 //newJoint = new COME_UniaxialJoint( parent, &(dofAux[0]) );
00485         } else if( !XMLString::compareString( attrNode->getNamedItem( XMLString::transcode("type") )->getNodeValue() , XMLString::transcode("biaxial") ) ){
00486                 //newJoint = new COME_BiaxialJoint( parent, &(dofAux[0]), &(dofAux[1]) );
00487         } else if( !XMLString::compareString( attrNode->getNamedItem( XMLString::transcode("type") )->getNodeValue() , XMLString::transcode("triaxial") ) ){
00488                 newJoint = new COME_PolyaxialJoint( parent, &(dofAux[0]), &(dofAux[1]), &(dofAux[2]) );
00489         } else if( !XMLString::compareString( attrNode->getNamedItem( XMLString::transcode("type") )->getNodeValue() , XMLString::transcode("noaxial") ) ){
00490                 newJoint = new COME_PolyaxialJoint( parent );
00491         }
00492         newJoint->setDescription( XMLString::transcode( attrNode->getNamedItem( XMLString::transcode( "description") )->getNodeValue() ) );
00493 
00494         vector<COME_BioStructure*> shapeAux = loadShapes( dofs_shapes );
00495         for( int i = 0; i < shapeAux.size(); i++ ){
00496                 newJoint->vpAddShape( shapeAux[ i ] );
00497                 patientOrganList.push_back( shapeAux[ i ] );
00498         }
00499         
00501         DOMNodeList *joints = root->getElementsByTagName( XMLString::transcode("joint") );
00502         for( int j = 0; j < joints->getLength(); j++ ){
00503                 DOMNamedNodeMap *attrAux = joints->item(j)->getAttributes();
00504                 if( !XMLString::compareString( attrAux->getNamedItem( XMLString::transcode("parent") )->getNodeValue(), attrNode->getNamedItem( XMLString::transcode("description") )->getNodeValue() ) ){
00505                         COME_Joint* auxJoint = loadJoint( joints->item(j), newJoint, patientOrganList );
00506                         newJoint->vpAddChild( auxJoint );
00507                 }
00508         }
00509         return newJoint;
00510 }
00511 
00512 COME_Dof*
00513 COME_Xml::loadDofs( DOMNodeList *paramList ){
00514 
00516         COME_Dof* listDof = new COME_Dof[6];
00517         int idof = 0;
00518         for( int i = 0; i < paramList->getLength(); i++ ){
00519                 if( !XMLString::compareString( paramList->item(i)->getNodeName(), XMLString::transcode( "dof") ) ){
00521                         COME_Vector3D axis;
00522                         COME_Point3D position;
00523                         COME_Curve* evoluta = new COME_Bezier();
00524                         float min = 0.0, max = 0.0 , curr = 0.0, rest = 0.0;
00525                         DOMNodeList *dof = paramList->item(i)->getChildNodes();
00526                         for( int j = 0; j < dof->getLength(); j++ ){
00527                                 if( !XMLString::compareString( dof->item(j)->getNodeName(), XMLString::transcode( "position") ) ){
00528                                         DOMNamedNodeMap *attrPos = dof->item(j)->getAttributes();
00529                                         position = COME_Point3D( (float)atof( XMLString::transcode( attrPos->getNamedItem( XMLString::transcode("x") )->getNodeValue() ) ),
00530                                                                                          (float)atof( XMLString::transcode( attrPos->getNamedItem( XMLString::transcode("y") )->getNodeValue() ) ),
00531                                                                                          (float)atof( XMLString::transcode( attrPos->getNamedItem( XMLString::transcode("z") )->getNodeValue() ) )
00532                                                                                         );
00533                                 } else if( !XMLString::compareString( dof->item(j)->getNodeName(), XMLString::transcode( "axis") )  ){
00534                                         DOMNamedNodeMap *attrAxis = dof->item(j)->getAttributes();
00535                                         axis = COME_Vector3D( (float)atof( XMLString::transcode( attrAxis->getNamedItem( XMLString::transcode("x") )->getNodeValue() ) ),
00536                                                                                   (float)atof( XMLString::transcode( attrAxis->getNamedItem( XMLString::transcode("y") )->getNodeValue() ) ),
00537                                                                                   (float)atof( XMLString::transcode( attrAxis->getNamedItem( XMLString::transcode("z") )->getNodeValue() ) )
00538                                                                                 );
00539                                 } else if( !XMLString::compareString( dof->item(j)->getNodeName(), XMLString::transcode( "range") )  ){
00540                                         DOMNamedNodeMap *attrRange = dof->item(j)->getAttributes();
00541                                         min = (float)atof( XMLString::transcode( attrRange->getNamedItem( XMLString::transcode("min") )->getNodeValue() ) );
00542                                         max = (float)atof( XMLString::transcode( attrRange->getNamedItem( XMLString::transcode("max") )->getNodeValue() ) );
00543                                 } else if( !XMLString::compareString( dof->item(j)->getNodeName(), XMLString::transcode( "evoluta") )  ){
00544                                         DOMNodeList *pts = dof->item(j)->getChildNodes();
00545                                         COME_Vertex3D*  ctrlPts = new COME_Vertex3D[4];
00546                                         int cp = 0;
00547                                         for( int k = 0; k < pts->getLength(); k++ ){
00548                                                 if( !XMLString::compareString( pts->item(k)->getNodeName(), XMLString::transcode("ctrl_point") ) ){
00549                                                 DOMNamedNodeMap *attrPt = pts->item(k)->getAttributes();
00550                                                 ctrlPts[cp++].setXYZ( (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("x") )->getNodeValue() ) ),
00551                                                                                           (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("y") )->getNodeValue() ) ),
00552                                                                                           (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("z") )->getNodeValue() ) )
00553                                                                                         );
00554                                                 }
00555                                         }
00556                                         evoluta = new COME_Bezier( ctrlPts );
00557                                 }
00558                         }
00560                         listDof[idof] = COME_Dof( axis, position, evoluta, min, max, curr, rest );
00561                         DOMNamedNodeMap *attrAux = paramList->item(i)->getAttributes();
00562                         listDof[idof].setDescription( XMLString::transcode( attrAux->getNamedItem( XMLString::transcode("description") )->getNodeValue() ) );
00563                         listDof[idof].vpRest();
00564                         
00565                         //put dof in the temporary list for modifiers
00566                         auxVec[iIndDofAux++] = &(listDof[idof]);
00567                         
00568                         idof++;
00569                 }
00570         }
00571         return listDof;
00572 }
00573 
00574 // Load patient molecule organs
00575 vector<COME_BioStructure*>
00576 COME_Xml::loadShapes( DOMNodeList *paramList ){
00577 
00578         vector<COME_BioStructure*> organList;
00579 
00580         for( int i = 0; i < paramList->getLength(); i++ ){
00581 
00582                 if( !XMLString::compareString( paramList->item(i)->getNodeName(), XMLString::transcode( "molecule_organ") ) ){
00583 
00584                         COME_BioStructure *tempOrgan = loadMoleculeOrgan( paramList->item(i) );
00585                         DOMNamedNodeMap *attr = paramList->item(i)->getAttributes();
00586                         string fileMesh = XMLString::transcode( attr->getNamedItem( XMLString::transcode("mesh_file") )->getNodeValue() );
00587                         if( !( fileMesh.find( COME::baseFolder, 0 ) == 0 ) )
00588                                 fileMesh = COME::baseFolder + "/" + fileMesh;
00589                         string fileTexture = COME::baseFolder + "/" + XMLString::transcode( attr->getNamedItem( XMLString::transcode("texture_file") )->getNodeValue() );
00590                         string descOrgan = XMLString::transcode( attr->getNamedItem( XMLString::transcode("description") )->getNodeValue() );
00591                         string fileDeformation = XMLString::transcode( attr->getNamedItem( XMLString::transcode("deformation_file") )->getNodeValue() );
00592                         
00593                         if( fileDeformation.size() == 0 )
00594                                 fileDeformation = fileMesh;
00595 
00596                         if( !( fileDeformation.find( COME::baseFolder, 0 ) == 0 ) )
00597                                 fileDeformation = COME::baseFolder + "/" + fileDeformation;
00598 
00599                         if( fileDeformation.find( ".vtk", 0 ) != string::npos ){
00600                                 string tempStr( fileDeformation, 0, fileDeformation.size()-4 );
00601                                 fileDeformation = tempStr + "points.dat";
00602                         } else if( fileDeformation.find( ".iv", 0 ) != string::npos ){
00603                                 string tempStr( fileDeformation, 0, fileDeformation.size()-3 );
00604                                 fileDeformation = tempStr + "points.dat";
00605                         }
00606                         
00607                         double fileScaleFactor = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("mesh_scale_factor") )->getNodeValue() ) );
00608                         double fileTansX = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("mesh_translate_X") )->getNodeValue() ) );
00609                         double fileTansY = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("mesh_translate_Y") )->getNodeValue() ) );
00610                         double fileTansZ = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("mesh_translate_Z") )->getNodeValue() ) );
00611                         double fileCollisionRadius = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("collision_radius") )->getNodeValue() ) );
00612         
00613                         tempOrgan->setDescription(descOrgan);
00614                         tempOrgan->setCollisionRadius(fileCollisionRadius);
00615                         
00616                         DOMNodeList *internals = paramList->item(i)->getChildNodes();
00617                         for( int ip = 0; ip < internals->getLength(); ip++ ){
00618                                 if( !XMLString::compareString( internals->item(ip)->getNodeName(), XMLString::transcode( "internals") ) ){
00619                                         
00620                                         DOMNodeList *internal = internals->item(ip)->getChildNodes();
00621                                         for( int iq = 0; iq < internal->getLength(); iq++ ){
00622                                                 if( !XMLString::compareString( internal->item(iq)->getNodeName(), XMLString::transcode( "internal") ) ){
00623                                                         DOMNamedNodeMap *attrInt = internal->item(iq)->getAttributes();
00624                                                         string intDesc = XMLString::transcode( attrInt->getNamedItem( XMLString::transcode("description") )->getNodeValue() );
00625                                                         tempOrgan->internalsDesc.push_back( intDesc );
00626                                                 }
00627                                         }
00628                                 }
00629                                 
00630                         }
00631                         
00632                         // Load mesh if it exists
00633                         printf( "fileMesh: %s base: %s \n", fileMesh.c_str(), ( COME::baseFolder + "/" ).c_str() );
00634                         if( fileMesh != ( COME::baseFolder + "/" )  ){
00635                                 COME_Mesh *newSurface = new COME_Mesh();
00636                                 //tempOrgan->getSurface()->loadFile( fileMesh, fileScaleFactor, COME_Point3D( -97.9, 4.5, -25.7 ) );
00637                                 
00638                                 // APPLY ALL TRANSLATIONS
00639                                 COME_Point3D oldhip( -97.9, 4.5, -25.7 );
00640                                 //COME_Point3D labrum( -119.8, 8.535, -34.84 );
00641                                 //COME_Point3D pubofemoral( -118.9, 9, -34.46 );
00642                                 COME_Point3D labrum( 21.9, -4.035, 9.14 );
00643                                 COME_Point3D pubofemoral( 21.0, -4.5, 8.76 );
00644                                 COME_Point3D comedemo( 0.0, 0.0, -2.5 );
00645                                 
00646                                 if( descOrgan == "labrum")
00647                                         newSurface->loadFile( fileMesh, fileScaleFactor, labrum );
00648                                 else if( ( descOrgan == "pubofemoral") || ( descOrgan == "ischiofemoral") )
00649                                         newSurface->loadFile( fileMesh, fileScaleFactor, pubofemoral );
00650                                 else if( descOrgan == "pelviscart")
00651                                         newSurface->loadFile( fileMesh, fileScaleFactor, oldhip );
00652                                 else if( descOrgan == "pelvisbone")
00653                                         newSurface->loadFile( fileMesh, fileScaleFactor, oldhip );
00654                                 else if( descOrgan == "femurcart")
00655                                         newSurface->loadFile( fileMesh, fileScaleFactor, oldhip );
00656                                 else if( descOrgan == "comedemo")
00657                                         newSurface->loadFile( fileMesh, fileScaleFactor, comedemo );
00658                                 else if( descOrgan == "femurbone"){
00659                                         newSurface->loadFile( fileMesh, fileScaleFactor, oldhip ); 
00660                                         //newSurface->translate( 0.117, 0, 0.352 ); ///OPERATION
00661                                 } else {
00662                                         newSurface->loadFile( fileMesh, fileScaleFactor, COME_Point3D( -fileTansX, -fileTansY, -fileTansZ ) );
00663                                 }
00664                                 //if( descOrgan == "ligament"){
00665                                 //      newSurface->rotate( -M_PI/2.0, 0.0, 0.0 );
00666                                 //}
00667                                 
00668                                 if( fileTexture != "" ){
00669                                         newSurface->loadImage( fileTexture );
00670                                 }
00671                                 tempOrgan->setSurface( newSurface );
00672                                 if( !tempOrgan->isFixed() )
00673                                         ((COME_MoleculesCartilage*)tempOrgan)->initializeSkinning();
00674                                 else ((COME_MoleculesBone*)tempOrgan)->initializeSkinning();
00675                                 printf( "skinning initialized \n" );
00676                                 tempOrgan->updateSkin();
00677                                 printf( "skin updated \n" );
00678                         } else {
00679                                 if( !tempOrgan->isFixed() ){
00680                                         ((COME_MoleculesCartilage*)tempOrgan)->initializeSkinning();
00681                                         printf( "skinning initialized \n" );
00682                                         ((COME_MoleculesCartilage*)tempOrgan)->updateSkin();
00683                                         printf( "skin updated \n" );
00684                                 } else {
00685                                         ((COME_MoleculesBone*)tempOrgan)->initializeSkinning();
00686                                         printf( "skinning initialized \n" );
00687                                         ((COME_MoleculesBone*)tempOrgan)->updateSkin();
00688                                         printf( "skin updated \n" );
00689                                 }
00690                         }
00691                         // Load precalculated deformation if it exists.
00692                         // Or set and initialize output file for offline simulation.
00693                         // Or do nothing for normal simulation.
00694                         if( !tempOrgan->isFixed()  ){
00695                                 ((COME_MoleculesCartilage*)tempOrgan)->setDeformationFile( fileDeformation );
00696                         }
00697 
00698                         if( tempOrgan->getGlobalHooke() == 0.0 ){
00699                                 tempOrgan->getTissue()->recalculateAllSpringConstants( simulatorXml->getHowRecalculate(), 0.0 );
00700                                 printf( "Recalculating springs by: %d \n", simulatorXml->getHowRecalculate() );
00701                         }
00702                         organList.push_back( tempOrgan );
00703                 }
00704         }
00705 
00706         return organList;
00707 }
00708 
00709 
00710 void
00711 COME_Xml::loadModifiers( DOMNodeList *joints ){
00712 
00713         for( int i = 0; i < joints->getLength(); i++ ){
00714                 DOMNodeList *xmlDofs = joints->item(i)->getChildNodes();
00715                 for( int j = 0; j < xmlDofs->getLength(); j++ ){
00716                         if( !XMLString::compareString( xmlDofs->item(j)->getNodeName(), XMLString::transcode( "dof") ) ){
00717                                 DOMNamedNodeMap *attrDof = xmlDofs->item(j)->getAttributes();
00718                                 DOMNodeList *xmlModif = xmlDofs->item(j)->getChildNodes();
00719                                 for( int k = 0; k < xmlModif->getLength(); k++ ){
00720                                         if( !XMLString::compareString( xmlModif->item(k)->getNodeName(), XMLString::transcode("modifier") ) ){
00721                                                 DOMNodeList *xmlRelation = xmlModif->item(k)->getChildNodes();
00722                                                 int numRelat = 0;
00723                                                 for( int x = 0; x <     xmlRelation->getLength(); x++ ){
00724                                                 if( !XMLString::compareString( xmlRelation->item(x)->getNodeName(), XMLString::transcode("relation") ) ) numRelat++;
00725                                         }
00726                                         COME_Dof** modifierDof = new COME_Dof*[numRelat];
00727                                         COME_Dof* modifiedDof = NULL;
00728                                         COME_Curve *min = new COME_Curve[numRelat];
00729                                         COME_Curve *max = new COME_Curve[numRelat];
00730                                                 
00731                                         int ll = 0;
00732                                         for( int l = 0; l <     xmlRelation->getLength(); l++ ){
00733                                                 while( XMLString::compareString( xmlRelation->item(l)->getNodeName(), XMLString::transcode("relation") ) ){
00734                                                         l++;
00735                                                         if( l >= xmlRelation->getLength() ) break;
00736                                                 }
00737                                                 if( l >= xmlRelation->getLength() ) break;
00738                                                 DOMNamedNodeMap *attrRelation = xmlRelation->item(l)->getAttributes();
00739                                                 int mm = 0;
00740                                         for( int m = 0; m <     iIndDofAux; m++ ){
00741                                                 if( !XMLString::compareString( attrRelation->getNamedItem( XMLString::transcode("dof") )->getNodeValue(), XMLString::transcode( auxVec[m]->getDescription().c_str() ) ) ){
00742                                                         modifierDof[mm++] = auxVec[m];
00743                                                 }
00744                                                 if( !XMLString::compareString( attrDof->getNamedItem( XMLString::transcode("description") )->getNodeValue(), XMLString::transcode( auxVec[m]->getDescription().c_str() ) ) ){
00745                                                         modifiedDof = auxVec[m];
00746                                                 }
00747                                         }
00748                                         
00749                                         // get the points of the relation curves
00750                                         DOMNodeList *xmlPoints = xmlRelation->item(l)->getChildNodes();
00751                                         COME_Vertex3D*  Ptm = new COME_Vertex3D[4];
00752                                         COME_Vertex3D*  PtM = new COME_Vertex3D[4];
00753                                         int nn = 0;
00754                                 for( int n = 0; n < xmlPoints->getLength(); n++ ){
00755                                         if( !XMLString::compareString( xmlPoints->item(n)->getNodeName(), XMLString::transcode( "ctrl_point") ) ){
00756                                                 DOMNamedNodeMap *attrPt = xmlPoints->item(n)->getAttributes();
00757                                                 if( nn < 4 ){
00758                                 Ptm[nn].setXYZ( (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("x") )->getNodeValue() ) ),
00759                                                                 (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("y") )->getNodeValue() ) ),
00760                                                                 (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("z") )->getNodeValue() ) ) );
00761                         }
00762                         if( nn >= 4 ){
00763                                 PtM[nn-4].setXYZ( (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("x") )->getNodeValue() ) ),
00764                                                                   (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("y") )->getNodeValue() ) ),
00765                                                                   (float)atof( XMLString::transcode( attrPt->getNamedItem( XMLString::transcode("z") )->getNodeValue() ) ) );
00766                         }
00767                         nn++;
00768                 }
00769               }
00770 
00771               min[ll].setControlPoints(Ptm);
00772               max[ll].setControlPoints(PtM);
00773                                         ll++;
00774                                 }
00775                                 // Create and set the modifier
00776                                         COME_Modifier *modif = new COME_Modifier( modifierDof, min, max, numRelat );
00777                                         modifiedDof->setRangeModifier( modif );
00778                                 }
00779                         }
00780                         }
00781                 }
00782         }
00783 }
00784 
00785 
00786 void
00787 COME_Xml::loadMaterials( DOMNodeList *materialList ){
00788 
00789         for( int im = 0; im < materialList->getLength(); im++ ){
00790 
00791                 if( !XMLString::compareString( materialList->item(im)->getNodeName(), XMLString::transcode("material" ) ) ){
00792                         DOMNamedNodeMap *attr = materialList->item(im)->getAttributes();
00794                         string materialDesc;
00795                         materialDesc = XMLString::transcode( attr->getNamedItem( XMLString::transcode("description") )->getNodeValue() );
00796                         
00797                         double cR = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("R") )->getNodeValue() ) );
00798                         double cG = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("G") )->getNodeValue() ) );
00799                         double cB = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("B") )->getNodeValue() ) );
00800                         double damping_const = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("damping_const") )->getNodeValue() ) );
00801                         double density = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("density") )->getNodeValue() ) );
00802                         double youngs_modulus = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("youngs_modulus") )->getNodeValue() ) );
00803                         double medium_density = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("medium_density") )->getNodeValue() ) );
00804                         double liquidFraction = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("liquidFraction") )->getNodeValue() ) );
00805                         double permeability = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("permeability") )->getNodeValue() ) );
00806                         double aI = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("anisoI") )->getNodeValue() ) );
00807                         double aJ = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("anisoJ") )->getNodeValue() ) );
00808                         double aK = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("anisoK") )->getNodeValue() ) );
00809                         double mx_stress = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("max_stress") )->getNodeValue() ) );
00810                         COME_Material *newMaterial = new COME_Material( COME_Vector3D( cR, cG, cB ), density, damping_const, youngs_modulus, medium_density, liquidFraction, permeability, COME_Vector3D( aI, aJ, aK ) );
00811                         newMaterial->setDescription( materialDesc );
00812                         newMaterial->setMaxStress( mx_stress );
00813                         materials->push_back( newMaterial );
00814                 }
00815         }
00816 }
00817 
00818 
00819 
00820 COME_BioStructure *
00821 COME_Xml::loadMoleculeOrgan( DOMNode *node ){
00822         
00823         
00824         COME_BioStructure *organ = NULL;
00825         DOMNodeList *moleculeList = node->getChildNodes();
00826 
00827         int type;
00828         DOMNamedNodeMap *organAtt = node->getAttributes();
00829         if( !XMLString::compareString( organAtt->getNamedItem( XMLString::transcode("type") )->getNodeValue(), XMLString::transcode("cartilage" ) ) ){
00830          
00831                 organ = new COME_MoleculesCartilage();
00832                 type = CARTILAGE;
00833                 organ->setFixed( false );
00834         } else if( !XMLString::compareString( organAtt->getNamedItem( XMLString::transcode("type") )->getNodeValue(), XMLString::transcode("ligament" ) ) ){
00835          
00836                 organ = new COME_MoleculesCartilage();
00837                 type = LIGAMENT;
00838                 organ->setFixed( false );
00839         } else {
00840 
00841                 organ = new COME_MoleculesBone(); //COME_MoleculesCartilage();
00842                 type = BONE;
00843                 organ->setFixed( true );
00844         }
00845         organ->setType( type );
00846 
00847         string description = XMLString::transcode( organAtt->getNamedItem( XMLString::transcode("description") )->getNodeValue() );
00848         organ->setDescription( description );
00849         double globalHooke = atof( XMLString::transcode( organAtt->getNamedItem( XMLString::transcode("global_hooke") )->getNodeValue() ) );
00850         organ->setGlobalHooke( globalHooke );
00851 
00852         for( int im = 0; im < moleculeList->getLength(); im++ ){
00853 
00854                 if( !XMLString::compareString( moleculeList->item(im)->getNodeName(), XMLString::transcode("molecule" ) ) ){
00855                         DOMNamedNodeMap *attr = moleculeList->item(im)->getAttributes();
00856                         string material = XMLString::transcode( attr->getNamedItem( XMLString::transcode("material") )->getNodeValue() );
00857                         double x = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("x") )->getNodeValue() ) );
00858                         double y = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("y") )->getNodeValue() ) );
00859                         double z = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("z") )->getNodeValue() ) );
00860                         double friction_const = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("friction_const") )->getNodeValue() ) );
00861                         double radius = atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("radius") )->getNodeValue() ) );
00862                         string fixed = XMLString::transcode( attr->getNamedItem( XMLString::transcode("fixed") )->getNodeValue() );
00863                         string molecName = XMLString::transcode( attr->getNamedItem( XMLString::transcode("description") )->getNodeValue() );
00864                                                 
00865                         //COME_Point3D position = COME_Point3D( x, y, z ) + COME_Point3D( 0.117, 0, 0.352 ); ///OPERATION
00866                         COME_Point3D position = COME_Point3D( x, y, z );
00867                         
00868                         if( materials->size() == 0 ){
00869                                 materials->push_back( new COME_Material() );
00870                                 (*materials)[0]->setDescription( "empty" );
00871                         }
00872                         
00874                         COME_Molecule *molecule = new COME_Molecule();
00875                         int i;
00876                         for( i = 0; i < materials->size(); i ++ ){
00877                                 if( (*materials)[i]->getDescription() == material ){
00878                                         delete molecule;
00879                                         molecule = new COME_Molecule( position, radius, friction_const, (*materials)[i], COME_Vector3D(), organ );
00880                                         break;
00881                                 }
00882                         }
00883                                                 
00884                         molecule->setDescription( molecName );
00885                         if( fixed == "true" ){
00886 
00887                                 molecule->setFixed(true);
00888                         }
00889                         
00891                         DOMNodeList *forceList = moleculeList->item(im)->getChildNodes();
00892                         for( int iF = 0; iF < forceList->getLength(); iF++ ){
00893                         
00894                                 if( !XMLString::compareString( forceList->item(iF)->getNodeName(), XMLString::transcode("force" ) ) ){
00895                                         DOMNamedNodeMap *attrF = forceList->item(iF)->getAttributes();
00896                                         double xf = atof( XMLString::transcode( attrF->getNamedItem( XMLString::transcode("x") )->getNodeValue() ) );
00897                                         double yf = atof( XMLString::transcode( attrF->getNamedItem( XMLString::transcode("y") )->getNodeValue() ) );
00898                                         double zf = atof( XMLString::transcode( attrF->getNamedItem( XMLString::transcode("z") )->getNodeValue() ) );
00899                                         double t = atof( XMLString::transcode( attrF->getNamedItem( XMLString::transcode("time") )->getNodeValue() ) );
00900                                         COME_TimeForce *force = new COME_TimeForce( xf, yf, zf, t );
00901                                         molecule->addExternalForce( force );
00902                                 }
00903                         }
00904                         if( ( type == CARTILAGE ) || ( type == LIGAMENT ) ){
00905                                 ((COME_MoleculesCartilage*)organ)->getTissue()->addMolecule( molecule );
00906                                 printf( "ADDED MOLECULE \n" );
00907                         } else if( type == BONE ){
00908                                 ((COME_MoleculesBone*)organ)->getTissue()->addMolecule( molecule );
00909                                 //((COME_MoleculesCartilage*)organ)->getTissue()->addMolecule( molecule );
00910                         }
00911 
00912                         //organ->getTissue()->setSurfaceMolecules();
00913 
00915                         if( material == "chain"){
00916                                 organ->getTissue()->chain.molecules.push_back( molecule );
00917                                 organ->getTissue()->chain.updateLengths( 0.0 );
00918                                 organ->getTissue()->chain.setNominal();
00919                         }
00921                 }
00922         }
00923 
00924         return organ;
00925 
00926 }
00927 
00928 //------------------------------------------------------------------------------------------------------------------------
00929 
00930 int
00931 COME_Xml::saveSceneFile( string file_name, const list<COME_Patient*> &patientL, COME_Simulator *simulator) {
00932 
00933         printf("Just came in \n");
00934         // Initialize the XML4C system
00935         try
00936         {
00937                 XMLPlatformUtils::Initialize();
00938         }
00939         
00940         catch (const XMLException& toCatch)
00941         {
00942                 printf( "Error during initialization! : %s\n", toCatch.getMessage() );
00943                 return 0;
00944         }
00945 
00946         XMLCh tempStr[100];
00947         XMLString::transcode("LS", tempStr, 99, XMLPlatformUtils::fgMemoryManager);
00948         DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
00949         DOMWriter* theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
00950 
00951         // Set some features on this serializer
00952         if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true))
00953             theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true);
00954 
00955         if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
00956              theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
00957         
00958         printf("after exception, before funny things \n");
00959 
00960         XMLString::transcode("\n", tempStr, 99);
00961         theSerializer->setNewLine( tempStr );
00962 
00963         // Create document
00964         XMLString::transcode("come", tempStr, 99);
00965         DOMDocumentType *comeDocType = impl->createDocumentType( tempStr, 0, XMLString::transcode("comescene.dtd") );
00966         DOMDocument*   doc = impl->createDocument(0, tempStr, comeDocType );
00967         DOMElement*   come = doc->getDocumentElement();
00968 
00969         char chrPtTemp[100];
00970 
00971         printf("Start adding tags \n");
00972         
00973         // Add scene tag to document
00974         XMLString::transcode("scene", tempStr, 99);
00975         DOMElement*   scene = doc->createElement(tempStr);
00976         come->appendChild(scene);
00977         sprintf( chrPtTemp, "%10.6f", simulator->getScene()->getGravity().getX() ) ;
00978         scene->setAttribute( XMLString::transcode("gX"), XMLString::transcode(chrPtTemp) );
00979         sprintf( chrPtTemp, "%10.6f", simulator->getScene()->getGravity().getX() ) ;
00980         scene->setAttribute( XMLString::transcode("gY"), XMLString::transcode(chrPtTemp) );
00981         sprintf( chrPtTemp, "%10.6f", simulator->getScene()->getGravity().getX() ) ;
00982         scene->setAttribute( XMLString::transcode("gZ"), XMLString::transcode(chrPtTemp) );
00983 
00984         // Add Simulation tag and attributes to document
00985         XMLString::transcode("simulation", tempStr, 99);
00986         DOMElement*   simulation = doc->createElement(tempStr);
00987         scene->appendChild(simulation);
00988                 
00989         sprintf( chrPtTemp, "%10.6f", simulator->getFPS() ) ;
00990         simulation->setAttribute( XMLString::transcode("fps"), XMLString::transcode(chrPtTemp) );
00991         sprintf( chrPtTemp, "%10.6f", simulator->getDuration() ) ;
00992         simulation->setAttribute( XMLString::transcode("duration"), XMLString::transcode(chrPtTemp) );
00993         simulation->setAttribute( XMLString::transcode("cycle"), XMLString::transcode("off") );
00994         simulation->setAttribute( XMLString::transcode("type"), XMLString::transcode("offline") );
00995 
00996         printf("Start adding patient \n" );
00997         // Add patients to document
00998         //   the front of the patient's list is used because there is only one patient in the scene
00999         XMLString::transcode("patient", tempStr, 99);
01000         DOMElement*   patient = doc->createElement(tempStr);
01001         scene->appendChild(patient);
01002                 
01003         patient->setAttribute( XMLString::transcode("name"), XMLString::transcode(patientL.front()->getName().c_str() ) );
01004         if( patientL.front()->getGender() ){
01005                 patient->setAttribute( XMLString::transcode("gender"), XMLString::transcode("M") );
01006         } else {
01007                 patient->setAttribute( XMLString::transcode("gender"), XMLString::transcode("F") );
01008         }
01009         sprintf( chrPtTemp, "%10.6f", patientL.front()->getWeight() );
01010         patient->setAttribute( XMLString::transcode("weight"), XMLString::transcode(chrPtTemp) );
01011         sprintf( chrPtTemp, "%10.6f", patientL.front()->getHeight() );
01012         patient->setAttribute( XMLString::transcode("height"), XMLString::transcode(chrPtTemp) );
01013         sprintf( chrPtTemp, "%d", patientL.front()->getAge() );
01014         patient->setAttribute( XMLString::transcode("age"), XMLString::transcode(chrPtTemp) );
01015 
01016         printf("before savematerials \n" );
01017         saveMaterials( doc, patient, patientL.front() );
01018         
01019         // Add a standard joint just to keep format
01020         XMLString::transcode("joint", tempStr, 99);
01021         DOMElement* joint = doc->createElement(tempStr);
01022         patient->appendChild( joint );
01023         joint->setAttribute( XMLString::transcode("description"), XMLString::transcode("root" ) );
01024         joint->setAttribute( XMLString::transcode("parent"), XMLString::transcode("null" ) );
01025         joint->setAttribute( XMLString::transcode("type"), XMLString::transcode("noaxial" ) );
01026         
01027         // Add MoleculeOrgans of this patient
01028         printf("before savemoleculeorgan \n" );
01029         saveMoleculeOrgan( doc, joint, patientL.front() );
01030         printf("after savemoleculeorgan \n" );
01031 
01032         // StdOutFormatTarget prints the resultant XML stream
01033         // to stdout once it receives any thing from the serializer.
01034         XMLFormatTarget *myFormTarget = new LocalFileFormatTarget( file_name.c_str() );
01035 
01036         try {
01037             // do the serialization through DOMWriter::writeNode();
01038             theSerializer->writeNode(myFormTarget, *doc);
01039         }
01040         catch (const XMLException& toCatch) {
01041             char* message = XMLString::transcode(toCatch.getMessage());
01042             printf( "Exception message is: \n %s\n ", message );
01043             delete [] message;
01044             return 0;
01045         }
01046         catch (const DOMException& toCatch) {
01047             char* message = XMLString::transcode(toCatch.msg);
01048             printf( "Exception message is: \n %s\n ", message );
01049             delete [] message;
01050             return 0;
01051         }
01052         catch (...) {
01053             cout << "Unexpected Exception \n" ;
01054             return 0;
01055         }
01056 
01057         theSerializer->release();
01058         delete myFormTarget;
01059         return 1;
01060 }
01061 
01062     
01063 
01064 void
01065 COME_Xml::saveMaterials( DOMDocument *doc, DOMElement *patientNode, COME_Patient patient ){
01066 
01067         DOMElement *materialList = doc->createElement( XMLString::transcode("materials" ) );
01068                 
01069         vector<string> includedMaterials;
01070         list<COME_MoleculesCartilage*>::const_iterator iter;
01071         for( iter = ((list<COME_MoleculesCartilage *>*)patient.getPtOrganList())->begin(); iter != ((list<COME_MoleculesCartilage *>*)patient.getPtOrganList())->end(); iter++ ){
01072         
01073                 list<COME_Molecule*>::const_iterator iterM;
01074                 for( iterM = (*iter)->getTissue()->getShape()->begin(); iterM != (*iter)->getTissue()->getShape()->end(); iterM++ ){
01075                 
01076                         if( ( (*iterM)->getMaterial()->getDescription() != "" ) && ( find( includedMaterials.begin(), includedMaterials.end(), (*iterM)->getMaterial()->getDescription() ) == includedMaterials.end() ) ){
01077                                 includedMaterials.push_back( (*iterM)->getMaterial()->getDescription() );
01078 
01079                                 DOMElement *materialNode = doc->createElement( XMLString::transcode("material" ) );
01080 
01081                                 char chrPtTemp[100];
01082                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getMaterial()->getDensity() );
01083                                 materialNode->setAttribute( XMLString::transcode("density"), XMLString::transcode(chrPtTemp) );
01084                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getMaterial()->getDamping() );
01085                                 materialNode->setAttribute( XMLString::transcode("damping_const"), XMLString::transcode(chrPtTemp) );
01086                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getMaterial()->getYoungsModulus() );
01087                                 materialNode->setAttribute( XMLString::transcode("youngs_modulus"), XMLString::transcode(chrPtTemp) );
01088                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getMaterial()->getMediumDensity() );
01089                                 materialNode->setAttribute( XMLString::transcode("medium_density"), XMLString::transcode(chrPtTemp) );
01090                                 materialNode->setAttribute( XMLString::transcode("description"), XMLString::transcode((*iterM)->getMaterial()->getDescription().c_str() ) );
01091                                 COME_Vector3D color = (*iterM)->getMaterial()->getColor();
01092                                 sprintf( chrPtTemp, "%10.6f", color.getX() );
01093                                 materialNode->setAttribute( XMLString::transcode("R"), XMLString::transcode(chrPtTemp) );
01094                                 sprintf( chrPtTemp, "%10.6f", color.getY() );
01095                                 materialNode->setAttribute( XMLString::transcode("G"), XMLString::transcode(chrPtTemp) );
01096                                 sprintf( chrPtTemp, "%10.6f", color.getZ() );
01097                                 materialNode->setAttribute( XMLString::transcode("B"), XMLString::transcode(chrPtTemp) );
01098                                 COME_Vector3D anisotropy = (*iterM)->getMaterial()->getAnisotropyVector();
01099                                 sprintf( chrPtTemp, "%10.6f", anisotropy.getX() );
01100                                 materialNode->setAttribute( XMLString::transcode("anisoI"), XMLString::transcode(chrPtTemp) );
01101                                 sprintf( chrPtTemp, "%10.6f", anisotropy.getY() );
01102                                 materialNode->setAttribute( XMLString::transcode("anisoJ"), XMLString::transcode(chrPtTemp) );
01103                                 sprintf( chrPtTemp, "%10.6f", anisotropy.getZ() );
01104                                 materialNode->setAttribute( XMLString::transcode("anisoK"), XMLString::transcode(chrPtTemp) );
01105 
01106                                 materialList->appendChild( materialNode );
01107                         }
01108                 }
01109                 // if saving an organ without any material specified
01110                 if( includedMaterials.size() == 0 ){
01111                 
01112                         DOMElement *materialNode = doc->createElement( XMLString::transcode("material" ) );
01113 
01114                         materialNode->setAttribute( XMLString::transcode("density"), XMLString::transcode("1.0") );
01115                         materialNode->setAttribute( XMLString::transcode("damping_const"), XMLString::transcode("0.2") );
01116                         materialNode->setAttribute( XMLString::transcode("youngs_modulus"), XMLString::transcode("1000.0") );
01117                         materialNode->setAttribute( XMLString::transcode("medium_density"), XMLString::transcode("1.0") );
01118                         materialNode->setAttribute( XMLString::transcode("description"), XMLString::transcode("void") );
01119                         materialNode->setAttribute( XMLString::transcode("R"), XMLString::transcode("1.0") );
01120                         materialNode->setAttribute( XMLString::transcode("G"), XMLString::transcode("1.0") );
01121                         materialNode->setAttribute( XMLString::transcode("B"), XMLString::transcode("1.0") );
01122                         
01123                         materialList->appendChild( materialNode );
01124                 }
01125 
01126         }
01127 
01128         patientNode->appendChild( materialList );
01129 }
01130 
01131 
01132 void
01133 COME_Xml::saveMoleculeOrgan( DOMDocument *doc, DOMElement *jointNode, COME_Patient patient ){
01134         
01135         
01136         list<COME_MoleculesCartilage*>::const_iterator iter;
01137         for( iter = ((list<COME_MoleculesCartilage *>*)patient.getPtOrganList())->begin(); iter != ((list<COME_MoleculesCartilage *>*)patient.getPtOrganList())->end(); iter++ ){
01138         
01139                 if( ( (*iter)->getDescription() != "clamp0" ) && ( (*iter)->getDescription() != "clamp1" ) ){
01140                         
01141                         char chrPtTemp[100];
01142                         DOMElement *organNode = doc->createElement( XMLString::transcode("molecule_organ" ) );
01143                         organNode->setAttribute( XMLString::transcode("description"), XMLString::transcode((*iter)->getDescription().c_str()) );
01144                         organNode->setAttribute( XMLString::transcode("mesh_file"), XMLString::transcode((*iter)->getSurface()->getFileName().c_str() ) );
01145                         sprintf( chrPtTemp, "%10.6f", (*iter)->getGlobalHooke() );
01146                         organNode->setAttribute( XMLString::transcode("global_hooke"), XMLString::transcode( chrPtTemp ) );
01147         
01148                         bool isLigament = false;
01149                         list<COME_Molecule*>::const_iterator iterM;
01150                         for( iterM = (*iter)->getTissue()->getShape()->begin(); iterM != (*iter)->getTissue()->getShape()->end(); iterM++ ){
01151         
01152                                 DOMElement *moleculeNode = doc->createElement( XMLString::transcode("molecule" ) );
01153                                 char chrPtTemp[100];
01154                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getRadius() );
01155                                 moleculeNode->setAttribute( XMLString::transcode("radius"), XMLString::transcode(chrPtTemp) );
01156                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getFrictionConst() );
01157                                 moleculeNode->setAttribute( XMLString::transcode("friction_const"), XMLString::transcode(chrPtTemp) );
01158                                 moleculeNode->setAttribute( XMLString::transcode("material"), XMLString::transcode((*iterM)->getMaterial()->getDescription().c_str() ) );
01159                                 COME_Point3D position = (*iterM)->getPosition();
01160                                 sprintf( chrPtTemp, "%10.6f", position.getZ() );
01161                                 moleculeNode->setAttribute( XMLString::transcode("z"), XMLString::transcode(chrPtTemp) );
01162                                 sprintf( chrPtTemp, "%10.6f", position.getY() );
01163                                 moleculeNode->setAttribute( XMLString::transcode("y"), XMLString::transcode(chrPtTemp) );
01164                                 sprintf( chrPtTemp, "%10.6f", position.getX() );
01165                                 moleculeNode->setAttribute( XMLString::transcode("x"), XMLString::transcode(chrPtTemp) );
01166                                 if( (*iterM)->isFixed() ){
01167                                         moleculeNode->setAttribute( XMLString::transcode("fixed"), XMLString::transcode( "true" ) );
01168                                 } else {
01169                                         moleculeNode->setAttribute( XMLString::transcode("fixed"), XMLString::transcode( "false" ) );
01170                                 }
01171                                 moleculeNode->setAttribute( XMLString::transcode("description"), XMLString::transcode( (*iterM)->getDescription().c_str() ) );
01172                                 if( (*iterM)->getDescription() == "origin" ) isLigament = true;
01173 
01174                                 organNode->appendChild( moleculeNode );
01175                         }
01176                         if( isLigament ){
01177                                 organNode->setAttribute( XMLString::transcode("type"), XMLString::transcode("ligament") );
01178                         } else {
01179                                 organNode->setAttribute( XMLString::transcode("type"), XMLString::transcode("cartilage") );
01180                         }
01181                         jointNode->appendChild( organNode );
01182                         
01183                         saveSurface( (*iter)->getSurface(), (*iter)->getDescription() + ".ivc" );
01184                 }
01185         }
01186 }
01187 
01188 
01189 void
01190 COME_Xml::saveSurface( COME_Mesh *mesh, string f_name ){
01191 
01192         FILE *file;
01193         string strMode;
01194 
01195         strMode = "wt";// create new
01196 
01197         if( file = fopen( f_name.c_str(), strMode.c_str() ) ){
01198         
01199                 if( mesh ){
01200                         vector<COME_Vertex3D> *verts = mesh->getVerticesGlobalPt();
01201                         //vector<COME_Vertex3D> *vertsOriginal = ((COME_MoleculesCartilage*)parent)->getSurface()->getVerticesPt();
01202                         for ( int i = 0; i < verts->size(); i++ ){
01203         
01204                                 COME_Vertex3D vertex = verts->at(i);
01205                                 COME_Point3D minusoldhip( -97.9, 4.5, -25.7 );
01206                                 COME_Point3D minusfemuroperation( -0.117, 0, -0.352 );
01207                                 vertex+=minusfemuroperation;
01208                                 vertex.x = vertex.x / 0.005;
01209                                 vertex.y = vertex.y / 0.005;
01210                                 vertex.z = vertex.z / 0.005;
01211                                 vertex+= minusoldhip;
01212         
01213                                 fprintf( file, "%f %f %f,\n", vertex.x, vertex.y, vertex.z );
01214                         }
01215                         fclose(file);
01216                 }
01217         }
01218 
01219 }
01220 
01221 //------------------------------------------------------------------------------------------------------------------------
01222 
01223 int
01224 COME_Xml::saveAnimationFile( string file_name, const list<COME_Patient*> &patientL, COME_Simulator *simulator) {
01225 
01226         // Initialize the XML4C system
01227         try
01228         {
01229                 XMLPlatformUtils::Initialize();
01230         }
01231         
01232         catch (const XMLException& toCatch)
01233         {
01234                 printf( "Error during initialization! : %s\n", toCatch.getMessage() );
01235                 return 0;
01236         }
01237 
01238         XMLCh tempStr[100];
01239         XMLString::transcode("LS", tempStr, 99, XMLPlatformUtils::fgMemoryManager);
01240         DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
01241         DOMWriter* theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
01242 
01243         // Set some features on this serializer
01244         if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true))
01245             theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true);
01246 
01247         if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
01248              theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
01249         
01250         XMLString::transcode("\n", tempStr, 99);
01251         theSerializer->setNewLine( tempStr );
01252 
01253         // Create document
01254         XMLString::transcode("animation", tempStr, 99);
01255         DOMDocumentType *comeDocType = impl->createDocumentType( tempStr, 0, XMLString::transcode("comeanimation.dtd") );
01256         DOMDocument*   doc = impl->createDocument(0, tempStr, comeDocType );
01257         DOMElement*   come = doc->getDocumentElement();
01258 
01259         char chrPtTemp[100];
01260         DOMText* textValue;
01261         
01262         // Add version tag to document
01263         DOMElement* version = doc->createElement(XMLString::transcode("version"));
01264         textValue = doc->createTextNode(XMLString::transcode("0.1"));
01265         version->appendChild(textValue);
01266         come->appendChild(version);
01267         
01268         // Add description tag to document
01269         DOMElement* description = doc->createElement(XMLString::transcode("description"));
01270         textValue = doc->createTextNode(XMLString::transcode(file_name.c_str()));
01271         description->appendChild(textValue);
01272         come->appendChild(description);
01273         
01274         // Add length tag to document
01275         DOMElement* length = doc->createElement(XMLString::transcode("length"));
01276         sprintf( chrPtTemp, "%10.6f", simulator->getDuration() );
01277         textValue = doc->createTextNode(XMLString::transcode(chrPtTemp));
01278         length->appendChild(textValue);
01279         come->appendChild(length);
01280         
01281         // Add timestep tag to document
01282         DOMElement* timestep = doc->createElement(XMLString::transcode("timestep"));
01283         sprintf( chrPtTemp, "%10.6f", simulator->getTimestep() );
01284         textValue = doc->createTextNode(XMLString::transcode(chrPtTemp));
01285         timestep->appendChild(textValue);
01286         come->appendChild(timestep);
01287         
01288         // Add number of frames tag to document
01289         DOMElement* nFrames = doc->createElement(XMLString::transcode("nFrames"));
01290         //sprintf( chrPtTemp, "%d", (int)( ceil(simulator->getDuration()/COME::flagAnimationResolution) ));
01291                 framesOnFile = framesOnFile / ((list<COME_BioStructure *>*)(patientL.front()->getPtOrganList()))->size();
01292                 sprintf( chrPtTemp, "%d", framesOnFile );
01293         textValue = doc->createTextNode(XMLString::transcode(chrPtTemp));
01294         nFrames->appendChild(textValue);
01295         come->appendChild(nFrames);
01296         
01297         // Add organs tag to document
01298         DOMElement* organs = doc->createElement(XMLString::transcode("organs"));
01299         come->appendChild(organs);
01300         saveOrgansAnimation(doc, organs, patientL.front());
01301         
01302         // Add joints tag to document
01303         DOMElement* joints = doc->createElement(XMLString::transcode("joints"));
01304         come->appendChild(joints);
01305         saveJointsAnimation( doc, joints, patientL.front()->getRootJoint() );
01306 
01307 
01308         // StdOutFormatTarget prints the resultant XML stream
01309         // to stdout once it receives any thing from the serializer.
01310         file_name = COME::baseFolder + "/" + file_name;
01311         XMLFormatTarget *myFormTarget = new LocalFileFormatTarget( file_name.c_str() );
01312 
01313         try {
01314             // do the serialization through DOMWriter::writeNode();
01315             theSerializer->writeNode(myFormTarget, *doc);
01316         }
01317         catch (const XMLException& toCatch) {
01318             char* message = XMLString::transcode(toCatch.getMessage());
01319             printf( "Exception message is: \n %s\n ", message );
01320             delete [] message;
01321             return -1;
01322         }
01323         catch (const DOMException& toCatch) {
01324             char* message = XMLString::transcode(toCatch.msg);
01325             printf( "Exception message is: \n %s\n ", message );
01326             delete [] message;
01327             return -1;
01328         }
01329         catch (...) {
01330             cout << "Unexpected Exception \n" ;
01331             return -1;
01332         }
01333 
01334         theSerializer->release();
01335         delete myFormTarget;
01336         return 0;
01337 }
01338 
01339 // Add all organs tags to document
01340 void
01341 COME_Xml::saveOrgansAnimation( DOMDocument *doc, DOMElement *organsNode, COME_Patient *patient ){
01342 
01343         list<COME_BioStructure*>::const_iterator iter;
01344         for( iter = ((list<COME_BioStructure *>*)patient->getPtOrganList())->begin(); iter != ((list<COME_BioStructure *>*)patient->getPtOrganList())->end(); iter++ ){
01345         
01346                 if( ( (*iter)->getDescription() != "clamp0" ) && ( (*iter)->getDescription() != "clamp1" ) ){
01347                 
01348                         DOMElement* organ = doc->createElement(XMLString::transcode("organ"));
01349                         organsNode->appendChild(organ);
01350                         organ->setAttribute( XMLString::transcode("description"), XMLString::transcode((*iter)->getDescription().c_str() ) );
01351                         organ->setAttribute( XMLString::transcode("mesh"), XMLString::transcode((*iter)->getSurface()->getFileName().c_str() ) );
01352                         
01353                         string pts_file = ((COME_MoleculesCartilage*)(*iter))->getDeformationFile();
01354                         string tempStr( pts_file, 0, pts_file.size()-10 );
01355                         string stress_file = tempStr + "stress.dat";
01356 
01357                         organ->setAttribute( XMLString::transcode("points"), XMLString::transcode(pts_file.c_str() ) );
01358                         organ->setAttribute( XMLString::transcode("stress"), XMLString::transcode(stress_file.c_str() ) );
01359                 }
01360         }
01361 }
01362 
01363 // Add all joints tags to document
01364 void
01365 COME_Xml::saveJointsAnimation( DOMDocument *doc, DOMElement *jointsNode, COME_Joint *currJoint ){
01366 
01367         // Add the current joint
01368         if( currJoint ){
01369                 DOMElement* joint = doc->createElement(XMLString::transcode("joint"));
01370                 jointsNode->appendChild(joint);
01371                 joint->setAttribute( XMLString::transcode("description"), XMLString::transcode(currJoint->getDescription().c_str() ) );
01372                 string file_a = COME::baseFolder + "/" + currJoint->getDescription() + "angles.dat";
01373                 joint->setAttribute( XMLString::transcode("angles_file"), XMLString::transcode(file_a.c_str() ) );
01374                 
01375                 // Call this function recursively to add all joints
01376                 list<COME_Joint*>::iterator childAux;
01377                 int conta = 0;
01378                 for( childAux = currJoint->getChildListPt()->begin(); conta < currJoint->getChildListPt()->size();  childAux++, conta++ ){
01379                         // strangely the test childAux != currJoint->getChildList().end() doesn't work to stop the loop, so I used "conta" and implemented getChildPt
01380                         saveJointsAnimation( doc, jointsNode, (*childAux) );
01381                 }
01382         }
01383 }
01384 
01385 
01387 int
01388 COME_Xml::loadIntegrationFile( string fileName, list<COME_Patient*> &patientL, COME_Simulator *simulator, COME_Scenario *parentScene ){
01389 
01390 
01391     // Initialize the XML4C systemvoid
01392     try
01393     {
01394         XMLPlatformUtils::Initialize();
01395     }
01396 
01397     catch (const XMLException& toCatch)
01398     {
01399          printf( "Error during initialization! : %s\n", toCatch.getMessage() );
01400          return 0;
01401     }
01402 
01403     XercesDOMParser::ValSchemes    valScheme = XercesDOMParser::Val_Auto; //Val_Never Val_Always
01404     bool                     doNamespaces    = false;
01405 
01406     // Instantiate the DOM parser.
01407     XercesDOMParser parser;
01408     parser.setValidationScheme(valScheme);
01409     parser.setDoNamespaces(doNamespaces);
01410 
01411     // And create our error handler and install it
01412     DOMCountErrorHandler errorHandler;
01413     parser.setErrorHandler(&errorHandler);
01414 
01415     //
01416     //  Get the starting time and kick off the parse of the indicated
01417     //  file. Catch any exceptions that might propogate out of it.
01418     //
01419     unsigned long duration;
01420     try
01421     {
01422         const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
01423         parser.parse( fileName.c_str() );
01424         const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
01425         duration = endMillis - startMillis;
01426     }
01427 
01428     catch (const XMLException& toCatch)
01429     {
01430         cerr << "\nError during parsing: '" << fileName << "'\n"
01431              << "Exception message is:  \n"
01432              << StrX(toCatch.getMessage()) << "\n" << endl;
01433         return 0;
01434     }
01435     catch (const DOMException& toCatch)
01436     {
01437         cerr << "\nError during parsing: '" << fileName << "'\n"
01438              << "Exception message is:  \n"
01439              << toCatch.msg << "\n" << endl;
01440         XMLPlatformUtils::Terminate();
01441         return 0;
01442     }
01443     catch (...)
01444     {
01445        cerr << "\nUnexpected exception during parsing: '" << fileName << "'\n";
01446         XMLPlatformUtils::Terminate();
01447         return 0;
01448     }
01449 
01450     //
01451     //  Extract the DOM tree, get the list of all the elements and report the
01452     //  length as the count of elements.
01453     //
01454     if (errorHandler.getSawErrors())
01455     {
01456         printf( "\nErrors occured, no output available\n" );
01457     }
01458      else
01459     {
01461         DOMDocument *doc = parser.getDocument();
01462         unsigned int elementCount = doc->getElementsByTagName(XMLString::transcode("*"))->getLength();
01463                         
01465         root = doc->getDocumentElement();
01466         if( strcmp( XMLString::transcode(root->getTagName()), "model" ) ){
01467                 printf( "Invalid XML file.\n" );
01468                 exit(0);
01469         }
01470 
01471         simulatorXml = simulator;
01472 
01473         // Load organs [OK]
01474         list<COME_BioStructure*> shapesList;
01475         DOMNodeList *organs = root->getElementsByTagName( XMLString::transcode("organ") );
01476         for( int oi = 0; oi < organs->getLength(); oi++ ){
01477         
01478                 if( !XMLString::compareString( organs->item(oi)->getNodeName(), XMLString::transcode("organ" ) ) ){
01479                         DOMNamedNodeMap *attr = organs->item(oi)->getAttributes();
01480                         string name = XMLString::transcode( attr->getNamedItem( XMLString::transcode("name") )->getNodeValue() );
01481                         string file = XMLString::transcode( attr->getNamedItem( XMLString::transcode("file") )->getNodeValue() );
01482 
01483                         // Load materials from organ file
01484                         loadMaterialsFromOrganFile( file );
01485 
01486                         // load organ from file
01487                         COME_BioStructure* organAux = loadOrganFile( file, patientL, simulator, parentScene );
01488                         organAux->setDescription( name );
01489                         shapesList.push_back( organAux );
01490                 }
01491         }
01492 
01493         // Load joints [OK]
01494         DOMNodeList *joints = doc->getDocumentElement()->getElementsByTagName( XMLString::transcode("joint") );
01495         vector<COME_Joint *> tempJointList;
01496         for( int ji = 0; ji < joints->getLength(); ji++ ){
01497         
01498                 if( !XMLString::compareString( joints->item(ji)->getNodeName(), XMLString::transcode("joint" ) ) ){
01499                         DOMNamedNodeMap *attr = joints->item(ji)->getAttributes();
01500                         string description = XMLString::transcode( attr->getNamedItem( XMLString::transcode("description") )->getNodeValue() );
01501                         
01502                         COME_Matrix jointMatrix;
01503                         jointMatrix.setValueAt( 0, 0, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m00") )->getNodeValue() ) ) );
01504                         jointMatrix.setValueAt( 0, 1, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m01") )->getNodeValue() ) ) );
01505                         jointMatrix.setValueAt( 0, 2, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m02") )->getNodeValue() ) ) );
01506                         jointMatrix.setValueAt( 1, 0, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m10") )->getNodeValue() ) ) );
01507                         jointMatrix.setValueAt( 1, 1, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m11") )->getNodeValue() ) ) );
01508                         jointMatrix.setValueAt( 1, 2, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m12") )->getNodeValue() ) ) );
01509                         jointMatrix.setValueAt( 2, 0, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m20") )->getNodeValue() ) ) );
01510                         jointMatrix.setValueAt( 2, 1, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m21") )->getNodeValue() ) ) );
01511                         jointMatrix.setValueAt( 2, 2, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m22") )->getNodeValue() ) ) );
01512                         jointMatrix.setValueAt( 0, 3, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m03") )->getNodeValue() ) ) );
01513                         jointMatrix.setValueAt( 1, 3, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m13") )->getNodeValue() ) ) );
01514                         jointMatrix.setValueAt( 2, 3, atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("m23") )->getNodeValue() ) ) );
01515                         
01516                         COME_Vector3D vectorI = COME_Vector3D( jointMatrix.getValueAt(0,0), jointMatrix.getValueAt(0,1), jointMatrix.getValueAt(0,2) );
01517                         COME_Vector3D vectorJ = COME_Vector3D( jointMatrix.getValueAt(1,0), jointMatrix.getValueAt(1,1), jointMatrix.getValueAt(1,2) );
01518                         COME_Vector3D vectorK = COME_Vector3D( jointMatrix.getValueAt(2,0), jointMatrix.getValueAt(2,1), jointMatrix.getValueAt(2,2) );
01519                         COME_Point3D pointPos = COME_Vector3D( jointMatrix.getValueAt(0,3), jointMatrix.getValueAt(1,3), jointMatrix.getValueAt(2,3) );
01520 
01521                         // create Dofs [OK]
01522                         DOMNodeList *dofElements = joints->item(ji)->getChildNodes();
01523                         COME_Dof *dofAux = new COME_Dof[3];
01524                         int idof = 0;
01525                         for( int iD = 0; iD < dofElements->getLength(); iD++ ){
01526                 
01527                                 if( !XMLString::compareString( dofElements->item(iD)->getNodeName(), XMLString::transcode("limit" ) ) ){
01528                                         DOMNamedNodeMap *attr = dofElements->item(iD)->getAttributes();
01529                                         string type = XMLString::transcode( attr->getNamedItem( XMLString::transcode("type") )->getNodeValue());
01530                                         float min = ( (float)atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("min") )->getNodeValue() ) ) ) * M_PI / 180.0;
01531                                         float max = ( (float)atof( XMLString::transcode( attr->getNamedItem( XMLString::transcode("max") )->getNodeValue() ) ) ) * M_PI / 180.0;
01532                                         COME_Curve* evoluta = new COME_Bezier();
01533                                         float curr = 0.0, rest = 0.0;
01534 
01535                                         if( type == "FLEX" ){
01536                                                 dofAux[0] = COME_Dof( vectorI, pointPos, evoluta, min, max, curr, rest );
01537                                                 dofAux[0].setDescription( type );
01538                                                 dofAux[0].vpRest();
01539                                         }
01540                                         if( type == "ADDUCT" ){
01541                                                 dofAux[1] = COME_Dof( vectorJ, pointPos, evoluta, min, max, curr, rest );
01542                                                 dofAux[1].setDescription( type );
01543                                                 dofAux[1].vpRest();
01544                                         }
01545                                         if( type == "TWIST" ){
01546                                                 dofAux[2] = COME_Dof( vectorK, pointPos, evoluta, min, max, curr, rest );
01547                                                 dofAux[2].setDescription( type );
01548                                                 dofAux[2].vpRest();
01549                                         }
01550                                 }
01551                         }
01552 
01553                         // create Joint
01554                         COME_Joint *newJoint = new COME_PolyaxialJoint( NULL, &(dofAux[0]), &(dofAux[1]), &(dofAux[2]) );
01555                         newJoint->setDescription( description );
01556                         tempJointList.push_back( newJoint );
01557                 }
01558         }
01559 
01560         // build joint hierarchy
01561         COME_Joint *rootJoint;
01562         for( int ih = 0; ih < tempJointList.size(); ih++ ){
01563 
01564                 int ihh;
01565                 if( tempJointList[ih]->getDescription() == "root" ){
01566                         tempJointList[ih]->setParent( NULL );
01567                         rootJoint = tempJointList[ih];
01568                 } else
01569                 if( tempJointList[ih]->getDescription() == "hip" ){
01570                         for( ihh = 0; ihh < tempJointList.size(); ihh++ ){
01571                                 if( tempJointList[ihh]->getDescription() == "root" ){
01572                                         tempJointList[ih]->setParent( tempJointList[ihh] );
01573                                         tempJointList[ihh]->vpAddChild( tempJointList[ih] );
01574                                 }
01575                         }
01576                 } else
01577                 if( tempJointList[ih]->getDescription() == "knee" ){
01578                         for( ihh = 0; ihh < tempJointList.size(); ihh++ ){
01579                                 if( tempJointList[ihh]->getDescription() == "hip" ){
01580                                         tempJointList[ih]->setParent( tempJointList[ihh] );
01581                                         tempJointList[ihh]->vpAddChild( tempJointList[ih] );
01582                                 }
01583                         }
01584                 }
01585         }
01586 
01587         // Run joints from the root to apply composed transformations
01588         // This simplified version reads only the first child of every joint, not allowing bifurcation
01589         COME_Joint *rJoint = rootJoint;
01590         COME_Matrix composedMatrix, parentMatrix;
01591         do{
01592                 parentMatrix = composedMatrix;
01593                 composedMatrix = rJoint->getLim() * composedMatrix;
01594                 // add organs to the joint
01595                 list<COME_BioStructure*>::const_iterator iter;
01596                 for( iter = shapesList.begin(); iter != shapesList.end(); iter++ ){
01597 
01598                         // test if current organ belongs to this joint then add
01599                         string strROOT = ROOT_PARTS;
01600                         string strHIP = HIP_PARTS;
01601                         if( ( ( rJoint->getDescription() == "root" ) && ( strROOT.find( (*iter)->getDescription(), 0 ) != string::npos ) ) ||
01602                                 ( ( rJoint->getDescription() == "hip" ) && ( strHIP.find( (*iter)->getDescription(), 0 ) != string::npos ) ) ){
01603 
01604                                 (*iter)->globalToLocal( composedMatrix, parentMatrix );
01605                                 rJoint->vpAddShape( (*iter) );
01606                         }
01607                 }
01608                 if( rJoint->getChildListPt()->empty() )
01609                         break;
01610         }while( rJoint = rJoint->getChildListPt()->front() );
01611 
01612 
01613         // Load movements
01614         DOMNodeList *simulation = doc->getElementsByTagName( XMLString::transcode("simulation") );
01615         for( int sim = 0; sim < simulation->getLength(); sim++ ){
01616         
01617                 if( !XMLString::compareString( simulation->item(sim)->getNodeName(), XMLString::transcode("simulation" ) ) ){
01618                         
01619                         parentScene->movement = new COME_Movement();
01620 
01621                         DOMNodeList *motionElements = simulation->item(sim)->getChildNodes();
01622 
01623                         int numMotion = 0;
01624                         for( int jM = 0; jM < motionElements->getLength(); jM++ ){
01625                                 if( !XMLString::compareString( motionElements->item(jM)->getNodeName(), XMLString::transcode("motion" ) ) ) numMotion++;
01626                         }
01627                         COME_JointMotion *tempTimeLine = new COME_JointMotion [ numMotion ];
01628                         int qtdMotion = 0;
01629                         int tFinal = 0;
01630                         
01631                         int iMotion = 0;
01632                         for( int iM = 0; iM < motionElements->getLength(); iM++ ){
01633                 
01634                                 if( !XMLString::compareString( motionElements->item(iM)->getNodeName(), XMLString::transcode("motion" ) ) ){
01635                                         DOMNamedNodeMap *attrMotion = motionElements->item(iM)->getAttributes();
01636                                         string jointName = XMLString::transcode( attrMotion->getNamedItem( XMLString::transcode("joint_name") )->getNodeValue());
01637                                         string typeMotion = XMLString::transcode( attrMotion->getNamedItem( XMLString::transcode("type") )->getNodeValue());
01638                                         float t0 = ( (float)atof( XMLString::transcode( attrMotion->getNamedItem( XMLString::transcode("t0") )->getNodeValue() ) ) );
01639                                         float tf = ( (float)atof( XMLString::transcode( attrMotion->getNamedItem( XMLString::transcode("tf") )->getNodeValue() ) ) );
01640                                         float parameter = ( (float)atof( XMLString::transcode( attrMotion->getNamedItem( XMLString::transcode("parameter") )->getNodeValue() ) ) );
01641                                         int motionType = FLEX;
01642                                         if( !XMLString::compareString( XMLString::transcode( typeMotion.c_str() ), XMLString::transcode( "ADDUCT" ) ) ){
01643                                                 motionType = ADDUCT;
01644                                         } else if( !XMLString::compareString( XMLString::transcode( typeMotion.c_str() ), XMLString::transcode( "TWIST" ) ) ){
01645                                                 motionType = TWIST;
01646                                         }
01647                                         
01648                                         tempTimeLine[qtdMotion++] = *( new COME_JointMotion( jointName, motionType, t0, tf, parameter ) );
01649                                         if( tf > tFinal ) tFinal = tf;
01650                                 }
01651                         }
01652                         parentScene->movement->setTimeFinal( tFinal);
01653                         simulator->setDuration( tFinal );
01654                         parentScene->movement->setQtdMotion( qtdMotion );
01655                         parentScene->movement->setTimeLine( tempTimeLine );
01656                 }
01657         }
01658 
01659         // Build patient
01660         COME_Patient* patientN = new COME_Patient( "loaded", 30, MALE, 80, 1.80, rootJoint, shapesList, parentScene );
01661 
01662         // Add patient to the list
01663         patientL.clear();
01664         patientL.push_back( patientN );
01665 
01666 
01668         // Print out the stats that we collected and time taken.
01669         cout << fileName << ": " << duration << " ms ("
01670              << elementCount << " elems)." << endl;
01671     }
01672     // And call the termination method
01673     //XMLPlatformUtils::Terminate();
01674 
01675     return 1;
01676 }
01677 
01678 
01679 void
01680 COME_Xml::loadMaterialsFromOrganFile( string fileName ){
01681 
01682         // Initialize the XML4C system
01683     try
01684     {
01685         XMLPlatformUtils::Initialize();
01686     }
01687 
01688     catch (const XMLException& toCatch)
01689     {
01690          printf( "Error during initialization! : %s\n", toCatch.getMessage() );
01691          return;
01692     }
01693 
01694         XercesDOMParser::ValSchemes    valScheme = XercesDOMParser::Val_Auto; //Val_Never Val_Always
01695         bool doNamespaces    = false;
01696 
01697         // Instantiate the DOM parser.
01698         XercesDOMParser parser;
01699         parser.setValidationScheme(valScheme);
01700         parser.setDoNamespaces(doNamespaces);
01701 
01702         // And create our error handler and install it
01703         DOMCountErrorHandler errorHandler;
01704         parser.setErrorHandler(&errorHandler);
01705 
01706         //
01707         //  Get the starting time and kick off the parse of the indicated
01708         //  file. Catch any exceptions that might propogate out of it.
01709         //
01710         unsigned long duration;
01711         try
01712         {
01713                 const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
01714                 parser.parse( fileName.c_str() );
01715                 const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
01716                 duration = endMillis - startMillis;
01717         }
01718 
01719         catch (const XMLException& toCatch)
01720         {
01721                 cerr << "\nError during parsing: '" << fileName << "'\n"
01722                         << "Exception message is:  \n"
01723                         << StrX(toCatch.getMessage()) << "\n" << endl;
01724                 return;
01725         }
01726         catch (const DOMException& toCatch)
01727         {
01728                 cerr << "\nError during parsing: '" << fileName << "'\n"
01729                         << "Exception message is:  \n"
01730                         << toCatch.msg << "\n" << endl;
01731                 XMLPlatformUtils::Terminate();
01732                 return;
01733         }
01734         catch (...)
01735         {
01736         cerr << "\nUnexpected exception during parsing: '" << fileName << "'\n";
01737                 XMLPlatformUtils::Terminate();
01738                 return;
01739         }
01740 
01741         //
01742         //  Extract the DOM tree, get the list of all the elements and report the
01743         //  length as the count of elements.
01744         //
01745         if (errorHandler.getSawErrors())
01746         {
01747                 printf( "\nErrors occured, no output available\n" );
01748         }
01749         else
01750         {
01751 
01753                 DOMDocument *doc = parser.getDocument();
01754                 DOMNodeList *materialNodes = doc->getElementsByTagName( XMLString::transcode("material") );
01755                 loadMaterials( materialNodes );
01756         }
01757 }
01758 
01759 int
01760 COME_Xml::exportIntegrationFile( string file_name, const list<COME_Patient*> &patientL, COME_Simulator *simulator) {
01761 
01762         printf("Just came in \n");
01763         // Initialize the XML4C system
01764         try
01765         {
01766                 XMLPlatformUtils::Initialize();
01767         }
01768         
01769         catch (const XMLException& toCatch)
01770         {
01771                 printf( "Error during initialization! : %s\n", toCatch.getMessage() );
01772                 return 0;
01773         }
01774 
01775         XMLCh tempStr[100];
01776         XMLString::transcode("LS", tempStr, 99, XMLPlatformUtils::fgMemoryManager);
01777         DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
01778         DOMWriter* theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
01779 
01780         // Set some features on this serializer
01781         if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true))
01782             theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true);
01783 
01784         if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
01785              theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
01786         
01787         printf("after exception, before funny things \n");
01788 
01789         XMLString::transcode("\n", tempStr, 99);
01790         theSerializer->setNewLine( tempStr );
01791 
01792         // Create document
01793         XMLString::transcode("come", tempStr, 99);
01794         DOMDocumentType *comeDocType = impl->createDocumentType( tempStr, 0, XMLString::transcode("comescene.dtd") );
01795         DOMDocument*   doc = impl->createDocument(0, tempStr, comeDocType );
01796         DOMElement*   come = doc->getDocumentElement();
01797 
01798         char chrPtTemp[100];
01799 
01800         printf("Start adding tags \n");
01801         
01802         // Add scene tag to document
01803     XMLString::transcode("scene", tempStr, 99);
01804     DOMElement*   scene = doc->createElement(tempStr);
01805     come->appendChild(scene);
01806         sprintf( chrPtTemp, "%10.6f", simulator->getScene()->getGravity().getX() ) ;
01807         scene->setAttribute( XMLString::transcode("gX"), XMLString::transcode(chrPtTemp) );
01808         sprintf( chrPtTemp, "%10.6f", simulator->getScene()->getGravity().getX() ) ;
01809         scene->setAttribute( XMLString::transcode("gY"), XMLString::transcode(chrPtTemp) );
01810         sprintf( chrPtTemp, "%10.6f", simulator->getScene()->getGravity().getX() ) ;
01811         scene->setAttribute( XMLString::transcode("gZ"), XMLString::transcode(chrPtTemp) );
01812 
01813         // Add Simulation tag and attributes to document
01814         XMLString::transcode("simulation", tempStr, 99);
01815     DOMElement*   simulation = doc->createElement(tempStr);
01816     scene->appendChild(simulation);
01817                 
01818         sprintf( chrPtTemp, "%10.6f", simulator->getFPS() ) ;
01819         simulation->setAttribute( XMLString::transcode("fps"), XMLString::transcode(chrPtTemp) );
01820         sprintf( chrPtTemp, "%10.6f", simulator->getDuration() ) ;
01821         simulation->setAttribute( XMLString::transcode("duration"), XMLString::transcode(chrPtTemp) );
01822         simulation->setAttribute( XMLString::transcode("cycle"), XMLString::transcode("off") );
01823         simulation->setAttribute( XMLString::transcode("type"), XMLString::transcode("offline") );
01824 
01825         //Add motion to document
01826         COME_JointMotion *timeline = simulator->getScene()->movement->getTimeline();
01827         int numMotion = simulator->getScene()->movement->getQtdMotion();
01828         for( int iMotion = 0; iMotion < numMotion; iMotion++ ){
01829 
01830                 XMLString::transcode("motion", tempStr, 99);
01831                 DOMElement*   motion = doc->createElement(tempStr);
01832                 simulation->appendChild(motion);
01833                 motion->setAttribute( XMLString::transcode("joint_name"), XMLString::transcode( timeline[iMotion].getJointName().c_str() ) );
01834                 if( timeline[iMotion].getMotionType() == TWIST )
01835                         motion->setAttribute( XMLString::transcode("type"), XMLString::transcode( "TWIST" ) );
01836                 if( timeline[iMotion].getMotionType() == FLEX )
01837                         motion->setAttribute( XMLString::transcode("type"), XMLString::transcode( "FLEX" ) );
01838                 if( timeline[iMotion].getMotionType() == ADDUCT )
01839                         motion->setAttribute( XMLString::transcode("type"), XMLString::transcode( "ADDUCT" ) );
01840 
01841                 sprintf( chrPtTemp, "%10.6f", timeline[iMotion].getTimeIni() );
01842                 motion->setAttribute( XMLString::transcode("t0"), XMLString::transcode( chrPtTemp ) );
01843                 sprintf( chrPtTemp, "%10.6f", timeline[iMotion].getTimeFin() );
01844                 motion->setAttribute( XMLString::transcode("tf"), XMLString::transcode( chrPtTemp ) );
01845                 sprintf( chrPtTemp, "%10.6f", timeline[iMotion].getParameter() );
01846                 motion->setAttribute( XMLString::transcode("parameter"), XMLString::transcode( chrPtTemp ) );
01847         }
01848 
01849 
01850         printf("Start adding patient \n" );
01851         // Add patients to document
01852         // the front of the patient's list is used because there is only one patient in the scene
01853         XMLString::transcode("patient", tempStr, 99);
01854     DOMElement*   patient = doc->createElement(tempStr);
01855     scene->appendChild(patient);
01856                 
01857         patient->setAttribute( XMLString::transcode("name"), XMLString::transcode(patientL.front()->getName().c_str() ) );
01858         if( patientL.front()->getGender() == MALE ){
01859                 patient->setAttribute( XMLString::transcode("gender"), XMLString::transcode("M") );
01860         } else {
01861                 patient->setAttribute( XMLString::transcode("gender"), XMLString::transcode("F") );
01862         }
01863         sprintf( chrPtTemp, "%10.6f", patientL.front()->getWeight() );
01864         patient->setAttribute( XMLString::transcode("weight"), XMLString::transcode(chrPtTemp) );
01865         sprintf( chrPtTemp, "%10.6f", patientL.front()->getHeight() );
01866         patient->setAttribute( XMLString::transcode("height"), XMLString::transcode(chrPtTemp) );
01867         sprintf( chrPtTemp, "%d", patientL.front()->getAge() );
01868         patient->setAttribute( XMLString::transcode("age"), XMLString::transcode(chrPtTemp) );
01869 
01870         saveMaterials( doc, patient, patientL.front() );
01871         
01872         // Add joints and organs
01873         COME_Joint *rJoint = patientL.front()->getRootJoint();
01874         COME_Matrix composedMatrix, parentMatrix;
01875         do{
01876 
01877                 XMLString::transcode("joint", tempStr, 99);
01878                 DOMElement* joint = doc->createElement(tempStr);
01879                 patient->appendChild( joint );
01880                 joint->setAttribute( XMLString::transcode("description"), XMLString::transcode( rJoint->getDescription().c_str() ) );
01881                 string parentDesc = "null";
01882                 if( rJoint->getParent() )
01883                         parentDesc = rJoint->getParent()->getDescription();
01884                 joint->setAttribute( XMLString::transcode("parent"), XMLString::transcode( parentDesc.c_str() ) );
01885                 joint->setAttribute( XMLString::transcode("type"), XMLString::transcode("triaxial" ) );
01886 
01887                 // Add Dofs of this joint (only triaxial)
01888                 COME_Dof** dofList = rJoint->getDofList();
01889                 for( int iD = 0; iD < 3; iD++ ){
01890 
01891                         XMLString::transcode("dof", tempStr, 99);
01892                         DOMElement* dof = doc->createElement(tempStr);
01893                         joint->appendChild( dof );
01894                         dof->setAttribute( XMLString::transcode("description"), XMLString::transcode( dofList[iD]->getDescription().c_str() ) );
01895                         
01896                         COME_Point3D dofPos = dofList[iD]->getPosition();
01897                         XMLString::transcode("position", tempStr, 99);
01898                         DOMElement* position = doc->createElement(tempStr);
01899                         dof->appendChild( position );
01900 
01901                         sprintf( chrPtTemp, "%10.6f", dofPos.getX() );
01902                         position->setAttribute( XMLString::transcode("x"), XMLString::transcode( chrPtTemp ) );
01903                         sprintf( chrPtTemp, "%10.6f", dofPos.getY() );
01904                         position->setAttribute( XMLString::transcode("y"), XMLString::transcode( chrPtTemp ) );
01905                         sprintf( chrPtTemp, "%10.6f", dofPos.getZ() );
01906                         position->setAttribute( XMLString::transcode("z"), XMLString::transcode( chrPtTemp ) );
01907 
01908                         COME_Vector3D dofAxis = dofList[iD]->getAxis();
01909                         XMLString::transcode("axis", tempStr, 99);
01910                         DOMElement* axis = doc->createElement(tempStr);
01911                         dof->appendChild( axis );
01912                         sprintf( chrPtTemp, "%10.6f", dofAxis.getX() );
01913                         axis->setAttribute( XMLString::transcode("x"), XMLString::transcode( chrPtTemp ) );
01914                         sprintf( chrPtTemp, "%10.6f", dofAxis.getY() );
01915                         axis->setAttribute( XMLString::transcode("y"), XMLString::transcode( chrPtTemp ) );
01916                         sprintf( chrPtTemp, "%10.6f", dofAxis.getZ() );
01917                         axis->setAttribute( XMLString::transcode("z"), XMLString::transcode( chrPtTemp ) );
01918 
01919                         XMLString::transcode("range", tempStr, 99);
01920                         DOMElement* range = doc->createElement(tempStr);
01921                         dof->appendChild( range );
01922                         sprintf( chrPtTemp, "%10.6f", dofList[iD]->getMin() );
01923                         range->setAttribute( XMLString::transcode("min"), XMLString::transcode( chrPtTemp ) );
01924                         sprintf( chrPtTemp, "%10.6f", dofList[iD]->getMax() );
01925                         range->setAttribute( XMLString::transcode("max"), XMLString::transcode( chrPtTemp ) );
01926                 }
01927                 
01928                 // Add MoleculeOrgans of this joint
01929                 saveJointOrgans( doc, joint, rJoint );
01930 
01931                 // Add specification for functional information export
01932 
01933                 
01934                 // Test if all the joints have been included
01935                 if( rJoint->getChildListPt()->empty() )
01936                         break;
01937 
01938         }while( rJoint = rJoint->getChildListPt()->front() );
01939         
01940     // StdOutFormatTarget prints the resultant XML stream
01941     // to stdout once it receives any thing from the serializer.
01942     XMLFormatTarget *myFormTarget = new LocalFileFormatTarget( file_name.c_str() );
01943 
01944     try {
01945         // do the serialization through DOMWriter::writeNode();
01946         theSerializer->writeNode(myFormTarget, *doc);
01947     }
01948     catch (const XMLException& toCatch) {
01949         char* message = XMLString::transcode(toCatch.getMessage());
01950         printf( "Exception message is: \n %s\n ", message );
01951         delete [] message;
01952         return 0;
01953     }
01954     catch (const DOMException& toCatch) {
01955         char* message = XMLString::transcode(toCatch.msg);
01956         printf( "Exception message is: \n %s\n ", message );
01957         delete [] message;
01958         return 0;
01959     }
01960     catch (...) {
01961         cout << "Unexpected Exception \n" ;
01962         return 0;
01963     }
01964 
01965     theSerializer->release();
01966     delete myFormTarget;
01967     return 1;
01968 }
01969 
01970 
01971 void
01972 COME_Xml::saveJointOrgans( DOMDocument *doc, DOMElement *jointNode, COME_Joint *jointThis ){
01973         
01974         
01975         list<COME_MoleculesCartilage*>::const_iterator iter;
01976         for( iter = ((list<COME_MoleculesCartilage *>*)jointThis->getShapeListPt())->begin(); iter != ((list<COME_MoleculesCartilage *>*)jointThis->getShapeListPt())->end(); iter++ ){
01977         
01978                 if( ( (*iter)->getDescription() != "clamp0" ) && ( (*iter)->getDescription() != "clamp1" ) ){
01979                         
01980                         char chrPtTemp[100];
01981                         DOMElement *organNode = doc->createElement( XMLString::transcode("molecule_organ" ) );
01982                         organNode->setAttribute( XMLString::transcode("description"), XMLString::transcode((*iter)->getDescription().c_str()) );
01983                         organNode->setAttribute( XMLString::transcode("mesh_file"), XMLString::transcode((*iter)->getSurface()->getFileName().c_str() ) );
01984                         sprintf( chrPtTemp, "%10.6f", (*iter)->getGlobalHooke() );
01985                         organNode->setAttribute( XMLString::transcode("global_hooke"), XMLString::transcode( chrPtTemp ) );
01986         
01987                         bool isLigament = false;
01988                         list<COME_Molecule*>::const_iterator iterM;
01989                         for( iterM = (*iter)->getTissue()->getShape()->begin(); iterM != (*iter)->getTissue()->getShape()->end(); iterM++ ){
01990         
01991                                 DOMElement *moleculeNode = doc->createElement( XMLString::transcode("molecule" ) );
01992                                 char chrPtTemp[100];
01993                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getRadius() );
01994                                 moleculeNode->setAttribute( XMLString::transcode("radius"), XMLString::transcode(chrPtTemp) );
01995                                 sprintf( chrPtTemp, "%10.6f", (*iterM)->getFrictionConst() );
01996                                 moleculeNode->setAttribute( XMLString::transcode("friction_const"), XMLString::transcode(chrPtTemp) );
01997                                 moleculeNode->setAttribute( XMLString::transcode("material"), XMLString::transcode((*iterM)->getMaterial()->getDescription().c_str() ) );
01998                                 COME_Point3D position = (*iterM)->getPosition();
01999                                 sprintf( chrPtTemp, "%10.6f", position.getZ() );
02000                                 moleculeNode->setAttribute( XMLString::transcode("z"), XMLString::transcode(chrPtTemp) );
02001                                 sprintf( chrPtTemp, "%10.6f", position.getY() );
02002                                 moleculeNode->setAttribute( XMLString::transcode("y"), XMLString::transcode(chrPtTemp) );
02003                                 sprintf( chrPtTemp, "%10.6f", position.getX() );
02004                                 moleculeNode->setAttribute( XMLString::transcode("x"), XMLString::transcode(chrPtTemp) );
02005                                 if( (*iterM)->isFixed() ){
02006                                         moleculeNode->setAttribute( XMLString::transcode("fixed"), XMLString::transcode( "true" ) );
02007                                 } else {
02008                                         moleculeNode->setAttribute( XMLString::transcode("fixed"), XMLString::transcode( "false" ) );
02009                                 }
02010                                 moleculeNode->setAttribute( XMLString::transcode("description"), XMLString::transcode( (*iterM)->getDescription().c_str() ) );
02011                                 if( (*iterM)->getDescription() == "origin" ) isLigament = true;
02012 
02013                                 organNode->appendChild( moleculeNode );
02014                         }
02015                         if( isLigament ){
02016                                 organNode->setAttribute( XMLString::transcode("type"), XMLString::transcode("ligament") );
02017                         } else {
02018                                 organNode->setAttribute( XMLString::transcode("type"), XMLString::transcode("cartilage") );
02019                         }
02020                         jointNode->appendChild( organNode );
02021                         
02022                         //saveSurface( (*iter)->getSurface(), (*iter)->getDescription() + ".ivc" );
02023                 }
02024         }
02025 }
02026 
02027 
02028 
02029 //------------------------------------------------------------------------------------------------------------------------
02030 
02031 ostream& operator<<(ostream& target, const StrX& toDump){
02032     target << toDump.localForm();
02033     return target;
02034 }
02035 
02036 //---------------------------Error methods---------------------------
02037 
02038 DOMCountErrorHandler::DOMCountErrorHandler() :
02039 
02040     fSawErrors(false)
02041 {
02042 }
02043 
02044 DOMCountErrorHandler::~DOMCountErrorHandler()
02045 {
02046 }
02047 
02048 
02049 // ---------------------------------------------------------------------------
02050 //  DOMCountHandlers: Overrides of the SAX ErrorHandler interface
02051 // ---------------------------------------------------------------------------
02052 void DOMCountErrorHandler::error(const SAXParseException& e)
02053 {
02054     fSawErrors = true;
02055     cerr << "\nError at file " << StrX(e.getSystemId())
02056          << ", line " << e.getLineNumber()
02057          << ", char " << e.getColumnNumber()
02058          << "\n  Message: " << StrX(e.getMessage()) << endl;
02059 }
02060 
02061 void DOMCountErrorHandler::fatalError(const SAXParseException& e)
02062 {
02063     fSawErrors = true;
02064     cerr << "\nFatal Error at file " << StrX(e.getSystemId())
02065          << ", line " << e.getLineNumber()
02066          << ", char " << e.getColumnNumber()
02067          << "\n  Message: " << StrX(e.getMessage()) << endl;
02068 }
02069 
02070 void DOMCountErrorHandler::warning(const SAXParseException& e)
02071 {
02072     cerr << "\nWarning at file " << StrX(e.getSystemId())
02073          << ", line " << e.getLineNumber()
02074          << ", char " << e.getColumnNumber()
02075          << "\n  Message: " << StrX(e.getMessage()) << endl;
02076 }
02077 
02078 void DOMCountErrorHandler::resetErrors()
02079 {
02080 }
02081 
02082 
02083 bool DOMCountErrorHandler::getSawErrors() const
02084 {
02085     return fSawErrors;
02086 }
02087 //----------------------------------------------------

Generated on Thu Dec 1 10:13:37 2005 for COME - Biomechanical Joint Model by  doxygen 1.4.5