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";
383 aScript += "import SALOMEDS\n\n";
384 aScript += "def RebuildData(theStudy):";
385 aScript += "\n\tgeompy.init_geom(theStudy)";
387 Standard_Integer posToInertGlobalVars = aScript.Length() + 1;
389 Handle(TDataStd_TreeNode) aNode, aRoot;
390 Handle(GEOM_Function) aFunction;
391 TColStd_MapOfTransient aMap;
393 if(aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
394 TDataStd_ChildNodeIterator Itr(aRoot);
395 for(; Itr.More(); Itr.Next()) {
397 aFunction = GEOM_Function::GetFunction(aNode->Label());
398 if(aFunction.IsNull()) {
399 cout << "Null function !!!!" << endl;
402 ProcessFunction(aFunction, aScript, aMap);
406 Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
407 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
408 // build maps entry <-> studyEntry
409 for (anEntryToNameIt.Initialize( theObjectNames );
410 anEntryToNameIt.More();
411 anEntryToNameIt.Next())
413 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
414 // look for an object by entry
416 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
417 if ( L.IsNull() ) continue;
418 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
420 if ( !obj.IsNull() ) {
421 TCollection_AsciiString aStudyEntry (obj->GetAuxData());
422 aEntry2StEntry.Bind( aEntry, aStudyEntry);
423 aStEntry2Entry.Bind( aStudyEntry, aEntry );
427 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
428 Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
429 Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
431 //Replace entries by the names
432 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
433 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
434 if(aLen == 0) anUpdatedScript = aScript;
436 for(Standard_Integer i = 1; i <= aLen; i+=2) {
437 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
438 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
439 if(theObjectNames.IsBound(anEntry)) {
440 aName = theObjectNames.Find(anEntry);
441 // check validity of aName
442 bool isValidName = true;
443 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
444 aName.Insert( 1, 'a' );
447 int p, p2=1; // replace not allowed chars
448 while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
449 aName.SetValue(p, '_');
453 if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
454 { // diff objects have same name - make a new name by appending a digit
455 TCollection_AsciiString aName2;
456 Standard_Integer i = 0;
458 aName2 = aName + "_" + ++i;
459 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
463 if ( !isValidName ) {
465 anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
466 theObjectNames( anEntry ) = aName;
471 aName = aBaseName + TCollection_AsciiString(++objectCounter);
472 } while(aNameToEntry.IsBound(aName));
473 theObjectNames.Bind(anEntry, aName);
475 aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
477 anUpdatedScript += aName;
478 aStart = aSeq->Value(i+1) + 1;
481 //Add final part of the script
482 if(aLen && aSeq->Value(aLen) < aScriptLength) anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
485 for (anEntryToNameIt.Initialize( theObjectNames );
486 anEntryToNameIt.More();
487 anEntryToNameIt.Next())
489 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
490 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
493 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
497 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
501 bool anAutoColor = obj->GetAutoColor();
504 TCollection_AsciiString aCommand( "\n\t" );
505 aCommand += aName + ".SetAutoColor(1)";
506 anUpdatedScript += aCommand.ToCString();
509 SALOMEDS::Color aColor = obj->GetColor();
510 if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
512 TCollection_AsciiString aCommand( "\n\t" );
513 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
514 anUpdatedScript += aCommand.ToCString();
518 // Make script to publish in study
521 map< int, string > anEntryToCommandMap; // sort publishing commands by object entry
522 for (anEntryToNameIt.Initialize( theObjectNames );
523 anEntryToNameIt.More();
524 anEntryToNameIt.Next())
526 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
527 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
528 if ( !aEntry2StEntry.IsBound( aEntry ))
529 continue; // was not published
530 TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
532 // find a father entry
533 const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
534 TCollection_AsciiString aFatherStudyEntry =
535 aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
536 if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
537 aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
540 if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
541 aCommand += "addToStudyInFather( ";
542 aCommand += theObjectNames( aFatherEntry ) + ", ";
545 aCommand += "addToStudy( ";
546 if ( anEntryToBadName.IsBound( aEntry ))
547 aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
549 aCommand += aName + ", \"" + aName + "\" )";
551 // bind a command to the last digit of the entry
553 aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
554 anEntryToCommandMap.insert( make_pair( tag, aCommand.ToCString() ));
557 // add publishing commands to the script
558 map< int, string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
559 for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
560 anUpdatedScript += (char*)anEntryToCommand->second.c_str();
564 anUpdatedScript += "\n\tpass\n";
567 // fill _studyEntry2NameMap and build globalVars
568 TCollection_AsciiString globalVars;
569 _studyEntry2NameMap.Clear();
570 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
571 for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
572 aStEntryToEntryIt.More();
573 aStEntryToEntryIt.Next() )
575 const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
576 _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
577 if ( !globalVars.IsEmpty() )
581 if ( !globalVars.IsEmpty() ) {
582 globalVars.Insert( 1, "\n\tglobal " );
583 anUpdatedScript.Insert( posToInertGlobalVars, globalVars );
586 return anUpdatedScript;
589 //=======================================================================
590 //function : GetDumpName
592 //=======================================================================
594 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
596 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
597 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
602 //=======================================================================
603 //function : GetAllDumpNames
605 //=======================================================================
607 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
609 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
611 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
612 for (; it.More(); it.Next()) {
613 aRetSeq->Append(it.Value());
620 //===========================================================================
621 // Internal functions
622 //===========================================================================
623 void ProcessFunction(Handle(GEOM_Function)& theFunction,
624 TCollection_AsciiString& theScript,
625 TColStd_MapOfTransient& theProcessed)
627 if(theFunction.IsNull() || theProcessed.Contains(theFunction)) return;
630 TDF_LabelSequence aSeq;
631 theFunction->GetDependency(aSeq);
632 Standard_Integer aLen = aSeq.Length();
633 for(Standard_Integer i = 1; i<= aLen; i++) {
634 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aSeq.Value(i));
635 if(aFunction.IsNull()) continue;
636 ProcessFunction(aFunction, theScript, theProcessed);
640 TCollection_AsciiString aDescr = theFunction->GetDescription();
641 if(aDescr.Length() == 0) {
642 //cout << "Warning: the function has no description" << endl;
645 //Check if its internal function which doesn't requires dumping
646 if(aDescr == "None") return;
651 theProcessed.Add(theFunction);
655 //=============================================================================
657 * FindEntries: Returns a sequence of start/end positions of entries in the string
659 //=============================================================================
660 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
662 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
663 Standard_Integer aLen = theString.Length();
664 Standard_Boolean isFound = Standard_False;
666 char* arr = theString.ToCString();
667 Standard_Integer i = 0, j;
672 if(c >= 48 && c <= 57) { //Is digit?
674 isFound = Standard_False;
675 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
677 if(c == 58) isFound = Standard_True;
680 if(isFound && arr[j-2] != 58) { // last char should be a diggit
681 aSeq->Append(i+1); // +1 because AsciiString starts from 1