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;
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 void ReplaceVariables(TCollection_AsciiString& theCommand,
127 const TVariablesList& theVariables);
129 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
131 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
132 TSting2ObjDataMap& aEntry2ObjData,
133 const bool theIsPublished,
134 TColStd_SequenceOfAsciiString& theObjListToPublish,
135 Standard_Integer& objectCounter,
136 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
138 void AddObjectColors (int theDocID,
139 TCollection_AsciiString& theScript,
140 const TSting2ObjDataMap& theEntry2ObjData);
142 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
144 void PublishObject (TObjectData& theObjectData,
145 TSting2ObjDataMap& theEntry2ObjData,
146 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
147 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
148 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
149 std::set<TCollection_AsciiString>& theMapOfPublished);
151 //================================================================================
153 * \brief Fix up the name of python variable
155 //================================================================================
157 void GEOM_Engine::healPyName( TCollection_AsciiString& pyName,
158 const TCollection_AsciiString& anEntry,
159 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
161 const TCollection_AsciiString allowedChars
162 ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
164 if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
165 pyName.Insert( 1, 'a' );
167 int p, p2=1; // replace not allowed chars
168 while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
169 pyName.SetValue(p, '_');
172 if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
173 { // diff objects have same name - make a new name by appending a digit
174 TCollection_AsciiString aName2;
175 Standard_Integer i = 0;
177 aName2 = pyName + "_" + ++i;
178 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
183 //=======================================================================
184 //function : GetTextureGUID
186 //=======================================================================
187 const Standard_GUID& GEOM_Engine::GetTextureGUID()
189 static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
193 //=============================================================================
197 //=============================================================================
198 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
200 //=============================================================================
204 //=============================================================================
205 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
207 //=============================================================================
211 //=============================================================================
212 GEOM_Engine::GEOM_Engine()
214 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
216 _OCAFApp = new GEOM_Application();
223 GEOM_Engine::~GEOM_Engine()
225 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
226 std::list< Handle(GEOM_Object) > objs;
227 for(; It.More(); It.Next())
228 objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
229 std::list< Handle(GEOM_Object) >::iterator objit;
230 for(objit = objs.begin(); objit != objs.end(); ++objit)
231 RemoveObject(*objit);
233 //Close all documents not closed
234 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
235 for (; anItr.More(); anItr.Next())
238 anItr.Initialize( _mapIDDocument ); // anItr becomes invalid at _mapIDDocument.UnBind(docId)
240 _mapIDDocument.Clear();
244 //=============================================================================
248 //=============================================================================
249 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
251 Handle(TDocStd_Document) aDoc;
252 if(_mapIDDocument.IsBound(theDocID)) {
253 aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
256 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
257 aDoc->SetUndoLimit(_UndoLimit);
258 _mapIDDocument.Bind(theDocID, aDoc);
259 TDataStd_Integer::Set(aDoc->Main(), theDocID);
264 //=============================================================================
268 //=============================================================================
269 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
271 if (theDocument.IsNull()) return -1;
272 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
273 for (; anItr.More(); anItr.Next())
274 if (anItr.Value() == theDocument) return anItr.Key();
279 //=============================================================================
283 //=============================================================================
285 Handle(GEOM_BaseObject) GEOM_Engine::GetObject(int theDocID, const char* theEntry, bool force)
287 Handle(GEOM_BaseObject) anObject;
289 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
291 if (_objects.IsBound(anID)) {
292 anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
295 Handle(TDocStd_Document) aDoc = GetDocument(theDocID, force);
296 if ( !aDoc.IsNull()) {
298 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
299 if ( !aLabel.IsNull() ) {
300 int objType = GEOM_BaseObject::GetType( aLabel );
302 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break;
303 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break;
304 default: anObject = new GEOM_Object (aLabel);
306 _objects.Bind(anID, anObject);
314 //=============================================================================
318 //=============================================================================
320 Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theDocID, int theType)
322 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
323 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
325 // NPAL18604: use existing label to decrease memory usage,
326 // if this label has been freed (object deleted)
327 bool useExisting = false;
329 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
330 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
331 if (!aFreeLabels.empty()) {
333 aChild = aFreeLabels.front();
334 aFreeLabels.pop_front();
339 aChild = TDF_TagSource::NewChild(aDoc->Main());
342 Handle(GEOM_BaseObject) anObject;
344 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break;
345 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break;
346 default: anObject = new GEOM_Object (aChild, theType);
349 //Put an object in the map of created objects
350 TCollection_AsciiString anID = BuildIDFromObject(anObject);
351 if(_objects.IsBound(anID)) _objects.UnBind(anID);
352 _objects.Bind(anID, anObject);
357 //================================================================================
359 * \brief Adds a new object of the type theType in the OCAF document
361 //================================================================================
363 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
365 return Handle(GEOM_Object)::DownCast( AddBaseObject(theDocID, theType) );
368 //=============================================================================
372 //=============================================================================
374 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
375 Handle(TColStd_HArray1OfInteger) theIndices,
376 bool isStandaloneOperation)
378 if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
380 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
381 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
383 // NPAL18604: use existing label to decrease memory usage,
384 // if this label has been freed (object deleted)
385 bool useExisting = false;
387 int aDocID = theMainShape->GetDocID();
388 if (_freeLabels.find(aDocID) != _freeLabels.end()) {
389 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
390 if (!aFreeLabels.empty()) {
392 aChild = aFreeLabels.front();
393 aFreeLabels.pop_front();
398 aChild = TDF_TagSource::NewChild(aDoc->Main());
401 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
402 Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
403 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
405 GEOM_ISubShape aSSI (aFunction);
406 aSSI.SetMainShape(aMainShape);
407 aSSI.SetIndices(theIndices);
411 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
412 if (!aSolver.ComputeFunction(aFunction)) {
413 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
417 catch (Standard_Failure) {
418 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
419 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
423 // Put an object in the map of created objects
424 TCollection_AsciiString anID = BuildIDFromObject(anObject);
425 if (_objects.IsBound(anID)) _objects.UnBind(anID);
426 _objects.Bind(anID, anObject);
428 // Put this sub-shape in the list of sub-shapes of theMainShape
429 aMainShape->AddSubShapeReference(aFunction);
431 GEOM::TPythonDump pd (aFunction);
433 if (isStandaloneOperation) {
434 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
435 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
436 for (; i <= up - 1; i++) {
437 pd << theIndices->Value(i) << ", ";
439 pd << theIndices->Value(up) << "])";
447 //=============================================================================
451 //=============================================================================
452 bool GEOM_Engine::RemoveObject(Handle(GEOM_BaseObject)& theObject)
454 if (theObject.IsNull()) return false;
456 int aDocID = theObject->GetDocID();
457 if(!_mapIDDocument.IsBound(aDocID))
458 return false; // document is closed...
460 //Remove an object from the map of available objects
461 TCollection_AsciiString anID = BuildIDFromObject(theObject);
462 if (_objects.IsBound(anID)) {
463 Handle(GEOM_BaseObject) anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
464 if ( anObject != theObject )
465 anObject->_label = anObject->_label.Root();
466 _objects.UnBind(anID);
469 // If sub-shape, remove it from the list of sub-shapes of its main shape
470 Handle(GEOM_Object) aGO = Handle(GEOM_Object)::DownCast( theObject );
471 if ( !aGO.IsNull() && !aGO->IsMainShape()) {
472 Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
473 GEOM_ISubShape aSSI (aFunction);
474 Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
475 //If main shape is not null, then remove
476 if(!aMainShape.IsNull())
477 aMainShape->RemoveSubShapeReference(aFunction);
480 int nb = theObject->GetNbFunctions();
481 Handle(TDataStd_TreeNode) aNode;
482 for (int i = 1; i <= nb; i++) {
483 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
484 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
488 TDF_Label aLabel = theObject->GetEntry();
489 aLabel.ForgetAllAttributes(Standard_True);
491 // Remember the label to reuse it then
492 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
493 if ( aFreeLabels.empty() || aFreeLabels.back() != aLabel )
494 aFreeLabels.push_back(aLabel);
496 // we can't explicitely delete theObject. At least prevent its functioning
497 // as an alive object when aLabel is reused for a new object
498 theObject->_label = aLabel.Root();
499 theObject->_ior.Clear();
500 theObject->_parameters.Clear();
501 theObject->_docID = -1;
508 //=============================================================================
512 //=============================================================================
513 void GEOM_Engine::Undo(int theDocID)
515 GetDocument(theDocID)->Undo();
518 //=============================================================================
522 //=============================================================================
523 void GEOM_Engine::Redo(int theDocID)
525 GetDocument(theDocID)->Redo();
528 //=============================================================================
532 //=============================================================================
533 bool GEOM_Engine::Save(int theDocID, const char* theFileName)
535 if(!_mapIDDocument.IsBound(theDocID)) return false;
536 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
538 _OCAFApp->SaveAs(aDoc, theFileName);
543 //=============================================================================
547 //=============================================================================
548 bool GEOM_Engine::Load(int theDocID, const char* theFileName)
550 Handle(TDocStd_Document) aDoc;
551 if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
555 aDoc->SetUndoLimit(_UndoLimit);
557 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
558 _mapIDDocument.Bind(theDocID, aDoc);
560 TDataStd_Integer::Set(aDoc->Main(), theDocID);
565 //=============================================================================
569 //=============================================================================
570 void GEOM_Engine::Close(int theDocID)
572 if (_mapIDDocument.IsBound(theDocID)) {
573 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
575 //Remove all GEOM Objects associated to the given document
576 TColStd_SequenceOfAsciiString aSeq;
577 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
578 for (; It.More(); It.Next()) {
579 TCollection_AsciiString anObjID (It.Key());
580 Standard_Integer anID = ExtractDocID(anObjID);
581 if (theDocID == anID) aSeq.Append(It.Key());
583 for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
585 // Forget free labels for this document
586 TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
587 if (anIt != _freeLabels.end()) {
588 _freeLabels.erase(anIt);
591 _mapIDDocument.UnBind(theDocID);
592 _OCAFApp->Close(aDoc);
597 //=============================================================================
601 //=============================================================================
602 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
603 std::vector<TObjectData>& theObjectData,
604 TVariablesList theVariables,
609 // Set "C" numeric locale to save numbers correctly
610 Kernel_Utils::Localizer loc;
612 TCollection_AsciiString aScript;
613 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
617 TCollection_AsciiString anEmptyScript;
619 anEmptyScript = "def RebuildData(theStudy): pass\n";
620 return anEmptyScript;
623 aScript = "import GEOM\n";
624 aScript += "from salome.geom import geomBuilder\n";
625 aScript += "import math\n";
626 aScript += "import SALOMEDS\n\n";
628 aScript += "def RebuildData(theStudy):";
630 aScript += "\n\tgeompy = geomBuilder.New(theStudy)\n";
632 AddTextures(theDocID, aScript);
634 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
636 // a map containing copies of TObjectData from theObjectData
637 TSting2ObjDataMap aEntry2ObjData;
638 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
639 // occures when several StudyEntries correspond to one Entry
640 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
642 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
643 for (unsigned i = 0; i < theObjectData.size(); ++i )
645 TObjectData& data = theObjectData[i];
646 // look for an object by entry
648 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
649 if ( L.IsNull() ) continue;
650 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
652 if ( !obj.IsNull() ) {
653 TSting2ObjDataMap::iterator ent2Data =
654 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
656 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
657 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
659 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
663 // collect objects entries to be published
664 TColStd_SequenceOfAsciiString aObjListToPublish;
666 // iterates on functions till critical (that requiers publication of objects)
667 Handle(TDataStd_TreeNode) aNode, aRoot;
668 Handle(GEOM_Function) aFunction;
669 TDF_LabelMap aCheckedFuncMap;
670 std::set< TCollection_AsciiString > anIgnoreObjMap;
672 TCollection_AsciiString aFuncScript;
674 // Mantis issue 0020768
675 Standard_Integer objectCounter = 0;
676 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
678 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
679 TDataStd_ChildNodeIterator Itr(aRoot);
680 for (; Itr.More(); Itr.Next()) {
682 aFunction = GEOM_Function::GetFunction(aNode->Label());
683 if (aFunction.IsNull()) {
684 MESSAGE ( "Null function !!!!" );
687 bool isDumpCollected = false;
688 TCollection_AsciiString aCurScript, anAfterScript;
689 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
690 isPublished, aCheckedFuncMap, anIgnoreObjMap,
693 // add function description before dump
694 if (!aCurScript.IsEmpty())
696 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
697 aFuncScript.Length() > aCurScript.Length() )
698 // avoid repeated SubShape...() command at the end
699 if (aFuncScript.Location( aCurScript,
700 aFuncScript.Length() - aCurScript.Length(),
701 aFuncScript.Length()))
702 continue; // aCurScript is already at the end of aFuncScript
703 aFuncScript += aCurScript;
705 if (isDumpCollected ) {
706 // Replace entries by the names
707 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
708 aObjListToPublish, objectCounter, aNameToEntry );
710 // publish collected objects
711 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
712 int i = 1, n = aObjListToPublish.Length();
713 for ( ; i <= n; i++ )
715 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
716 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
717 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
719 // add publishing commands to the script
720 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
721 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
722 aFuncScript += anEntryToCmd->second;
724 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
725 // because they will be published during command execution
726 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
728 indx = anAfterScript.Search( "RestoreSubShapes" );
730 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
731 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
732 i = 1, n = aSeq->Length();
733 for ( ; i <= n; i+=2) {
734 TCollection_AsciiString anEntry =
735 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
736 anIgnoreObjMap.insert(anEntry.ToCString());
740 aObjListToPublish.Clear();
741 aScript += aFuncScript;
744 aFuncScript += anAfterScript;
748 // Replace entries by the names
749 aObjListToPublish.Clear();
750 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
751 objectCounter, aNameToEntry );
753 aScript += aFuncScript;
756 AddObjectColors( theDocID, aScript, aEntry2ObjData );
758 // Make script to publish in study
759 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
762 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
764 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
765 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
766 ++aStEntry2ObjDataPtrIt)
768 TObjectData* data = aStEntry2ObjDataPtrIt->second;
769 if ( anIgnoreObjMap.count( data->_entry ))
770 continue; // should not be dumped
771 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
772 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
774 // add publishing commands to the script
775 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
776 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
777 aScript += anEntryToCmd->second;
780 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
781 //Add unpublish command if need
782 TCollection_AsciiString unpublishCmd("\n");
784 unpublishCmd += "\t";
785 unpublishCmd += "geompy.hideInStudy(";
787 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
788 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
789 ++aStEntry2ObjDataPtrIt)
791 TObjectData* data = aStEntry2ObjDataPtrIt->second;
792 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
793 aScript += unpublishCmd + data->_pyName + ")";
797 //aScript += "\n\tpass\n";
801 // fill _studyEntry2NameMap and build globalVars
802 TCollection_AsciiString globalVars;
803 _studyEntry2NameMap.Clear();
804 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
805 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
806 ++aStEntry2ObjDataPtrIt)
808 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
809 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
810 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
811 if ( !globalVars.IsEmpty() )
813 globalVars += data->_pyName;
815 if ( isMultiFile && !globalVars.IsEmpty() ) {
816 globalVars.Insert( 1, "\n\tglobal " );
817 aScript.Insert( posToInsertGlobalVars, globalVars );
823 //=======================================================================
824 //function : GetDumpName
826 //=======================================================================
828 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
830 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
831 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
836 //=======================================================================
837 //function : GetAllDumpNames
839 //=======================================================================
841 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
843 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
845 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
846 for (; it.More(); it.Next()) {
847 aRetSeq->Append(it.Value());
853 #define TEXTURE_LABEL_ID 1
854 #define TEXTURE_LABEL_FILE 2
855 #define TEXTURE_LABEL_WIDTH 3
856 #define TEXTURE_LABEL_HEIGHT 4
857 #define TEXTURE_LABEL_DATA 5
859 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
860 const Handle(TColStd_HArray1OfByte)& theTexture,
861 const TCollection_AsciiString& theFileName)
863 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
864 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
866 // NPAL18604: use existing label to decrease memory usage,
867 // if this label has been freed (object deleted)
868 bool useExisting = false;
870 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
871 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
872 if (!aFreeLabels.empty()) {
874 aChild = aFreeLabels.front();
875 aFreeLabels.pop_front();
880 aChild = TDF_TagSource::NewChild(aDoc->Main());
883 aChild.ForgetAllAttributes(Standard_True);
884 Handle(TDataStd_TreeNode) node;
885 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
886 node = TDataStd_TreeNode::Set(aChild);
887 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
889 static int aTextureID = 0;
891 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
892 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
893 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
894 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
896 Handle(TDataStd_ByteArray) anAttr =
897 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
898 theTexture.IsNull() ? 0 : theTexture->Lower(),
899 theTexture.IsNull() ? 0 : theTexture->Upper());
900 anAttr->ChangeArray(theTexture);
905 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
906 int& theWidth, int& theHeight,
907 TCollection_AsciiString& theFileName)
909 Handle(TColStd_HArray1OfByte) anArray;
910 theWidth = theHeight = 0;
912 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
914 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
916 for (; anIterator.More() && !found; anIterator.Next()) {
917 TDF_Label aTextureLabel = anIterator.Value();
918 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
919 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
920 Handle(TDataStd_Integer) anIdAttr;
921 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
922 anIdAttr->Get() == theTextureID) {
923 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
924 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
925 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
926 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
927 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
928 Handle(TDataStd_ByteArray) aTextureAttr;
929 Handle(TDataStd_Comment) aFileAttr;
930 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
931 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
932 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
933 theWidth = aWidthAttr->Get();
934 theHeight = aHeightAttr->Get();
935 anArray = aTextureAttr->InternalArray();
937 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
938 theFileName = aFileAttr->Get();
946 std::list<int> GEOM_Engine::getAllTextures(int theDocID)
948 std::list<int> id_list;
950 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
952 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
953 for (; anIterator.More(); anIterator.Next()) {
954 TDF_Label aTextureLabel = anIterator.Value();
955 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
956 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
957 Handle(TDataStd_Integer) anIdAttr;
958 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
959 id_list.push_back((int)anIdAttr->Get());
965 void GEOM_Engine::DocumentModified(const int theDocId, const bool isModified)
967 if (isModified) _mapModifiedDocs.Add(theDocId);
968 else _mapModifiedDocs.Remove(theDocId);
971 bool GEOM_Engine::DocumentModified(const int theDocId)
973 return _mapModifiedDocs.Contains(theDocId);
976 //===========================================================================
977 // Internal functions
978 //===========================================================================
980 //=============================================================================
982 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
984 //=============================================================================
985 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
987 TCollection_AsciiString aNewDescr;
989 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
990 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
991 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
992 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
993 // "3DSketcher:CMD[:CMD[:CMD...]]"
994 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
996 // Split the command string to separate CMDs
998 TColStd_SequenceOfAsciiString aSequence;
999 if (aCommand.Length()) {
1000 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
1001 while (aToken.Length() > 0) {
1002 aSequence.Append(aToken);
1003 aToken = aCommand.Token(":", ++icmd);
1007 if (aSequence.Length() > 0) {
1009 aNewDescr += "\n\t";
1011 aNewDescr += "\nsk = geompy.Sketcher3D()";
1012 int nbCMDs = aSequence.Length();
1013 for (icmd = 1; icmd <= nbCMDs; icmd++) {
1014 aNewDescr += "\n\t";
1016 TCollection_AsciiString aCMD = aSequence.Value(icmd);
1018 // Split the CMD into string values
1019 TColStd_SequenceOfAsciiString aStrVals;
1021 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1022 while (aToken.Length() > 0) {
1023 aStrVals.Append(aToken);
1024 aToken = aCMD.Token(" ", ++ival);
1027 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1028 if (aCMDpref == "TT") {
1029 aNewDescr += "sk.addPointsAbsolute(";
1030 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1032 else if (aCMDpref == "T") {
1033 aNewDescr += "sk.addPointsRelative(";
1034 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1036 else if (aCMDpref == "WW") {
1037 aNewDescr += "sk.close()";
1039 else if (aCMDpref.Value(1) == 'O'){
1040 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1042 if (aCMDpref.Value(4) == 'C')
1043 aNewDescr += "sk.addPointRadiusAngleH";
1045 aNewDescr += "sk.addPointRadiusAngles";
1046 if (aCMDpref.Value(5) == 'A')
1047 aNewDescr += "Absolute(";
1049 aNewDescr += "Relative(";
1050 aNewDescr += aStrVals.Value(4) + ", " +
1051 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1054 aNewDescr += "\n\t";
1055 aNewDescr += aResult + " = sk.wire()";
1057 } // Make3DSketcherCommand
1058 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1059 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1060 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1061 aCommand = aCommand.Token("]", 1);
1063 aNewDescr += "\n\t";
1064 aNewDescr += "\nsk = geompy.Sketcher3D()";
1065 aNewDescr += "\n\t";
1066 aNewDescr += "sk.addPointsAbsolute(";
1067 aNewDescr += aCommand + ")";
1068 aNewDescr += "\n\t";
1069 aNewDescr += aResult + " = sk.wire()";
1073 aNewDescr += "\n\t";
1074 aNewDescr += aSubStr;
1081 //=============================================================================
1083 * ProcessFunction: Dump function description into script
1085 //=============================================================================
1086 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1087 TCollection_AsciiString& theScript,
1088 TCollection_AsciiString& theAfterScript,
1089 const TVariablesList& theVariables,
1090 const bool theIsPublished,
1091 TDF_LabelMap& theProcessed,
1092 std::set<TCollection_AsciiString>& theIgnoreObjs,
1093 bool& theIsDumpCollected)
1095 theIsDumpCollected = false;
1096 if (theFunction.IsNull()) return false;
1098 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1100 // pass functions, that depends on nonexisting ones
1101 bool doNotProcess = false;
1102 TDF_LabelSequence aSeq;
1103 theFunction->GetDependency(aSeq);
1104 Standard_Integer aLen = aSeq.Length();
1105 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1106 TDF_Label aRefLabel = aSeq.Value(i);
1107 Handle(TDF_Reference) aRef;
1108 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1109 doNotProcess = true;
1112 if (aRef.IsNull() || aRef->Get().IsNull()) {
1113 doNotProcess = true;
1116 Handle(TDataStd_TreeNode) aT;
1117 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1118 doNotProcess = true;
1121 TDF_Label aDepLabel = aT->Label();
1122 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1124 if (aFunction.IsNull()) doNotProcess = true;
1125 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1132 TCollection_AsciiString anObjEntry;
1133 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1134 theIgnoreObjs.insert(anObjEntry);
1137 theProcessed.Add(theFunction->GetEntry());
1139 TCollection_AsciiString aDescr = theFunction->GetDescription();
1140 if(aDescr.Length() == 0) return false;
1142 //Check if its internal function which doesn't requires dumping
1143 if(aDescr == "None") return false;
1145 //Check the very specific case of RestoreShape function,
1146 //which is not dumped, but the result can be published by the user.
1147 //We do not publish such objects to decrease danger of dumped script failure.
1148 if(aDescr.Value(1) == '#') {
1149 TCollection_AsciiString anObjEntry;
1150 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1151 theIgnoreObjs.insert(anObjEntry);
1155 // 0020001 PTv, check for critical functions, which require dump of objects
1158 // currently, there is only one function "RestoreGivenSubShapes",
1159 // later this check could be replaced by iterations on list of such functions
1160 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1161 theIsDumpCollected = true;
1162 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1163 theIsDumpCollected = true;
1166 //Replace parameter by notebook variables
1167 ReplaceVariables(aDescr,theVariables);
1169 //Process sketcher functions, replacing string command by calls to Sketcher interface
1170 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1171 Sketcher_Profile aProfile( aDescr.ToCString());
1172 // Make new command for SketcherOnPlane and for Sketcher
1173 aDescr = aProfile.GetDump();
1175 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1176 aDescr = MakeCommandfor3DSketcher ( aDescr );
1179 if ( theIsDumpCollected ) {
1181 bool isBefore = true;
1182 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1183 while (!aSubStr.IsEmpty()) {
1185 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1186 aSubStr.Search( "RestoreSubShapes" ) == -1)
1187 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1189 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1190 aSubStr = aDescr.Token("\n\t", i++);
1194 theScript += "\n\t";
1195 theScript += aDescr;
1200 //=============================================================================
1202 * FindEntries: Returns a sequence of start/end positions of entries in the string
1204 //=============================================================================
1205 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1207 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1208 Standard_Integer aLen = theString.Length();
1209 Standard_Boolean isFound = Standard_False;
1211 const char* arr = theString.ToCString();
1212 Standard_Integer i = 0, j;
1215 int c = (int)arr[i];
1217 if(c >= 48 && c <= 57) { //Is digit?
1219 isFound = Standard_False;
1220 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1222 if(c == 58) isFound = Standard_True;
1225 if(isFound && arr[j-2] != 58) { // last char should be a diggit
1226 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1237 //=============================================================================
1239 * ReplaceVariables: Replace parameters of the function by variales from
1242 //=============================================================================
1243 void ReplaceVariables(TCollection_AsciiString& theCommand,
1244 const TVariablesList& theVariables)
1247 cout<<"Command : "<<theCommand<<endl;
1250 cout<<"All Entries:"<<endl;
1251 TVariablesList::const_iterator it = theVariables.begin();
1252 for(;it != theVariables.end();it++)
1253 cout<<"\t'"<<(*it).first<<"'"<<endl;
1256 //Additional case - multi-row commands
1257 int aCommandIndex = 1;
1258 while( aCommandIndex < 10 ) { // tmp check
1259 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1260 if( aCommand.Length() == 0 )
1264 cout<<"Sub-command : "<<aCommand<<endl;
1266 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1267 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1269 //Get Entry of the result object
1270 TCollection_AsciiString anEntry;
1271 if( aCommand.Search("=") != -1 ) // command returns an object
1272 anEntry = aCommand.Token("=",1);
1273 else { // command modifies the object
1274 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1275 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1276 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1278 //Remove white spaces
1279 anEntry.RightAdjust();
1280 anEntry.LeftAdjust();
1282 cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1284 if ( anEntry.IsEmpty() ) {
1289 //Check if result is list of entries - enough to get the first entry in this case
1291 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1292 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1294 TCollection_AsciiString aSeparator(COMMA);
1295 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1296 anEntry.Remove( 1, 1 );
1297 anEntry.RightAdjust();
1298 anEntry.LeftAdjust();
1300 cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1303 //Find variables used for object construction
1304 ObjectStates* aStates = 0;
1305 TVariablesList::const_iterator it = theVariables.find(anEntry);
1306 if( it != theVariables.end() )
1307 aStates = (*it).second;
1311 cout<<"Valiables list empty!!!"<<endl;
1316 TState aVariables = aStates->GetCurrectState();
1319 cout<<"Variables from SObject:"<<endl;
1320 for (int i = 0; i < aVariables.size();i++)
1321 cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1324 //Calculate total number of parameters
1325 Standard_Integer aTotalNbParams = 1;
1326 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1330 cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1332 Standard_Integer aFirstParam = aNbEntries;
1334 //Replace parameters by variables
1335 Standard_Integer aStartPos = 0;
1336 Standard_Integer aEndPos = 0;
1338 TCollection_AsciiString aVar, aReplacedVar;
1339 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1340 //Replace first parameter (bettwen '(' character and first ',' character)
1341 if(i == aFirstParam)
1343 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1344 if(aTotalNbParams - aNbEntries > 0 )
1345 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1347 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1349 //Replace last parameter (bettwen ',' character and ')' character)
1350 else if(i == aTotalNbParams)
1352 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1353 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1355 //Replace other parameters (bettwen two ',' characters)
1356 else if(i != aFirstParam && i != aTotalNbParams )
1358 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1359 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1362 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1364 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1366 if ( aStartPos == aEndPos )
1367 continue; // PAL20889: for "[]"
1370 cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1372 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1377 cout<<"Variable: '"<< aVar <<"'"<<endl;
1379 // specific case for sketcher
1380 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1381 Standard_Integer aNbSections = 1;
1382 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1386 int aStartSectionPos = 0, aEndSectionPos = 0;
1387 TCollection_AsciiString aSection, aReplacedSection;
1388 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1389 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1390 if( aSectionIndex != aNbSections )
1391 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1393 aEndSectionPos = aVar.Length();
1395 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1397 cout<<"aSection: "<<aSection<<endl;
1399 Standard_Integer aNbParams = 1;
1400 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1404 int aStartParamPos = 0, aEndParamPos = 0;
1405 TCollection_AsciiString aParameter, aReplacedParameter;
1406 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1407 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1408 if( aParamIndex != aNbParams )
1409 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1411 aEndParamPos = aSection.Length() + 1;
1414 cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
1416 if ( aStartParamPos == aEndParamPos)
1419 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1421 cout<<"aParameter: "<<aParameter<<endl;
1423 if(iVar >= aVariables.size())
1426 aReplacedParameter = aVariables[iVar].myVariable;
1427 if(aReplacedParameter.IsEmpty()) {
1432 if(aVariables[iVar].isVariable) {
1433 aReplacedParameter.InsertBefore(1,"'");
1434 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1438 cout<<"aSection before : "<<aSection<<endl;
1439 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1440 aSection.Insert(aStartParamPos, aReplacedParameter);
1442 cout<<"aSection after : "<<aSection<<endl<<endl;
1446 cout<<"aVar before : "<<aVar<<endl;
1447 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1448 aVar.Insert(aStartSectionPos, aSection);
1450 cout<<"aVar after : "<<aVar<<endl<<endl;
1454 cout<<"aCommand before : "<<aCommand<<endl;
1455 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1456 aCommand.Insert(aStartPos, aVar);
1458 cout<<"aCommand after : "<<aCommand<<endl;
1461 } // end of specific case for sketcher
1463 //If parameter is entry or 'None', skip it
1464 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1467 if(iVar >= aVariables.size())
1470 aReplacedVar = aVariables[iVar].myVariable;
1471 if(aReplacedVar.IsEmpty()) {
1476 if(aVariables[iVar].isVariable) {
1477 aReplacedVar.InsertBefore(1,"\"");
1478 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1481 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1482 aCommand.Insert(aStartPos, aReplacedVar);
1486 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1487 theCommand.Insert(aStartCommandPos, aCommand);
1491 aStates->IncrementState();
1495 cout<<"Command : "<<theCommand<<endl;
1498 //=============================================================================
1500 * ReplaceEntriesByNames: Replace object entries by their names
1502 //=============================================================================
1503 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1504 TSting2ObjDataMap& aEntry2ObjData,
1505 const bool theIsPublished,
1506 TColStd_SequenceOfAsciiString& theObjListToPublish,
1507 Standard_Integer& objectCounter,
1508 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1510 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1511 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1512 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1514 //Replace entries by the names
1515 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1516 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1517 if (aLen == 0) anUpdatedScript = theScript;
1519 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1520 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1521 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1522 theObjListToPublish.Append( anEntry );
1524 TObjectData& data = aEntry2ObjData[ anEntry ];
1525 if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1526 if ( !data._name.IsEmpty() ) { // published object
1527 data._pyName = data._name;
1528 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1532 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1533 } while(aNameToEntry.IsBound(data._pyName));
1537 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1539 anUpdatedScript += data._pyName;
1540 aStart = aSeq->Value(i+1) + 1;
1543 //Add final part of the script
1544 if (aLen && aSeq->Value(aLen) < aScriptLength)
1545 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1547 theScript = anUpdatedScript;
1550 //=============================================================================
1552 * AddObjectColors: Add color to objects
1554 //=============================================================================
1555 void AddObjectColors (int theDocID,
1556 TCollection_AsciiString& theScript,
1557 const TSting2ObjDataMap& theEntry2ObjData)
1559 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1560 Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
1562 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1563 for (anEntryToNameIt = theEntry2ObjData.begin();
1564 anEntryToNameIt!= theEntry2ObjData.end();
1567 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1568 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1571 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1575 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1579 bool anAutoColor = obj->GetAutoColor();
1582 TCollection_AsciiString aCommand( "\n\t" );
1583 aCommand += aName + ".SetAutoColor(1)";
1584 theScript += aCommand.ToCString();
1587 GEOM_Object::Color aColor = obj->GetColor();
1588 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1590 TCollection_AsciiString aCommand( "\n\t" );
1591 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1592 theScript += aCommand.ToCString();
1595 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1596 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1597 TCollection_AsciiString aCommand( "\n\t" );
1598 aCommand += aName + ".SetMarkerStd(";
1599 switch (aMarkerType) {
1600 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1601 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1602 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1603 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1604 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1605 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1606 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1607 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1608 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1609 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1610 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1611 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1612 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1613 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1616 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1618 case 1: aCommand += "GEOM.MS_10"; break;
1619 case 2: aCommand += "GEOM.MS_15"; break;
1620 case 3: aCommand += "GEOM.MS_20"; break;
1621 case 4: aCommand += "GEOM.MS_25"; break;
1622 case 5: aCommand += "GEOM.MS_30"; break;
1623 case 6: aCommand += "GEOM.MS_35"; break;
1624 case 7: aCommand += "GEOM.MS_40"; break;
1625 case 8: aCommand += "GEOM.MS_45"; break;
1626 case 9: aCommand += "GEOM.MS_50"; break;
1627 case 10: aCommand += "GEOM.MS_55"; break;
1628 case 11: aCommand += "GEOM.MS_60"; break;
1629 case 12: aCommand += "GEOM.MS_65"; break;
1630 case 13: aCommand += "GEOM.MS_70"; break;
1631 default: aCommand += "GEOM.MS_NONE"; break;
1634 theScript += aCommand.ToCString();
1636 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1637 int aMarkerTextureID = obj->GetMarkerTexture();
1638 if (aMarkerTextureID >= 0) {
1639 TCollection_AsciiString aCommand( "\n\t" );
1640 aCommand += aName + ".SetMarkerTexture(texture_map[";
1641 aCommand += aMarkerTextureID;
1643 theScript += aCommand.ToCString();
1649 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1651 TCollection_AsciiString stream;
1652 if (!aData.IsNull()) {
1653 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1654 Standard_Byte byte = aData->Value(i);
1655 TCollection_AsciiString strByte = "";
1656 for (int j = 0; j < 8; j++)
1657 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1664 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
1666 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1667 std::list<int> allTextures = engine->getAllTextures(theDocID);
1668 std::list<int>::const_iterator it;
1670 if (allTextures.size() > 0) {
1671 theScript += "\n\ttexture_map = {}\n";
1673 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1674 if (*it <= 0) continue;
1675 Standard_Integer aWidth, aHeight;
1676 TCollection_AsciiString aFileName;
1677 Handle(TColStd_HArray1OfByte) aTexture =
1678 engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
1679 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1680 TCollection_AsciiString aCommand = "\n\t";
1681 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1682 if (aFileName != "" ) {
1683 aCommand += "geompy.LoadTexture(\"";
1684 aCommand += aFileName.ToCString();
1688 aCommand += "geompy.AddTexture(";
1689 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1690 aCommand += pack_data(aTexture);
1693 theScript += aCommand;
1700 //=============================================================================
1702 * PublishObject: publish object in study script
1704 //=============================================================================
1705 void PublishObject (TObjectData& theObjectData,
1706 TSting2ObjDataMap& theEntry2ObjData,
1707 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1708 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1709 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1710 std::set< TCollection_AsciiString>& theIgnoreMap)
1712 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1713 if ( theObjectData._studyEntry.IsEmpty() )
1714 return; // was not published
1715 if ( theIgnoreMap.count( theObjectData._entry ) )
1716 return; // not to publish
1718 TCollection_AsciiString aCommand("\n\tgeompy.");
1720 // find a father entry
1721 TObjectData* aFatherData = 0;
1722 TCollection_AsciiString aFatherStudyEntry =
1723 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1724 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1725 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1726 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1727 aFatherData = stEntry2DataPtr->second;
1729 const int geomObjDepth = 3;
1731 // treat multiply published object
1732 if ( theObjectData._pyName.IsEmpty() )
1734 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1735 if ( data0._pyName.IsEmpty() ) return; // something wrong
1737 theObjectData._pyName = theObjectData._name;
1738 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1740 TCollection_AsciiString aCreationCommand("\n\t");
1741 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1743 // store aCreationCommand before publishing commands
1744 int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1745 theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1749 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1750 aCommand += "addToStudyInFather( ";
1751 aCommand += aFatherData->_pyName + ", ";
1754 aCommand += "addToStudy( ";
1756 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1758 // bind a command to the study entry
1759 int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1760 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1762 theObjectData._studyEntry.Clear(); // not to publish any more
1765 //================================================================================
1767 * \brief Constructor
1769 //================================================================================
1770 ObjectStates::ObjectStates()
1775 //================================================================================
1779 //================================================================================
1780 ObjectStates::~ObjectStates()
1784 //================================================================================
1786 * \brief Return current object state
1787 * \retval state - Object state (vector of notebook variable)
1789 //================================================================================
1790 TState ObjectStates::GetCurrectState() const
1792 if(_states.size() > _dumpstate)
1793 return _states[_dumpstate];
1797 //================================================================================
1799 * \brief Add new object state
1800 * \param theState - Object state (vector of notebook variable)
1802 //================================================================================
1803 void ObjectStates::AddState(const TState &theState)
1805 _states.push_back(theState);
1808 //================================================================================
1810 * \brief Increment object state
1812 //================================================================================
1813 void ObjectStates::IncrementState()