X-Git-Url: http://git.salome-platform.org/gitweb/?a=blobdiff_plain;f=src%2FGEOM%2FGEOM_Engine.cxx;h=13aea9601b606aade95657920fd67df2db75b5ff;hb=14e1a694c4cf249fe205a39c099482bc5b28a6e5;hp=46726dceae50e4fe1aa259f96269528c3c775f30;hpb=d3dd282390888d7dc091ba2c2ffe7923bd7458e6;p=modules%2Fgeom.git diff --git a/src/GEOM/GEOM_Engine.cxx b/src/GEOM/GEOM_Engine.cxx index 46726dcea..13aea9601 100644 --- a/src/GEOM/GEOM_Engine.cxx +++ b/src/GEOM/GEOM_Engine.cxx @@ -1,21 +1,56 @@ +// Copyright (C) 2007-2024 CEA, EDF, OPEN CASCADE +// +// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifdef WIN32 +#pragma warning( disable:4786 ) +#endif + #include "GEOM_Engine.hxx" -#include "GEOM_Solver.hxx" +#include "GEOM_Field.hxx" #include "GEOM_Function.hxx" #include "GEOM_ISubShape.hxx" +#include "GEOM_PythonDump.hxx" +#include "GEOM_Solver.hxx" #include "GEOM_SubShapeDriver.hxx" -#include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx" +#include "Sketcher_Profile.hxx" #include "utilities.h" -#include +#include +#include #include #include +#include +#include #include #include #include #include +#include +#include +#include +#include #include #include @@ -23,31 +58,258 @@ #include #include #include +#include +#include + +#include + +#if OCC_VERSION_LARGE < 0x07050000 +#include +#endif + +#include +#include +#include + +#include +#include #include // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC +#define COMMA ',' +#define O_BRACKET '(' +#define C_BRACKET ')' +#define O_SQR_BRACKET '[' +#define C_SQR_BRACKET ']' +#define PY_NULL "None" + +// VSR 29/08/2017: 0023327, 0023428: eliminate unnecessary lines in Python dump +// Next macro, when defined, causes appearing of SubShapeAllIDs(), SubShapeAllSortedIDs(), GetSameIDs() +// and other such commands in Python dump. +// See also GEOMImpl_IShapesOperations.cxx. +// --------------------------------------- +// #define DUMP_SUBSHAPE_IDS +// --------------------------------------- + +typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap; +typedef std::map< TCollection_AsciiString, TObjectData > TSting2ObjDataMap; +typedef std::map< TCollection_AsciiString, TObjectData* > TSting2ObjDataPtrMap; +typedef std::map< int, std::list < int > > TIntToListIntMap; + static GEOM_Engine* TheEngine = NULL; -static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject) + +static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_BaseObject)& theObject) { - TCollection_AsciiString anID(theObject->GetDocID()), anEntry; + TCollection_AsciiString anEntry; TDF_Tool::Entry(theObject->GetEntry(), anEntry); - anID+=(TCollection_AsciiString("_")+anEntry); - return anID; + return anEntry; } -static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry) +bool ProcessFunction(Handle(GEOM_Function)& theFunction, + TCollection_AsciiString& theScript, + TCollection_AsciiString& theAfterScript, + const TVariablesList& theVariables, + const bool /*theIsPublished*/, + TDF_LabelMap& theProcessed, + std::set& theIgnoreObjs, + bool& theIsDumpCollected); + +static int GetTag(const TCollection_AsciiString &theEntry); + +static void FillMapOfRef(const Handle(GEOM_Function) &theFunction, + TIntToListIntMap &theRefMap); + +void ReplaceVariables(TCollection_AsciiString& theCommand, + const TVariablesList& theVariables); + +Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString); + +void ReplaceEntriesByNames (TCollection_AsciiString& theScript, + TSting2ObjDataMap& aEntry2ObjData, + const bool theIsPublished, + TColStd_SequenceOfAsciiString& theObjListToPublish, + Standard_Integer& objectCounter, + Resource_DataMapOfAsciiStringAsciiString& aNameToEntry); + +void AddObjectColors (TCollection_AsciiString& theScript, + const TSting2ObjDataMap& theEntry2ObjData); + +void AddTextures (TCollection_AsciiString& theScript); + +void PublishObject (TObjectData& theObjectData, + TSting2ObjDataMap& theEntry2ObjData, + const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr, + Resource_DataMapOfAsciiStringAsciiString& theNameToEntry, + std::map< int, TCollection_AsciiString >& theEntryToCmdMap, + std::set& theMapOfPublished); + +static TCollection_AsciiString GetPublishCommands + (const int theTag, + const std::map< int, TCollection_AsciiString > &theEntryToCmdMap, + const TIntToListIntMap &theMapRefs, + std::set< int > &thePublished); + +void Prettify(TCollection_AsciiString& theScript); + +// Helper functions +namespace { - TCollection_AsciiString anID(theDocID); - anID+=(TCollection_AsciiString("_")+theEntry); - return anID; + // Specifies a way to process a given function + enum FunctionProcessType { NOT_PROCESS, TO_PROCESS, UPDATE_DESCRIPTION }; + + // Starting string for an edge case where function was dumped from Python code + const Standard_CString funcFromPythonStartString = "from salome.geom.geomrepairadv"; + + + //================================================================================ + /*! + * \brief Checks if a description contents a function that was dumped from Python code + */ + //================================================================================ + bool IsFunctionSetFromPython(const TCollection_AsciiString& aDescr) + { + // TODO: make it more generic and not depended on geomrepairadv name + return aDescr.Search(funcFromPythonStartString) != -1; + } + + + //================================================================================ + /*! + * \brief Removes from description the part before specific import statement + */ + //================================================================================ + void UpdateFuncFromPythonDescription(TCollection_AsciiString& aDescr) + { + const Standard_Integer startStringPos = aDescr.Search(funcFromPythonStartString); + MESSAGE("Description should start from pos: " << startStringPos); + if (startStringPos == -1) + { + MESSAGE("Can't find a string:\n" << funcFromPythonStartString << " \nin func description!"); + return; + } + + // Remove everything from the beginning till the starting point. + // Index starts from 1 not 0! + aDescr.Remove(1, startStringPos - 1); + MESSAGE("Updated func description: " << aDescr); + } + + + //================================================================================ + /*! + * \brief Finds out how we should process a given function for Python dump + */ + //================================================================================ + FunctionProcessType GetFunctionProcessingType(const Handle(GEOM_Function)& theFunction, const TDF_LabelMap& theProcessed, const TCollection_AsciiString& aDescr) + { + MESSAGE("Start check function dependencies..."); + + TDF_LabelSequence aSeq; + theFunction->GetDependency(aSeq); + const Standard_Integer aLen = aSeq.Length(); + + for (Standard_Integer i = 1; i <= aLen; i++) { + TDF_Label aRefLabel = aSeq.Value(i); + Handle(TDF_Reference) aRef; + if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) { + MESSAGE("Can't find TDF_Reference::GetID() attribute. Do not process."); + return NOT_PROCESS; + } + + if (aRef.IsNull() || aRef->Get().IsNull()) { + MESSAGE("Reference to attribute is null. Do not process."); + return NOT_PROCESS; + } + + Handle(TDataStd_TreeNode) aT; + if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) { + MESSAGE("Can't find a tree node. Do not process."); + return NOT_PROCESS; + } + + TDF_Label aDepLabel = aT->Label(); + Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel); + if (aFunction.IsNull()) { + MESSAGE("Function is null. Do not process." << aFunction->GetDescription()); + return NOT_PROCESS; + } + + if (!theProcessed.Contains(aDepLabel)) { + // Special case for function dumped from Python, because it's appended to + // description of other function that should be rejected early. + // TODO: it's not clear if we need to check every given function or + // checking on this level is enough. At this moment it's better to stay here + // for performance reason. + if (IsFunctionSetFromPython(aDescr)) { + MESSAGE("Function set from Python. Do process with updated description."); + return UPDATE_DESCRIPTION; + } + + MESSAGE("The dependency label is not in processed list. Do not process."); + return NOT_PROCESS; + } + } + + MESSAGE("OK. Do process the function."); + return TO_PROCESS; + } + + //================================================================================ + /*! + * \brief Adds function's object to ignored for Python dump output + */ + //================================================================================ + void AddFuncObjectToIgnored(const Handle(GEOM_Function)& theFunction, std::set& theIgnoreObjs) + { + TCollection_AsciiString anObjEntry; + TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry); + theIgnoreObjs.insert(anObjEntry); + } + } -static Standard_Integer ExtractDocID(TCollection_AsciiString& theID) + +//================================================================================ +/*! + * \brief Fix up the name of python variable + */ +//================================================================================ + +void GEOM_Engine::healPyName( TCollection_AsciiString& pyName, + const TCollection_AsciiString& anEntry, + Resource_DataMapOfAsciiStringAsciiString& aNameToEntry) { - TCollection_AsciiString aDocID = theID.Token("_"); - if(aDocID.Length() < 1) return -1; - return aDocID.IntegerValue(); + const TCollection_AsciiString allowedChars + ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_"); + + if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit + pyName.Insert( 1, 'a' ); + } + int p, p2=1; // replace not allowed chars + while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) { + pyName.SetValue(p, '_'); + p2=p; + } + if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName )) + { // diff objects have same name - make a new name by appending a digit + TCollection_AsciiString aName2; + Standard_Integer i = 0; + do { + aName2 = pyName + "_" + ++i; + } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 )); + pyName = aName2; + } +} + +//======================================================================= +//function : GetTextureGUID +//purpose : +//======================================================================= +const Standard_GUID& GEOM_Engine::GetTextureGUID() +{ + static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17"); + return anID; } //============================================================================= @@ -57,7 +319,6 @@ static Standard_Integer ExtractDocID(TCollection_AsciiString& theID) //============================================================================= GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; } - //============================================================================= /*! * SetEngine @@ -73,9 +334,30 @@ void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; } GEOM_Engine::GEOM_Engine() { TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver()); - + _OCAFApp = new GEOM_Application(); - _UndoLimit = 10; + _OCAFApp->DefineFormat("SALOME_GEOM", "GEOM Document Version 1.0", "sgd", + new StdDrivers_DocumentRetrievalDriver, 0); + BinDrivers::DefineFormat(_OCAFApp); + _UndoLimit = 0; +} + +/*! + * Destructor + */ +GEOM_Engine::~GEOM_Engine() +{ + GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects); + std::list< Handle(GEOM_Object) > objs; + for(; It.More(); It.Next()) + objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) ); + std::list< Handle(GEOM_Object) >::iterator objit; + for(objit = objs.begin(); objit != objs.end(); ++objit) + RemoveObject(*objit); + + //Close document + Close(); + _objects.Clear(); } //============================================================================= @@ -83,73 +365,102 @@ GEOM_Engine::GEOM_Engine() * GetDocument */ //============================================================================= -Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID) +Handle(TDocStd_Document) GEOM_Engine::GetDocument(bool force) { Handle(TDocStd_Document) aDoc; - if(!_mapIDDocument.IsBound(theDocID)) { - _OCAFApp->NewDocument("SALOME_GEOM", aDoc); + if (_document) { + aDoc = _document; + } + else if (force) { + _OCAFApp->NewDocument("BinOcaf", aDoc); aDoc->SetUndoLimit(_UndoLimit); - _mapIDDocument.Bind(theDocID, aDoc); - TDataStd_Integer::Set(aDoc->Main(), theDocID); + _document = aDoc; } - - return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID)); + return aDoc; } //============================================================================= /*! - * GetDocID + * GetObject */ //============================================================================= -int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument) + +Handle(GEOM_BaseObject) GEOM_Engine::GetObject(const char* theEntry, bool force) { - if(theDocument.IsNull()) return -1; - for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next()) - if(anItr.Value() == theDocument) return anItr.Key(); + Handle(GEOM_BaseObject) anObject; - return -1; + if (_objects.IsBound(theEntry)) { + anObject = Handle(GEOM_BaseObject)::DownCast(_objects(theEntry)); + } + else if (force) { + Handle(TDocStd_Document) aDoc = GetDocument(force); + if ( !aDoc.IsNull()) { + TDF_Label aLabel; + TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True); + if ( !aLabel.IsNull() ) { + int objType = GEOM_BaseObject::GetType( aLabel ); + switch ( objType ) { + case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break; + case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break; + default: anObject = new GEOM_Object (aLabel); + } + _objects.Bind(theEntry, anObject); + } + } + } + return anObject; } //============================================================================= /*! - * GetObject + * AddBaseObject */ //============================================================================= -Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry) + +Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theType) { - TCollection_AsciiString anID = BuildID(theDocID, theEntry); - if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID)); + Handle(TDocStd_Document) aDoc = GetDocument(); + Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main()); + + // NPAL18604: use existing label to decrease memory usage, + // if this label has been freed (object deleted) + bool useExisting = false; + TDF_Label aChild; + if (!_freeLabels.empty()) { + useExisting = true; + aChild = _freeLabels.front(); + _freeLabels.pop_front(); + } + if (!useExisting) { + // create new label + aChild = TDF_TagSource::NewChild(aDoc->Main()); + } - TDF_Label aLabel; - Handle(TDocStd_Document) aDoc = GetDocument(theDocID); - TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True); - Handle(GEOM_Object) anObject = new GEOM_Object(aLabel); + Handle(GEOM_BaseObject) anObject; + switch ( theType ) { + case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break; + case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break; + default: anObject = new GEOM_Object (aChild, theType); + } + //Put an object in the map of created objects + TCollection_AsciiString anID = BuildIDFromObject(anObject); + if(_objects.IsBound(anID)) _objects.UnBind(anID); _objects.Bind(anID, anObject); return anObject; } -//============================================================================= +//================================================================================ /*! - * AddObject + * \brief Adds a new object of the type theType in the OCAF document */ -//============================================================================= -Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType) -{ - Handle(TDocStd_Document) aDoc = GetDocument(theDocID); - Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main()); - - TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main()); - Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType); - - //Put an object in the map of created objects - TCollection_AsciiString anID = BuildIDFromObject(anObject); - if(_objects.IsBound(anID)) _objects.UnBind(anID); - _objects.Bind(anID, anObject); +//================================================================================ - return anObject; +Handle(GEOM_Object) GEOM_Engine::AddObject(int theType) +{ + return Handle(GEOM_Object)::DownCast( AddBaseObject(theType) ); } //============================================================================= @@ -157,54 +468,71 @@ Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType) * AddSubShape */ //============================================================================= -Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape, Handle(TColStd_HArray1OfInteger) theIndices) + +Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape, + Handle(TColStd_HArray1OfInteger) theIndices, + bool isStandaloneOperation) { - if(theMainShape.IsNull() || theIndices.IsNull()) return NULL; + if (theMainShape.IsNull() || theIndices.IsNull()) return NULL; - Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID()); + Handle(TDocStd_Document) aDoc = GetDocument(); Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main()); - TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main()); + // NPAL18604: use existing label to decrease memory usage, + // if this label has been freed (object deleted) + bool useExisting = false; + TDF_Label aChild;; + if (!_freeLabels.empty()) { + useExisting = true; + aChild = _freeLabels.front(); + _freeLabels.pop_front(); + } + if (!useExisting) { + // create new label + aChild = TDF_TagSource::NewChild(aDoc->Main()); + } Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction(); - Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type + Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1); - GEOM_ISubShape aSSI(aFunction); + GEOM_ISubShape aSSI (aFunction); aSSI.SetMainShape(aMainShape); aSSI.SetIndices(theIndices); try { + OCC_CATCH_SIGNALS; GEOM_Solver aSolver (GEOM_Engine::GetEngine()); if (!aSolver.ComputeFunction(aFunction)) { MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape"); return NULL; } } - catch (Standard_Failure) { - Handle(Standard_Failure) aFail = Standard_Failure::Caught(); - MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString()); + catch (Standard_Failure& aFail) { + MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail.GetMessageString()); return NULL; } - //Put an object in the map of created objects + // Put an object in the map of created objects TCollection_AsciiString anID = BuildIDFromObject(anObject); - if(_objects.IsBound(anID)) _objects.UnBind(anID); + if (_objects.IsBound(anID)) _objects.UnBind(anID); _objects.Bind(anID, anObject); - TCollection_AsciiString anEntry, aDescr(""); - TDF_Tool::Entry(anObject->GetEntry(), anEntry); - aDescr += anEntry; - aDescr += " = geom.AddSubShape("; - TDF_Tool::Entry(theMainShape->GetEntry(), anEntry); - aDescr += (anEntry+", "); - aDescr += (", ["); - for(Standard_Integer i=theIndices->Lower(); i<=theIndices->Upper(); i++) { - aDescr += (TCollection_AsciiString(theIndices->Value(i))+", "); + // Put this sub-shape in the list of sub-shapes of theMainShape + aMainShape->AddSubShapeReference(aFunction); + + GEOM::TPythonDump pd (aFunction); + + if (isStandaloneOperation) { + pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", ["; + Standard_Integer i = theIndices->Lower(), up = theIndices->Upper(); + for (; i <= up - 1; i++) { + pd << theIndices->Value(i) << ", "; + } + pd << theIndices->Value(up) << "])"; } - aDescr.Trunc(aDescr.Length()-1); - aDescr += "])"; - aFunction->SetDescription(aDescr); + else + pd << "None"; return anObject; } @@ -214,17 +542,57 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape, H * RemoveObject */ //============================================================================= -bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject) +bool GEOM_Engine::RemoveObject(Handle(GEOM_BaseObject)& theObject) { - if(!theObject) return false; + if (theObject.IsNull()) return false; + + if(!_document) + return false; // document is closed... + + TDF_Label aLabel = theObject->GetEntry(); + if ( aLabel == aLabel.Root() ) + return false; // already removed object //Remove an object from the map of available objects TCollection_AsciiString anID = BuildIDFromObject(theObject); - if(_objects.IsBound(anID)) _objects.UnBind(anID); + if (_objects.IsBound(anID)) { + Handle(GEOM_BaseObject) anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID)); + if ( anObject != theObject ) + anObject->_label = anObject->_label.Root(); + _objects.UnBind(anID); + } + + // If sub-shape, remove it from the list of sub-shapes of its main shape + Handle(GEOM_Object) aGO = Handle(GEOM_Object)::DownCast( theObject ); + if ( !aGO.IsNull() && !aGO->IsMainShape()) { + Handle(GEOM_Function) aFunction = theObject->GetFunction(1); + GEOM_ISubShape aSSI (aFunction); + Handle(GEOM_Function) aMainShape = aSSI.GetMainShape(); + //If main shape is not null, then remove + if(!aMainShape.IsNull()) + aMainShape->RemoveSubShapeReference(aFunction); + } + + int nb = theObject->GetNbFunctions(); + Handle(TDataStd_TreeNode) aNode; + for (int i = 1; i <= nb; i++) { + Handle(GEOM_Function) aFunction = theObject->GetFunction(i); + if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode)) + aNode->Remove(); + } - TDF_Label aLabel = theObject->GetEntry(); aLabel.ForgetAllAttributes(Standard_True); + // Remember the label to reuse it then + if ( _freeLabels.empty() || _freeLabels.back() != aLabel ) + _freeLabels.push_back(aLabel); + + // we can't explicitly delete theObject. At least prevent its functioning + // as an alive object when aLabel is reused for a new object + theObject->_label = aLabel.Root(); + theObject->_ior.Clear(); + theObject->_parameters.Clear();; + theObject.Nullify(); return true; @@ -235,9 +603,9 @@ bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject) * Undo */ //============================================================================= -void GEOM_Engine::Undo(int theDocID) +void GEOM_Engine::Undo() { - GetDocument(theDocID)->Undo(); + GetDocument()->Undo(); } //============================================================================= @@ -245,9 +613,9 @@ void GEOM_Engine::Undo(int theDocID) * Redo */ //============================================================================= -void GEOM_Engine::Redo(int theDocID) +void GEOM_Engine::Redo() { - GetDocument(theDocID)->Redo(); + GetDocument()->Redo(); } //============================================================================= @@ -255,14 +623,17 @@ void GEOM_Engine::Redo(int theDocID) * Save */ //============================================================================= -bool GEOM_Engine::Save(int theDocID, char* theFileName) +bool GEOM_Engine::Save(const char* theFileName) { - if(!_mapIDDocument.IsBound(theDocID)) return false; - Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID)); + if(!_document) return false; - _OCAFApp->SaveAs(aDoc, theFileName); +#if defined(WIN32) && defined(UNICODE) + std::wstring aFileName = Kernel_Utils::utf8_decode_s(theFileName); +#else + std::string aFileName = theFileName; +#endif - return true; + return _OCAFApp->SaveAs( _document, aFileName.c_str() ) == PCDM_SS_OK; } //============================================================================= @@ -270,17 +641,26 @@ bool GEOM_Engine::Save(int theDocID, char* theFileName) * Load */ //============================================================================= -bool GEOM_Engine::Load(int theDocID, char* theFileName) +bool GEOM_Engine::Load(const char* theFileName) { +#if defined(WIN32) && defined(UNICODE) + std::wstring aFileName = Kernel_Utils::utf8_decode_s(theFileName); +#else + std::string aFileName = theFileName; +#endif Handle(TDocStd_Document) aDoc; - if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) return false; + if (_OCAFApp->Open(aFileName.c_str(), aDoc) != PCDM_RS_OK) { + return false; + } - aDoc->SetUndoLimit(_UndoLimit); + // Replace old document format by the new one. + if (aDoc->StorageFormat().IsEqual("SALOME_GEOM")) { + aDoc->ChangeStorageFormat("BinOcaf"); + } - if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID); - _mapIDDocument.Bind(theDocID, aDoc); + aDoc->SetUndoLimit(_UndoLimit); - TDataStd_Integer::Set(aDoc->Main(), theDocID); + _document = aDoc; return true; } @@ -290,23 +670,1391 @@ bool GEOM_Engine::Load(int theDocID, char* theFileName) * Close */ //============================================================================= -void GEOM_Engine::Close(int theDocID) +void GEOM_Engine::Close() { - if(_mapIDDocument.IsBound(theDocID)) { - Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID)); - - //Remove all GEOM Objects associated to the given document + if (_document) { + //Remove all GEOM Objects associated to the document TColStd_SequenceOfAsciiString aSeq; - GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects); - for(; It.More(); It.Next()) { - TCollection_AsciiString anObjID(It.Key()); - Standard_Integer anID = ExtractDocID(anObjID); - if(theDocID == anID) aSeq.Append(It.Key()); + GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects); + for (; It.More(); It.Next()) { + aSeq.Append(It.Key()); + } + for (Standard_Integer i=1; i<=aSeq.Length(); i++) { + _objects.UnBind(aSeq.Value(i)); + } + + // Forget free labels for document + _freeLabels.clear(); + + _OCAFApp->Close(_document); + _document.Nullify(); + } +} + +//============================================================================= +/*! + * DumpPython + */ +//============================================================================= +TCollection_AsciiString GEOM_Engine::DumpPython(std::vector& theObjectData, + TVariablesList theVariables, + bool isPublished, + bool isMultiFile, + bool& aValidScript) +{ + // Set "C" numeric locale to save numbers correctly + Kernel_Utils::Localizer loc; + + TCollection_AsciiString aScript; + Handle(TDocStd_Document) aDoc = GetDocument(); + + if (aDoc.IsNull()) + { + TCollection_AsciiString anEmptyScript; + if( isMultiFile ) + anEmptyScript = "def RebuildData(): pass\n"; + return anEmptyScript; + } + + if( isMultiFile ) + aScript = "import salome\n"; + + aScript += "import GEOM\n"; + aScript += "from salome.geom import geomBuilder\n"; + aScript += "import math\n"; + aScript += "import SALOMEDS\n\n"; + if( isMultiFile ) + aScript += "def RebuildData():"; + + aScript += "\n\tgeompy = geomBuilder.New()\n"; + + AddTextures(aScript); + + Standard_Integer posToInsertGlobalVars = aScript.Length() + 1; + + // a map containing copies of TObjectData from theObjectData + TSting2ObjDataMap aEntry2ObjData; + // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter + // occurs when several StudyEntries correspond to one Entry + TSting2ObjDataPtrMap aStEntry2ObjDataPtr; + + //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames; + for (unsigned i = 0; i < theObjectData.size(); ++i ) + { + TObjectData& data = theObjectData[i]; + // look for an object by entry + TDF_Label L; + TDF_Tool::Label( aDoc->GetData(), data._entry, L ); + if ( L.IsNull() ) continue; + Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L ); + // fill maps + if ( !obj.IsNull() ) { + TSting2ObjDataMap::iterator ent2Data = + aEntry2ObjData.insert( std::make_pair( data._entry, data )).first; + + if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time + aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second )); + else + aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data )); + } + } + + // collect objects entries to be published + TColStd_SequenceOfAsciiString aObjListToPublish; + + // iterates on functions till critical (that requiers publication of objects) + Handle(TDataStd_TreeNode) aNode, aRoot; + Handle(GEOM_Function) aFunction; + TDF_LabelMap aCheckedFuncMap; + std::set< TCollection_AsciiString > anIgnoreObjMap; + + TCollection_AsciiString aFuncScript; + + // Mantis issue 0020768 + Standard_Integer objectCounter = 0; + Resource_DataMapOfAsciiStringAsciiString aNameToEntry; + TIntToListIntMap aRefMap; + + if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) { + TDataStd_ChildNodeIterator Itr(aRoot); + for (; Itr.More(); Itr.Next()) { + aNode = Itr.Value(); + aFunction = GEOM_Function::GetFunction(aNode->Label()); + if (aFunction.IsNull()) { + MESSAGE ( "Null function !!!!" ); + continue; + } + bool isDumpCollected = false; + TCollection_AsciiString aCurScript, anAfterScript; + if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables, + isPublished, aCheckedFuncMap, anIgnoreObjMap, + isDumpCollected )) + continue; + // add function description before dump + if (!aCurScript.IsEmpty()) + { + if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() && + aFuncScript.Length() > aCurScript.Length() ) + // avoid repeated SubShape...() command at the end + if (aFuncScript.Location( aCurScript, + aFuncScript.Length() - aCurScript.Length(), + aFuncScript.Length())) + continue; // aCurScript is already at the end of aFuncScript + aFuncScript += aCurScript; + } + + // Fill the map of references. + FillMapOfRef(aFunction, aRefMap); + + if (isDumpCollected ) { + // Replace entries by the names + ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, + aObjListToPublish, objectCounter, aNameToEntry ); + + // publish collected objects + std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry + int i = 1, n = aObjListToPublish.Length(); + for ( ; i <= n; i++ ) + { + const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i); + PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr, + aNameToEntry, anEntryToCmdMap, anIgnoreObjMap ); + } + // add publishing commands to the script + std::set< int > aPublished; + std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin(); + + for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) { + const TCollection_AsciiString aPublishCmds = + GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap, + aRefMap, aPublished); + + aFuncScript += aPublishCmds; + } + + // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list, + // because they will be published during command execution + int indx = anAfterScript.Search( "RestoreGivenSubShapes" ); + if ( indx == -1 ) + indx = anAfterScript.Search( "RestoreSubShapes" ); + if ( indx != -1 ) { + TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx); + Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr); + i = 1, n = aSeq->Length(); + for ( ; i <= n; i+=2) { + TCollection_AsciiString anEntry = + aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1)); + anIgnoreObjMap.insert(anEntry.ToCString()); + } + } + + aObjListToPublish.Clear(); + aScript += aFuncScript; + aFuncScript.Clear(); + } + aFuncScript += anAfterScript; + } + } + + // Replace entries by the names + aObjListToPublish.Clear(); + ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish, + objectCounter, aNameToEntry ); + + aScript += aFuncScript; + + // ouv : NPAL12872 + AddObjectColors(aScript, aEntry2ObjData ); + + // Make script to publish in study + TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt; + if ( isPublished ) + { + std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry + + for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin(); + aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end(); + ++aStEntry2ObjDataPtrIt) + { + TObjectData* data = aStEntry2ObjDataPtrIt->second; + if ( anIgnoreObjMap.count( data->_entry )) + continue; // should not be dumped + PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr, + aNameToEntry, anEntryToCmdMap, anIgnoreObjMap ); + } + // add publishing commands to the script + std::set< int > aPublished; + std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin(); + + for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) { + const TCollection_AsciiString aPublishCmds = + GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap, + aRefMap, aPublished); + + aScript += aPublishCmds; + } + } + + //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function + //Add unpublish command if need + TCollection_AsciiString unpublishCmd("\n"); + if(isMultiFile) + unpublishCmd += "\t"; + unpublishCmd += "geompy.hideInStudy("; + + for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin(); + aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end(); + ++aStEntry2ObjDataPtrIt) + { + TObjectData* data = aStEntry2ObjDataPtrIt->second; + if ( data->_unpublished && !data->_pyName.IsEmpty() ) { + aScript += unpublishCmd + data->_pyName + ")"; + } + } + + //aScript += "\n\tpass\n"; + aScript += "\n"; + aValidScript = true; + + // fill _studyEntry2NameMap and build globalVars + TCollection_AsciiString globalVars; + _studyEntry2NameMap.Clear(); + for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin(); + aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end(); + ++aStEntry2ObjDataPtrIt) + { + const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first; + const TObjectData* data = aStEntry2ObjDataPtrIt->second; + _studyEntry2NameMap.Bind ( studyEntry, data->_pyName ); + if ( !globalVars.IsEmpty() ) + globalVars += ", "; + globalVars += data->_pyName; + } + if ( isMultiFile && !globalVars.IsEmpty() ) { + globalVars.Insert( 1, "\n\tglobal " ); + aScript.Insert( posToInsertGlobalVars, globalVars ); + } + + // VSR 29/08/2017: 0023327, 0023428: eliminate unnecessary lines in Python dump +#ifndef DUMP_SUBSHAPE_IDS + Prettify(aScript); +#endif + + return aScript; +} + +//======================================================================= +//function : GetDumpName +//purpose : +//======================================================================= + +const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const +{ + if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry )) + return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString(); + + return NULL; +} + +//======================================================================= +//function : GetAllDumpNames +//purpose : +//======================================================================= + +Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const +{ + Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString; + + Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap); + for (; it.More(); it.Next()) { + aRetSeq->Append(it.Value()); + } + + return aRetSeq; +} + +#define TEXTURE_LABEL_ID 1 +#define TEXTURE_LABEL_FILE 2 +#define TEXTURE_LABEL_WIDTH 3 +#define TEXTURE_LABEL_HEIGHT 4 +#define TEXTURE_LABEL_DATA 5 + +int GEOM_Engine::addTexture(int theWidth, int theHeight, + const Handle(TColStd_HArray1OfByte)& theTexture, + const TCollection_AsciiString& theFileName) +{ + Handle(TDocStd_Document) aDoc = GetDocument(); + Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main()); + + // NPAL18604: use existing label to decrease memory usage, + // if this label has been freed (object deleted) + bool useExisting = false; + TDF_Label aChild; + if (!_freeLabels.empty()) { + useExisting = true; + aChild = _freeLabels.front(); + _freeLabels.pop_front(); + } + if (!useExisting) { + // create new label + aChild = TDF_TagSource::NewChild(aDoc->Main()); + } + + aChild.ForgetAllAttributes(Standard_True); + Handle(TDataStd_TreeNode) node; + if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) ) + node = TDataStd_TreeNode::Set(aChild); + TDataStd_UAttribute::Set(aChild, GetTextureGUID()); + + static int aTextureID = 0; + + TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID); + TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName); + TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth); + TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight); + + Handle(TDataStd_ByteArray) anAttr = + TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA), + theTexture.IsNull() ? 0 : theTexture->Lower(), + theTexture.IsNull() ? 0 : theTexture->Upper()); + anAttr->ChangeArray(theTexture); + + return aTextureID; +} + +Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theTextureID, + int& theWidth, int& theHeight, + TCollection_AsciiString& theFileName) +{ + Handle(TColStd_HArray1OfByte) anArray; + theWidth = theHeight = 0; + + Handle(TDocStd_Document) aDoc = GetDocument(); + + TDF_ChildIterator anIterator(aDoc->Main(), Standard_True); + bool found = false; + for (; anIterator.More() && !found; anIterator.Next()) { + TDF_Label aTextureLabel = anIterator.Value(); + if (aTextureLabel.IsAttribute( GetTextureGUID())) { + TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False); + Handle(TDataStd_Integer) anIdAttr; + if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) && + anIdAttr->Get() == theTextureID) { + TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False); + TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False); + TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False); + TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False); + Handle(TDataStd_Integer) aWidthAttr, aHeightAttr; + Handle(TDataStd_ByteArray) aTextureAttr; + Handle(TDataStd_Comment) aFileAttr; + if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) && + !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) && + !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) { + theWidth = aWidthAttr->Get(); + theHeight = aHeightAttr->Get(); + anArray = aTextureAttr->InternalArray(); + } + if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr)) + theFileName = aFileAttr->Get(); + found = true; + } + } + } + return anArray; +} + +std::list GEOM_Engine::getAllTextures() +{ + std::list id_list; + + Handle(TDocStd_Document) aDoc = GetDocument(); + + TDF_ChildIterator anIterator(aDoc->Main(), Standard_True); + for (; anIterator.More(); anIterator.Next()) { + TDF_Label aTextureLabel = anIterator.Value(); + if (aTextureLabel.IsAttribute( GetTextureGUID())) { + TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False); + Handle(TDataStd_Integer) anIdAttr; + if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr)) + id_list.push_back((int)anIdAttr->Get()); } - for(Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i)); + } + return id_list; +} + +//=========================================================================== +// Internal functions +//=========================================================================== + +//============================================================================= +/*! + * MakeCommandfor3DSketcher: Make new command for 3DSketcher + */ +//============================================================================= +TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr ) +{ + TCollection_AsciiString aNewDescr; + int i = 1; + TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i); + for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) { + if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) { + TCollection_AsciiString aResult = aSubStr.Token(" ", 1); + // "3DSketcher:CMD[:CMD[:CMD...]]" + TCollection_AsciiString aCommand = aSubStr.Token("\"", 2); + + // Split the command string to separate CMDs + int icmd = 2; + TColStd_SequenceOfAsciiString aSequence; + if (aCommand.Length()) { + TCollection_AsciiString aToken = aCommand.Token(":", icmd); + while (aToken.Length() > 0) { + aSequence.Append(aToken); + aToken = aCommand.Token(":", ++icmd); + } + } + + if (aSequence.Length() > 0) { + if (i > 1) + aNewDescr += "\n\t"; + + aNewDescr += "\nsk = geompy.Sketcher3D()"; + int nbCMDs = aSequence.Length(); + for (icmd = 1; icmd <= nbCMDs; icmd++) { + aNewDescr += "\n\t"; + + TCollection_AsciiString aCMD = aSequence.Value(icmd); + + // Split the CMD into string values + TColStd_SequenceOfAsciiString aStrVals; + int ival = 1; + TCollection_AsciiString aToken = aCMD.Token(" ", ival); + while (aToken.Length() > 0) { + aStrVals.Append(aToken); + aToken = aCMD.Token(" ", ++ival); + } + + TCollection_AsciiString aCMDpref = aStrVals.Value(1); + if (aCMDpref == "TT") { + aNewDescr += "sk.addPointsAbsolute("; + aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")"; + } + else if (aCMDpref == "T") { + aNewDescr += "sk.addPointsRelative("; + aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")"; + } + else if (aCMDpref == "WW") { + aNewDescr += "sk.close()"; + } + else if (aCMDpref.Value(1) == 'O'){ + TCollection_AsciiString aCMDtrunc = aStrVals.Value(1); + aCMDtrunc.Trunc(3); + if (aCMDpref.Value(4) == 'C') + aNewDescr += "sk.addPointRadiusAngleH"; + else + aNewDescr += "sk.addPointRadiusAngles"; + if (aCMDpref.Value(5) == 'A') + aNewDescr += "Absolute("; + else + aNewDescr += "Relative("; + aNewDescr += aStrVals.Value(4) + ", " + + aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")"; + } + } + aNewDescr += "\n\t"; + aNewDescr += aResult + " = sk.wire()"; + } + } // Make3DSketcherCommand + else if (aSubStr.Search( "Make3DSketcher" ) != -1) { + TCollection_AsciiString aResult = aSubStr.Token(" ", 1); + TCollection_AsciiString aCommand = aSubStr.Token("[", 2); + aCommand = aCommand.Token("]", 1); + if (i > 1) + aNewDescr += "\n\t"; + aNewDescr += "\nsk = geompy.Sketcher3D()"; + aNewDescr += "\n\t"; + aNewDescr += "sk.addPointsAbsolute("; + aNewDescr += aCommand + ")"; + aNewDescr += "\n\t"; + aNewDescr += aResult + " = sk.wire()"; + } + else { + if (i > 1) + aNewDescr += "\n\t"; + aNewDescr += aSubStr; + } + i++; + } + return aNewDescr; +} + +//============================================================================= +/*! + * ProcessFunction: Dump function description into script + */ +//============================================================================= +bool ProcessFunction(Handle(GEOM_Function)& theFunction, + TCollection_AsciiString& theScript, + TCollection_AsciiString& theAfterScript, + const TVariablesList& theVariables, + const bool theIsPublished, + TDF_LabelMap& theProcessed, + std::set& theIgnoreObjs, + bool& theIsDumpCollected) +{ + theIsDumpCollected = false; - _mapIDDocument.UnBind(theDocID); - _OCAFApp->Close(aDoc); - aDoc.Nullify(); + if (theFunction.IsNull()) { + MESSAGE("Can't process a null function! Return."); + return false; } + + TCollection_AsciiString aDescr = theFunction->GetDescription(); + MESSAGE("The function description: " << aDescr); + + if (theProcessed.Contains(theFunction->GetEntry())) + return false; + + // Check if a given function depends on nonexisting ones + const FunctionProcessType funcProcessType = GetFunctionProcessingType(theFunction, theProcessed, aDescr); + switch (funcProcessType) + { + case TO_PROCESS: + // Just process it + break; + + case NOT_PROCESS: + { + // We don't need this function and its object in a dump + AddFuncObjectToIgnored(theFunction, theIgnoreObjs); + return false; + } + + case UPDATE_DESCRIPTION: + // Edge case for a function that was dumped from Python. + // Get rid of the parent function description. + UpdateFuncFromPythonDescription(aDescr); + // A result object is already added by an algo script, then + // if we keep it in the dump it will be added twice on the script loading. + AddFuncObjectToIgnored(theFunction, theIgnoreObjs); + break; + + default: + MESSAGE("Wrong type of the function processing!" << funcProcessType); + break; + } + + theProcessed.Add(theFunction->GetEntry()); + + // Check the length only after its fucntion was added to the processed! + if(!aDescr.Length()) + return false; + + // Check if it's an internal function which doesn't require dumping + if(aDescr == "None") + return false; + + //Check the very specific case of RestoreShape function, + //which is not dumped, but the result can be published by the user. + //We do not publish such objects to decrease danger of dumped script failure. + if(aDescr.Value(1) == '#') { + AddFuncObjectToIgnored(theFunction, theIgnoreObjs); + return false; + } + + // 0020001 PTv, check for critical functions, which require dump of objects + if (theIsPublished) + { + // currently, there is only one function "RestoreGivenSubShapes", + // later this check could be replaced by iterations on list of such functions + if (aDescr.Search( "RestoreGivenSubShapes" ) != -1) + theIsDumpCollected = true; + else if (aDescr.Search( "RestoreSubShapes" ) != -1) + theIsDumpCollected = true; + } + + //Replace parameter by notebook variables + ReplaceVariables(aDescr,theVariables); + // Check description, because we could lose entire command during variable processing + if (aDescr.IsEmpty()) + return false; + + //Process sketcher functions, replacing string command by calls to Sketcher interface + if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) { + Sketcher_Profile aProfile( aDescr.ToCString()); + // Make new command for SketcherOnPlane and for Sketcher + aDescr = aProfile.GetDump(); + } + if (aDescr.Search( "Make3DSketcher" ) != -1) { + aDescr = MakeCommandfor3DSketcher ( aDescr ); + } + + if ( theIsDumpCollected ) { + int i = 1; + bool isBefore = true; + TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++); + while (!aSubStr.IsEmpty()) { + if (isBefore && + aSubStr.Search( "RestoreGivenSubShapes" ) == -1 && + aSubStr.Search( "RestoreSubShapes" ) == -1) + theScript += TCollection_AsciiString("\n\t") + aSubStr; + else + theAfterScript += TCollection_AsciiString("\n\t") + aSubStr; + aSubStr = aDescr.Token("\n\t", i++); + } + } + else { + theScript += "\n\t"; + theScript += aDescr; + } + return true; +} + +//============================================================================= +/*! + * GetTag: Returns the tag from entry + */ +//============================================================================= +int GetTag(const TCollection_AsciiString &theEntry) +{ + const int aGeomObjDepth = 3; + const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue(); + + return aTag; +} + +//============================================================================= +/*! + * FillMapOfRef: Fill the map of references + */ +//============================================================================= +void FillMapOfRef(const Handle(GEOM_Function) &theFunction, + TIntToListIntMap &theRefMap) +{ + TDF_LabelSequence aSeq; + TCollection_AsciiString anObjEntry; + int anObjTag; + + TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry); + anObjTag = GetTag(anObjEntry); + theFunction->GetDependency(aSeq); + + const Standard_Integer aLen = aSeq.Length(); + Standard_Integer i; + + for (i = 1; i <= aLen; i++) { + TDF_Label aRefLabel = aSeq.Value(i); + Handle(TDF_Reference) aRef; + + if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) { + if (!aRef.IsNull() && !aRef->Get().IsNull()) { + Handle(TDataStd_TreeNode) aT; + + if (TDataStd_TreeNode::Find(aRef->Get(), aT)) { + TDF_Label aDepLabel = aT->Label(); + Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel); + + if (!aRefFunct.IsNull()) { + // Get entry of the referenced object. + TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry); + + const int aRefTag = GetTag(anObjEntry); + + if (anObjTag != aRefTag) { + // Avoid making references for operations without copy. + theRefMap[anObjTag].push_back(aRefTag); + } + } + } + } + } + } +} + +//============================================================================= +/*! + * FindEntries: Returns a sequence of start/end positions of entries in the string + */ +//============================================================================= +Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString) +{ + Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger; + Standard_Integer aLen = theString.Length(); + Standard_Boolean isFound = Standard_False; + + const char* arr = theString.ToCString(); + Standard_Integer i = 0, j; + + while(i < aLen) { + int c = (int)arr[i]; + j = i+1; + if(c >= 48 && c <= 57) { //Is digit? + + isFound = Standard_False; + while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry + c = (int)arr[j++]; + if(c == 58) isFound = Standard_True; + } + + if(isFound && arr[j-2] != 58) { // last char should be a digit + aSeq->Append(i+1); // +1 because AsciiString starts from 1 + aSeq->Append(j-1); + } + } + + i = j; + } + + return aSeq; +} + +//============================================================================= +/*! + * ReplaceVariables: Replace parameters of the function by variales from + * Notebook if need + */ +//============================================================================= +void ReplaceVariables(TCollection_AsciiString& theCommand, + const TVariablesList& theVariables) +{ + MESSAGE("Command : " << theCommand); + + if (SALOME::VerbosityActivated()) { + std::cout<<"All Entries:"<GetCurrectState(); + + if(SALOME::VerbosityActivated()) { + std::cout<<"Variables from SObject:"<= aVariables.size()) + continue; + + aReplacedParameter = aVariables[iVar].myVariable; + if(aReplacedParameter.IsEmpty()) { + iVar++; + continue; + } + + if(aVariables[iVar].isVariable) { + aReplacedParameter.InsertBefore(1,"'"); + aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'"); + } + + MESSAGE("aSection before : " << aSection); + aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos); + aSection.Insert(aStartParamPos, aReplacedParameter); + MESSAGE("aSection after : " << aSection << '\n'); + iVar++; + } + + MESSAGE("aVar before : " << aVar); + + aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos); + aVar.Insert(aStartSectionPos, aSection); + + MESSAGE("aVar after : " << aVar << '\n'); + } + + MESSAGE("aCommand before : " << aCommand); + aCommand.Remove(aStartPos, aEndPos - aStartPos); + aCommand.Insert(aStartPos, aVar); + MESSAGE("aCommand after : " << aCommand); + + break; + } // end of specific case for sketcher + + //If parameter is entry or 'None', skip it + if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL) + continue; + + if(iVar >= aVariables.size()) + continue; + + aReplacedVar = aVariables[iVar].myVariable; + if(aReplacedVar.IsEmpty()) { + iVar++; + continue; + } + + if(aVariables[iVar].isVariable) { + aReplacedVar.InsertBefore(1,"\""); + aReplacedVar.InsertAfter(aReplacedVar.Length(),"\""); + } + + aCommand.Remove(aStartPos, aEndPos - aStartPos); + aCommand.Insert(aStartPos, aReplacedVar); + iVar++; + } + + theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos); + theCommand.Insert(aStartCommandPos, aCommand); + + aCommandIndex++; + + aStates->IncrementState(); + } + + MESSAGE("Command after replacing of the variables: " << theCommand); +} + +//============================================================================= +/*! + * ReplaceEntriesByNames: Replace object entries by their names + */ +//============================================================================= +void ReplaceEntriesByNames (TCollection_AsciiString& theScript, + TSting2ObjDataMap& aEntry2ObjData, + const bool /*theIsPublished*/, + TColStd_SequenceOfAsciiString& theObjListToPublish, + Standard_Integer& objectCounter, + Resource_DataMapOfAsciiStringAsciiString& aNameToEntry) +{ + GEOM_Engine* engine = GEOM_Engine::GetEngine(); + Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript); + Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length(); + + //Replace entries by the names + TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"), + allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_"); + if (aLen == 0) anUpdatedScript = theScript; + + for (Standard_Integer i = 1; i <= aLen; i+=2) { + anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1); + anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1)); + theObjListToPublish.Append( anEntry ); + + TObjectData& data = aEntry2ObjData[ anEntry ]; + if ( data._pyName.IsEmpty() ) { // encountered for the 1st time + if ( !data._name.IsEmpty() ) { // published object + data._pyName = data._name; + engine->healPyName( data._pyName, anEntry, aNameToEntry); + } + else { + do { + data._pyName = aBaseName + TCollection_AsciiString(++objectCounter); + } while(aNameToEntry.IsBound(data._pyName)); + } + } + + aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects + + anUpdatedScript += data._pyName; + aStart = aSeq->Value(i+1) + 1; + } + + //Add final part of the script + if (aLen && aSeq->Value(aLen) < aScriptLength) + anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865 + + theScript = anUpdatedScript; +} + +//============================================================================= +/*! + * AddObjectColors: Add color to objects + */ +//============================================================================= +void AddObjectColors (TCollection_AsciiString& theScript, + const TSting2ObjDataMap& theEntry2ObjData) +{ + GEOM_Engine* engine = GEOM_Engine::GetEngine(); + Handle(TDocStd_Document) aDoc = engine->GetDocument(); + + TSting2ObjDataMap::const_iterator anEntryToNameIt; + for (anEntryToNameIt = theEntry2ObjData.begin(); + anEntryToNameIt!= theEntry2ObjData.end(); + ++anEntryToNameIt) + { + const TCollection_AsciiString& aEntry = anEntryToNameIt->first; + const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName; + + TDF_Label L; + TDF_Tool::Label( aDoc->GetData(), aEntry, L ); + if ( L.IsNull() ) + continue; + + Handle(GEOM_Object) obj = GEOM_Object::GetObject( L ); + if ( obj.IsNull() ) + continue; + + bool anAutoColor = obj->GetAutoColor(); + if ( anAutoColor ) + { + TCollection_AsciiString aCommand( "\n\t" ); + aCommand += aName + ".SetAutoColor(1)"; + theScript += aCommand.ToCString(); + } + + GEOM_Object::Color aColor = obj->GetColor(); + if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 ) + { + TCollection_AsciiString aCommand( "\n\t" ); + aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))"; + theScript += aCommand.ToCString(); + } + + Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType(); + if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) { + TCollection_AsciiString aCommand( "\n\t" ); + aCommand += aName + ".SetMarkerStd("; + switch (aMarkerType) { + case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break; + case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break; + case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break; + case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break; + case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break; + case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break; + case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break; + case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break; + case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break; + case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break; + case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break; + case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break; + case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break; + default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here + } + aCommand += ", "; + int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1; + switch (aSize) { + case 1: aCommand += "GEOM.MS_10"; break; + case 2: aCommand += "GEOM.MS_15"; break; + case 3: aCommand += "GEOM.MS_20"; break; + case 4: aCommand += "GEOM.MS_25"; break; + case 5: aCommand += "GEOM.MS_30"; break; + case 6: aCommand += "GEOM.MS_35"; break; + case 7: aCommand += "GEOM.MS_40"; break; + case 8: aCommand += "GEOM.MS_45"; break; + case 9: aCommand += "GEOM.MS_50"; break; + case 10: aCommand += "GEOM.MS_55"; break; + case 11: aCommand += "GEOM.MS_60"; break; + case 12: aCommand += "GEOM.MS_65"; break; + case 13: aCommand += "GEOM.MS_70"; break; + default: aCommand += "GEOM.MS_NONE"; break; + } + aCommand += ")"; + theScript += aCommand.ToCString(); + } + else if (aMarkerType == Aspect_TOM_USERDEFINED) { + int aMarkerTextureID = obj->GetMarkerTexture(); + if (aMarkerTextureID >= 0) { + TCollection_AsciiString aCommand( "\n\t" ); + aCommand += aName + ".SetMarkerTexture(texture_map["; + aCommand += aMarkerTextureID; + aCommand += "])"; + theScript += aCommand.ToCString(); + } + } + } +} + +static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData) +{ + TCollection_AsciiString stream; + if (!aData.IsNull()) { + for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) { + Standard_Byte byte = aData->Value(i); + TCollection_AsciiString strByte = ""; + for (int j = 0; j < 8; j++) + strByte.Prepend((byte & (1< allTextures = engine->getAllTextures(); + std::list::const_iterator it; + + if (allTextures.size() > 0) { + theScript += "\n\ttexture_map = {}\n"; + + for (it = allTextures.begin(); it != allTextures.end(); ++it) { + if (*it <= 0) continue; + Standard_Integer aWidth, aHeight; + TCollection_AsciiString aFileName; + Handle(TColStd_HArray1OfByte) aTexture = + engine->getTexture(*it, aWidth, aHeight, aFileName); + if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) { + TCollection_AsciiString aCommand = "\n\t"; + aCommand += "texture_map["; aCommand += *it; aCommand += "] = "; + if (aFileName != "" ) { + aCommand += "geompy.LoadTexture(\""; + aCommand += aFileName.ToCString(); + aCommand += "\")"; + } + else { + aCommand += "geompy.AddTexture("; + aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \""; + aCommand += pack_data(aTexture); + aCommand += "\")"; + } + theScript += aCommand; + } + } + theScript += "\n"; + } +} + +//============================================================================= +/*! + * PublishObject: publish object in study script + */ +//============================================================================= +void PublishObject (TObjectData& theObjectData, + TSting2ObjDataMap& theEntry2ObjData, + const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr, + Resource_DataMapOfAsciiStringAsciiString& theNameToEntry, + std::map< int, TCollection_AsciiString >& theEntryToCmdMap, + std::set< TCollection_AsciiString>& theIgnoreMap) +{ + GEOM_Engine* engine = GEOM_Engine::GetEngine(); + if ( theObjectData._studyEntry.IsEmpty() ) + return; // was not published + if ( theIgnoreMap.count( theObjectData._entry ) ) + return; // not to publish + + TCollection_AsciiString aCommand("\n\tgeompy."); + + // find a father entry + TObjectData* aFatherData = 0; + TCollection_AsciiString aFatherStudyEntry = + theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 ); + TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr = + theStEntry2ObjDataPtr.find( aFatherStudyEntry ); + if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() ) + aFatherData = stEntry2DataPtr->second; + + // treat multiply published object + if ( theObjectData._pyName.IsEmpty() ) + { + TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ]; + if ( data0._pyName.IsEmpty() ) return; // something wrong + + theObjectData._pyName = theObjectData._name; + engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry); + + TCollection_AsciiString aCreationCommand("\n\t"); + aCreationCommand += theObjectData._pyName + " = " + data0._pyName; + + // store aCreationCommand before publishing commands + int tag = GetTag(theObjectData._entry); + theEntryToCmdMap.insert( std::make_pair( tag + -2*theEntry2ObjData.size(), aCreationCommand )); + } + + // make a command + if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) { + aCommand += "addToStudyInFather( "; + aCommand += aFatherData->_pyName + ", "; + } + else { + aCommand += "addToStudy( "; + } + aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )"; + + // bind a command to the study entry + int tag = GetTag(theObjectData._entry); + theEntryToCmdMap.insert( std::make_pair( tag, aCommand )); + + theObjectData._studyEntry.Clear(); // not to publish any more +} + +//================================================================================ +/*! + * \brief Returns the string of publishing commands. Take into account that + * references should be published prior to the objects refer to them. + */ +//================================================================================ +TCollection_AsciiString GetPublishCommands + (const int theTag, + const std::map< int, TCollection_AsciiString > &theEntryToCmdMap, + const TIntToListIntMap &theMapRefs, + std::set< int > &thePublished) +{ + TCollection_AsciiString aResult; + + if (!thePublished.count(theTag)) { + // This object is not published yet. + thePublished.insert(theTag); + + std::map< int, TCollection_AsciiString >::const_iterator anIt = + theEntryToCmdMap.find(theTag); + + if (anIt != theEntryToCmdMap.end()) { + // There is a pubish cmd. + TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag); + + if (aRefIt != theMapRefs.end()) { + // Recursively publish all references. + std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin(); + + for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) { + const TCollection_AsciiString aRefCmd = GetPublishCommands + (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished); + + aResult += aRefCmd; + } + } + + // Add the object command. + aResult += anIt->second; + } + } + + return aResult; +} + +void Prettify(TCollection_AsciiString& theScript) +{ + TCollection_AsciiString output; + static std::list ToRemove; + if (ToRemove.empty()) { + ToRemove.push_back("geompy.SubShapeAllIDs"); + ToRemove.push_back("geompy.SubShapeAllSortedCentresIDs"); + ToRemove.push_back("geompy.SubShapeAllSortedIDs"); + ToRemove.push_back("geompy.GetFreeFacesIDs"); + ToRemove.push_back("geompy.GetShapesOnBoxIDs"); + ToRemove.push_back("geompy.GetShapesOnShapeIDs"); + ToRemove.push_back("geompy.GetShapesOnPlaneIDs"); + ToRemove.push_back("geompy.GetShapesOnPlaneWithLocationIDs"); + ToRemove.push_back("geompy.GetShapesOnCylinderIDs"); + ToRemove.push_back("geompy.GetShapesOnCylinderWithLocationIDs"); + ToRemove.push_back("geompy.GetShapesOnSphereIDs"); + ToRemove.push_back("geompy.GetShapesOnQuadrangleIDs"); + ToRemove.push_back("geompy.GetSameIDs"); + } + + int start = 1; + while (start <= theScript.Length()) { + int end = theScript.Location("\n", start, theScript.Length()); + if (end == -1) end = theScript.Length(); + TCollection_AsciiString line = theScript.SubString(start, end); + bool found = false; + for (std::list::const_iterator it = ToRemove.begin(); it != ToRemove.end() && !found; ++it) + found = line.Search( *it ) != -1; + if (!found) + output += line; + start = end + 1; + } + theScript = output; + + //OK @@@@@@@@@@@@@@@@@@@@@@@@@@@ +} + +//================================================================================ +/*! + * \brief Constructor + */ +//================================================================================ +ObjectStates::ObjectStates() +{ + _dumpstate = 0; +} + +//================================================================================ +/*! + * \brief Destructor + */ +//================================================================================ +ObjectStates::~ObjectStates() +{ +} + +//================================================================================ +/*! + * \brief Return current object state + * \retval state - Object state (vector of notebook variable) + */ +//================================================================================ +TState ObjectStates::GetCurrectState() const +{ + if((int)_states.size() > _dumpstate) + return _states[_dumpstate]; + return TState(); +} + +//================================================================================ +/*! + * \brief Add new object state + * \param theState - Object state (vector of notebook variable) + */ +//================================================================================ +void ObjectStates::AddState(const TState &theState) +{ + _states.push_back(theState); +} + +//================================================================================ +/*! + * \brief Increment object state + */ +//================================================================================ +void ObjectStates::IncrementState() +{ + _dumpstate++; }