Salome HOME
Merge remote-tracking branch 'remotes/origin/Dev_FolderFeature'
[modules/shaper.git] / src / ModelHighAPI / ModelHighAPI_Dumper.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "ModelHighAPI_Dumper.h"
22
23 #include <Config_PropManager.h>
24
25 #include <GeomAPI_Pnt.h>
26 #include <GeomAPI_Dir.h>
27 #include <GeomAPI_ShapeExplorer.h>
28
29 #include <GeomDataAPI_Dir.h>
30 #include <GeomDataAPI_Point.h>
31 #include <GeomDataAPI_Point2D.h>
32
33 #include <ModelAPI_AttributeBoolean.h>
34 #include <ModelAPI_AttributeDouble.h>
35 #include <ModelAPI_AttributeIntArray.h>
36 #include <ModelAPI_AttributeInteger.h>
37 #include <ModelAPI_AttributeRefAttr.h>
38 #include <ModelAPI_AttributeRefAttrList.h>
39 #include <ModelAPI_AttributeReference.h>
40 #include <ModelAPI_AttributeRefList.h>
41 #include <ModelAPI_AttributeSelection.h>
42 #include <ModelAPI_AttributeSelectionList.h>
43 #include <ModelAPI_AttributeString.h>
44 #include <ModelAPI_AttributeStringArray.h>
45 #include <ModelAPI_CompositeFeature.h>
46 #include <ModelAPI_Document.h>
47 #include <ModelAPI_Entity.h>
48 #include <ModelAPI_Feature.h>
49 #include <ModelAPI_Folder.h>
50 #include <ModelAPI_Result.h>
51 #include <ModelAPI_ResultBody.h>
52 #include <ModelAPI_ResultCompSolid.h>
53 #include <ModelAPI_ResultConstruction.h>
54 #include <ModelAPI_ResultPart.h>
55 #include <ModelAPI_Tools.h>
56
57 #include <PartSetPlugin_Part.h>
58
59 #include <OSD_OpenFile.hxx>
60
61 #include <fstream>
62
63 static int gCompositeStackDepth = 0;
64
65 ModelHighAPI_Dumper* ModelHighAPI_Dumper::mySelf = 0;
66
67 ModelHighAPI_Dumper::ModelHighAPI_Dumper()
68 {
69   clear();
70 }
71
72 void ModelHighAPI_Dumper::setInstance(ModelHighAPI_Dumper* theDumper)
73 {
74   if (mySelf == 0)
75     mySelf = theDumper;
76 }
77
78 ModelHighAPI_Dumper* ModelHighAPI_Dumper::getInstance()
79 {
80   return mySelf;
81 }
82
83 void ModelHighAPI_Dumper::clear(bool bufferOnly)
84 {
85   myDumpBuffer.str("");
86   myDumpBuffer << std::setprecision(16);
87
88   clearNotDumped();
89
90   if (!bufferOnly) {
91     myFullDump.str("");
92     myFullDump << std::setprecision(16);
93
94     myNames.clear();
95     myModules.clear();
96     myFeatureCount.clear();
97     while (!myEntitiesStack.empty())
98       myEntitiesStack.pop();
99   }
100 }
101
102 void ModelHighAPI_Dumper::clearNotDumped()
103 {
104   myNotDumpedEntities.clear();
105 }
106
107 // Convert string to integer. If the string is not a number, return -1
108 static int toInt(const std::string& theString)
109 {
110   std::string::const_iterator aChar = theString.begin();
111   for (; aChar != theString.end(); ++aChar)
112     if (!std::isdigit(*aChar))
113       break;
114   if (aChar != theString.end())
115     return -1; // not a number
116   return std::stoi(theString);
117 }
118
119 const std::string& ModelHighAPI_Dumper::name(const EntityPtr& theEntity,
120                                              bool theSaveNotDumped,
121                                              bool theUseEntityName)
122 {
123   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
124   if (aFound != myNames.end())
125     return aFound->second.myCurrentName;
126
127   // entity is not found, store it
128   std::string aName, aKind;
129   bool isDefaultName = false;
130   bool isSaveNotDumped = theSaveNotDumped;
131   std::ostringstream aDefaultName;
132   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
133   if (aFeature) {
134     aName = aFeature->name();
135     aKind = aFeature->getKind();
136   } else {
137     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theEntity);
138     if (aFolder) {
139       aName = aFolder->data()->name();
140       aKind = ModelAPI_Folder::ID();
141       isSaveNotDumped = false;
142       myNotDumpedFolders.insert(aFolder);
143     }
144   }
145
146   ObjectPtr anObject = std::dynamic_pointer_cast<ModelAPI_Object>(theEntity);
147   if (anObject) {
148     DocumentPtr aDoc = anObject->document();
149     int& aNbFeatures = myFeatureCount[aDoc][aKind];
150     aNbFeatures += 1;
151
152     size_t anIndex = aName.find(aKind);
153     if (anIndex == 0 && aName[aKind.length()] == '_') { // name starts with "FeatureKind_"
154       std::string anIdStr = aName.substr(aKind.length() + 1);
155       int anId = toInt(anIdStr);
156
157       // Check number of already registered objects of such kind. Index of current object
158       // should be the same to identify feature's name as automatically generated.
159       if (aNbFeatures == anId) {
160         // name is not user-defined
161         isDefaultName = true;
162       }
163     }
164
165     // obtain default name for the feature
166     if (theUseEntityName)
167       aDefaultName << aName;
168     else {
169       int aFullIndex = 0;
170       NbFeaturesMap::const_iterator aFIt = myFeatureCount.begin();
171       for (; aFIt != myFeatureCount.end(); ++aFIt) {
172         std::map<std::string, int>::const_iterator aFound = aFIt->second.find(aKind);
173         if (aFound != aFIt->second.end())
174           aFullIndex += aFound->second;
175       }
176       aDefaultName << aKind << "_" << aFullIndex;
177     }
178   }
179
180   myNames[theEntity] = EntityName(aDefaultName.str(), aName, isDefaultName);
181   if (isSaveNotDumped)
182     myNotDumpedEntities.insert(theEntity);
183
184   // store names of results
185   if (aFeature)
186     saveResultNames(aFeature);
187
188   return myNames[theEntity].myCurrentName;
189 }
190
191 const std::string& ModelHighAPI_Dumper::parentName(const FeaturePtr& theEntity)
192 {
193   const std::set<AttributePtr>& aRefs = theEntity->data()->refsToMe();
194   std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
195   for (; aRefIt != aRefs.end(); ++aRefIt) {
196     CompositeFeaturePtr anOwner = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
197         ModelAPI_Feature::feature((*aRefIt)->owner()));
198     if (anOwner)
199       return name(anOwner);
200   }
201
202   static const std::string DUMMY;
203   return DUMMY;
204 }
205
206 void ModelHighAPI_Dumper::saveResultNames(const FeaturePtr& theFeature)
207 {
208   // Default name of the feature
209   bool isFeatureDefaultName = myNames[theFeature].myIsDefault;
210
211   // Save only names of results which is not correspond to default feature name
212   const std::list<ResultPtr>& aResults = theFeature->results();
213   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
214   for (int i = 0; aResIt != aResults.end(); ++aResIt, ++i) {
215     std::string aDefaultName = ModelAPI_Tools::getDefaultName(*aResIt, i);
216     std::string aResName = (*aResIt)->data()->name();
217
218     bool isUserDefined = !(isFeatureDefaultName && aDefaultName == aResName);
219
220     myNames[*aResIt] = EntityName(aResName,
221         (isUserDefined ? aResName : std::string()), !isUserDefined);
222
223     // check names of sub-results for CompSolid
224     ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIt);
225     if (aCompSolid) {
226       int aNbSubs = aCompSolid->numberOfSubs();
227       for (int j = 0; j < aNbSubs; ++j) {
228         ResultPtr aSub = aCompSolid->subResult(j);
229         std::string aSubName = aSub->data()->name();
230         aDefaultName = ModelAPI_Tools::getDefaultName(aSub, j);
231
232         bool isUserDefinedSubName = isUserDefined || aDefaultName != aSubName;
233         myNames[aSub] = EntityName(aSubName,
234             (isUserDefinedSubName ? aSubName : std::string()), !isUserDefinedSubName);
235       }
236     }
237   }
238 }
239
240 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc,
241                                   const std::string& theFileName)
242 {
243   // dump top level document feature
244   static const std::string aDocName("partSet");
245   myNames[theDoc] = EntityName(aDocName, std::string(), true);
246   *this << aDocName << " = model.moduleDocument()" << std::endl;
247
248   // dump subfeatures and store result to file
249   return process(theDoc) && exportTo(theFileName);
250 }
251
252 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc)
253 {
254   bool isOk = true;
255   std::list<ObjectPtr> anObjects = theDoc->allObjects();
256   std::list<ObjectPtr>::const_iterator anObjIt = anObjects.begin();
257   // firstly, dump all parameters
258   for (; anObjIt != anObjects.end(); ++ anObjIt) {
259     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
260     if (aFeature)
261       dumpParameter(aFeature);
262   }
263   // dump all other features
264   for (anObjIt = anObjects.begin(); anObjIt != anObjects.end(); ++anObjIt) {
265     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anObjIt);
266     if (aCompFeat) // iteratively process composite features
267       isOk = process(aCompFeat) && isOk;
268     else if (!isDumped(*anObjIt)) {
269       // dump folder
270       FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anObjIt);
271       if (aFolder)
272         dumpFolder(aFolder);
273       else {
274         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
275         if (aFeature) // dump common feature
276           dumpFeature(aFeature);
277       }
278     }
279   }
280   return isOk;
281 }
282
283 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
284                                   bool isForce)
285 {
286   // increase composite features stack
287   ++gCompositeStackDepth;
288   // dump composite itself
289   if (!isDumped(theComposite) || isForce)
290     dumpFeature(FeaturePtr(theComposite), isForce);
291
292   // sub-part is processed independently, because it provides separate document
293   if (theComposite->getKind() == PartSetPlugin_Part::ID()) {
294     // dump name of the part if it is different from default
295     if (!myEntitiesStack.empty())
296       dumpEntitySetName();
297
298     // decrease composite features stack because we run into separate document
299     --gCompositeStackDepth;
300
301     ResultPartPtr aPartResult =
302         std::dynamic_pointer_cast<ModelAPI_ResultPart>(theComposite->lastResult());
303     if (!aPartResult)
304       return false;
305     DocumentPtr aSubDoc = aPartResult->partDoc();
306     if (!aSubDoc)
307       return false;
308     // set name of document
309     const std::string& aPartName = myNames[theComposite].myCurrentName;
310     std::string aDocName = aPartName + "_doc";
311     myNames[aSubDoc] = EntityName(aDocName, std::string(), true);
312
313     // dump document in a separate line
314     *this << aDocName << " = " << aPartName << ".document()" << std::endl;
315     // dump features in the document
316     bool aRes = process(aSubDoc);
317     *this << "model.do()" << std::endl;
318     return aRes;
319   }
320
321   // dump sub-features
322   bool isOk = processSubs(theComposite);
323   // decrease composite features stack
324   --gCompositeStackDepth;
325
326   return isOk;
327 }
328
329 bool ModelHighAPI_Dumper::processSubs(
330   const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
331   bool theDumpModelDo)
332 {
333   bool isOk = true;
334   // dump all sub-features;
335   bool isSubDumped = false;
336   int aNbSubs = theComposite->numberOfSubs();
337   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
338     FeaturePtr aFeature = theComposite->subFeature(anIndex);
339     if (isDumped(aFeature))
340       continue;
341
342     isSubDumped = true;
343     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
344     if (aCompFeat) // iteratively process composite features
345       isOk = process(aCompFeat) && isOk;
346     else
347       dumpFeature(aFeature, true);
348   }
349
350   bool isDumpSetName = !myEntitiesStack.empty() &&
351       myEntitiesStack.top().myEntity == EntityPtr(theComposite);
352   bool isForceModelDo = isSubDumped && isDumpSetName &&
353       (myEntitiesStack.top().myUserName || !myEntitiesStack.top().myResults.empty());
354   // It is necessary for the sketch to create its result when complete (command "model.do()").
355   // This option is set by flat theDumpModelDo.
356   // However, nested sketches are rebuilt by parent feature, so, they do not need
357   // explicit call of "model.do()". This will be controlled by the depth of the stack.
358   if (isForceModelDo || (theDumpModelDo && gCompositeStackDepth <= 1))
359     *this << "model.do()" << std::endl;
360
361   // dump "setName" for composite feature
362   if (isDumpSetName)
363     dumpEntitySetName();
364   // dump folders if any
365   dumpFolders();
366   return isOk;
367 }
368
369 void ModelHighAPI_Dumper::dumpFolders()
370 {
371   std::set<FolderPtr>::const_iterator aFolderIt = myNotDumpedFolders.begin();
372   while (aFolderIt != myNotDumpedFolders.end()) {
373     FolderPtr aFolder = *aFolderIt++;
374     dumpFolder(aFolder);
375   }
376 }
377
378 void ModelHighAPI_Dumper::dumpSubFeatureNameAndColor(const std::string theSubFeatureGet,
379                                                      const FeaturePtr& theSubFeature)
380 {
381   name(theSubFeature, false);
382   myNames[theSubFeature] = EntityName(theSubFeatureGet, theSubFeature->name(), false);
383
384   // store results if they have user-defined names or colors
385   std::list<ResultPtr> aResultsWithNameOrColor;
386   const std::list<ResultPtr>& aResults = theSubFeature->results();
387   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
388   for (; aResIt != aResults.end(); ++aResIt) {
389     std::string aResName = (*aResIt)->data()->name();
390     myNames[*aResIt] = EntityName(aResName, aResName, false);
391     aResultsWithNameOrColor.push_back(*aResIt);
392   }
393
394   // store just dumped entity to stack
395   myEntitiesStack.push(LastDumpedEntity(theSubFeature, true, aResultsWithNameOrColor));
396
397   dumpEntitySetName();
398 }
399
400 bool ModelHighAPI_Dumper::exportTo(const std::string& theFileName)
401 {
402   std::ofstream aFile;
403   OSD_OpenStream(aFile, theFileName.c_str(), std::ofstream::out);
404   if (!aFile.is_open())
405     return false;
406
407   // standard header
408   for (ModulesMap::const_iterator aModIt = myModules.begin();
409        aModIt != myModules.end(); ++aModIt) {
410     aFile << "from " << aModIt->first << " import ";
411     if (aModIt->second.empty() ||
412         aModIt->second.find(std::string()) != aModIt->second.end())
413       aFile << "*"; // import whole module
414     else {
415       // import specific features
416       std::set<std::string>::const_iterator anObjIt = aModIt->second.begin();
417       aFile << *anObjIt;
418       for (++anObjIt; anObjIt != aModIt->second.end(); ++anObjIt)
419         aFile << ", " << *anObjIt;
420     }
421     aFile << std::endl;
422   }
423   if (!myModules.empty())
424     aFile << std::endl;
425
426   aFile << "from salome.shaper import model" << std::endl << std::endl;
427   aFile << "model.begin()" << std::endl;
428
429   // dump collected data
430   aFile << myFullDump.str();
431   aFile << myDumpBuffer.str();
432
433   // standard footer
434   aFile << "model.end()" << std::endl;
435
436   aFile.close();
437   clear();
438
439   return true;
440 }
441
442 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName,
443                                        const std::string& theObject)
444 {
445   myModules[theModuleName].insert(theObject);
446 }
447
448 void ModelHighAPI_Dumper::dumpEntitySetName()
449 {
450   const LastDumpedEntity& aLastDumped = myEntitiesStack.top();
451
452   // dump "setName" for the entity
453   if (aLastDumped.myUserName) {
454     EntityName& anEntityNames = myNames[aLastDumped.myEntity];
455     if (!anEntityNames.myIsDefault)
456       myDumpBuffer << anEntityNames.myCurrentName << ".setName(\""
457                    << anEntityNames.myUserName << "\")" << std::endl;
458     // don't dump "setName" for the entity twice
459     anEntityNames.myUserName.clear();
460     anEntityNames.myIsDefault = true;
461   }
462   // dump "setName" for results
463   std::list<ResultPtr>::const_iterator aResIt = aLastDumped.myResults.begin();
464   std::list<ResultPtr>::const_iterator aResEnd = aLastDumped.myResults.end();
465   for (; aResIt != aResEnd; ++aResIt) {
466     // set result name
467     EntityName& anEntityNames = myNames[*aResIt];
468     if (!anEntityNames.myIsDefault) {
469       *this << *aResIt;
470       myDumpBuffer << ".setName(\"" << anEntityNames.myUserName << "\")" << std::endl;
471       // don't dump "setName" for the entity twice
472       anEntityNames.myUserName.clear();
473       anEntityNames.myIsDefault = true;
474     }
475     // set result color
476     if (!isDefaultColor(*aResIt)) {
477       AttributeIntArrayPtr aColor = (*aResIt)->data()->intArray(ModelAPI_Result::COLOR_ID());
478       if (aColor && aColor->isInitialized()) {
479         *this << *aResIt;
480         myDumpBuffer << ".setColor(" << aColor->value(0) << ", " << aColor->value(1)
481                      << ", " << aColor->value(2) << ")" << std::endl;
482       }
483     }
484     // set result deflection
485     if (!isDefaultDeflection(*aResIt)) {
486       AttributeDoublePtr aDeflectionAttr =
487         (*aResIt)->data()->real(ModelAPI_Result::DEFLECTION_ID());
488       if(aDeflectionAttr.get() && aDeflectionAttr->isInitialized()) {
489         *this << *aResIt;
490         myDumpBuffer << ".setDeflection(" << aDeflectionAttr->value() << ")" << std::endl;
491       }
492     }
493     // set result transparency
494     if (!isDefaultTransparency(*aResIt)) {
495       AttributeDoublePtr aTransparencyAttr =
496         (*aResIt)->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
497       if(aTransparencyAttr.get() && aTransparencyAttr->isInitialized()) {
498         *this << *aResIt;
499         myDumpBuffer << ".setTransparency(" << aTransparencyAttr->value() << ")" << std::endl;
500       }
501     }
502   }
503
504   myNames[aLastDumped.myEntity].myIsDumped = true;
505   myEntitiesStack.pop();
506 }
507
508 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
509 {
510   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
511   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
512   return (aFound != myNames.end() && aFound->second.myIsDumped) ||
513          myFeaturesToSkip.find(aFeature) != myFeaturesToSkip.end();
514 }
515
516 bool ModelHighAPI_Dumper::isDefaultColor(const ResultPtr& theResult) const
517 {
518   AttributeIntArrayPtr aColor = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
519   if (!aColor || !aColor->isInitialized())
520     return true;
521
522   std::string aSection, aName, aDefault;
523   theResult->colorConfigInfo(aSection, aName, aDefault);
524
525   // dump current color
526   std::ostringstream aColorInfo;
527   aColorInfo << aColor->value(0) << "," << aColor->value(1) << "," << aColor->value(2);
528
529   return aDefault == aColorInfo.str();
530 }
531
532 bool ModelHighAPI_Dumper::isDefaultDeflection(const ResultPtr& theResult) const
533 {
534   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
535   if(!aDeflectionAttr || !aDeflectionAttr->isInitialized()) {
536     return true;
537   }
538
539   double aCurrent = aDeflectionAttr->value();
540   double aDefault = -1;
541
542   bool isConstruction = false;
543   std::string aResultGroup = theResult->groupName();
544   if (aResultGroup == ModelAPI_ResultConstruction::group())
545     isConstruction = true;
546   else if (aResultGroup == ModelAPI_ResultBody::group()) {
547     GeomShapePtr aGeomShape = theResult->shape();
548     if (aGeomShape.get()) {
549       // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
550       // correction of deviation for them should not influence to the application performance
551       GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
552       isConstruction = !anExp.more();
553     }
554   }
555   if (isConstruction)
556     aDefault = Config_PropManager::real("Visualization", "construction_deflection");
557   else
558     aDefault = Config_PropManager::real("Visualization", "body_deflection");
559
560   return fabs(aCurrent - aDefault) < 1.e-12;
561 }
562
563 bool ModelHighAPI_Dumper::isDefaultTransparency(const ResultPtr& theResult) const
564 {
565   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
566   if(!anAttribute || !anAttribute->isInitialized()) {
567     return true;
568   }
569   return fabs(anAttribute->value()) < 1.e-12;
570 }
571
572 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
573 {
574   myDumpBuffer << theChar;
575   return *this;
576 }
577
578 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
579 {
580   myDumpBuffer << theString;
581   return *this;
582 }
583
584 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
585 {
586   myDumpBuffer << theString;
587   return *this;
588 }
589
590 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
591 {
592   myDumpBuffer << (theValue ? "True" : "False");
593   return *this;
594 }
595
596 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
597 {
598   myDumpBuffer << theValue;
599   return *this;
600 }
601
602 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
603 {
604   myDumpBuffer << theValue;
605   return *this;
606 }
607
608 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
609 {
610   importModule("GeomAPI", "GeomAPI_Pnt");
611   myDumpBuffer << "GeomAPI_Pnt(" << thePoint->x() << ", "
612                << thePoint->y() << ", " << thePoint->z() << ")";
613   return *this;
614 }
615
616 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
617 {
618   importModule("GeomAPI", "GeomAPI_Dir");
619   myDumpBuffer << "GeomAPI_Dir(" << theDir->x() << ", "
620                << theDir->y() << ", " << theDir->z() << ")";
621   return *this;
622 }
623
624 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
625     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
626 {
627   myDumpBuffer << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
628   return *this;
629 }
630
631 static void dumpArray(std::ostringstream& theOutput, int theSize,
632                       double* theValues, std::string* theTexts)
633 {
634   for (int i = 0; i < theSize; ++i) {
635     if (i > 0)
636       theOutput << ", ";
637     if (theTexts[i].empty())
638       theOutput << theValues[i];
639     else
640       theOutput << "\"" << theTexts[i] << "\"";
641   }
642 }
643
644 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
645     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
646 {
647   static const int aSize = 3;
648   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
649   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY(), thePoint->textZ()};
650   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
651   return *this;
652 }
653
654 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
655     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
656 {
657   static const int aSize = 2;
658   double aValues[aSize] = {thePoint->x(), thePoint->y()};
659   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY()};
660   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
661   return *this;
662 }
663
664 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
665     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
666 {
667   myDumpBuffer << (theAttrBool->value() ? "True" : "False");
668   return *this;
669 }
670
671 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
672     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
673 {
674   std::string aText = theAttrInt->text();
675   if (aText.empty())
676     myDumpBuffer << theAttrInt->value();
677   else
678     myDumpBuffer << "\"" << aText << "\"";
679   return *this;
680 }
681
682 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
683     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
684 {
685   std::string aText = theAttrReal->text();
686   if (aText.empty())
687     myDumpBuffer << theAttrReal->value();
688   else
689     myDumpBuffer << "\"" << aText << "\"";
690   return *this;
691 }
692
693 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
694     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
695 {
696   myDumpBuffer << "\"" << theAttrStr->value() << "\"";
697   return *this;
698 }
699
700 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FolderPtr& theFolder)
701 {
702   myDumpBuffer << name(theFolder);
703   myNotDumpedFolders.erase(theFolder);
704   return *this;
705 }
706
707 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
708 {
709   myDumpBuffer << name(theEntity);
710
711   if (!myNames[theEntity].myIsDumped) {
712     bool isUserDefinedName = !myNames[theEntity].myIsDefault;
713     // store results if they have user-defined names or colors
714     std::list<ResultPtr> aResultsWithNameOrColor;
715     const std::list<ResultPtr>& aResults = theEntity->results();
716     std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
717     for (; aResIt != aResults.end(); ++aResIt) {
718       if (!myNames[*aResIt].myIsDefault || !isDefaultColor(*aResIt) ||
719           !isDefaultDeflection(*aResIt) || !isDefaultTransparency(*aResIt))
720         aResultsWithNameOrColor.push_back(*aResIt);
721
722       ResultCompSolidPtr aCompSolid =
723           std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIt);
724       if (aCompSolid) {
725         int aNbSubs = aCompSolid->numberOfSubs();
726         for (int i = 0; i < aNbSubs; ++i) {
727           ResultPtr aCurRes = aCompSolid->subResult(i);
728           if (!myNames[aCurRes].myIsDefault || !isDefaultColor(aCurRes) ||
729               !isDefaultDeflection(aCurRes) || !isDefaultTransparency(aCurRes))
730             aResultsWithNameOrColor.push_back(aCurRes);
731         }
732       }
733     }
734     // store just dumped entity to stack
735     if (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theEntity)
736       myEntitiesStack.push(
737           LastDumpedEntity(theEntity, isUserDefinedName, aResultsWithNameOrColor));
738   }
739
740   // remove entity from the list of not dumped items
741   myNotDumpedEntities.erase(theEntity);
742   return *this;
743 }
744
745 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
746 {
747   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
748   int anIndex = 0;
749   int aSubIndex = -1;
750   std::list<ResultPtr> aResults = aFeature->results();
751   for(std::list<ResultPtr>::const_iterator
752       anIt = aResults.cbegin(); anIt != aResults.cend(); ++anIt, ++anIndex) {
753     if(theResult->isSame(*anIt)) {
754       break;
755     }
756
757     ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*anIt);
758     if (aCompSolid) {
759       int aNbSubs = aCompSolid->numberOfSubs();
760       for (aSubIndex = 0; aSubIndex < aNbSubs; ++aSubIndex)
761         if (theResult->isSame(aCompSolid->subResult(aSubIndex)))
762           break;
763       if (aSubIndex < aNbSubs)
764         break;
765       aSubIndex = -1;
766     }
767   }
768
769   myDumpBuffer << name(aFeature);
770   if(anIndex == 0) {
771     myDumpBuffer << ".result()";
772   } else {
773     myDumpBuffer << ".results()[" << anIndex << "]";
774   }
775   if (aSubIndex >= 0) {
776     myDumpBuffer << ".subResult(" << aSubIndex << ")";
777   }
778   return *this;
779 }
780
781 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
782 {
783   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
784   if(aFeature.get()) {
785     myDumpBuffer << name(aFeature);
786     return *this;
787   }
788
789   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
790   if(aResult.get()) {
791     *this << aResult;
792     return *this;
793   }
794
795   return *this;
796 }
797
798 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
799 {
800   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
801
802   std::string aWrapperPrefix, aWrapperSuffix;
803   // Check the attribute belongs to copied (in multi-translation or multi-rotation) feature.
804   // In this case we need to cast explicitly feature to appropriate type.
805   AttributeBooleanPtr isCopy = anOwner->boolean("Copy");
806   if (isCopy.get() && isCopy->value()) {
807     aWrapperPrefix = featureWrapper(anOwner) + "(";
808     aWrapperSuffix = ")";
809     importModule("SketchAPI");
810   }
811
812   myDumpBuffer << aWrapperPrefix << name(anOwner) << aWrapperSuffix
813                << "." << attributeGetter(anOwner, theAttr->id()) << "()";
814   return *this;
815 }
816
817 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
818     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
819 {
820   if (theRefAttr->isObject())
821     *this << theRefAttr->object();
822   else
823     *this << theRefAttr->attr();
824   return *this;
825 }
826
827 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
828     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
829 {
830   myDumpBuffer << "[";
831   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
832   bool isAdded = false;
833   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
834   for (; anIt != aList.end(); ++anIt) {
835     if (isAdded)
836       myDumpBuffer << ", ";
837     else
838       isAdded = true;
839     if (anIt->first)
840       *this << anIt->first;
841     else if (anIt->second)
842       * this << anIt->second;
843   }
844   myDumpBuffer << "]";
845   return *this;
846 }
847
848 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
849     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
850 {
851   *this << theReference->value();
852   return *this;
853 }
854
855 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
856     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
857 {
858   static const int aThreshold = 2;
859   // if number of elements in the list if greater than a threshold,
860   // dump it in a separate line with specific name
861   std::string aDumped = myDumpBuffer.str();
862   if (aDumped.empty() || theRefList->size() <= aThreshold) {
863     myDumpBuffer << "[";
864     std::list<ObjectPtr> aList = theRefList->list();
865     bool isAdded = false;
866     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
867     for (; anIt != aList.end(); ++anIt) {
868       if (isAdded)
869         myDumpBuffer << ", ";
870       else
871         isAdded = true;
872
873       *this << *anIt;
874     }
875     myDumpBuffer << "]";
876   } else {
877     // clear buffer and store list "as is"
878     myDumpBuffer.str("");
879     *this << theRefList;
880     // save buffer and clear it again
881     std::string aDumpedList = myDumpBuffer.str();
882     myDumpBuffer.str("");
883     // obtain name of list
884     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
885     std::string aListName = name(anOwner) + "_objects";
886     // store all previous data
887     myDumpBuffer << aListName << " = " << aDumpedList << std::endl
888                  << aDumped << aListName;
889   }
890   return *this;
891 }
892
893 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
894     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
895 {
896   myDumpBuffer << "model.selection(";
897
898   if(!theAttrSelect->isInitialized()) {
899     myDumpBuffer << ")";
900     return *this;
901   }
902
903   GeomShapePtr aShape = theAttrSelect->value();
904   if(!aShape.get()) {
905     aShape = theAttrSelect->context()->shape();
906   }
907
908   if(!aShape.get()) {
909     myDumpBuffer << ")";
910     return *this;
911   }
912
913   myDumpBuffer << "\"" << aShape->shapeTypeStr() << "\", \"" <<
914     theAttrSelect->namingName() << "\")";
915   return *this;
916 }
917
918 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
919     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
920 {
921   myDumpBuffer << "[";
922
923   GeomShapePtr aShape;
924   std::string aShapeTypeStr;
925
926   bool isAdded = false;
927
928   for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
929     AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
930     aShape = anAttribute->value();
931     if(!aShape.get()) {
932       ResultPtr aContext = anAttribute->context();
933       if (aContext.get())
934         aShape = aContext->shape();
935     }
936
937     if(!aShape.get()) {
938       continue;
939     }
940
941     if(isAdded) {
942       myDumpBuffer << ", ";
943     } else {
944       isAdded = true;
945     }
946     myDumpBuffer << "model.selection(\"" <<
947       aShape->shapeTypeStr() << "\", \"" << anAttribute->namingName() << "\")";
948   }
949
950   myDumpBuffer << "]";
951   return *this;
952 }
953
954 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
955   const std::shared_ptr<ModelAPI_AttributeStringArray>& theArray)
956 {
957   myDumpBuffer<<"[";
958   for(int anIndex = 0; anIndex < theArray->size(); ++anIndex) {
959     if (anIndex != 0)
960       myDumpBuffer<<", ";
961
962     myDumpBuffer<<"\""<<theArray->value(anIndex)<<"\"";
963   }
964
965   myDumpBuffer<<"]";
966   return *this;
967 }
968
969 /// Dump std::endl
970 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
971                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
972 {
973   theDumper.myDumpBuffer << theEndl;
974
975   if (!theDumper.myEntitiesStack.empty()) {
976     bool isCopy;
977     // all copies have been stored into stack, pop them all
978     do {
979       isCopy = false;
980       // Name for composite feature is dumped when all sub-entities are dumped
981       // (see method ModelHighAPI_Dumper::processSubs).
982       const ModelHighAPI_Dumper::LastDumpedEntity& aLastDumped = theDumper.myEntitiesStack.top();
983       CompositeFeaturePtr aComposite =
984           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aLastDumped.myEntity);
985       if (!aComposite) {
986         theDumper.dumpEntitySetName();
987         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastDumped.myEntity);
988         if (aFeature) {
989           AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
990           isCopy = aCopyAttr.get() && aCopyAttr->value();
991         }
992       }
993     } while (isCopy);
994   }
995
996   // store all not-dumped entities first
997   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
998   std::string aBufCopy = theDumper.myDumpBuffer.str();
999   theDumper.clear(true);
1000   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
1001   for (; anIt != aNotDumped.end(); ++anIt) {
1002     // if the feature is composite, dump it with all subs
1003     CompositeFeaturePtr aCompFeat =
1004         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
1005     if (aCompFeat)
1006       theDumper.process(aCompFeat, true);
1007     else {
1008       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1009       theDumper.dumpFeature(aFeature, true);
1010       // dump the Projection feature which produces this "Copy" entity
1011       AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1012       if (aCopyAttr.get() && aCopyAttr->value())
1013       {
1014         const std::set<AttributePtr>& aRefs = aFeature->data()->refsToMe();
1015         std::set<AttributePtr>::iterator aRefIt = aRefs.begin();
1016         for (; aRefIt != aRefs.end(); ++aRefIt)
1017           if ((*aRefIt)->id() == "ProjectedFeature")
1018           { // process projection only
1019             FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
1020             if (anOwner && !theDumper.isDumped(anOwner))
1021               theDumper.dumpFeature(anOwner, true);
1022           }
1023       }
1024     }
1025   }
1026
1027   // avoid multiple empty lines
1028   size_t anInd = std::string::npos;
1029   while ((anInd = aBufCopy.find("\n\n\n")) != std::string::npos)
1030     aBufCopy.erase(anInd, 1);
1031   // then store currently dumped string
1032   theDumper.myFullDump << aBufCopy;
1033
1034   // now, store all not dumped folders
1035   theDumper.dumpFolders();
1036
1037   return theDumper;
1038 }