1 // Copyright (C) 2005 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License.
9 // This library is distributed in the hope that it will be useful
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Lesser General Public License for more details.
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #pragma warning( disable:4786 )
24 #include "GEOM_Engine.hxx"
26 #include "GEOM_Solver.hxx"
27 #include "GEOM_Function.hxx"
28 #include "GEOM_ISubShape.hxx"
29 #include "GEOM_SubShapeDriver.hxx"
30 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
31 #include "GEOM_PythonDump.hxx"
33 #include "utilities.h"
35 #include <TDF_Tool.hxx>
36 #include <TDF_Data.hxx>
37 #include <TDF_LabelSequence.hxx>
38 #include <TDataStd_Integer.hxx>
39 #include <TDataStd_ChildNodeIterator.hxx>
40 #include <TFunction_Driver.hxx>
41 #include <TFunction_DriverTable.hxx>
44 #include <TopTools_IndexedMapOfShape.hxx>
46 #include <TCollection_AsciiString.hxx>
47 #include <TCollection_ExtendedString.hxx>
48 #include <TColStd_SequenceOfAsciiString.hxx>
49 #include <TColStd_MapOfTransient.hxx>
50 #include <TColStd_HSequenceOfInteger.hxx>
52 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
53 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
58 #include <Standard_Failure.hxx>
59 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
61 static GEOM_Engine* TheEngine = NULL;
63 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
65 TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
66 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
67 anID+=(TCollection_AsciiString("_")+anEntry);
71 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
73 TCollection_AsciiString anID(theDocID);
74 anID+=(TCollection_AsciiString("_")+theEntry);
78 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
80 TCollection_AsciiString aDocID = theID.Token("_");
81 if(aDocID.Length() < 1) return -1;
82 return aDocID.IntegerValue();
85 void ProcessFunction(Handle(GEOM_Function)& theFunction,
86 TCollection_AsciiString& theScript,
87 TColStd_MapOfTransient& theProcessed);
89 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
91 //=============================================================================
95 //=============================================================================
96 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
99 //=============================================================================
103 //=============================================================================
104 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
106 //=============================================================================
110 //=============================================================================
111 GEOM_Engine::GEOM_Engine()
113 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
115 _OCAFApp = new GEOM_Application();
119 //=============================================================================
123 //=============================================================================
124 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
126 Handle(TDocStd_Document) aDoc;
127 if(!_mapIDDocument.IsBound(theDocID)) {
128 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
129 aDoc->SetUndoLimit(_UndoLimit);
130 _mapIDDocument.Bind(theDocID, aDoc);
131 TDataStd_Integer::Set(aDoc->Main(), theDocID);
134 return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
137 //=============================================================================
141 //=============================================================================
142 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
144 if(theDocument.IsNull()) return -1;
145 for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
146 if(anItr.Value() == theDocument) return anItr.Key();
152 //=============================================================================
156 //=============================================================================
157 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
159 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
160 if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
163 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
164 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
165 Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
167 _objects.Bind(anID, anObject);
172 //=============================================================================
176 //=============================================================================
177 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
179 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
180 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
182 TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main());
183 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
185 //Put an object in the map of created objects
186 TCollection_AsciiString anID = BuildIDFromObject(anObject);
187 if(_objects.IsBound(anID)) _objects.UnBind(anID);
188 _objects.Bind(anID, anObject);
193 //=============================================================================
197 //=============================================================================
198 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
199 Handle(TColStd_HArray1OfInteger) theIndices,
200 bool isStandaloneOperation)
202 if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
204 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
205 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
207 TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main());
209 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
210 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
211 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
213 GEOM_ISubShape aSSI(aFunction);
214 aSSI.SetMainShape(aMainShape);
215 aSSI.SetIndices(theIndices);
218 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
221 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
222 if (!aSolver.ComputeFunction(aFunction)) {
223 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
227 catch (Standard_Failure) {
228 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
229 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
233 //Put an object in the map of created objects
234 TCollection_AsciiString anID = BuildIDFromObject(anObject);
235 if(_objects.IsBound(anID)) _objects.UnBind(anID);
236 _objects.Bind(anID, anObject);
238 GEOM::TPythonDump pd (aFunction);
240 if (isStandaloneOperation) {
241 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
242 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
243 for (; i <= up - 1; i++) {
244 pd << theIndices->Value(i) << ", ";
246 pd << theIndices->Value(up) << "])";
254 //=============================================================================
258 //=============================================================================
259 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
261 if(!theObject) return false;
263 //Remove an object from the map of available objects
264 TCollection_AsciiString anID = BuildIDFromObject(theObject);
265 if(_objects.IsBound(anID)) _objects.UnBind(anID);
267 int nb = theObject->GetNbFunctions();
268 Handle(TDataStd_TreeNode) aNode;
269 for(int i = 1; i<=nb; i++) {
270 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
271 if(aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
275 TDF_Label aLabel = theObject->GetEntry();
276 aLabel.ForgetAllAttributes(Standard_True);
283 //=============================================================================
287 //=============================================================================
288 void GEOM_Engine::Undo(int theDocID)
290 GetDocument(theDocID)->Undo();
293 //=============================================================================
297 //=============================================================================
298 void GEOM_Engine::Redo(int theDocID)
300 GetDocument(theDocID)->Redo();
303 //=============================================================================
307 //=============================================================================
308 bool GEOM_Engine::Save(int theDocID, char* theFileName)
310 if(!_mapIDDocument.IsBound(theDocID)) return false;
311 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
313 _OCAFApp->SaveAs(aDoc, theFileName);
318 //=============================================================================
322 //=============================================================================
323 bool GEOM_Engine::Load(int theDocID, char* theFileName)
325 Handle(TDocStd_Document) aDoc;
326 if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
330 aDoc->SetUndoLimit(_UndoLimit);
332 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
333 _mapIDDocument.Bind(theDocID, aDoc);
335 TDataStd_Integer::Set(aDoc->Main(), theDocID);
340 //=============================================================================
344 //=============================================================================
345 void GEOM_Engine::Close(int theDocID)
347 if(_mapIDDocument.IsBound(theDocID)) {
348 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
350 //Remove all GEOM Objects associated to the given document
351 TColStd_SequenceOfAsciiString aSeq;
352 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
353 for(; It.More(); It.Next()) {
354 TCollection_AsciiString anObjID(It.Key());
355 Standard_Integer anID = ExtractDocID(anObjID);
356 if(theDocID == anID) aSeq.Append(It.Key());
358 for(Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
360 _mapIDDocument.UnBind(theDocID);
361 _OCAFApp->Close(aDoc);
366 //=============================================================================
370 //=============================================================================
371 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
372 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
376 TCollection_AsciiString aScript;
377 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
379 if(aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
381 aScript = "import geompy\n";
382 aScript += "import math\n\n";
383 aScript += "def RebuildData(theStudy):";
384 aScript += "\n\tgeompy.init_geom(theStudy)";
386 Standard_Integer posToInertGlobalVars = aScript.Length() + 1;
388 Handle(TDataStd_TreeNode) aNode, aRoot;
389 Handle(GEOM_Function) aFunction;
390 TColStd_MapOfTransient aMap;
392 if(aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
393 TDataStd_ChildNodeIterator Itr(aRoot);
394 for(; Itr.More(); Itr.Next()) {
396 aFunction = GEOM_Function::GetFunction(aNode->Label());
397 if(aFunction.IsNull()) {
398 cout << "Null function !!!!" << endl;
401 ProcessFunction(aFunction, aScript, aMap);
405 Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
406 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
407 // build maps entry <-> studyEntry
408 for (anEntryToNameIt.Initialize( theObjectNames );
409 anEntryToNameIt.More();
410 anEntryToNameIt.Next())
412 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
413 // look for an object by entry
415 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
416 if ( L.IsNull() ) continue;
417 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
419 if ( !obj.IsNull() ) {
420 TCollection_AsciiString aStudyEntry (obj->GetAuxData());
421 aEntry2StEntry.Bind( aEntry, aStudyEntry);
422 aStEntry2Entry.Bind( aStudyEntry, aEntry );
426 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
427 Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
428 Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
430 //Replace entries by the names
431 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
432 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
433 if(aLen == 0) anUpdatedScript = aScript;
435 for(Standard_Integer i = 1; i <= aLen; i+=2) {
436 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
437 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
438 if(theObjectNames.IsBound(anEntry)) {
439 aName = theObjectNames.Find(anEntry);
440 // check validity of aName
441 bool isValidName = true;
442 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
443 aName.Insert( 1, 'a' );
446 int p, p2=1; // replace not allowed chars
447 while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
448 aName.SetValue(p, '_');
452 if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
453 { // diff objects have same name - make a new name by appending a digit
454 TCollection_AsciiString aName2;
455 Standard_Integer i = 0;
457 aName2 = aName + "_" + ++i;
458 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
462 if ( !isValidName ) {
464 anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
465 theObjectNames( anEntry ) = aName;
470 aName = aBaseName + TCollection_AsciiString(++objectCounter);
471 } while(aNameToEntry.IsBound(aName));
472 theObjectNames.Bind(anEntry, aName);
474 aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
476 anUpdatedScript += aName;
477 aStart = aSeq->Value(i+1) + 1;
480 //Add final part of the script
481 if(aLen && aSeq->Value(aLen) < aScriptLength) anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
483 // Make script to publish in study
486 map< int, string > anEntryToCommandMap; // sort publishing commands by object entry
487 for (anEntryToNameIt.Initialize( theObjectNames );
488 anEntryToNameIt.More();
489 anEntryToNameIt.Next())
491 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
492 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
493 if ( !aEntry2StEntry.IsBound( aEntry ))
494 continue; // was not published
495 TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
497 // find a father entry
498 const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
499 TCollection_AsciiString aFatherStudyEntry =
500 aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
501 if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
502 aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
505 if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
506 aCommand += "addToStudyInFather( ";
507 aCommand += theObjectNames( aFatherEntry ) + ", ";
510 aCommand += "addToStudy( ";
511 if ( anEntryToBadName.IsBound( aEntry ))
512 aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
514 aCommand += aName + ", \"" + aName + "\" )";
516 // bind a command to the last digit of the entry
518 aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
519 anEntryToCommandMap.insert( make_pair( tag, aCommand.ToCString() ));
522 // add publishing commands to the script
523 map< int, string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
524 for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
525 anUpdatedScript += (char*)anEntryToCommand->second.c_str();
529 anUpdatedScript += "\n\tpass\n";
532 // fill _studyEntry2NameMap and build globalVars
533 TCollection_AsciiString globalVars;
534 _studyEntry2NameMap.Clear();
535 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
536 for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
537 aStEntryToEntryIt.More();
538 aStEntryToEntryIt.Next() )
540 const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
541 _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
542 if ( !globalVars.IsEmpty() )
546 if ( !globalVars.IsEmpty() ) {
547 globalVars.Insert( 1, "\n\tglobal " );
548 anUpdatedScript.Insert( posToInertGlobalVars, globalVars );
551 return anUpdatedScript;
554 //=======================================================================
555 //function : GetDumpName
557 //=======================================================================
559 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
561 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
562 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
567 //=======================================================================
568 //function : GetAllDumpNames
570 //=======================================================================
572 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
574 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
576 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
577 for (; it.More(); it.Next()) {
578 aRetSeq->Append(it.Value());
585 //===========================================================================
586 // Internal functions
587 //===========================================================================
588 void ProcessFunction(Handle(GEOM_Function)& theFunction,
589 TCollection_AsciiString& theScript,
590 TColStd_MapOfTransient& theProcessed)
592 if(theFunction.IsNull() || theProcessed.Contains(theFunction)) return;
595 TDF_LabelSequence aSeq;
596 theFunction->GetDependency(aSeq);
597 Standard_Integer aLen = aSeq.Length();
598 for(Standard_Integer i = 1; i<= aLen; i++) {
599 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aSeq.Value(i));
600 if(aFunction.IsNull()) continue;
601 ProcessFunction(aFunction, theScript, theProcessed);
605 TCollection_AsciiString aDescr = theFunction->GetDescription();
606 if(aDescr.Length() == 0) {
607 //cout << "Warning: the function has no description" << endl;
610 //Check if its internal function which doesn't requires dumping
611 if(aDescr == "None") return;
616 theProcessed.Add(theFunction);
620 //=============================================================================
622 * FindEntries: Returns a sequence of start/end positions of entries in the string
624 //=============================================================================
625 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
627 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
628 Standard_Integer aLen = theString.Length();
629 Standard_Boolean isFound = Standard_False;
631 char* arr = theString.ToCString();
632 Standard_Integer i = 0, j;
637 if(c >= 48 && c <= 57) { //Is digit?
639 isFound = Standard_False;
640 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
642 if(c == 58) isFound = Standard_True;
645 if(isFound && arr[j-2] != 58) { // last char should be a diggit
646 aSeq->Append(i+1); // +1 because AsciiString starts from 1