1 // Copyright (C) 2007-2015 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_HArray1OfByte.hxx>
66 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
68 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
72 #include <Standard_Failure.hxx>
73 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
78 #define O_SQR_BRACKET '['
79 #define C_SQR_BRACKET ']'
80 #define PY_NULL "None"
83 static int MYDEBUG = 0;
85 static int MYDEBUG = 0;
88 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
89 typedef std::map< TCollection_AsciiString, TObjectData > TSting2ObjDataMap;
90 typedef std::map< TCollection_AsciiString, TObjectData* > TSting2ObjDataPtrMap;
91 typedef std::map< int, std::list < int > > TIntToListIntMap;
93 static GEOM_Engine* TheEngine = NULL;
96 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_BaseObject)& theObject)
98 TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
99 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
100 anID+=(TCollection_AsciiString("_")+anEntry);
104 static TCollection_AsciiString BuildID(Standard_Integer theDocID, const char* theEntry)
106 TCollection_AsciiString anID(theDocID);
107 anID+=(TCollection_AsciiString("_")+theEntry);
111 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
113 TCollection_AsciiString aDocID = theID.Token("_");
114 if(aDocID.Length() < 1) return -1;
115 return aDocID.IntegerValue();
118 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
119 TCollection_AsciiString& theScript,
120 TCollection_AsciiString& theAfterScript,
121 const TVariablesList& theVariables,
122 const bool theIsPublished,
123 TDF_LabelMap& theProcessed,
124 std::set<TCollection_AsciiString>& theIgnoreObjs,
125 bool& theIsDumpCollected);
127 static int GetTag(const TCollection_AsciiString &theEntry);
129 static void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
130 TIntToListIntMap &theRefMap);
132 void ReplaceVariables(TCollection_AsciiString& theCommand,
133 const TVariablesList& theVariables);
135 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
137 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
138 TSting2ObjDataMap& aEntry2ObjData,
139 const bool theIsPublished,
140 TColStd_SequenceOfAsciiString& theObjListToPublish,
141 Standard_Integer& objectCounter,
142 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
144 void AddObjectColors (int theDocID,
145 TCollection_AsciiString& theScript,
146 const TSting2ObjDataMap& theEntry2ObjData);
148 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
150 void PublishObject (TObjectData& theObjectData,
151 TSting2ObjDataMap& theEntry2ObjData,
152 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
153 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
154 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
155 std::set<TCollection_AsciiString>& theMapOfPublished);
157 static TCollection_AsciiString GetPublishCommands
159 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
160 const TIntToListIntMap &theMapRefs,
161 std::set< int > &thePublished);
163 //================================================================================
165 * \brief Fix up the name of python variable
167 //================================================================================
169 void GEOM_Engine::healPyName( TCollection_AsciiString& pyName,
170 const TCollection_AsciiString& anEntry,
171 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
173 const TCollection_AsciiString allowedChars
174 ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
176 if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
177 pyName.Insert( 1, 'a' );
179 int p, p2=1; // replace not allowed chars
180 while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
181 pyName.SetValue(p, '_');
184 if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
185 { // diff objects have same name - make a new name by appending a digit
186 TCollection_AsciiString aName2;
187 Standard_Integer i = 0;
189 aName2 = pyName + "_" + ++i;
190 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
195 //=======================================================================
196 //function : GetTextureGUID
198 //=======================================================================
199 const Standard_GUID& GEOM_Engine::GetTextureGUID()
201 static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
205 //=============================================================================
209 //=============================================================================
210 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
212 //=============================================================================
216 //=============================================================================
217 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
219 //=============================================================================
223 //=============================================================================
224 GEOM_Engine::GEOM_Engine()
226 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
228 _OCAFApp = new GEOM_Application();
235 GEOM_Engine::~GEOM_Engine()
237 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
238 std::list< Handle(GEOM_Object) > objs;
239 for(; It.More(); It.Next())
240 objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
241 std::list< Handle(GEOM_Object) >::iterator objit;
242 for(objit = objs.begin(); objit != objs.end(); ++objit)
243 RemoveObject(*objit);
245 //Close all documents not closed
246 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
247 for (; anItr.More(); anItr.Next())
250 anItr.Initialize( _mapIDDocument ); // anItr becomes invalid at _mapIDDocument.UnBind(docId)
252 _mapIDDocument.Clear();
256 //=============================================================================
260 //=============================================================================
261 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
263 Handle(TDocStd_Document) aDoc;
264 if(_mapIDDocument.IsBound(theDocID)) {
265 aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
268 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
269 aDoc->SetUndoLimit(_UndoLimit);
270 _mapIDDocument.Bind(theDocID, aDoc);
271 TDataStd_Integer::Set(aDoc->Main(), theDocID);
276 //=============================================================================
280 //=============================================================================
281 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
283 if (theDocument.IsNull()) return -1;
284 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
285 for (; anItr.More(); anItr.Next())
286 if (anItr.Value() == theDocument) return anItr.Key();
291 //=============================================================================
295 //=============================================================================
297 Handle(GEOM_BaseObject) GEOM_Engine::GetObject(int theDocID, const char* theEntry, bool force)
299 Handle(GEOM_BaseObject) anObject;
301 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
303 if (_objects.IsBound(anID)) {
304 anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
307 Handle(TDocStd_Document) aDoc = GetDocument(theDocID, force);
308 if ( !aDoc.IsNull()) {
310 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
311 if ( !aLabel.IsNull() ) {
312 int objType = GEOM_BaseObject::GetType( aLabel );
314 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break;
315 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break;
316 default: anObject = new GEOM_Object (aLabel);
318 _objects.Bind(anID, anObject);
326 //=============================================================================
330 //=============================================================================
332 Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theDocID, int theType)
334 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
335 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
337 // NPAL18604: use existing label to decrease memory usage,
338 // if this label has been freed (object deleted)
339 bool useExisting = false;
341 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
342 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
343 if (!aFreeLabels.empty()) {
345 aChild = aFreeLabels.front();
346 aFreeLabels.pop_front();
351 aChild = TDF_TagSource::NewChild(aDoc->Main());
354 Handle(GEOM_BaseObject) anObject;
356 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break;
357 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break;
358 default: anObject = new GEOM_Object (aChild, theType);
361 //Put an object in the map of created objects
362 TCollection_AsciiString anID = BuildIDFromObject(anObject);
363 if(_objects.IsBound(anID)) _objects.UnBind(anID);
364 _objects.Bind(anID, anObject);
369 //================================================================================
371 * \brief Adds a new object of the type theType in the OCAF document
373 //================================================================================
375 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
377 return Handle(GEOM_Object)::DownCast( AddBaseObject(theDocID, theType) );
380 //=============================================================================
384 //=============================================================================
386 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
387 Handle(TColStd_HArray1OfInteger) theIndices,
388 bool isStandaloneOperation)
390 if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
392 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
393 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
395 // NPAL18604: use existing label to decrease memory usage,
396 // if this label has been freed (object deleted)
397 bool useExisting = false;
399 int aDocID = theMainShape->GetDocID();
400 if (_freeLabels.find(aDocID) != _freeLabels.end()) {
401 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
402 if (!aFreeLabels.empty()) {
404 aChild = aFreeLabels.front();
405 aFreeLabels.pop_front();
410 aChild = TDF_TagSource::NewChild(aDoc->Main());
413 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
414 Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
415 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
417 GEOM_ISubShape aSSI (aFunction);
418 aSSI.SetMainShape(aMainShape);
419 aSSI.SetIndices(theIndices);
423 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
424 if (!aSolver.ComputeFunction(aFunction)) {
425 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
429 catch (Standard_Failure) {
430 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
431 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
435 // Put an object in the map of created objects
436 TCollection_AsciiString anID = BuildIDFromObject(anObject);
437 if (_objects.IsBound(anID)) _objects.UnBind(anID);
438 _objects.Bind(anID, anObject);
440 // Put this sub-shape in the list of sub-shapes of theMainShape
441 aMainShape->AddSubShapeReference(aFunction);
443 GEOM::TPythonDump pd (aFunction);
445 if (isStandaloneOperation) {
446 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
447 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
448 for (; i <= up - 1; i++) {
449 pd << theIndices->Value(i) << ", ";
451 pd << theIndices->Value(up) << "])";
459 //=============================================================================
463 //=============================================================================
464 bool GEOM_Engine::RemoveObject(Handle(GEOM_BaseObject)& theObject)
466 if (theObject.IsNull()) return false;
468 int aDocID = theObject->GetDocID();
469 if(!_mapIDDocument.IsBound(aDocID))
470 return false; // document is closed...
472 //Remove an object from the map of available objects
473 TCollection_AsciiString anID = BuildIDFromObject(theObject);
474 if (_objects.IsBound(anID)) {
475 Handle(GEOM_BaseObject) anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
476 if ( anObject != theObject )
477 anObject->_label = anObject->_label.Root();
478 _objects.UnBind(anID);
481 // If sub-shape, remove it from the list of sub-shapes of its main shape
482 Handle(GEOM_Object) aGO = Handle(GEOM_Object)::DownCast( theObject );
483 if ( !aGO.IsNull() && !aGO->IsMainShape()) {
484 Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
485 GEOM_ISubShape aSSI (aFunction);
486 Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
487 //If main shape is not null, then remove
488 if(!aMainShape.IsNull())
489 aMainShape->RemoveSubShapeReference(aFunction);
492 int nb = theObject->GetNbFunctions();
493 Handle(TDataStd_TreeNode) aNode;
494 for (int i = 1; i <= nb; i++) {
495 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
496 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
500 TDF_Label aLabel = theObject->GetEntry();
501 aLabel.ForgetAllAttributes(Standard_True);
503 // Remember the label to reuse it then
504 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
505 if ( aFreeLabels.empty() || aFreeLabels.back() != aLabel )
506 aFreeLabels.push_back(aLabel);
508 // we can't explicitely delete theObject. At least prevent its functioning
509 // as an alive object when aLabel is reused for a new object
510 theObject->_label = aLabel.Root();
511 theObject->_ior.Clear();
512 theObject->_parameters.Clear();
513 theObject->_docID = -1;
520 //=============================================================================
524 //=============================================================================
525 void GEOM_Engine::Undo(int theDocID)
527 GetDocument(theDocID)->Undo();
530 //=============================================================================
534 //=============================================================================
535 void GEOM_Engine::Redo(int theDocID)
537 GetDocument(theDocID)->Redo();
540 //=============================================================================
544 //=============================================================================
545 bool GEOM_Engine::Save(int theDocID, const char* theFileName)
547 if(!_mapIDDocument.IsBound(theDocID)) return false;
548 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
550 _OCAFApp->SaveAs(aDoc, theFileName);
555 //=============================================================================
559 //=============================================================================
560 bool GEOM_Engine::Load(int theDocID, const char* theFileName)
562 Handle(TDocStd_Document) aDoc;
563 if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
567 aDoc->SetUndoLimit(_UndoLimit);
569 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
570 _mapIDDocument.Bind(theDocID, aDoc);
572 TDataStd_Integer::Set(aDoc->Main(), theDocID);
577 //=============================================================================
581 //=============================================================================
582 void GEOM_Engine::Close(int theDocID)
584 if (_mapIDDocument.IsBound(theDocID)) {
585 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
587 //Remove all GEOM Objects associated to the given document
588 TColStd_SequenceOfAsciiString aSeq;
589 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
590 for (; It.More(); It.Next()) {
591 TCollection_AsciiString anObjID (It.Key());
592 Standard_Integer anID = ExtractDocID(anObjID);
593 if (theDocID == anID) aSeq.Append(It.Key());
595 for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
597 // Forget free labels for this document
598 TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
599 if (anIt != _freeLabels.end()) {
600 _freeLabels.erase(anIt);
603 _mapIDDocument.UnBind(theDocID);
604 _OCAFApp->Close(aDoc);
609 //=============================================================================
613 //=============================================================================
614 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
615 std::vector<TObjectData>& theObjectData,
616 TVariablesList theVariables,
621 // Set "C" numeric locale to save numbers correctly
622 Kernel_Utils::Localizer loc;
624 TCollection_AsciiString aScript;
625 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
629 TCollection_AsciiString anEmptyScript;
631 anEmptyScript = "def RebuildData(theStudy): pass\n";
632 return anEmptyScript;
635 aScript = "import GEOM\n";
636 aScript += "from salome.geom import geomBuilder\n";
637 aScript += "import math\n";
638 aScript += "import SALOMEDS\n\n";
640 aScript += "def RebuildData(theStudy):";
642 aScript += "\n\tgeompy = geomBuilder.New(theStudy)\n";
644 AddTextures(theDocID, aScript);
646 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
648 // a map containing copies of TObjectData from theObjectData
649 TSting2ObjDataMap aEntry2ObjData;
650 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
651 // occures when several StudyEntries correspond to one Entry
652 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
654 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
655 for (unsigned i = 0; i < theObjectData.size(); ++i )
657 TObjectData& data = theObjectData[i];
658 // look for an object by entry
660 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
661 if ( L.IsNull() ) continue;
662 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
664 if ( !obj.IsNull() ) {
665 TSting2ObjDataMap::iterator ent2Data =
666 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
668 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
669 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
671 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
675 // collect objects entries to be published
676 TColStd_SequenceOfAsciiString aObjListToPublish;
678 // iterates on functions till critical (that requiers publication of objects)
679 Handle(TDataStd_TreeNode) aNode, aRoot;
680 Handle(GEOM_Function) aFunction;
681 TDF_LabelMap aCheckedFuncMap;
682 std::set< TCollection_AsciiString > anIgnoreObjMap;
684 TCollection_AsciiString aFuncScript;
686 // Mantis issue 0020768
687 Standard_Integer objectCounter = 0;
688 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
689 TIntToListIntMap aRefMap;
691 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
692 TDataStd_ChildNodeIterator Itr(aRoot);
693 for (; Itr.More(); Itr.Next()) {
695 aFunction = GEOM_Function::GetFunction(aNode->Label());
696 if (aFunction.IsNull()) {
697 MESSAGE ( "Null function !!!!" );
700 bool isDumpCollected = false;
701 TCollection_AsciiString aCurScript, anAfterScript;
702 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
703 isPublished, aCheckedFuncMap, anIgnoreObjMap,
706 // add function description before dump
707 if (!aCurScript.IsEmpty())
709 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
710 aFuncScript.Length() > aCurScript.Length() )
711 // avoid repeated SubShape...() command at the end
712 if (aFuncScript.Location( aCurScript,
713 aFuncScript.Length() - aCurScript.Length(),
714 aFuncScript.Length()))
715 continue; // aCurScript is already at the end of aFuncScript
716 aFuncScript += aCurScript;
719 // Fill the map of references.
720 FillMapOfRef(aFunction, aRefMap);
722 if (isDumpCollected ) {
723 // Replace entries by the names
724 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
725 aObjListToPublish, objectCounter, aNameToEntry );
727 // publish collected objects
728 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
729 int i = 1, n = aObjListToPublish.Length();
730 for ( ; i <= n; i++ )
732 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
733 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
734 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
736 // add publishing commands to the script
737 std::set< int > aPublished;
738 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
740 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
741 const TCollection_AsciiString aPublishCmds =
742 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
743 aRefMap, aPublished);
745 aFuncScript += aPublishCmds;
748 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
749 // because they will be published during command execution
750 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
752 indx = anAfterScript.Search( "RestoreSubShapes" );
754 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
755 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
756 i = 1, n = aSeq->Length();
757 for ( ; i <= n; i+=2) {
758 TCollection_AsciiString anEntry =
759 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
760 anIgnoreObjMap.insert(anEntry.ToCString());
764 aObjListToPublish.Clear();
765 aScript += aFuncScript;
768 aFuncScript += anAfterScript;
772 // Replace entries by the names
773 aObjListToPublish.Clear();
774 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
775 objectCounter, aNameToEntry );
777 aScript += aFuncScript;
780 AddObjectColors( theDocID, aScript, aEntry2ObjData );
782 // Make script to publish in study
783 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
786 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
788 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
789 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
790 ++aStEntry2ObjDataPtrIt)
792 TObjectData* data = aStEntry2ObjDataPtrIt->second;
793 if ( anIgnoreObjMap.count( data->_entry ))
794 continue; // should not be dumped
795 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
796 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
798 // add publishing commands to the script
799 std::set< int > aPublished;
800 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
802 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
803 const TCollection_AsciiString aPublishCmds =
804 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
805 aRefMap, aPublished);
807 aScript += aPublishCmds;
811 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
812 //Add unpublish command if need
813 TCollection_AsciiString unpublishCmd("\n");
815 unpublishCmd += "\t";
816 unpublishCmd += "geompy.hideInStudy(";
818 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
819 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
820 ++aStEntry2ObjDataPtrIt)
822 TObjectData* data = aStEntry2ObjDataPtrIt->second;
823 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
824 aScript += unpublishCmd + data->_pyName + ")";
828 //aScript += "\n\tpass\n";
832 // fill _studyEntry2NameMap and build globalVars
833 TCollection_AsciiString globalVars;
834 _studyEntry2NameMap.Clear();
835 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
836 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
837 ++aStEntry2ObjDataPtrIt)
839 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
840 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
841 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
842 if ( !globalVars.IsEmpty() )
844 globalVars += data->_pyName;
846 if ( isMultiFile && !globalVars.IsEmpty() ) {
847 globalVars.Insert( 1, "\n\tglobal " );
848 aScript.Insert( posToInsertGlobalVars, globalVars );
854 //=======================================================================
855 //function : GetDumpName
857 //=======================================================================
859 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
861 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
862 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
867 //=======================================================================
868 //function : GetAllDumpNames
870 //=======================================================================
872 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
874 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
876 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
877 for (; it.More(); it.Next()) {
878 aRetSeq->Append(it.Value());
884 #define TEXTURE_LABEL_ID 1
885 #define TEXTURE_LABEL_FILE 2
886 #define TEXTURE_LABEL_WIDTH 3
887 #define TEXTURE_LABEL_HEIGHT 4
888 #define TEXTURE_LABEL_DATA 5
890 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
891 const Handle(TColStd_HArray1OfByte)& theTexture,
892 const TCollection_AsciiString& theFileName)
894 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
895 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
897 // NPAL18604: use existing label to decrease memory usage,
898 // if this label has been freed (object deleted)
899 bool useExisting = false;
901 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
902 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
903 if (!aFreeLabels.empty()) {
905 aChild = aFreeLabels.front();
906 aFreeLabels.pop_front();
911 aChild = TDF_TagSource::NewChild(aDoc->Main());
914 aChild.ForgetAllAttributes(Standard_True);
915 Handle(TDataStd_TreeNode) node;
916 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
917 node = TDataStd_TreeNode::Set(aChild);
918 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
920 static int aTextureID = 0;
922 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
923 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
924 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
925 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
927 Handle(TDataStd_ByteArray) anAttr =
928 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
929 theTexture.IsNull() ? 0 : theTexture->Lower(),
930 theTexture.IsNull() ? 0 : theTexture->Upper());
931 anAttr->ChangeArray(theTexture);
936 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
937 int& theWidth, int& theHeight,
938 TCollection_AsciiString& theFileName)
940 Handle(TColStd_HArray1OfByte) anArray;
941 theWidth = theHeight = 0;
943 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
945 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
947 for (; anIterator.More() && !found; anIterator.Next()) {
948 TDF_Label aTextureLabel = anIterator.Value();
949 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
950 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
951 Handle(TDataStd_Integer) anIdAttr;
952 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
953 anIdAttr->Get() == theTextureID) {
954 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
955 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
956 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
957 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
958 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
959 Handle(TDataStd_ByteArray) aTextureAttr;
960 Handle(TDataStd_Comment) aFileAttr;
961 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
962 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
963 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
964 theWidth = aWidthAttr->Get();
965 theHeight = aHeightAttr->Get();
966 anArray = aTextureAttr->InternalArray();
968 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
969 theFileName = aFileAttr->Get();
977 std::list<int> GEOM_Engine::getAllTextures(int theDocID)
979 std::list<int> id_list;
981 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
983 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
984 for (; anIterator.More(); anIterator.Next()) {
985 TDF_Label aTextureLabel = anIterator.Value();
986 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
987 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
988 Handle(TDataStd_Integer) anIdAttr;
989 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
990 id_list.push_back((int)anIdAttr->Get());
996 void GEOM_Engine::DocumentModified(const int theDocId, const bool isModified)
998 if (isModified) _mapModifiedDocs.Add(theDocId);
999 else _mapModifiedDocs.Remove(theDocId);
1002 bool GEOM_Engine::DocumentModified(const int theDocId)
1004 return _mapModifiedDocs.Contains(theDocId);
1007 //===========================================================================
1008 // Internal functions
1009 //===========================================================================
1011 //=============================================================================
1013 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
1015 //=============================================================================
1016 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
1018 TCollection_AsciiString aNewDescr;
1020 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
1021 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
1022 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
1023 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1024 // "3DSketcher:CMD[:CMD[:CMD...]]"
1025 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
1027 // Split the command string to separate CMDs
1029 TColStd_SequenceOfAsciiString aSequence;
1030 if (aCommand.Length()) {
1031 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
1032 while (aToken.Length() > 0) {
1033 aSequence.Append(aToken);
1034 aToken = aCommand.Token(":", ++icmd);
1038 if (aSequence.Length() > 0) {
1040 aNewDescr += "\n\t";
1042 aNewDescr += "\nsk = geompy.Sketcher3D()";
1043 int nbCMDs = aSequence.Length();
1044 for (icmd = 1; icmd <= nbCMDs; icmd++) {
1045 aNewDescr += "\n\t";
1047 TCollection_AsciiString aCMD = aSequence.Value(icmd);
1049 // Split the CMD into string values
1050 TColStd_SequenceOfAsciiString aStrVals;
1052 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1053 while (aToken.Length() > 0) {
1054 aStrVals.Append(aToken);
1055 aToken = aCMD.Token(" ", ++ival);
1058 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1059 if (aCMDpref == "TT") {
1060 aNewDescr += "sk.addPointsAbsolute(";
1061 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1063 else if (aCMDpref == "T") {
1064 aNewDescr += "sk.addPointsRelative(";
1065 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1067 else if (aCMDpref == "WW") {
1068 aNewDescr += "sk.close()";
1070 else if (aCMDpref.Value(1) == 'O'){
1071 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1073 if (aCMDpref.Value(4) == 'C')
1074 aNewDescr += "sk.addPointRadiusAngleH";
1076 aNewDescr += "sk.addPointRadiusAngles";
1077 if (aCMDpref.Value(5) == 'A')
1078 aNewDescr += "Absolute(";
1080 aNewDescr += "Relative(";
1081 aNewDescr += aStrVals.Value(4) + ", " +
1082 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1085 aNewDescr += "\n\t";
1086 aNewDescr += aResult + " = sk.wire()";
1088 } // Make3DSketcherCommand
1089 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1090 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1091 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1092 aCommand = aCommand.Token("]", 1);
1094 aNewDescr += "\n\t";
1095 aNewDescr += "\nsk = geompy.Sketcher3D()";
1096 aNewDescr += "\n\t";
1097 aNewDescr += "sk.addPointsAbsolute(";
1098 aNewDescr += aCommand + ")";
1099 aNewDescr += "\n\t";
1100 aNewDescr += aResult + " = sk.wire()";
1104 aNewDescr += "\n\t";
1105 aNewDescr += aSubStr;
1112 //=============================================================================
1114 * ProcessFunction: Dump function description into script
1116 //=============================================================================
1117 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1118 TCollection_AsciiString& theScript,
1119 TCollection_AsciiString& theAfterScript,
1120 const TVariablesList& theVariables,
1121 const bool theIsPublished,
1122 TDF_LabelMap& theProcessed,
1123 std::set<TCollection_AsciiString>& theIgnoreObjs,
1124 bool& theIsDumpCollected)
1126 theIsDumpCollected = false;
1127 if (theFunction.IsNull()) return false;
1129 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1131 // pass functions, that depends on nonexisting ones
1132 bool doNotProcess = false;
1133 TDF_LabelSequence aSeq;
1134 theFunction->GetDependency(aSeq);
1135 Standard_Integer aLen = aSeq.Length();
1136 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1137 TDF_Label aRefLabel = aSeq.Value(i);
1138 Handle(TDF_Reference) aRef;
1139 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1140 doNotProcess = true;
1143 if (aRef.IsNull() || aRef->Get().IsNull()) {
1144 doNotProcess = true;
1147 Handle(TDataStd_TreeNode) aT;
1148 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1149 doNotProcess = true;
1152 TDF_Label aDepLabel = aT->Label();
1153 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1155 if (aFunction.IsNull()) doNotProcess = true;
1156 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1163 TCollection_AsciiString anObjEntry;
1164 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1165 theIgnoreObjs.insert(anObjEntry);
1168 theProcessed.Add(theFunction->GetEntry());
1170 TCollection_AsciiString aDescr = theFunction->GetDescription();
1171 if(aDescr.Length() == 0) return false;
1173 //Check if its internal function which doesn't requires dumping
1174 if(aDescr == "None") return false;
1176 //Check the very specific case of RestoreShape function,
1177 //which is not dumped, but the result can be published by the user.
1178 //We do not publish such objects to decrease danger of dumped script failure.
1179 if(aDescr.Value(1) == '#') {
1180 TCollection_AsciiString anObjEntry;
1181 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1182 theIgnoreObjs.insert(anObjEntry);
1186 // 0020001 PTv, check for critical functions, which require dump of objects
1189 // currently, there is only one function "RestoreGivenSubShapes",
1190 // later this check could be replaced by iterations on list of such functions
1191 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1192 theIsDumpCollected = true;
1193 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1194 theIsDumpCollected = true;
1197 //Replace parameter by notebook variables
1198 ReplaceVariables(aDescr,theVariables);
1200 //Process sketcher functions, replacing string command by calls to Sketcher interface
1201 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1202 Sketcher_Profile aProfile( aDescr.ToCString());
1203 // Make new command for SketcherOnPlane and for Sketcher
1204 aDescr = aProfile.GetDump();
1206 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1207 aDescr = MakeCommandfor3DSketcher ( aDescr );
1210 if ( theIsDumpCollected ) {
1212 bool isBefore = true;
1213 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1214 while (!aSubStr.IsEmpty()) {
1216 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1217 aSubStr.Search( "RestoreSubShapes" ) == -1)
1218 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1220 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1221 aSubStr = aDescr.Token("\n\t", i++);
1225 theScript += "\n\t";
1226 theScript += aDescr;
1231 //=============================================================================
1233 * GetTag: Returns the tag from entry
1235 //=============================================================================
1236 int GetTag(const TCollection_AsciiString &theEntry)
1238 const int aGeomObjDepth = 3;
1239 const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue();
1244 //=============================================================================
1246 * FillMapOfRef: Fill the map of references
1248 //=============================================================================
1249 void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
1250 TIntToListIntMap &theRefMap)
1252 TDF_LabelSequence aSeq;
1253 TCollection_AsciiString anObjEntry;
1256 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1257 anObjTag = GetTag(anObjEntry);
1258 theFunction->GetDependency(aSeq);
1260 const Standard_Integer aLen = aSeq.Length();
1263 for (i = 1; i <= aLen; i++) {
1264 TDF_Label aRefLabel = aSeq.Value(i);
1265 Handle(TDF_Reference) aRef;
1267 if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1268 if (!aRef.IsNull() && !aRef->Get().IsNull()) {
1269 Handle(TDataStd_TreeNode) aT;
1271 if (TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1272 TDF_Label aDepLabel = aT->Label();
1273 Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel);
1275 if (!aRefFunct.IsNull()) {
1276 // Get entry of the referenced object.
1277 TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry);
1279 const int aRefTag = GetTag(anObjEntry);
1281 theRefMap[anObjTag].push_back(aRefTag);
1289 //=============================================================================
1291 * FindEntries: Returns a sequence of start/end positions of entries in the string
1293 //=============================================================================
1294 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1296 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1297 Standard_Integer aLen = theString.Length();
1298 Standard_Boolean isFound = Standard_False;
1300 const char* arr = theString.ToCString();
1301 Standard_Integer i = 0, j;
1304 int c = (int)arr[i];
1306 if(c >= 48 && c <= 57) { //Is digit?
1308 isFound = Standard_False;
1309 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1311 if(c == 58) isFound = Standard_True;
1314 if(isFound && arr[j-2] != 58) { // last char should be a diggit
1315 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1326 //=============================================================================
1328 * ReplaceVariables: Replace parameters of the function by variales from
1331 //=============================================================================
1332 void ReplaceVariables(TCollection_AsciiString& theCommand,
1333 const TVariablesList& theVariables)
1336 cout<<"Command : "<<theCommand<<endl;
1339 cout<<"All Entries:"<<endl;
1340 TVariablesList::const_iterator it = theVariables.begin();
1341 for(;it != theVariables.end();it++)
1342 cout<<"\t'"<<(*it).first<<"'"<<endl;
1345 //Additional case - multi-row commands
1346 int aCommandIndex = 1;
1347 while( aCommandIndex < 10 ) { // tmp check
1348 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1349 if( aCommand.Length() == 0 )
1353 cout<<"Sub-command : "<<aCommand<<endl;
1355 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1356 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1358 //Get Entry of the result object
1359 TCollection_AsciiString anEntry;
1360 if( aCommand.Search("=") != -1 ) // command returns an object
1361 anEntry = aCommand.Token("=",1);
1362 else { // command modifies the object
1363 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1364 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1365 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1367 //Remove white spaces
1368 anEntry.RightAdjust();
1369 anEntry.LeftAdjust();
1371 cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1373 if ( anEntry.IsEmpty() ) {
1378 //Check if result is list of entries - enough to get the first entry in this case
1380 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1381 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1383 TCollection_AsciiString aSeparator(COMMA);
1384 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1385 anEntry.Remove( 1, 1 );
1386 anEntry.RightAdjust();
1387 anEntry.LeftAdjust();
1389 cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1392 //Find variables used for object construction
1393 ObjectStates* aStates = 0;
1394 TVariablesList::const_iterator it = theVariables.find(anEntry);
1395 if( it != theVariables.end() )
1396 aStates = (*it).second;
1400 cout<<"Valiables list empty!!!"<<endl;
1405 TState aVariables = aStates->GetCurrectState();
1408 cout<<"Variables from SObject:"<<endl;
1409 for (int i = 0; i < aVariables.size();i++)
1410 cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1413 //Calculate total number of parameters
1414 Standard_Integer aTotalNbParams = 1;
1415 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1419 cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1421 Standard_Integer aFirstParam = aNbEntries;
1423 //Replace parameters by variables
1424 Standard_Integer aStartPos = 0;
1425 Standard_Integer aEndPos = 0;
1427 TCollection_AsciiString aVar, aReplacedVar;
1428 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1429 //Replace first parameter (bettwen '(' character and first ',' character)
1430 if(i == aFirstParam)
1432 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1433 if(aTotalNbParams - aNbEntries > 0 )
1434 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1436 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1438 //Replace last parameter (bettwen ',' character and ')' character)
1439 else if(i == aTotalNbParams)
1441 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1442 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1444 //Replace other parameters (bettwen two ',' characters)
1445 else if(i != aFirstParam && i != aTotalNbParams )
1447 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1448 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1451 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1453 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1455 if ( aStartPos == aEndPos )
1456 continue; // PAL20889: for "[]"
1459 cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1461 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1466 cout<<"Variable: '"<< aVar <<"'"<<endl;
1468 // specific case for sketcher
1469 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1470 Standard_Integer aNbSections = 1;
1471 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1475 int aStartSectionPos = 0, aEndSectionPos = 0;
1476 TCollection_AsciiString aSection, aReplacedSection;
1477 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1478 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1479 if( aSectionIndex != aNbSections )
1480 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1482 aEndSectionPos = aVar.Length();
1484 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1486 cout<<"aSection: "<<aSection<<endl;
1488 Standard_Integer aNbParams = 1;
1489 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1493 int aStartParamPos = 0, aEndParamPos = 0;
1494 TCollection_AsciiString aParameter, aReplacedParameter;
1495 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1496 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1497 if( aParamIndex != aNbParams )
1498 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1500 aEndParamPos = aSection.Length() + 1;
1503 cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
1505 if ( aStartParamPos == aEndParamPos)
1508 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1510 cout<<"aParameter: "<<aParameter<<endl;
1512 if(iVar >= aVariables.size())
1515 aReplacedParameter = aVariables[iVar].myVariable;
1516 if(aReplacedParameter.IsEmpty()) {
1521 if(aVariables[iVar].isVariable) {
1522 aReplacedParameter.InsertBefore(1,"'");
1523 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1527 cout<<"aSection before : "<<aSection<<endl;
1528 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1529 aSection.Insert(aStartParamPos, aReplacedParameter);
1531 cout<<"aSection after : "<<aSection<<endl<<endl;
1535 cout<<"aVar before : "<<aVar<<endl;
1536 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1537 aVar.Insert(aStartSectionPos, aSection);
1539 cout<<"aVar after : "<<aVar<<endl<<endl;
1543 cout<<"aCommand before : "<<aCommand<<endl;
1544 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1545 aCommand.Insert(aStartPos, aVar);
1547 cout<<"aCommand after : "<<aCommand<<endl;
1550 } // end of specific case for sketcher
1552 //If parameter is entry or 'None', skip it
1553 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1556 if(iVar >= aVariables.size())
1559 aReplacedVar = aVariables[iVar].myVariable;
1560 if(aReplacedVar.IsEmpty()) {
1565 if(aVariables[iVar].isVariable) {
1566 aReplacedVar.InsertBefore(1,"\"");
1567 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1570 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1571 aCommand.Insert(aStartPos, aReplacedVar);
1575 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1576 theCommand.Insert(aStartCommandPos, aCommand);
1580 aStates->IncrementState();
1584 cout<<"Command : "<<theCommand<<endl;
1587 //=============================================================================
1589 * ReplaceEntriesByNames: Replace object entries by their names
1591 //=============================================================================
1592 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1593 TSting2ObjDataMap& aEntry2ObjData,
1594 const bool theIsPublished,
1595 TColStd_SequenceOfAsciiString& theObjListToPublish,
1596 Standard_Integer& objectCounter,
1597 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1599 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1600 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1601 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1603 //Replace entries by the names
1604 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1605 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1606 if (aLen == 0) anUpdatedScript = theScript;
1608 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1609 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1610 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1611 theObjListToPublish.Append( anEntry );
1613 TObjectData& data = aEntry2ObjData[ anEntry ];
1614 if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1615 if ( !data._name.IsEmpty() ) { // published object
1616 data._pyName = data._name;
1617 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1621 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1622 } while(aNameToEntry.IsBound(data._pyName));
1626 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1628 anUpdatedScript += data._pyName;
1629 aStart = aSeq->Value(i+1) + 1;
1632 //Add final part of the script
1633 if (aLen && aSeq->Value(aLen) < aScriptLength)
1634 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1636 theScript = anUpdatedScript;
1639 //=============================================================================
1641 * AddObjectColors: Add color to objects
1643 //=============================================================================
1644 void AddObjectColors (int theDocID,
1645 TCollection_AsciiString& theScript,
1646 const TSting2ObjDataMap& theEntry2ObjData)
1648 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1649 Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
1651 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1652 for (anEntryToNameIt = theEntry2ObjData.begin();
1653 anEntryToNameIt!= theEntry2ObjData.end();
1656 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1657 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1660 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1664 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1668 bool anAutoColor = obj->GetAutoColor();
1671 TCollection_AsciiString aCommand( "\n\t" );
1672 aCommand += aName + ".SetAutoColor(1)";
1673 theScript += aCommand.ToCString();
1676 GEOM_Object::Color aColor = obj->GetColor();
1677 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1679 TCollection_AsciiString aCommand( "\n\t" );
1680 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1681 theScript += aCommand.ToCString();
1684 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1685 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1686 TCollection_AsciiString aCommand( "\n\t" );
1687 aCommand += aName + ".SetMarkerStd(";
1688 switch (aMarkerType) {
1689 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1690 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1691 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1692 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1693 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1694 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1695 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1696 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1697 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1698 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1699 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1700 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1701 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1702 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1705 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1707 case 1: aCommand += "GEOM.MS_10"; break;
1708 case 2: aCommand += "GEOM.MS_15"; break;
1709 case 3: aCommand += "GEOM.MS_20"; break;
1710 case 4: aCommand += "GEOM.MS_25"; break;
1711 case 5: aCommand += "GEOM.MS_30"; break;
1712 case 6: aCommand += "GEOM.MS_35"; break;
1713 case 7: aCommand += "GEOM.MS_40"; break;
1714 case 8: aCommand += "GEOM.MS_45"; break;
1715 case 9: aCommand += "GEOM.MS_50"; break;
1716 case 10: aCommand += "GEOM.MS_55"; break;
1717 case 11: aCommand += "GEOM.MS_60"; break;
1718 case 12: aCommand += "GEOM.MS_65"; break;
1719 case 13: aCommand += "GEOM.MS_70"; break;
1720 default: aCommand += "GEOM.MS_NONE"; break;
1723 theScript += aCommand.ToCString();
1725 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1726 int aMarkerTextureID = obj->GetMarkerTexture();
1727 if (aMarkerTextureID >= 0) {
1728 TCollection_AsciiString aCommand( "\n\t" );
1729 aCommand += aName + ".SetMarkerTexture(texture_map[";
1730 aCommand += aMarkerTextureID;
1732 theScript += aCommand.ToCString();
1738 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1740 TCollection_AsciiString stream;
1741 if (!aData.IsNull()) {
1742 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1743 Standard_Byte byte = aData->Value(i);
1744 TCollection_AsciiString strByte = "";
1745 for (int j = 0; j < 8; j++)
1746 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1753 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
1755 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1756 std::list<int> allTextures = engine->getAllTextures(theDocID);
1757 std::list<int>::const_iterator it;
1759 if (allTextures.size() > 0) {
1760 theScript += "\n\ttexture_map = {}\n";
1762 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1763 if (*it <= 0) continue;
1764 Standard_Integer aWidth, aHeight;
1765 TCollection_AsciiString aFileName;
1766 Handle(TColStd_HArray1OfByte) aTexture =
1767 engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
1768 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1769 TCollection_AsciiString aCommand = "\n\t";
1770 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1771 if (aFileName != "" ) {
1772 aCommand += "geompy.LoadTexture(\"";
1773 aCommand += aFileName.ToCString();
1777 aCommand += "geompy.AddTexture(";
1778 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1779 aCommand += pack_data(aTexture);
1782 theScript += aCommand;
1789 //=============================================================================
1791 * PublishObject: publish object in study script
1793 //=============================================================================
1794 void PublishObject (TObjectData& theObjectData,
1795 TSting2ObjDataMap& theEntry2ObjData,
1796 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1797 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1798 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1799 std::set< TCollection_AsciiString>& theIgnoreMap)
1801 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1802 if ( theObjectData._studyEntry.IsEmpty() )
1803 return; // was not published
1804 if ( theIgnoreMap.count( theObjectData._entry ) )
1805 return; // not to publish
1807 TCollection_AsciiString aCommand("\n\tgeompy.");
1809 // find a father entry
1810 TObjectData* aFatherData = 0;
1811 TCollection_AsciiString aFatherStudyEntry =
1812 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1813 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1814 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1815 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1816 aFatherData = stEntry2DataPtr->second;
1818 // treat multiply published object
1819 if ( theObjectData._pyName.IsEmpty() )
1821 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1822 if ( data0._pyName.IsEmpty() ) return; // something wrong
1824 theObjectData._pyName = theObjectData._name;
1825 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1827 TCollection_AsciiString aCreationCommand("\n\t");
1828 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1830 // store aCreationCommand before publishing commands
1831 int tag = GetTag(theObjectData._entry);
1832 theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1836 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1837 aCommand += "addToStudyInFather( ";
1838 aCommand += aFatherData->_pyName + ", ";
1841 aCommand += "addToStudy( ";
1843 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1845 // bind a command to the study entry
1846 int tag = GetTag(theObjectData._entry);
1847 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1849 theObjectData._studyEntry.Clear(); // not to publish any more
1852 //================================================================================
1854 * \brief Returns the string of publishing commands. Take into account that
1855 * references should be published prior to the objects refer to them.
1857 //================================================================================
1858 TCollection_AsciiString GetPublishCommands
1860 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
1861 const TIntToListIntMap &theMapRefs,
1862 std::set< int > &thePublished)
1864 TCollection_AsciiString aResult;
1866 if (!thePublished.count(theTag)) {
1867 // This object is not published yet.
1868 std::map< int, TCollection_AsciiString >::const_iterator anIt =
1869 theEntryToCmdMap.find(theTag);
1871 if (anIt != theEntryToCmdMap.end()) {
1872 // There is a pubish cmd.
1873 TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag);
1875 if (aRefIt != theMapRefs.end()) {
1876 // Recursively publish all references.
1877 std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin();
1879 for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) {
1880 const TCollection_AsciiString aRefCmd = GetPublishCommands
1881 (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished);
1887 // Add the object command.
1888 aResult += anIt->second;
1891 thePublished.insert(theTag);
1897 //================================================================================
1899 * \brief Constructor
1901 //================================================================================
1902 ObjectStates::ObjectStates()
1907 //================================================================================
1911 //================================================================================
1912 ObjectStates::~ObjectStates()
1916 //================================================================================
1918 * \brief Return current object state
1919 * \retval state - Object state (vector of notebook variable)
1921 //================================================================================
1922 TState ObjectStates::GetCurrectState() const
1924 if(_states.size() > _dumpstate)
1925 return _states[_dumpstate];
1929 //================================================================================
1931 * \brief Add new object state
1932 * \param theState - Object state (vector of notebook variable)
1934 //================================================================================
1935 void ObjectStates::AddState(const TState &theState)
1937 _states.push_back(theState);
1940 //================================================================================
1942 * \brief Increment object state
1944 //================================================================================
1945 void ObjectStates::IncrementState()