1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
24 #pragma warning( disable:4786 )
27 #include "GEOM_Engine.hxx"
29 #include "GEOM_Field.hxx"
30 #include "GEOM_Function.hxx"
31 #include "GEOM_ISubShape.hxx"
32 #include "GEOM_PythonDump.hxx"
33 #include "GEOM_Solver.hxx"
34 #include "GEOM_SubShapeDriver.hxx"
35 #include "Sketcher_Profile.hxx"
37 #include <Basics_OCCTVersion.hxx>
39 #include "utilities.h"
41 #include <Basics_Utils.hxx>
43 #include <TDF_Tool.hxx>
44 #include <TDF_Data.hxx>
45 #include <TDF_Reference.hxx>
46 #include <TDF_LabelSequence.hxx>
47 #include <TDataStd_Integer.hxx>
48 #include <TDataStd_ChildNodeIterator.hxx>
49 #include <TFunction_Driver.hxx>
50 #include <TFunction_DriverTable.hxx>
51 #include <TDataStd_ByteArray.hxx>
52 #include <TDataStd_UAttribute.hxx>
53 #include <TDF_ChildIterator.hxx>
54 #include <TDataStd_Comment.hxx>
57 #include <TopTools_IndexedMapOfShape.hxx>
59 #include <TCollection_AsciiString.hxx>
60 #include <TCollection_ExtendedString.hxx>
61 #include <TColStd_SequenceOfAsciiString.hxx>
62 #include <TColStd_MapOfTransient.hxx>
63 #include <TColStd_HSequenceOfInteger.hxx>
65 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
67 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
71 #include <Standard_Failure.hxx>
72 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
77 #define O_SQR_BRACKET '['
78 #define C_SQR_BRACKET ']'
79 #define PY_NULL "None"
82 static int MYDEBUG = 0;
84 static int MYDEBUG = 0;
87 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
88 typedef std::map< TCollection_AsciiString, TObjectData > TSting2ObjDataMap;
89 typedef std::map< TCollection_AsciiString, TObjectData* > TSting2ObjDataPtrMap;
90 typedef std::map< int, std::list < int > > TIntToListIntMap;
92 static GEOM_Engine* TheEngine = NULL;
95 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_BaseObject)& theObject)
97 TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
98 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
99 anID+=(TCollection_AsciiString("_")+anEntry);
103 static TCollection_AsciiString BuildID(Standard_Integer theDocID, const char* theEntry)
105 TCollection_AsciiString anID(theDocID);
106 anID+=(TCollection_AsciiString("_")+theEntry);
110 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
112 TCollection_AsciiString aDocID = theID.Token("_");
113 if(aDocID.Length() < 1) return -1;
114 return aDocID.IntegerValue();
117 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
118 TCollection_AsciiString& theScript,
119 TCollection_AsciiString& theAfterScript,
120 const TVariablesList& theVariables,
121 const bool theIsPublished,
122 TDF_LabelMap& theProcessed,
123 std::set<TCollection_AsciiString>& theIgnoreObjs,
124 bool& theIsDumpCollected);
126 static int GetTag(const TCollection_AsciiString &theEntry);
128 static void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
129 TIntToListIntMap &theRefMap);
131 void ReplaceVariables(TCollection_AsciiString& theCommand,
132 const TVariablesList& theVariables);
134 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
136 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
137 TSting2ObjDataMap& aEntry2ObjData,
138 const bool theIsPublished,
139 TColStd_SequenceOfAsciiString& theObjListToPublish,
140 Standard_Integer& objectCounter,
141 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
143 void AddObjectColors (int theDocID,
144 TCollection_AsciiString& theScript,
145 const TSting2ObjDataMap& theEntry2ObjData);
147 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
149 void PublishObject (TObjectData& theObjectData,
150 TSting2ObjDataMap& theEntry2ObjData,
151 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
152 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
153 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
154 std::set<TCollection_AsciiString>& theMapOfPublished);
156 static TCollection_AsciiString GetPublishCommands
158 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
159 const TIntToListIntMap &theMapRefs,
160 std::set< int > &thePublished);
162 //================================================================================
164 * \brief Fix up the name of python variable
166 //================================================================================
168 void GEOM_Engine::healPyName( TCollection_AsciiString& pyName,
169 const TCollection_AsciiString& anEntry,
170 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
172 const TCollection_AsciiString allowedChars
173 ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
175 if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
176 pyName.Insert( 1, 'a' );
178 int p, p2=1; // replace not allowed chars
179 while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
180 pyName.SetValue(p, '_');
183 if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
184 { // diff objects have same name - make a new name by appending a digit
185 TCollection_AsciiString aName2;
186 Standard_Integer i = 0;
188 aName2 = pyName + "_" + ++i;
189 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
194 //=======================================================================
195 //function : GetTextureGUID
197 //=======================================================================
198 const Standard_GUID& GEOM_Engine::GetTextureGUID()
200 static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
204 //=============================================================================
208 //=============================================================================
209 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
211 //=============================================================================
215 //=============================================================================
216 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
218 //=============================================================================
222 //=============================================================================
223 GEOM_Engine::GEOM_Engine()
225 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
227 _OCAFApp = new GEOM_Application();
234 GEOM_Engine::~GEOM_Engine()
236 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
237 std::list< Handle(GEOM_Object) > objs;
238 for(; It.More(); It.Next())
239 objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
240 std::list< Handle(GEOM_Object) >::iterator objit;
241 for(objit = objs.begin(); objit != objs.end(); ++objit)
242 RemoveObject(*objit);
244 //Close all documents not closed
245 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
246 for (; anItr.More(); anItr.Next())
249 anItr.Initialize( _mapIDDocument ); // anItr becomes invalid at _mapIDDocument.UnBind(docId)
251 _mapIDDocument.Clear();
255 //=============================================================================
259 //=============================================================================
260 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
262 Handle(TDocStd_Document) aDoc;
263 if(_mapIDDocument.IsBound(theDocID)) {
264 aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
267 #if OCC_VERSION_MAJOR > 6
268 _OCAFApp->NewDocument("BinOcaf", aDoc);
270 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
272 aDoc->SetUndoLimit(_UndoLimit);
273 _mapIDDocument.Bind(theDocID, aDoc);
274 TDataStd_Integer::Set(aDoc->Main(), theDocID);
279 //=============================================================================
283 //=============================================================================
284 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
286 if (theDocument.IsNull()) return -1;
287 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
288 for (; anItr.More(); anItr.Next())
289 if (anItr.Value() == theDocument) return anItr.Key();
294 //=============================================================================
298 //=============================================================================
300 Handle(GEOM_BaseObject) GEOM_Engine::GetObject(int theDocID, const char* theEntry, bool force)
302 Handle(GEOM_BaseObject) anObject;
304 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
306 if (_objects.IsBound(anID)) {
307 anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
310 Handle(TDocStd_Document) aDoc = GetDocument(theDocID, force);
311 if ( !aDoc.IsNull()) {
313 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
314 if ( !aLabel.IsNull() ) {
315 int objType = GEOM_BaseObject::GetType( aLabel );
317 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break;
318 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break;
319 default: anObject = new GEOM_Object (aLabel);
321 _objects.Bind(anID, anObject);
329 //=============================================================================
333 //=============================================================================
335 Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theDocID, int theType)
337 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
338 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
340 // NPAL18604: use existing label to decrease memory usage,
341 // if this label has been freed (object deleted)
342 bool useExisting = false;
344 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
345 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
346 if (!aFreeLabels.empty()) {
348 aChild = aFreeLabels.front();
349 aFreeLabels.pop_front();
354 aChild = TDF_TagSource::NewChild(aDoc->Main());
357 Handle(GEOM_BaseObject) anObject;
359 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break;
360 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break;
361 default: anObject = new GEOM_Object (aChild, theType);
364 //Put an object in the map of created objects
365 TCollection_AsciiString anID = BuildIDFromObject(anObject);
366 if(_objects.IsBound(anID)) _objects.UnBind(anID);
367 _objects.Bind(anID, anObject);
372 //================================================================================
374 * \brief Adds a new object of the type theType in the OCAF document
376 //================================================================================
378 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
380 return Handle(GEOM_Object)::DownCast( AddBaseObject(theDocID, theType) );
383 //=============================================================================
387 //=============================================================================
389 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
390 Handle(TColStd_HArray1OfInteger) theIndices,
391 bool isStandaloneOperation)
393 if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
395 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
396 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
398 // NPAL18604: use existing label to decrease memory usage,
399 // if this label has been freed (object deleted)
400 bool useExisting = false;
402 int aDocID = theMainShape->GetDocID();
403 if (_freeLabels.find(aDocID) != _freeLabels.end()) {
404 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
405 if (!aFreeLabels.empty()) {
407 aChild = aFreeLabels.front();
408 aFreeLabels.pop_front();
413 aChild = TDF_TagSource::NewChild(aDoc->Main());
416 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
417 Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
418 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
420 GEOM_ISubShape aSSI (aFunction);
421 aSSI.SetMainShape(aMainShape);
422 aSSI.SetIndices(theIndices);
426 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
427 if (!aSolver.ComputeFunction(aFunction)) {
428 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
432 catch (Standard_Failure) {
433 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
434 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
438 // Put an object in the map of created objects
439 TCollection_AsciiString anID = BuildIDFromObject(anObject);
440 if (_objects.IsBound(anID)) _objects.UnBind(anID);
441 _objects.Bind(anID, anObject);
443 // Put this sub-shape in the list of sub-shapes of theMainShape
444 aMainShape->AddSubShapeReference(aFunction);
446 GEOM::TPythonDump pd (aFunction);
448 if (isStandaloneOperation) {
449 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
450 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
451 for (; i <= up - 1; i++) {
452 pd << theIndices->Value(i) << ", ";
454 pd << theIndices->Value(up) << "])";
462 //=============================================================================
466 //=============================================================================
467 bool GEOM_Engine::RemoveObject(Handle(GEOM_BaseObject)& theObject)
469 if (theObject.IsNull()) return false;
471 int aDocID = theObject->GetDocID();
472 if(!_mapIDDocument.IsBound(aDocID))
473 return false; // document is closed...
475 //Remove an object from the map of available objects
476 TCollection_AsciiString anID = BuildIDFromObject(theObject);
477 if (_objects.IsBound(anID)) {
478 Handle(GEOM_BaseObject) anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
479 if ( anObject != theObject )
480 anObject->_label = anObject->_label.Root();
481 _objects.UnBind(anID);
484 // If sub-shape, remove it from the list of sub-shapes of its main shape
485 Handle(GEOM_Object) aGO = Handle(GEOM_Object)::DownCast( theObject );
486 if ( !aGO.IsNull() && !aGO->IsMainShape()) {
487 Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
488 GEOM_ISubShape aSSI (aFunction);
489 Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
490 //If main shape is not null, then remove
491 if(!aMainShape.IsNull())
492 aMainShape->RemoveSubShapeReference(aFunction);
495 int nb = theObject->GetNbFunctions();
496 Handle(TDataStd_TreeNode) aNode;
497 for (int i = 1; i <= nb; i++) {
498 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
499 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
503 TDF_Label aLabel = theObject->GetEntry();
504 aLabel.ForgetAllAttributes(Standard_True);
506 // Remember the label to reuse it then
507 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
508 if ( aFreeLabels.empty() || aFreeLabels.back() != aLabel )
509 aFreeLabels.push_back(aLabel);
511 // we can't explicitely delete theObject. At least prevent its functioning
512 // as an alive object when aLabel is reused for a new object
513 theObject->_label = aLabel.Root();
514 theObject->_ior.Clear();
515 theObject->_parameters.Clear();
516 theObject->_docID = -1;
523 //=============================================================================
527 //=============================================================================
528 void GEOM_Engine::Undo(int theDocID)
530 GetDocument(theDocID)->Undo();
533 //=============================================================================
537 //=============================================================================
538 void GEOM_Engine::Redo(int theDocID)
540 GetDocument(theDocID)->Redo();
543 //=============================================================================
547 //=============================================================================
548 bool GEOM_Engine::Save(int theDocID, const char* theFileName)
550 if(!_mapIDDocument.IsBound(theDocID)) return false;
551 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
553 _OCAFApp->SaveAs(aDoc, theFileName);
558 //=============================================================================
562 //=============================================================================
563 bool GEOM_Engine::Load(int theDocID, const char* theFileName)
565 Handle(TDocStd_Document) aDoc;
566 if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
570 #if OCC_VERSION_MAJOR > 6
571 // Replace old document format by the new one.
572 if (aDoc->StorageFormat().IsEqual("SALOME_GEOM")) {
573 aDoc->ChangeStorageFormat("BinOcaf");
577 aDoc->SetUndoLimit(_UndoLimit);
579 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
580 _mapIDDocument.Bind(theDocID, aDoc);
582 TDataStd_Integer::Set(aDoc->Main(), theDocID);
587 //=============================================================================
591 //=============================================================================
592 void GEOM_Engine::Close(int theDocID)
594 if (_mapIDDocument.IsBound(theDocID)) {
595 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
597 //Remove all GEOM Objects associated to the given document
598 TColStd_SequenceOfAsciiString aSeq;
599 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
600 for (; It.More(); It.Next()) {
601 TCollection_AsciiString anObjID (It.Key());
602 Standard_Integer anID = ExtractDocID(anObjID);
603 if (theDocID == anID) aSeq.Append(It.Key());
605 for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
607 // Forget free labels for this document
608 TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
609 if (anIt != _freeLabels.end()) {
610 _freeLabels.erase(anIt);
613 _mapIDDocument.UnBind(theDocID);
614 _OCAFApp->Close(aDoc);
619 //=============================================================================
623 //=============================================================================
624 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
625 std::vector<TObjectData>& theObjectData,
626 TVariablesList theVariables,
631 // Set "C" numeric locale to save numbers correctly
632 Kernel_Utils::Localizer loc;
634 TCollection_AsciiString aScript;
635 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
639 TCollection_AsciiString anEmptyScript;
641 anEmptyScript = "def RebuildData(theStudy): pass\n";
642 return anEmptyScript;
645 aScript = "import GEOM\n";
646 aScript += "from salome.geom import geomBuilder\n";
647 aScript += "import math\n";
648 aScript += "import SALOMEDS\n\n";
650 aScript += "def RebuildData(theStudy):";
652 aScript += "\n\tgeompy = geomBuilder.New(theStudy)\n";
654 AddTextures(theDocID, aScript);
656 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
658 // a map containing copies of TObjectData from theObjectData
659 TSting2ObjDataMap aEntry2ObjData;
660 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
661 // occures when several StudyEntries correspond to one Entry
662 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
664 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
665 for (unsigned i = 0; i < theObjectData.size(); ++i )
667 TObjectData& data = theObjectData[i];
668 // look for an object by entry
670 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
671 if ( L.IsNull() ) continue;
672 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
674 if ( !obj.IsNull() ) {
675 TSting2ObjDataMap::iterator ent2Data =
676 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
678 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
679 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
681 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
685 // collect objects entries to be published
686 TColStd_SequenceOfAsciiString aObjListToPublish;
688 // iterates on functions till critical (that requiers publication of objects)
689 Handle(TDataStd_TreeNode) aNode, aRoot;
690 Handle(GEOM_Function) aFunction;
691 TDF_LabelMap aCheckedFuncMap;
692 std::set< TCollection_AsciiString > anIgnoreObjMap;
694 TCollection_AsciiString aFuncScript;
696 // Mantis issue 0020768
697 Standard_Integer objectCounter = 0;
698 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
699 TIntToListIntMap aRefMap;
701 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
702 TDataStd_ChildNodeIterator Itr(aRoot);
703 for (; Itr.More(); Itr.Next()) {
705 aFunction = GEOM_Function::GetFunction(aNode->Label());
706 if (aFunction.IsNull()) {
707 MESSAGE ( "Null function !!!!" );
710 bool isDumpCollected = false;
711 TCollection_AsciiString aCurScript, anAfterScript;
712 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
713 isPublished, aCheckedFuncMap, anIgnoreObjMap,
716 // add function description before dump
717 if (!aCurScript.IsEmpty())
719 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
720 aFuncScript.Length() > aCurScript.Length() )
721 // avoid repeated SubShape...() command at the end
722 if (aFuncScript.Location( aCurScript,
723 aFuncScript.Length() - aCurScript.Length(),
724 aFuncScript.Length()))
725 continue; // aCurScript is already at the end of aFuncScript
726 aFuncScript += aCurScript;
729 // Fill the map of references.
730 FillMapOfRef(aFunction, aRefMap);
732 if (isDumpCollected ) {
733 // Replace entries by the names
734 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
735 aObjListToPublish, objectCounter, aNameToEntry );
737 // publish collected objects
738 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
739 int i = 1, n = aObjListToPublish.Length();
740 for ( ; i <= n; i++ )
742 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
743 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
744 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
746 // add publishing commands to the script
747 std::set< int > aPublished;
748 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
750 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
751 const TCollection_AsciiString aPublishCmds =
752 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
753 aRefMap, aPublished);
755 aFuncScript += aPublishCmds;
758 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
759 // because they will be published during command execution
760 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
762 indx = anAfterScript.Search( "RestoreSubShapes" );
764 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
765 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
766 i = 1, n = aSeq->Length();
767 for ( ; i <= n; i+=2) {
768 TCollection_AsciiString anEntry =
769 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
770 anIgnoreObjMap.insert(anEntry.ToCString());
774 aObjListToPublish.Clear();
775 aScript += aFuncScript;
778 aFuncScript += anAfterScript;
782 // Replace entries by the names
783 aObjListToPublish.Clear();
784 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
785 objectCounter, aNameToEntry );
787 aScript += aFuncScript;
790 AddObjectColors( theDocID, aScript, aEntry2ObjData );
792 // Make script to publish in study
793 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
796 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
798 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
799 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
800 ++aStEntry2ObjDataPtrIt)
802 TObjectData* data = aStEntry2ObjDataPtrIt->second;
803 if ( anIgnoreObjMap.count( data->_entry ))
804 continue; // should not be dumped
805 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
806 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
808 // add publishing commands to the script
809 std::set< int > aPublished;
810 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
812 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
813 const TCollection_AsciiString aPublishCmds =
814 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
815 aRefMap, aPublished);
817 aScript += aPublishCmds;
821 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
822 //Add unpublish command if need
823 TCollection_AsciiString unpublishCmd("\n");
825 unpublishCmd += "\t";
826 unpublishCmd += "geompy.hideInStudy(";
828 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
829 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
830 ++aStEntry2ObjDataPtrIt)
832 TObjectData* data = aStEntry2ObjDataPtrIt->second;
833 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
834 aScript += unpublishCmd + data->_pyName + ")";
838 //aScript += "\n\tpass\n";
842 // fill _studyEntry2NameMap and build globalVars
843 TCollection_AsciiString globalVars;
844 _studyEntry2NameMap.Clear();
845 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
846 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
847 ++aStEntry2ObjDataPtrIt)
849 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
850 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
851 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
852 if ( !globalVars.IsEmpty() )
854 globalVars += data->_pyName;
856 if ( isMultiFile && !globalVars.IsEmpty() ) {
857 globalVars.Insert( 1, "\n\tglobal " );
858 aScript.Insert( posToInsertGlobalVars, globalVars );
864 //=======================================================================
865 //function : GetDumpName
867 //=======================================================================
869 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
871 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
872 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
877 //=======================================================================
878 //function : GetAllDumpNames
880 //=======================================================================
882 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
884 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
886 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
887 for (; it.More(); it.Next()) {
888 aRetSeq->Append(it.Value());
894 #define TEXTURE_LABEL_ID 1
895 #define TEXTURE_LABEL_FILE 2
896 #define TEXTURE_LABEL_WIDTH 3
897 #define TEXTURE_LABEL_HEIGHT 4
898 #define TEXTURE_LABEL_DATA 5
900 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
901 const Handle(TColStd_HArray1OfByte)& theTexture,
902 const TCollection_AsciiString& theFileName)
904 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
905 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
907 // NPAL18604: use existing label to decrease memory usage,
908 // if this label has been freed (object deleted)
909 bool useExisting = false;
911 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
912 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
913 if (!aFreeLabels.empty()) {
915 aChild = aFreeLabels.front();
916 aFreeLabels.pop_front();
921 aChild = TDF_TagSource::NewChild(aDoc->Main());
924 aChild.ForgetAllAttributes(Standard_True);
925 Handle(TDataStd_TreeNode) node;
926 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
927 node = TDataStd_TreeNode::Set(aChild);
928 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
930 static int aTextureID = 0;
932 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
933 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
934 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
935 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
937 Handle(TDataStd_ByteArray) anAttr =
938 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
939 theTexture.IsNull() ? 0 : theTexture->Lower(),
940 theTexture.IsNull() ? 0 : theTexture->Upper());
941 anAttr->ChangeArray(theTexture);
946 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
947 int& theWidth, int& theHeight,
948 TCollection_AsciiString& theFileName)
950 Handle(TColStd_HArray1OfByte) anArray;
951 theWidth = theHeight = 0;
953 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
955 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
957 for (; anIterator.More() && !found; anIterator.Next()) {
958 TDF_Label aTextureLabel = anIterator.Value();
959 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
960 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
961 Handle(TDataStd_Integer) anIdAttr;
962 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
963 anIdAttr->Get() == theTextureID) {
964 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
965 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
966 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
967 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
968 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
969 Handle(TDataStd_ByteArray) aTextureAttr;
970 Handle(TDataStd_Comment) aFileAttr;
971 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
972 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
973 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
974 theWidth = aWidthAttr->Get();
975 theHeight = aHeightAttr->Get();
976 anArray = aTextureAttr->InternalArray();
978 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
979 theFileName = aFileAttr->Get();
987 std::list<int> GEOM_Engine::getAllTextures(int theDocID)
989 std::list<int> id_list;
991 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
993 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
994 for (; anIterator.More(); anIterator.Next()) {
995 TDF_Label aTextureLabel = anIterator.Value();
996 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
997 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
998 Handle(TDataStd_Integer) anIdAttr;
999 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
1000 id_list.push_back((int)anIdAttr->Get());
1006 void GEOM_Engine::DocumentModified(const int theDocId, const bool isModified)
1008 if (isModified) _mapModifiedDocs.Add(theDocId);
1009 else _mapModifiedDocs.Remove(theDocId);
1012 bool GEOM_Engine::DocumentModified(const int theDocId)
1014 return _mapModifiedDocs.Contains(theDocId);
1017 //===========================================================================
1018 // Internal functions
1019 //===========================================================================
1021 //=============================================================================
1023 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
1025 //=============================================================================
1026 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
1028 TCollection_AsciiString aNewDescr;
1030 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
1031 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
1032 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
1033 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1034 // "3DSketcher:CMD[:CMD[:CMD...]]"
1035 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
1037 // Split the command string to separate CMDs
1039 TColStd_SequenceOfAsciiString aSequence;
1040 if (aCommand.Length()) {
1041 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
1042 while (aToken.Length() > 0) {
1043 aSequence.Append(aToken);
1044 aToken = aCommand.Token(":", ++icmd);
1048 if (aSequence.Length() > 0) {
1050 aNewDescr += "\n\t";
1052 aNewDescr += "\nsk = geompy.Sketcher3D()";
1053 int nbCMDs = aSequence.Length();
1054 for (icmd = 1; icmd <= nbCMDs; icmd++) {
1055 aNewDescr += "\n\t";
1057 TCollection_AsciiString aCMD = aSequence.Value(icmd);
1059 // Split the CMD into string values
1060 TColStd_SequenceOfAsciiString aStrVals;
1062 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1063 while (aToken.Length() > 0) {
1064 aStrVals.Append(aToken);
1065 aToken = aCMD.Token(" ", ++ival);
1068 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1069 if (aCMDpref == "TT") {
1070 aNewDescr += "sk.addPointsAbsolute(";
1071 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1073 else if (aCMDpref == "T") {
1074 aNewDescr += "sk.addPointsRelative(";
1075 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1077 else if (aCMDpref == "WW") {
1078 aNewDescr += "sk.close()";
1080 else if (aCMDpref.Value(1) == 'O'){
1081 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1083 if (aCMDpref.Value(4) == 'C')
1084 aNewDescr += "sk.addPointRadiusAngleH";
1086 aNewDescr += "sk.addPointRadiusAngles";
1087 if (aCMDpref.Value(5) == 'A')
1088 aNewDescr += "Absolute(";
1090 aNewDescr += "Relative(";
1091 aNewDescr += aStrVals.Value(4) + ", " +
1092 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1095 aNewDescr += "\n\t";
1096 aNewDescr += aResult + " = sk.wire()";
1098 } // Make3DSketcherCommand
1099 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1100 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1101 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1102 aCommand = aCommand.Token("]", 1);
1104 aNewDescr += "\n\t";
1105 aNewDescr += "\nsk = geompy.Sketcher3D()";
1106 aNewDescr += "\n\t";
1107 aNewDescr += "sk.addPointsAbsolute(";
1108 aNewDescr += aCommand + ")";
1109 aNewDescr += "\n\t";
1110 aNewDescr += aResult + " = sk.wire()";
1114 aNewDescr += "\n\t";
1115 aNewDescr += aSubStr;
1122 //=============================================================================
1124 * ProcessFunction: Dump function description into script
1126 //=============================================================================
1127 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1128 TCollection_AsciiString& theScript,
1129 TCollection_AsciiString& theAfterScript,
1130 const TVariablesList& theVariables,
1131 const bool theIsPublished,
1132 TDF_LabelMap& theProcessed,
1133 std::set<TCollection_AsciiString>& theIgnoreObjs,
1134 bool& theIsDumpCollected)
1136 theIsDumpCollected = false;
1137 if (theFunction.IsNull()) return false;
1139 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1141 // pass functions, that depends on nonexisting ones
1142 bool doNotProcess = false;
1143 TDF_LabelSequence aSeq;
1144 theFunction->GetDependency(aSeq);
1145 Standard_Integer aLen = aSeq.Length();
1146 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1147 TDF_Label aRefLabel = aSeq.Value(i);
1148 Handle(TDF_Reference) aRef;
1149 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1150 doNotProcess = true;
1153 if (aRef.IsNull() || aRef->Get().IsNull()) {
1154 doNotProcess = true;
1157 Handle(TDataStd_TreeNode) aT;
1158 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1159 doNotProcess = true;
1162 TDF_Label aDepLabel = aT->Label();
1163 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1165 if (aFunction.IsNull()) doNotProcess = true;
1166 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1173 TCollection_AsciiString anObjEntry;
1174 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1175 theIgnoreObjs.insert(anObjEntry);
1178 theProcessed.Add(theFunction->GetEntry());
1180 TCollection_AsciiString aDescr = theFunction->GetDescription();
1181 if(aDescr.Length() == 0) return false;
1183 //Check if its internal function which doesn't requires dumping
1184 if(aDescr == "None") return false;
1186 //Check the very specific case of RestoreShape function,
1187 //which is not dumped, but the result can be published by the user.
1188 //We do not publish such objects to decrease danger of dumped script failure.
1189 if(aDescr.Value(1) == '#') {
1190 TCollection_AsciiString anObjEntry;
1191 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1192 theIgnoreObjs.insert(anObjEntry);
1196 // 0020001 PTv, check for critical functions, which require dump of objects
1199 // currently, there is only one function "RestoreGivenSubShapes",
1200 // later this check could be replaced by iterations on list of such functions
1201 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1202 theIsDumpCollected = true;
1203 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1204 theIsDumpCollected = true;
1207 //Replace parameter by notebook variables
1208 ReplaceVariables(aDescr,theVariables);
1210 //Process sketcher functions, replacing string command by calls to Sketcher interface
1211 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1212 Sketcher_Profile aProfile( aDescr.ToCString());
1213 // Make new command for SketcherOnPlane and for Sketcher
1214 aDescr = aProfile.GetDump();
1216 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1217 aDescr = MakeCommandfor3DSketcher ( aDescr );
1220 if ( theIsDumpCollected ) {
1222 bool isBefore = true;
1223 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1224 while (!aSubStr.IsEmpty()) {
1226 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1227 aSubStr.Search( "RestoreSubShapes" ) == -1)
1228 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1230 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1231 aSubStr = aDescr.Token("\n\t", i++);
1235 theScript += "\n\t";
1236 theScript += aDescr;
1241 //=============================================================================
1243 * GetTag: Returns the tag from entry
1245 //=============================================================================
1246 int GetTag(const TCollection_AsciiString &theEntry)
1248 const int aGeomObjDepth = 3;
1249 const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue();
1254 //=============================================================================
1256 * FillMapOfRef: Fill the map of references
1258 //=============================================================================
1259 void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
1260 TIntToListIntMap &theRefMap)
1262 TDF_LabelSequence aSeq;
1263 TCollection_AsciiString anObjEntry;
1266 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1267 anObjTag = GetTag(anObjEntry);
1268 theFunction->GetDependency(aSeq);
1270 const Standard_Integer aLen = aSeq.Length();
1273 for (i = 1; i <= aLen; i++) {
1274 TDF_Label aRefLabel = aSeq.Value(i);
1275 Handle(TDF_Reference) aRef;
1277 if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1278 if (!aRef.IsNull() && !aRef->Get().IsNull()) {
1279 Handle(TDataStd_TreeNode) aT;
1281 if (TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1282 TDF_Label aDepLabel = aT->Label();
1283 Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel);
1285 if (!aRefFunct.IsNull()) {
1286 // Get entry of the referenced object.
1287 TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry);
1289 const int aRefTag = GetTag(anObjEntry);
1291 if (anObjTag != aRefTag) {
1292 // Avoid making references for operations without copy.
1293 theRefMap[anObjTag].push_back(aRefTag);
1302 //=============================================================================
1304 * FindEntries: Returns a sequence of start/end positions of entries in the string
1306 //=============================================================================
1307 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1309 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1310 Standard_Integer aLen = theString.Length();
1311 Standard_Boolean isFound = Standard_False;
1313 const char* arr = theString.ToCString();
1314 Standard_Integer i = 0, j;
1317 int c = (int)arr[i];
1319 if(c >= 48 && c <= 57) { //Is digit?
1321 isFound = Standard_False;
1322 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1324 if(c == 58) isFound = Standard_True;
1327 if(isFound && arr[j-2] != 58) { // last char should be a diggit
1328 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1339 //=============================================================================
1341 * ReplaceVariables: Replace parameters of the function by variales from
1344 //=============================================================================
1345 void ReplaceVariables(TCollection_AsciiString& theCommand,
1346 const TVariablesList& theVariables)
1349 cout<<"Command : "<<theCommand<<endl;
1352 cout<<"All Entries:"<<endl;
1353 TVariablesList::const_iterator it = theVariables.begin();
1354 for(;it != theVariables.end();it++)
1355 cout<<"\t'"<<(*it).first<<"'"<<endl;
1358 //Additional case - multi-row commands
1359 int aCommandIndex = 1;
1360 while( aCommandIndex < 10 ) { // tmp check
1361 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1362 if( aCommand.Length() == 0 )
1366 cout<<"Sub-command : "<<aCommand<<endl;
1368 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1369 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1371 //Get Entry of the result object
1372 TCollection_AsciiString anEntry;
1373 if( aCommand.Search("=") != -1 ) // command returns an object
1374 anEntry = aCommand.Token("=",1);
1375 else { // command modifies the object
1376 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1377 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1378 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1380 //Remove white spaces
1381 anEntry.RightAdjust();
1382 anEntry.LeftAdjust();
1384 cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1386 if ( anEntry.IsEmpty() ) {
1391 //Check if result is list of entries - enough to get the first entry in this case
1393 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1394 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1396 TCollection_AsciiString aSeparator(COMMA);
1397 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1398 anEntry.Remove( 1, 1 );
1399 anEntry.RightAdjust();
1400 anEntry.LeftAdjust();
1402 cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1405 //Find variables used for object construction
1406 ObjectStates* aStates = 0;
1407 TVariablesList::const_iterator it = theVariables.find(anEntry);
1408 if( it != theVariables.end() )
1409 aStates = (*it).second;
1413 cout<<"Valiables list empty!!!"<<endl;
1418 TState aVariables = aStates->GetCurrectState();
1421 cout<<"Variables from SObject:"<<endl;
1422 for (int i = 0; i < aVariables.size();i++)
1423 cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1426 //Calculate total number of parameters
1427 Standard_Integer aTotalNbParams = 1;
1428 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1432 cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1434 Standard_Integer aFirstParam = aNbEntries;
1436 //Replace parameters by variables
1437 Standard_Integer aStartPos = 0;
1438 Standard_Integer aEndPos = 0;
1440 TCollection_AsciiString aVar, aReplacedVar;
1441 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1442 //Replace first parameter (bettwen '(' character and first ',' character)
1443 if(i == aFirstParam)
1445 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1446 if(aTotalNbParams - aNbEntries > 0 )
1447 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1449 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1451 //Replace last parameter (bettwen ',' character and ')' character)
1452 else if(i == aTotalNbParams)
1454 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1455 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1457 //Replace other parameters (bettwen two ',' characters)
1458 else if(i != aFirstParam && i != aTotalNbParams )
1460 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1461 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1464 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1466 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1468 if ( aStartPos == aEndPos )
1469 continue; // PAL20889: for "[]"
1472 cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1474 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1479 cout<<"Variable: '"<< aVar <<"'"<<endl;
1481 // specific case for sketcher
1482 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1483 Standard_Integer aNbSections = 1;
1484 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1488 int aStartSectionPos = 0, aEndSectionPos = 0;
1489 TCollection_AsciiString aSection, aReplacedSection;
1490 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1491 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1492 if( aSectionIndex != aNbSections )
1493 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1495 aEndSectionPos = aVar.Length();
1497 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1499 cout<<"aSection: "<<aSection<<endl;
1501 Standard_Integer aNbParams = 1;
1502 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1506 int aStartParamPos = 0, aEndParamPos = 0;
1507 TCollection_AsciiString aParameter, aReplacedParameter;
1508 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1509 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1510 if( aParamIndex != aNbParams )
1511 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1513 aEndParamPos = aSection.Length() + 1;
1516 cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
1518 if ( aStartParamPos == aEndParamPos)
1521 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1523 cout<<"aParameter: "<<aParameter<<endl;
1525 if(iVar >= aVariables.size())
1528 aReplacedParameter = aVariables[iVar].myVariable;
1529 if(aReplacedParameter.IsEmpty()) {
1534 if(aVariables[iVar].isVariable) {
1535 aReplacedParameter.InsertBefore(1,"'");
1536 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1540 cout<<"aSection before : "<<aSection<<endl;
1541 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1542 aSection.Insert(aStartParamPos, aReplacedParameter);
1544 cout<<"aSection after : "<<aSection<<endl<<endl;
1548 cout<<"aVar before : "<<aVar<<endl;
1549 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1550 aVar.Insert(aStartSectionPos, aSection);
1552 cout<<"aVar after : "<<aVar<<endl<<endl;
1556 cout<<"aCommand before : "<<aCommand<<endl;
1557 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1558 aCommand.Insert(aStartPos, aVar);
1560 cout<<"aCommand after : "<<aCommand<<endl;
1563 } // end of specific case for sketcher
1565 //If parameter is entry or 'None', skip it
1566 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1569 if(iVar >= aVariables.size())
1572 aReplacedVar = aVariables[iVar].myVariable;
1573 if(aReplacedVar.IsEmpty()) {
1578 if(aVariables[iVar].isVariable) {
1579 aReplacedVar.InsertBefore(1,"\"");
1580 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1583 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1584 aCommand.Insert(aStartPos, aReplacedVar);
1588 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1589 theCommand.Insert(aStartCommandPos, aCommand);
1593 aStates->IncrementState();
1597 cout<<"Command : "<<theCommand<<endl;
1600 //=============================================================================
1602 * ReplaceEntriesByNames: Replace object entries by their names
1604 //=============================================================================
1605 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1606 TSting2ObjDataMap& aEntry2ObjData,
1607 const bool theIsPublished,
1608 TColStd_SequenceOfAsciiString& theObjListToPublish,
1609 Standard_Integer& objectCounter,
1610 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1612 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1613 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1614 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1616 //Replace entries by the names
1617 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1618 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1619 if (aLen == 0) anUpdatedScript = theScript;
1621 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1622 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1623 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1624 theObjListToPublish.Append( anEntry );
1626 TObjectData& data = aEntry2ObjData[ anEntry ];
1627 if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1628 if ( !data._name.IsEmpty() ) { // published object
1629 data._pyName = data._name;
1630 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1634 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1635 } while(aNameToEntry.IsBound(data._pyName));
1639 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1641 anUpdatedScript += data._pyName;
1642 aStart = aSeq->Value(i+1) + 1;
1645 //Add final part of the script
1646 if (aLen && aSeq->Value(aLen) < aScriptLength)
1647 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1649 theScript = anUpdatedScript;
1652 //=============================================================================
1654 * AddObjectColors: Add color to objects
1656 //=============================================================================
1657 void AddObjectColors (int theDocID,
1658 TCollection_AsciiString& theScript,
1659 const TSting2ObjDataMap& theEntry2ObjData)
1661 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1662 Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
1664 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1665 for (anEntryToNameIt = theEntry2ObjData.begin();
1666 anEntryToNameIt!= theEntry2ObjData.end();
1669 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1670 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1673 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1677 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1681 bool anAutoColor = obj->GetAutoColor();
1684 TCollection_AsciiString aCommand( "\n\t" );
1685 aCommand += aName + ".SetAutoColor(1)";
1686 theScript += aCommand.ToCString();
1689 GEOM_Object::Color aColor = obj->GetColor();
1690 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1692 TCollection_AsciiString aCommand( "\n\t" );
1693 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1694 theScript += aCommand.ToCString();
1697 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1698 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1699 TCollection_AsciiString aCommand( "\n\t" );
1700 aCommand += aName + ".SetMarkerStd(";
1701 switch (aMarkerType) {
1702 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1703 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1704 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1705 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1706 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1707 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1708 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1709 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1710 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1711 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1712 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1713 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1714 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1715 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1718 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1720 case 1: aCommand += "GEOM.MS_10"; break;
1721 case 2: aCommand += "GEOM.MS_15"; break;
1722 case 3: aCommand += "GEOM.MS_20"; break;
1723 case 4: aCommand += "GEOM.MS_25"; break;
1724 case 5: aCommand += "GEOM.MS_30"; break;
1725 case 6: aCommand += "GEOM.MS_35"; break;
1726 case 7: aCommand += "GEOM.MS_40"; break;
1727 case 8: aCommand += "GEOM.MS_45"; break;
1728 case 9: aCommand += "GEOM.MS_50"; break;
1729 case 10: aCommand += "GEOM.MS_55"; break;
1730 case 11: aCommand += "GEOM.MS_60"; break;
1731 case 12: aCommand += "GEOM.MS_65"; break;
1732 case 13: aCommand += "GEOM.MS_70"; break;
1733 default: aCommand += "GEOM.MS_NONE"; break;
1736 theScript += aCommand.ToCString();
1738 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1739 int aMarkerTextureID = obj->GetMarkerTexture();
1740 if (aMarkerTextureID >= 0) {
1741 TCollection_AsciiString aCommand( "\n\t" );
1742 aCommand += aName + ".SetMarkerTexture(texture_map[";
1743 aCommand += aMarkerTextureID;
1745 theScript += aCommand.ToCString();
1751 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1753 TCollection_AsciiString stream;
1754 if (!aData.IsNull()) {
1755 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1756 Standard_Byte byte = aData->Value(i);
1757 TCollection_AsciiString strByte = "";
1758 for (int j = 0; j < 8; j++)
1759 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1766 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
1768 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1769 std::list<int> allTextures = engine->getAllTextures(theDocID);
1770 std::list<int>::const_iterator it;
1772 if (allTextures.size() > 0) {
1773 theScript += "\n\ttexture_map = {}\n";
1775 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1776 if (*it <= 0) continue;
1777 Standard_Integer aWidth, aHeight;
1778 TCollection_AsciiString aFileName;
1779 Handle(TColStd_HArray1OfByte) aTexture =
1780 engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
1781 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1782 TCollection_AsciiString aCommand = "\n\t";
1783 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1784 if (aFileName != "" ) {
1785 aCommand += "geompy.LoadTexture(\"";
1786 aCommand += aFileName.ToCString();
1790 aCommand += "geompy.AddTexture(";
1791 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1792 aCommand += pack_data(aTexture);
1795 theScript += aCommand;
1802 //=============================================================================
1804 * PublishObject: publish object in study script
1806 //=============================================================================
1807 void PublishObject (TObjectData& theObjectData,
1808 TSting2ObjDataMap& theEntry2ObjData,
1809 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1810 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1811 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1812 std::set< TCollection_AsciiString>& theIgnoreMap)
1814 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1815 if ( theObjectData._studyEntry.IsEmpty() )
1816 return; // was not published
1817 if ( theIgnoreMap.count( theObjectData._entry ) )
1818 return; // not to publish
1820 TCollection_AsciiString aCommand("\n\tgeompy.");
1822 // find a father entry
1823 TObjectData* aFatherData = 0;
1824 TCollection_AsciiString aFatherStudyEntry =
1825 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1826 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1827 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1828 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1829 aFatherData = stEntry2DataPtr->second;
1831 // treat multiply published object
1832 if ( theObjectData._pyName.IsEmpty() )
1834 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1835 if ( data0._pyName.IsEmpty() ) return; // something wrong
1837 theObjectData._pyName = theObjectData._name;
1838 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1840 TCollection_AsciiString aCreationCommand("\n\t");
1841 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1843 // store aCreationCommand before publishing commands
1844 int tag = GetTag(theObjectData._entry);
1845 theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1849 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1850 aCommand += "addToStudyInFather( ";
1851 aCommand += aFatherData->_pyName + ", ";
1854 aCommand += "addToStudy( ";
1856 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1858 // bind a command to the study entry
1859 int tag = GetTag(theObjectData._entry);
1860 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1862 theObjectData._studyEntry.Clear(); // not to publish any more
1865 //================================================================================
1867 * \brief Returns the string of publishing commands. Take into account that
1868 * references should be published prior to the objects refer to them.
1870 //================================================================================
1871 TCollection_AsciiString GetPublishCommands
1873 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
1874 const TIntToListIntMap &theMapRefs,
1875 std::set< int > &thePublished)
1877 TCollection_AsciiString aResult;
1879 if (!thePublished.count(theTag)) {
1880 // This object is not published yet.
1881 std::map< int, TCollection_AsciiString >::const_iterator anIt =
1882 theEntryToCmdMap.find(theTag);
1884 if (anIt != theEntryToCmdMap.end()) {
1885 // There is a pubish cmd.
1886 TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag);
1888 if (aRefIt != theMapRefs.end()) {
1889 // Recursively publish all references.
1890 std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin();
1892 for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) {
1893 const TCollection_AsciiString aRefCmd = GetPublishCommands
1894 (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished);
1900 // Add the object command.
1901 aResult += anIt->second;
1904 thePublished.insert(theTag);
1910 //================================================================================
1912 * \brief Constructor
1914 //================================================================================
1915 ObjectStates::ObjectStates()
1920 //================================================================================
1924 //================================================================================
1925 ObjectStates::~ObjectStates()
1929 //================================================================================
1931 * \brief Return current object state
1932 * \retval state - Object state (vector of notebook variable)
1934 //================================================================================
1935 TState ObjectStates::GetCurrectState() const
1937 if(_states.size() > _dumpstate)
1938 return _states[_dumpstate];
1942 //================================================================================
1944 * \brief Add new object state
1945 * \param theState - Object state (vector of notebook variable)
1947 //================================================================================
1948 void ObjectStates::AddState(const TState &theState)
1950 _states.push_back(theState);
1953 //================================================================================
1955 * \brief Increment object state
1957 //================================================================================
1958 void ObjectStates::IncrementState()