1 // Copyright (C) 2007-2023 CEA, EDF, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Basics_OCCTVersion.hxx>
37 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
38 #if OCC_VERSION_LARGE < 0x07050000
39 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
42 #include "SMESH_Gen_i.hxx"
43 /* SALOME headers that include CORBA headers that include windows.h
44 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
45 * that declare methods named GetObject - to apply the same rules of GetObject renaming
46 * and thus to avoid mess with GetObject symbol on Windows */
48 #include <LDOMParser.hxx>
56 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient)
57 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient)
58 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient)
59 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject)
60 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject)
61 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject)
62 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject)
63 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject)
64 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject)
65 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject)
66 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject)
67 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis)
68 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis)
69 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis)
70 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis)
71 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis)
74 using SMESH::TPythonDump;
77 * \brief Container of commands into which the initial script is split.
78 * It also contains data corresponding to SMESH_Gen contents
80 static Handle(_pyGen) theGen;
82 static TCollection_AsciiString theEmptyString;
84 //#define DUMP_CONVERSION
86 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
87 #undef DUMP_CONVERSION
93 //================================================================================
95 * \brief Set of TCollection_AsciiString initialized by C array of C strings
97 //================================================================================
99 struct TStringSet: public set<TCollection_AsciiString>
102 * \brief Filling. The last string must be ""
104 void Insert(const char* names[]) {
105 for ( int i = 0; names[i][0] ; ++i )
106 insert( (char*) names[i] );
109 * \brief Check if a string is in
111 bool Contains(const TCollection_AsciiString& name ) {
112 return find( name ) != end();
116 //================================================================================
118 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
119 * Odd items of the C array are map keys, and even items are values
121 //================================================================================
123 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
126 * \brief Filling. The last string must be ""
128 void Insert(const char* names_values[]) {
129 for ( int i = 0; names_values[i][0] ; i += 2 )
130 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
133 * \brief Check if a string is in
135 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
136 map< _AString, _AString >::iterator it = find( name );
137 return it == end() ? "" : it->second;
141 //================================================================================
143 * \brief Returns a mesh by object
145 //================================================================================
147 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
151 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
152 return Handle(_pyMesh)::DownCast( obj );
153 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
154 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
155 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
156 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
158 return Handle(_pyMesh)();
161 //================================================================================
163 * \brief Check if objects used as args have been created by previous commands
165 //================================================================================
167 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
169 // either comment or erase a command including NotPublishedObjectName()
170 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
172 bool isResultPublished = false;
173 const int nbRes = cmd->GetNbResultValues();
174 for ( int i = 0; i < nbRes; i++ )
176 _pyID objID = cmd->GetResultValue( i+1 );
177 if ( cmd->IsStudyEntry( objID ))
178 isResultPublished = (! theGen->IsNotPublished( objID ));
179 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
181 if ( isResultPublished )
187 // check if an Object was created in the script
190 _pyID obj = cmd->GetObject();
191 if ( obj.Search( "print(" ) == 1 )
192 return; // print statement
194 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
195 // remove an accessor method
196 obj = _pyCommand( obj ).GetObject();
198 const bool isMethodCall = cmd->IsMethodCall();
199 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
201 comment = "not created Object";
202 theGen->ObjectCreationRemoved( obj );
204 // check if a command has not created args
205 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
207 const _pyID& arg = cmd->GetArg( iArg );
208 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
210 list< _pyID > idList = cmd->GetStudyEntries( arg );
211 list< _pyID >::iterator id = idList.begin();
212 for ( ; id != idList.end(); ++id )
213 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
215 comment += *id + " has not been yet created";
218 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
219 // comment += arg + " has not been yet created";
221 // treat result objects
222 const _pyID& result = cmd->GetResultValue();
223 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
225 list< _pyID > idList = cmd->GetStudyEntries( result );
226 list< _pyID >::iterator id = idList.begin();
227 for ( ; id != idList.end(); ++id )
229 if ( comment.IsEmpty() )
230 presentObjects.insert( *id );
232 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
234 if ( idList.empty() && cmd->IsID( result ))
235 presentObjects.insert( result );
237 // comment the command
238 if ( !comment.IsEmpty() )
241 cmd->GetString() += " ### ";
242 cmd->GetString() += comment;
246 //================================================================================
248 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
250 //================================================================================
252 void fixFunctorType( TCollection_AsciiString& Type,
253 TCollection_AsciiString& Compare,
254 TCollection_AsciiString& UnaryOp,
255 TCollection_AsciiString& BinaryOp )
257 // The problem is that dumps of old studies created using filters becomes invalid
258 // when new items are inserted in the enum SMESH::FunctorType since values
259 // of this enum are dumped as integer values.
260 // This function corrects enum values of old studies given as args (Type,Compare,...)
261 // We can find out how to correct them by value of BinaryOp which can have only two
262 // values: FT_Undefined or FT_LogicalNOT.
263 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
264 // where PythonDump appeared
265 // v 3.0.0: FT_Undefined == 25
266 // v 3.1.0: FT_Undefined == 26, new items:
268 // v 4.1.2: FT_Undefined == 27, new items:
269 // - FT_BelongToGenSurface = 17
270 // v 5.1.1: FT_Undefined == 32, new items:
271 // - FT_FreeNodes = 10
272 // - FT_FreeFaces = 11
273 // - FT_LinearOrQuadratic = 23
274 // - FT_GroupColor = 24
275 // - FT_ElemGeomType = 25
276 // v 5.1.5: FT_Undefined == 33, new items:
277 // - FT_CoplanarFaces = 26
278 // v 6.2.0: FT_Undefined == 39, new items:
279 // - FT_MaxElementLength2D = 8
280 // - FT_MaxElementLength3D = 9
281 // - FT_BareBorderVolume = 25
282 // - FT_BareBorderFace = 26
283 // - FT_OverConstrainedVolume = 27
284 // - FT_OverConstrainedFace = 28
285 // v 6.5.0: FT_Undefined == 43, new items:
286 // - FT_EqualNodes = 14
287 // - FT_EqualEdges = 15
288 // - FT_EqualFaces = 16
289 // - FT_EqualVolumes = 17
290 // v 6.6.0: FT_Undefined == 44, new items:
291 // - FT_BallDiameter = 37
292 // v 6.7.1: FT_Undefined == 45, new items:
293 // - FT_EntityType = 36
294 // v 7.3.0: FT_Undefined == 46, new items:
295 // - FT_ConnectedElements = 39
296 // v 7.6.0: FT_Undefined == 47, new items:
297 // - FT_BelongToMeshGroup = 22
298 // v 8.1.0: FT_Undefined == 48, new items:
299 // - FT_NodeConnectivityNumber= 22
300 // v 8.5.0: FT_Undefined == 49, new items:
301 // - FT_Deflection2D = 22
302 // v 9.3.0: FT_Undefined == 50, new items:
303 // - FT_Length3D = 22
304 // v 9.12.0: FT_Undefined == 51, new items:
305 // - FT_ScaledJacobian = 8
307 // It's necessary to continue recording this history and to fill
308 // undef2newItems (see below) accordingly.
310 typedef map< int, vector< int > > TUndef2newItems;
311 static TUndef2newItems undef2newItems;
312 if ( undef2newItems.empty() )
314 undef2newItems[ 26 ].push_back( 7 );
315 undef2newItems[ 27 ].push_back( 17 );
316 { int items[] = { 10, 11, 23, 24, 25 };
317 undef2newItems[ 32 ].assign( items, items+5 ); }
318 undef2newItems[ 33 ].push_back( 26 );
319 { int items[] = { 8, 9, 25, 26, 27, 28 };
320 undef2newItems[ 39 ].assign( items, items+6 ); }
321 { int items[] = { 14, 15, 16, 17 };
322 undef2newItems[ 43 ].assign( items, items+4 ); }
323 undef2newItems[ 44 ].push_back( 37 );
324 undef2newItems[ 45 ].push_back( 36 );
325 undef2newItems[ 46 ].push_back( 39 );
326 undef2newItems[ 47 ].push_back( 22 );
327 undef2newItems[ 48 ].push_back( 22 );
328 undef2newItems[ 49 ].push_back( 22 );
329 undef2newItems[ 50 ].push_back( 22 );
330 undef2newItems[ 51 ].push_back( 8 );
332 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
335 int iType = Type.IntegerValue();
336 int iCompare = Compare.IntegerValue();
337 int iUnaryOp = UnaryOp.IntegerValue();
338 int iBinaryOp = BinaryOp.IntegerValue();
340 // find out integer value of FT_Undefined at the moment of dump
341 int oldUndefined = iBinaryOp;
342 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
345 // apply history to args
346 TUndef2newItems::const_iterator undef_items =
347 undef2newItems.upper_bound( oldUndefined );
348 if ( undef_items != undef2newItems.end() )
350 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
351 for ( ; undef_items != undef2newItems.end(); ++undef_items )
353 const vector< int > & addedItems = undef_items->second;
354 for ( size_t i = 0; i < addedItems.size(); ++i )
355 for ( int iArg = 0; iArg < 4; ++iArg )
357 int& arg = *pArg[iArg];
358 if ( arg >= addedItems[i] )
362 Type = TCollection_AsciiString( iType );
363 Compare = TCollection_AsciiString( iCompare );
364 UnaryOp = TCollection_AsciiString( iUnaryOp );
365 BinaryOp = TCollection_AsciiString( iBinaryOp );
369 //================================================================================
371 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
372 * arguments of a given command by a list "[x,y,z]" if the list is accessible
375 //================================================================================
377 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
379 static TStringSet methodsAcceptingList;
380 if ( methodsAcceptingList.empty() ) {
381 const char * methodNames[] = {
382 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
383 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
384 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
385 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
386 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
387 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
388 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
389 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
390 "Translate","TranslateMakeGroups","TranslateMakeMesh",
391 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
392 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
393 ,"" }; // <- mark of the end
394 methodsAcceptingList.Insert( methodNames );
396 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
398 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
400 const _AString & arg = theCommand->GetArg( i );
401 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
402 arg.Search( "SMESH.DirStruct" ) == 1 )
404 Handle(_pyCommand) workCmd = new _pyCommand( arg );
405 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
407 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
409 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
411 _AString newArg = "[ ";
412 newArg += ( workCmd->GetArg( 1 ) + ", " +
413 workCmd->GetArg( 2 ) + ", " +
414 workCmd->GetArg( 3 ) + " ]");
415 theCommand->SetArg( i, newArg );
421 //================================================================================
423 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
424 * a list "[id1,id2]" if the list is an accessible type of argument.
426 //================================================================================
428 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
430 static TStringSet methodsAcceptingList;
431 if ( methodsAcceptingList.empty() ) {
432 const char * methodNames[] = {
433 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
434 "ExportCGNS","ExportGMF",
435 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
436 "ScaleMakeGroups","Scale","ScaleMakeMesh",
437 "FindCoincidentNodesOnPartBut","DoubleElements",
438 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
439 ,"" }; // <- mark of the end
440 methodsAcceptingList.Insert( methodNames );
442 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
444 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
446 _pyCommand argCmd( theCommand->GetArg( i ));
447 if ( argCmd.GetMethod() == "GetIDSource" &&
448 argCmd.GetNbArgs() == 2 )
450 theCommand->SetArg( i, argCmd.GetArg( 1 ));
456 bool _FilterArg( const _AString& theArg )
458 static std::list<_AString> filteredArgs;
459 static bool initialized = false;
460 if ( !initialized ) {
462 filteredArgs.push_back( "SMESH.MED_V2_1" );
463 filteredArgs.push_back( "SMESH.MED_V2_2" );
465 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
469 //================================================================================
471 * \brief Convert a python script using commands of smeshBuilder.py
472 * \param theScriptLines - Lines of the input script
473 * \param theEntry2AccessorMethod - returns method names to access to
474 * objects wrapped with python class
475 * \param theObjectNames - names of objects
476 * \param theRemovedObjIDs - entries of objects whose created commands were removed
477 * \param theHistoricalDump - true means to keep all commands, false means
478 * to exclude commands relating to objects removed from study
479 * \retval TCollection_AsciiString - Conversion result
481 //================================================================================
484 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
485 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
486 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
487 std::set< TCollection_AsciiString >& theRemovedObjIDs,
488 const bool theToKeepAllCommands)
490 std::list< TCollection_AsciiString >::iterator lineIt;
491 // process notebook variables
493 SMESH_NoteBook aNoteBook;
495 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
496 aNoteBook.AddCommand( *lineIt );
498 theScriptLines.clear();
500 aNoteBook.ReplaceVariables();
502 aNoteBook.GetResultLines( theScriptLines );
505 // convert to smeshBuilder.py API
507 theGen = new _pyGen( theEntry2AccessorMethod,
510 theToKeepAllCommands );
512 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
513 theGen->AddCommand( *lineIt );
515 theScriptLines.clear();
519 #ifdef DUMP_CONVERSION
520 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
523 // clean commands of removed objects depending on myIsPublished flag
524 theGen->ClearCommands();
526 // reorder commands after conversion
527 list< Handle(_pyCommand) >::iterator cmd;
530 orderChanges = false;
531 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
532 if ( (*cmd)->SetDependentCmdsAfter() )
534 } while ( orderChanges );
536 // concat commands back into a script
537 TCollection_AsciiString aPrevCmd;
538 set<_pyID> createdObjects;
539 createdObjects.insert( "smeshBuilder" );
540 createdObjects.insert( "smesh" );
541 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
543 #ifdef DUMP_CONVERSION
544 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
546 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
547 CheckObjectPresence( *cmd, createdObjects );
548 if ( !(*cmd)->IsEmpty() ) {
549 aPrevCmd = (*cmd)->GetString();
550 theScriptLines.push_back( aPrevCmd );
559 //================================================================================
561 * \brief _pyGen constructor
563 //================================================================================
565 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
566 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
567 std::set< TCollection_AsciiString >& theRemovedObjIDs,
568 const bool theToKeepAllCommands)
569 : _pyObject( new _pyCommand( "", 0 )),
571 myID2AccessorMethod( theEntry2AccessorMethod ),
572 myObjectNames( theObjectNames ),
573 myRemovedObjIDs( theRemovedObjIDs ),
575 myToKeepAllCommands( theToKeepAllCommands ),
576 myGeomIDNb(0), myGeomIDIndex(-1),
577 myShaperIDNb(0), myShaperIDIndex(-1)
579 // make that GetID() to return TPythonDump::SMESHGenName()
580 GetCreationCmd()->Clear();
581 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
582 GetCreationCmd()->GetString() += "=";
584 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
585 if (!theObjectNames.IsEmpty())
587 // find a GEOM (aPass == 0) and SHAPERSTUDY (aPass == 1) entries
588 for(int aPass = 0; aPass < 2; aPass++) {
590 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->
591 FindComponent(aPass == 0 ? "GEOM" : "SHAPERSTUDY");
592 if (geomComp->_is_nil()) continue;
593 CORBA::String_var entry = geomComp->GetID();
596 // find a SMESH entry
598 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n(theObjectNames);
599 for (; e2n.More() && smeshID.IsEmpty(); e2n.Next())
600 if (_pyCommand::IsStudyEntry(e2n.Key()))
603 // find 1st difference between smeshID and geomID
604 if (!geomID.IsEmpty() && !smeshID.IsEmpty())
605 for (int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i)
606 if (geomID.Value(i) != smeshID.Value(i))
609 myGeomIDNb = geomID.Value(i);
612 myShaperIDNb = geomID.Value(i);
620 //================================================================================
622 * \brief name of SMESH_Gen in smeshBuilder.py
624 //================================================================================
626 const char* _pyGen::AccessorMethod() const
628 return SMESH_2smeshpy::GenName();
631 //================================================================================
633 * \brief Convert a command using a specific converter
634 * \param theCommand - the command to convert
636 //================================================================================
638 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
640 // store theCommand in the sequence
641 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
643 Handle(_pyCommand) aCommand = myCommands.back();
644 #ifdef DUMP_CONVERSION
645 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
648 const _pyID& objID = aCommand->GetObject();
650 if ( objID.IsEmpty() )
653 // Prevent moving a command creating a sub-mesh to the end of the script
654 // if the sub-mesh is used in theCommand as argument
655 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
657 // PlaceSubmeshAfterItsCreation( aCommand );
660 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
661 StructToList( aCommand );
663 const TCollection_AsciiString& method = aCommand->GetMethod();
665 // not to erase _pySelfEraser's etc. used as args in some commands
667 #ifdef USE_STRING_FAMILY
668 std::list<_pyID> objIDs;
669 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
671 std::list<_pyID>::iterator objID = objIDs.begin();
672 for ( ; objID != objIDs.end(); ++objID )
674 Handle(_pyObject) obj = FindObject( *objID );
677 obj->AddArgCmd( aCommand );
678 //cout << objID << " found in " << theCommand << endl;
683 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
684 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
685 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
687 Handle(_pyObject) obj = FindObject( *id );
689 obj->AddArgCmd( aCommand );
694 // Find an object to process theCommand
697 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
699 this->Process( aCommand );
700 //addFilterUser( aCommand, theGen ); // protect filters from clearing
704 // SMESH_Mesh method?
705 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
706 if ( id_mesh != myMeshes.end() )
708 //id_mesh->second->AddProcessedCmd( aCommand );
710 // Wrap Export*() into try-except
711 if ( aCommand->MethodStartsFrom("Export"))
714 _AString indent = aCommand->GetIndentation();
715 _AString tryStr = indent + "try:";
716 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
717 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
718 _AString excStr = indent + "except:";
719 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
721 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
723 aCommand->GetString() = newCmd;
724 aCommand->SetOrderNb( ++myNbCommands );
725 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
726 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
727 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
729 // check for mesh editor object
730 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
731 _pyID editorID = aCommand->GetResultValue();
732 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
733 myMeshEditors.insert( make_pair( editorID, editor ));
736 // check for SubMesh objects
737 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
738 _pyID subMeshID = aCommand->GetResultValue();
739 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
740 AddObject( subMesh );
743 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
744 GetIDSourceToList( aCommand );
746 //addFilterUser( aCommand, theGen ); // protect filters from clearing
748 id_mesh->second->Process( aCommand );
749 id_mesh->second->AddProcessedCmd( aCommand );
753 // SMESH_MeshEditor method?
754 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
755 if ( id_editor != myMeshEditors.end() )
757 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
758 GetIDSourceToList( aCommand );
760 //addFilterUser( aCommand, theGen ); // protect filters from clearing
762 // some commands of SMESH_MeshEditor create meshes and groups
763 _pyID meshID, groups;
764 if ( method.Search("MakeMesh") != -1 )
765 meshID = aCommand->GetResultValue();
766 else if ( method == "MakeBoundaryMesh")
767 meshID = aCommand->GetResultValue(1);
768 else if ( method == "MakeBoundaryElements" || method == "MakeBoundaryOfEachElement" )
769 meshID = aCommand->GetResultValue(2);
771 if ( method.Search("MakeGroups") != -1 ||
772 method == "ExtrusionAlongPathX" ||
773 method == "ExtrusionAlongPathObjX" ||
774 method == "DoubleNodeGroupNew" ||
775 method == "DoubleNodeGroupsNew" ||
776 method == "DoubleNodeElemGroupNew" ||
777 method == "DoubleNodeElemGroupsNew" ||
778 method == "DoubleNodeElemGroup2New" ||
779 method == "DoubleNodeElemGroups2New" ||
780 method == "AffectedElemGroupsInRegion"
782 groups = aCommand->GetResultValue();
783 else if ( method == "MakeBoundaryMesh" )
784 groups = aCommand->GetResultValue(2);
785 else if ( method == "MakeBoundaryElements" || method == "MakeBoundaryOfEachElement" )
786 groups = aCommand->GetResultValue(3);
787 else if ( method == "Create0DElementsOnAllNodes" &&
788 aCommand->GetArg(2).Length() > 2 ) // group name != ''
789 groups = aCommand->GetResultValue();
791 id_editor->second->Process( aCommand );
792 id_editor->second->AddProcessedCmd( aCommand );
795 if ( !meshID.IsEmpty() &&
796 !myMeshes.count( meshID ) &&
797 aCommand->IsStudyEntry( meshID ))
799 _AString processedCommand = aCommand->GetString();
800 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
801 CheckObjectIsReCreated( mesh );
802 myMeshes.insert( make_pair( meshID, mesh ));
804 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
807 if ( !groups.IsEmpty() )
809 if ( !aCommand->IsStudyEntry( meshID ))
810 meshID = id_editor->second->GetMesh();
811 Handle(_pyMesh) mesh = myMeshes[ meshID ];
813 list< _pyID > idList = aCommand->GetStudyEntries( groups );
814 list< _pyID >::iterator grID = idList.begin();
815 for ( ; grID != idList.end(); ++grID )
816 if ( !myObjects.count( *grID ))
818 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
820 if ( !mesh.IsNull() ) mesh->AddGroup( group );
824 } // SMESH_MeshEditor methods
826 // SMESH_Hypothesis method?
827 Handle(_pyHypothesis) hyp = FindHyp( objID );
828 if ( !hyp.IsNull() && !hyp->IsAlgo() )
830 hyp->Process( aCommand );
831 hyp->AddProcessedCmd( aCommand );
835 // aFilterManager.CreateFilter() ?
836 if ( aCommand->GetMethod() == "CreateFilter" )
838 // Set a more human readable name to a filter
839 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
840 _pyID newID, filterID = aCommand->GetResultValue();
841 int pos = filterID.Search( "0x" );
843 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
845 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
848 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
849 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
851 // create _pySelfEraser for functors
852 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
853 functor->IgnoreOwnCalls(); // to erase if not used as an argument
854 AddObject( functor );
857 // other object method?
858 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
859 if ( id_obj != myObjects.end() ) {
860 id_obj->second->Process( aCommand );
861 id_obj->second->AddProcessedCmd( aCommand );
865 // Add access to a wrapped mesh
866 AddMeshAccessorMethod( aCommand );
868 // Add access to a wrapped algorithm
869 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
871 // PAL12227. PythonDump was not updated at proper time; result is
872 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
873 // TypeError: __init__() takes exactly 11 arguments (10 given)
874 const char wrongCommand[] = "SMESH.Filter.Criterion(";
875 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
877 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
878 // there must be 10 arguments, 5-th arg ThresholdID is missing,
879 const int wrongNbArgs = 9, missingArg = 5;
880 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
882 for ( int i = wrongNbArgs; i > missingArg; --i )
883 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
884 tmpCmd.SetArg( missingArg, "''");
885 aCommand->GetString().Trunc( beg - 1 );
886 aCommand->GetString() += tmpCmd.GetString();
889 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
891 // instead of "SMESH.Filter.Criterion(
892 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
893 // 1 2 3 4 5 6 7 8 9 10
894 // in order to avoid the problem of type mismatch of long and FunctorType
895 const TCollection_AsciiString
896 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
897 TCollection_AsciiString
898 Type = aCommand->GetArg(1), // long
899 Compare = aCommand->GetArg(2), // long
900 Threshold = aCommand->GetArg(3), // double
901 ThresholdStr = aCommand->GetArg(4), // string
902 ThresholdID = aCommand->GetArg(5), // string
903 UnaryOp = aCommand->GetArg(6), // long
904 BinaryOp = aCommand->GetArg(7), // long
905 Tolerance = aCommand->GetArg(8), // double
906 TypeOfElement = aCommand->GetArg(9), // ElementType
907 Precision = aCommand->GetArg(10); // long
908 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
909 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
910 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
911 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
912 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
914 if ( Compare == "SMESH.FT_EqualTo" )
917 aCommand->RemoveArgs();
918 aCommand->SetObject( SMESH_2smeshpy::GenName() );
919 aCommand->SetMethod( "GetCriterion" );
921 aCommand->SetArg( 1, TypeOfElement );
922 aCommand->SetArg( 2, Type );
923 aCommand->SetArg( 3, Compare );
925 if ( Threshold.IsIntegerValue() )
927 int iGeom = Threshold.IntegerValue();
928 if ( Type == "SMESH.FT_ElemGeomType" )
930 // set SMESH.GeometryType instead of a numerical Threshold
931 const int nbTypes = SMESH::Geom_LAST;
932 const char* types[] = {
933 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
934 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
935 "Geom_POLYHEDRA", "Geom_BALL" };
936 if ( -1 < iGeom && iGeom < nbTypes )
937 Threshold = SMESH + types[ iGeom ];
939 if (SALOME::VerbosityActivated())
941 // is types complete? (compilation failure means that enum GeometryType changed)
942 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
943 "Update names of GeometryType's!!!" );
946 if (Type == "SMESH.FT_EntityType")
948 // set SMESH.EntityType instead of a numerical Threshold
949 const int nbTypes = SMESH::Entity_Last;
950 const char* types[] = {
951 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
952 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
953 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
954 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
955 "Entity_Pyramid", "Entity_Quad_Pyramid",
956 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
957 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
958 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
959 if ( -1 < iGeom && iGeom < nbTypes )
960 Threshold = SMESH + types[ iGeom ];
962 if (SALOME::VerbosityActivated())
964 // is 'types' complete? (compilation failure means that enum EntityType changed)
965 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
966 "Update names of EntityType's!!!" );
970 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
971 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
972 else if ( ThresholdStr.Length() != 2 )
973 aCommand->SetArg( 4, ThresholdStr );
974 else if ( ThresholdID.Length() != 2 )
975 aCommand->SetArg( 4, ThresholdID );
977 aCommand->SetArg( 4, Threshold );
978 // find the last not default arg
980 if ( Tolerance == dfltTol ) {
982 if ( BinaryOp == dfltFunctor ) {
984 if ( UnaryOp == dfltFunctor )
988 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
989 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
990 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
991 if ( Precision != dfltPreci )
993 TCollection_AsciiString crit = aCommand->GetResultValue();
994 aCommand->GetString() += "; ";
995 aCommand->GetString() += crit + ".Precision = " + Precision;
1001 //================================================================================
1003 * \brief Convert the command or remember it for later conversion
1004 * \param theCommand - The python command calling a method of SMESH_Gen
1006 //================================================================================
1008 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
1010 // there are methods to convert:
1011 // CreateMesh( shape )
1012 // Concatenate( [mesh1, ...], ... )
1013 // CreateHypothesis( theHypType, theLibName )
1014 // Compute( mesh, geom )
1015 // Evaluate( mesh, geom )
1017 TCollection_AsciiString method = theCommand->GetMethod();
1019 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
1021 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1024 _pyID id = mesh->GetID(), comma("'");
1025 if ( myObjectNames.IsBound( id ))
1026 theCommand->SetArg( theCommand->GetNbArgs() + 1,
1027 comma + myObjectNames( id ) + comma);
1030 if ( method == "CreateMeshesFromUNV" ||
1031 method == "CreateMeshesFromSTL" ||
1032 method == "CreateDualMesh" ||
1033 method == "CopyMesh" ) // command result is a mesh
1035 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1039 if ( method == "CreateMeshesFromMED" ||
1040 method == "CreateMeshesFromCGNS" ||
1041 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1043 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1044 std::list< _pyID >::iterator meshID = meshIDs.begin();
1045 for ( ; meshID != meshIDs.end(); ++meshID )
1047 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1050 if ( method == "CreateMeshesFromGMF" )
1052 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1053 // CreateMeshesFromGMF( theFileName )
1054 _AString file = theCommand->GetArg(1);
1055 theCommand->RemoveArgs();
1056 theCommand->SetArg( 1, file );
1059 if ( method == "CopyMeshWithGeom" )
1061 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1062 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1066 // CreateHypothesis()
1067 if ( method == "CreateHypothesis" )
1069 // issue 199929, remove standard library name (default parameter)
1070 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1071 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1072 // keep the first argument
1073 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1074 theCommand->RemoveArgs();
1075 theCommand->SetArg( 1, arg );
1078 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1079 CheckObjectIsReCreated( hyp );
1080 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1085 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1086 if ( method == "Compute" )
1088 const _pyID& meshID = theCommand->GetArg( 1 );
1089 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1090 if ( id_mesh != myMeshes.end() ) {
1091 theCommand->SetObject( meshID );
1092 theCommand->RemoveArgs();
1093 id_mesh->second->Process( theCommand );
1094 id_mesh->second->AddProcessedCmd( theCommand );
1099 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1100 if ( method == "Evaluate" )
1102 const _pyID& meshID = theCommand->GetArg( 1 );
1103 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1104 if ( id_mesh != myMeshes.end() ) {
1105 theCommand->SetObject( meshID );
1106 _pyID geom = theCommand->GetArg( 2 );
1107 theCommand->RemoveArgs();
1108 theCommand->SetArg( 1, geom );
1109 id_mesh->second->AddProcessedCmd( theCommand );
1114 // objects erasing creation command if no more its commands invoked:
1115 // SMESH_Pattern, FilterManager
1116 if ( method == "GetPattern" ||
1117 method == "CreateFilterManager" ||
1118 method == "CreateMeasurements" )
1120 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1121 if ( !AddObject( obj ) )
1122 theCommand->Clear(); // already created
1124 // Concatenate( [mesh1, ...], ... )
1125 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1127 // OLD IDL: ( meshes, uniteGroups, toMerge, tol )
1128 // IDL: ( meshes, uniteGroups, toMerge, tol, meshToAppendTo )
1129 // PY: ( meshes, uniteGroups, toMerge, tol, allGroups=False, name="", meshToAppendTo=None )
1130 _pyID appendMesh = theCommand->GetArg( 5 );
1131 if ( method == "ConcatenateWithGroups" ) {
1132 theCommand->SetMethod( "Concatenate" );
1133 theCommand->SetArg( 5, "True" );
1136 theCommand->SetArg( 5, "False" );
1138 if ( !appendMesh.IsEmpty() && appendMesh != "None" )
1140 appendMesh.Insert( 1, "meshToAppendTo=" );
1141 theCommand->SetArg( theCommand->GetNbArgs() + 1, appendMesh );
1143 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1145 AddMeshAccessorMethod( theCommand );
1147 else if ( method == "SetName" ) // SetName(obj,name)
1149 // store theCommand as one of object commands to erase it along with the object
1150 const _pyID& objID = theCommand->GetArg( 1 );
1151 Handle(_pyObject) obj = FindObject( objID );
1152 if ( !obj.IsNull() )
1153 obj->AddProcessedCmd( theCommand );
1156 // Replace name of SMESH_Gen
1158 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1159 static TStringSet smeshpyMethods;
1160 if ( smeshpyMethods.empty() ) {
1161 const char * names[] =
1162 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1163 "GetPattern","GetSubShapesId",
1164 "" }; // <- mark of array end
1165 smeshpyMethods.Insert( names );
1167 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1168 // smeshgen.Method() --> smesh.Method()
1169 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1171 // smeshgen.Method() --> smesh.Method()
1172 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1175 //================================================================================
1177 * \brief Convert the remembered commands
1179 //================================================================================
1181 void _pyGen::Flush()
1183 // create an empty command
1184 myLastCommand = new _pyCommand();
1186 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1187 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1188 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1190 if ( IsToKeepAllCommands() ) // historical dump
1192 // set myIsPublished = true to all objects
1193 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1194 id_mesh->second->SetRemovedFromStudy( false );
1195 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1196 id_hyp->second->SetRemovedFromStudy( false );
1197 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1198 id_obj->second->SetRemovedFromStudy( false );
1202 // let hypotheses find referred objects in order to prevent clearing
1203 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1204 list< Handle(_pyMesh) > fatherMeshes;
1205 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1206 if ( !id_hyp->second.IsNull() )
1207 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1209 // set myIsPublished = false to all objects depending on
1210 // meshes built on a removed geometry
1211 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1212 if ( id_mesh->second->IsNotGeomPublished() )
1213 id_mesh->second->SetRemovedFromStudy( true );
1216 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1217 if ( ! id_mesh->second.IsNull() )
1218 id_mesh->second->Flush();
1221 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1222 if ( !id_hyp->second.IsNull() ) {
1223 id_hyp->second->Flush();
1224 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1225 if ( !id_hyp->second->IsWrapped() )
1226 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1229 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1230 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1231 for ( ; robj != myOrderedObjects.rend(); ++robj )
1232 if ( ! robj->IsNull() )
1234 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1235 for ( ; obj != myOrderedObjects.end(); ++obj )
1236 if ( ! obj->IsNull() )
1239 myLastCommand->SetOrderNb( ++myNbCommands );
1240 myCommands.push_back( myLastCommand );
1243 //================================================================================
1245 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1246 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1248 //================================================================================
1250 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) /*theCmdUsingSubmesh*/ ) const
1252 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1253 // for ( ; id_obj != myObjects.end(); ++id_obj )
1255 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1256 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1258 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1259 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1261 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1262 // list< _pyID >::iterator id = idList.begin();
1263 // for ( ; id != idList.end(); ++id )
1264 // if ( id_obj->first == *id )
1265 // // _pySubMesh::Process() does what we need
1266 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1271 //================================================================================
1273 * \brief Clean commands of removed objects depending on myIsPublished flag
1275 //================================================================================
1277 void _pyGen::ClearCommands()
1279 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1280 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1281 id_mesh->second->ClearCommands();
1283 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1284 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1285 if ( !id_hyp->second.IsNull() )
1286 id_hyp->second->ClearCommands();
1288 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1289 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1290 for ( ; robj != myOrderedObjects.rend(); ++robj )
1291 if ( ! robj->IsNull() )
1292 (*robj)->ClearCommands();
1293 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1294 for ( ; obj != myOrderedObjects.end(); ++obj )
1295 if ( ! obj->IsNull() )
1296 (*obj)->ClearCommands();
1299 //================================================================================
1301 * \brief Release mutual handles of objects
1303 //================================================================================
1307 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1308 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1309 id_mesh->second->Free();
1312 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1313 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1314 id_ed->second->Free();
1315 myMeshEditors.clear();
1317 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1318 for ( ; id_obj != myObjects.end(); ++id_obj )
1319 id_obj->second->Free();
1322 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1323 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1324 if ( !id_hyp->second.IsNull() )
1325 id_hyp->second->Free();
1328 myFile2ExportedMesh.clear();
1330 //myKeepAgrCmdsIDs.Print();
1333 //================================================================================
1335 * \brief Add access method to mesh that is an argument
1336 * \param theCmd - command to add access method
1337 * \retval bool - true if added
1339 //================================================================================
1341 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1344 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1345 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1346 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1352 //================================================================================
1354 * \brief Add access method to algo that is an object or an argument
1355 * \param theCmd - command to add access method
1356 * \retval bool - true if added
1358 //================================================================================
1360 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1363 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1364 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1365 if ( !id_hyp->second.IsNull() &&
1366 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1367 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1368 id_hyp->second->AccessorMethod() ))
1374 //================================================================================
1376 * \brief Find hypothesis by ID (entry)
1377 * \param theHypID - The hypothesis ID
1378 * \retval Handle(_pyHypothesis) - The found hypothesis
1380 //================================================================================
1382 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1384 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1385 if ( id_hyp != myHypos.end() &&
1386 !id_hyp->second.IsNull() &&
1387 theHypID == id_hyp->second->GetID() )
1388 return id_hyp->second;
1389 return Handle(_pyHypothesis)();
1392 //================================================================================
1394 * \brief Find algorithm able to create a hypothesis
1395 * \param theGeom - The shape ID the algorithm was created on
1396 * \param theMesh - The mesh ID that created the algorithm
1397 * \param theHypothesis - The hypothesis the algorithm should be able to create
1398 * \retval Handle(_pyHypothesis) - The found algo
1400 //================================================================================
1402 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1403 const Handle(_pyHypothesis)& theHypothesis )
1405 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1406 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1407 if ( !id_hyp->second.IsNull() &&
1408 id_hyp->second->IsAlgo() &&
1409 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1410 id_hyp->second->GetGeom() == theGeom &&
1411 id_hyp->second->GetMesh() == theMesh )
1412 return id_hyp->second;
1413 return Handle(_pyHypothesis)();
1416 //================================================================================
1418 * \brief Find subMesh by ID (entry)
1419 * \param theSubMeshID - The subMesh ID
1420 * \retval Handle(_pySubMesh) - The found subMesh
1422 //================================================================================
1424 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1426 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1427 if ( id_subMesh != myObjects.end() )
1428 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1429 return Handle(_pySubMesh)();
1433 //================================================================================
1435 * \brief Change order of commands in the script
1436 * \param theCmd1 - One command
1437 * \param theCmd2 - Another command
1439 //================================================================================
1441 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1443 list< Handle(_pyCommand) >::iterator pos1, pos2;
1444 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1445 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1446 myCommands.insert( pos1, theCmd2 );
1447 myCommands.insert( pos2, theCmd1 );
1448 myCommands.erase( pos1 );
1449 myCommands.erase( pos2 );
1451 int nb1 = theCmd1->GetOrderNb();
1452 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1453 theCmd2->SetOrderNb( nb1 );
1454 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1455 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1458 //================================================================================
1460 * \brief Set one command after the other
1461 * \param theCmd - Command to move
1462 * \param theAfterCmd - Command ater which to insert the first one
1464 //================================================================================
1466 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1468 setNeighbourCommand( theCmd, theAfterCmd, true );
1471 //================================================================================
1473 * \brief Set one command before the other
1474 * \param theCmd - Command to move
1475 * \param theBeforeCmd - Command before which to insert the first one
1477 //================================================================================
1479 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1481 setNeighbourCommand( theCmd, theBeforeCmd, false );
1484 //================================================================================
1486 * \brief Set one command before or after the other
1487 * \param theCmd - Command to move
1488 * \param theOtherCmd - Command ater or before which to insert the first one
1490 //================================================================================
1492 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1493 Handle(_pyCommand)& theOtherCmd,
1494 const bool theIsAfter )
1496 list< Handle(_pyCommand) >::iterator pos;
1497 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1498 myCommands.erase( pos );
1499 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1500 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1503 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1504 (*pos)->SetOrderNb( i++ );
1507 //================================================================================
1509 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1511 //================================================================================
1513 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1515 // No more needed after adding _pyObject::myArgCommands
1517 // const char filterPrefix[] = "aFilter0x";
1518 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1521 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1523 // const _AString & arg = theCommand->GetArg( i );
1524 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1525 // if ( arg.Search( filterPrefix ) != 1 )
1528 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1529 // if ( !filter.IsNull() )
1531 // filter->AddUser( user );
1532 // if ( !filter->GetNewID().IsEmpty() )
1533 // theCommand->SetArg( i, filter->GetNewID() );
1538 //================================================================================
1540 * \brief Set command be last in list of commands
1541 * \param theCmd - Command to be last
1543 //================================================================================
1545 Handle(_pyCommand)& _pyGen::GetLastCommand()
1547 return myLastCommand;
1550 //================================================================================
1552 * \brief Set method to access to object wrapped with python class
1553 * \param theID - The wrapped object entry
1554 * \param theMethod - The accessor method
1556 //================================================================================
1558 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1560 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1563 //================================================================================
1565 * \brief Generated new ID for object and assign with existing name
1566 * \param theID - ID of existing object
1568 //================================================================================
1570 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1575 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1577 while ( myObjectNames.IsBound( aNewID ) );
1579 if ( myObjectNames.IsBound( theID ) )
1580 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1582 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1586 //================================================================================
1588 * \brief Stores theObj in myObjects
1590 //================================================================================
1592 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1594 if ( theObj.IsNull() ) return false;
1596 CheckObjectIsReCreated( theObj );
1600 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1601 add = myMeshes.insert( make_pair( theObj->GetID(),
1602 Handle(_pyMesh)::DownCast( theObj ))).second;
1604 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1605 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1606 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1609 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1610 if ( add ) myOrderedObjects.push_back( theObj );
1615 //================================================================================
1617 * \brief Erases an existing object with the same ID. This method should be called
1618 * before storing theObj in _pyGen
1620 //================================================================================
1622 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1624 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1627 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1628 Handle(_pyObject) existing;
1630 existing = FindHyp( theObj->GetID() );
1632 existing = FindObject( theObj->GetID() );
1633 if ( !existing.IsNull() && existing != theObj )
1635 existing->SetRemovedFromStudy( true );
1636 existing->ClearCommands();
1639 if ( myHypos.count( theObj->GetID() ))
1640 myHypos.erase( theObj->GetID() );
1642 else if ( myMeshes.count( theObj->GetID() ))
1644 myMeshes.erase( theObj->GetID() );
1646 else if ( myObjects.count( theObj->GetID() ))
1648 myObjects.erase( theObj->GetID() );
1653 //================================================================================
1655 * \brief Re-register an object with other ID to make it Process() commands of
1656 * other object having this ID
1658 //================================================================================
1660 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1662 if ( theObj.IsNull() ) return;
1664 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1665 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1667 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1668 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1671 myObjects.insert( make_pair( theID, theObj ));
1674 //================================================================================
1676 * \brief Finds a _pyObject by ID
1678 //================================================================================
1680 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1683 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1684 if ( id_obj != myObjects.end() )
1685 return id_obj->second;
1688 _pyGen* me = const_cast< _pyGen* >( this );
1689 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1690 if ( id_obj != myMeshes.end() )
1691 return id_obj->second;
1694 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1695 // if ( id_obj != myMeshEditors.end() )
1696 // return id_obj->second;
1698 return Handle(_pyObject)();
1701 //================================================================================
1703 * \brief Check if a study entry is under GEOM component
1705 //================================================================================
1707 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1709 bool isGeom = myGeomIDNb && myGeomIDIndex <= theObjID.Length() &&
1710 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb;
1711 bool isShaper = myShaperIDNb && myShaperIDIndex <= theObjID.Length() &&
1712 int( theObjID.Value( myShaperIDIndex )) == myShaperIDNb;
1713 return ((isGeom || isShaper) && _pyCommand::IsStudyEntry( theObjID ));
1716 //================================================================================
1718 * \brief Returns true if an object is not present in a study
1720 //================================================================================
1722 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1724 if ( theObjID.IsEmpty() ) return false;
1726 if ( myObjectNames.IsBound( theObjID ))
1727 return false; // SMESH object is in study
1729 // either the SMESH object is not in study or it is a GEOM object
1730 if ( IsGeomObject( theObjID ))
1732 SALOMEDS::SObject_wrap so = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( theObjID.ToCString() );
1733 if ( so->_is_nil() ) return true;
1734 CORBA::Object_var obj = so->GetObject();
1735 return CORBA::is_nil( obj );
1737 return true; // SMESH object not in study
1740 //================================================================================
1742 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1743 * this object is not dumped
1744 * \param [in] theObjID - entry of the object whose creation command was eliminated
1746 //================================================================================
1748 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1750 myRemovedObjIDs.insert( theObjID );
1753 //================================================================================
1755 * \brief Return reader of hypotheses of plugins
1757 //================================================================================
1759 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1761 if (myHypReader.IsNull() )
1762 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1768 //================================================================================
1770 * \brief Mesh created by SMESH_Gen
1772 //================================================================================
1774 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1775 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1777 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1778 myGeomNotInStudy = true;
1780 // convert my creation command --> smeshpy.Mesh(...)
1781 Handle(_pyCommand) creationCmd = GetCreationCmd();
1782 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1783 creationCmd->SetMethod( "Mesh" );
1784 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1787 //================================================================================
1789 * \brief Mesh created by SMESH_MeshEditor
1791 //================================================================================
1793 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1794 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1796 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1798 // this mesh depends on the exported mesh
1799 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1800 if ( !file.IsEmpty() )
1802 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1803 addFatherMesh( exportData.myMesh );
1804 if ( !exportData.myLastComputeCmd.IsNull() )
1806 // restore cleared Compute() by which the exported mesh was generated
1807 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1808 // protect that Compute() cmd from clearing
1809 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1810 exportData.myMesh->myLastComputeCmd.Nullify();
1814 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1816 // this mesh depends on concatenated meshes
1817 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1818 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1819 list< _pyID >::iterator meshID = idList.begin();
1820 for ( ; meshID != idList.end(); ++meshID )
1821 addFatherMesh( *meshID );
1823 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1825 // this mesh depends on a copied IdSource
1826 const _pyID& objID = theCreationCmd->GetArg( 1 );
1827 addFatherMesh( objID );
1829 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1830 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1831 theCreationCmd->GetMethod() == "MakeBoundaryElements" ||
1832 theCreationCmd->GetMethod() == "MakeBoundaryOfEachElement" )
1834 // this mesh depends on a source mesh
1835 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1836 const _pyID& meshID = theCreationCmd->GetObject();
1837 addFatherMesh( meshID );
1840 // convert my creation command
1841 Handle(_pyCommand) creationCmd = GetCreationCmd();
1842 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1843 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1846 //================================================================================
1848 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1849 * \param theCommand - Engine method called for this mesh
1851 //================================================================================
1853 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1855 // some methods of SMESH_Mesh interface need special conversion
1856 // to methods of Mesh python class
1858 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1859 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1860 // 2. AddHypothesis(geom, hyp)
1861 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1862 // 3. CreateGroupFromGEOM(type, name, grp)
1863 // --> in Mesh.Group(grp, name="")
1864 // 4. ExportToMED(f, auto_groups, version)
1865 // --> in Mesh.ExportMED( f, auto_groups, version )
1868 const TCollection_AsciiString& method = theCommand->GetMethod();
1869 // ----------------------------------------------------------------------
1870 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1872 if ( !theGen->IsToKeepAllCommands() ) // !historical
1874 list< Handle(_pyHypothesis) >::iterator hyp;
1875 if ( !myLastComputeCmd.IsNull() )
1877 // check if the previously computed mesh has been edited,
1878 // if so then we do not clear the previous Compute()
1879 bool toClear = true;
1880 if ( myLastComputeCmd->GetMethod() == "Compute" )
1882 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1883 for ( ; e != myEditors.end() && toClear; ++e )
1885 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1886 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1887 if ( cmd != cmds.rend() &&
1888 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1894 // clear hyp commands called before myLastComputeCmd
1895 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1896 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1898 myLastComputeCmd->Clear();
1901 myLastComputeCmd = theCommand;
1903 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1904 (*hyp)->MeshComputed( myLastComputeCmd );
1908 // ----------------------------------------------------------------------
1909 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1911 if ( !theGen->IsToKeepAllCommands() ) // !historical
1914 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1915 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1916 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1918 if ( !myLastComputeCmd.IsNull() )
1920 list< Handle(_pyHypothesis) >::iterator hyp;
1921 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1922 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1924 myLastComputeCmd->Clear();
1927 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1928 for ( ; e != myEditors.end(); ++e )
1930 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1931 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1932 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1933 if ( !(*cmd)->IsEmpty() )
1935 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1939 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1942 // ----------------------------------------------------------------------
1943 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1944 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1945 if ( !subMesh.IsNull() ) {
1946 subMesh->SetCreator( this );
1947 mySubmeshes.push_back( subMesh );
1950 // ----------------------------------------------------------------------
1951 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1952 theCommand->Clear();
1954 // ----------------------------------------------------------------------
1955 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1956 myAddHypCmds.push_back( theCommand );
1958 const _pyID& hypID = theCommand->GetArg( 2 );
1959 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1960 if ( !hyp.IsNull() ) {
1961 myHypos.push_back( hyp );
1962 if ( hyp->GetMesh().IsEmpty() )
1963 hyp->SetMesh( this->GetID() );
1966 // ----------------------------------------------------------------------
1967 else if ( method == "CreateGroup" ||
1968 method == "CreateGroupFromGEOM" ||
1969 method == "CreateGroupFromFilter" ||
1970 method == "CreateDimGroup" )
1972 Handle(_pyGroup) group = new _pyGroup( theCommand );
1973 myGroups.push_back( group );
1974 theGen->AddObject( group );
1976 // ----------------------------------------------------------------------
1977 // update list of groups
1978 else if ( method == "GetGroups" )
1980 bool allGroupsRemoved = true;
1981 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1982 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1983 list< _pyID >::iterator grID = idList.begin();
1984 const size_t nbGroupsBefore = myGroups.size();
1985 Handle(_pyObject) obj;
1986 for ( ; grID != idList.end(); ++grID )
1988 obj = theGen->FindObject( *grID );
1991 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1992 theGen->AddObject( group );
1993 myGroups.push_back( group );
1996 if ( !obj->CanClear() )
1997 allGroupsRemoved = false;
1999 if ( nbGroupsBefore == myGroups.size() && !obj.IsNull() ) // no new _pyGroup created
2000 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
2002 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
2004 // check if the preceding command is Compute();
2005 // if GetGroups() is just after Compute(), this can mean that the groups
2006 // were created by some algorithm and hence Compute() should not be discarded
2007 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
2008 std::list< Handle(_pyCommand) >::reverse_iterator cmd = cmdList.rbegin();
2009 while ( (*cmd)->GetMethod() == "GetGroups" )
2011 if ( myLastComputeCmd == (*cmd))
2012 // protect last Compute() from clearing by the next Compute()
2013 myLastComputeCmd.Nullify();
2016 // ----------------------------------------------------------------------
2017 // notify a group about full removal
2018 else if ( method == "RemoveGroupWithContents" ||
2019 method == "RemoveGroup")
2021 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
2022 const _pyID groupID = theCommand->GetArg( 1 );
2023 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
2024 if ( !grp.IsNull() )
2026 if ( method == "RemoveGroupWithContents" )
2027 grp->RemovedWithContents();
2028 // to clear RemoveGroup() if the group creation is cleared
2029 grp->AddProcessedCmd( theCommand );
2033 // ----------------------------------------------------------------------
2034 else if ( theCommand->MethodStartsFrom( "Export" ))
2036 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
2037 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
2038 method == "ExportMED" )
2040 theCommand->SetMethod( "ExportMED" );
2041 // filter out deprecated version parameter
2042 vector< _AString > args;
2043 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2044 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2045 args.push_back( theCommand->GetArg( i ) );
2047 theCommand->RemoveArgs();
2048 for ( unsigned int i = 0; i < args.size(); i++ )
2049 theCommand->SetArg( i+1, args[i] );
2050 if ( theCommand->GetNbArgs() == 4 )
2052 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2053 _AString autoDimension = theCommand->GetArg( 4 );
2054 theCommand->SetArg( 4, "None" );
2055 theCommand->SetArg( 5, autoDimension );
2058 else if ( method == "ExportCGNS" )
2059 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2060 _pyID partID = theCommand->GetArg( 1 );
2061 int nbArgs = theCommand->GetNbArgs();
2062 for ( int i = 2; i <= nbArgs; ++i )
2063 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2064 theCommand->SetArg( nbArgs, partID );
2066 else if ( method == "ExportGMF" )
2067 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2068 _pyID partID = theCommand->GetArg( 1 );
2069 _AString file = theCommand->GetArg( 2 );
2070 theCommand->RemoveArgs();
2071 theCommand->SetArg( 1, file );
2072 theCommand->SetArg( 2, partID );
2074 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2075 { // ExportPartTo*(part, ...) -> Export*(..., part)
2077 // remove "PartTo" from the method
2078 TCollection_AsciiString newMethod = method;
2079 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2080 theCommand->SetMethod( newMethod );
2081 // replace version parameter by minor
2082 std::list< _AString > args;
2083 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2084 if ( _FilterArg( theCommand->GetArg( i )))
2085 args.push_back( "minor=0");
2087 args.push_back( theCommand->GetArg( i ));
2089 // check the 1st arg meshPart, it must be SMESH_IDSource
2090 _AString meshPart = args.front();
2091 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2092 meshPart.Search( "Filter" ) > 0 ||
2093 meshPart.Search( "GetIDSource" ) > 0 ||
2094 meshPart.Search( "meshPart" ) > 0 )
2096 // set the 1st arg meshPart
2097 // - to 5th place for ExportMED command
2098 // - to last place for the rest commands
2099 std::list< _AString >::iterator newPos = args.end();
2100 if ( newMethod == "ExportMED" )
2101 std::advance( newPos = args.begin(), 5 );
2102 args.splice( newPos, args, args.begin() );
2104 std::list< _AString >::iterator a = args.begin();
2105 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2106 theCommand->SetArg( i, *a );
2108 // remember file name
2109 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2110 ExportedMeshData( this, myLastComputeCmd ));
2112 // ----------------------------------------------------------------------
2113 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2115 _pyID hypID = theCommand->GetArg( 2 );
2116 _pyID geomID = theCommand->GetArg( 1 );
2117 bool isLocal = ( geomID != GetGeom() );
2119 // check if this mesh still has corresponding addition command
2120 Handle(_pyCommand) addCmd;
2121 list< Handle(_pyCommand) >::iterator cmd;
2122 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2123 for ( int i = 0; i < 2; ++i )
2125 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2126 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2128 bool sameHyp = true;
2129 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2130 sameHyp = false; // other hyp
2131 if ( (*cmd)->GetNbArgs() == 2 &&
2132 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2133 sameHyp = false; // other geom
2134 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2135 sameHyp = false; // other geom
2139 cmd = addHypCmds.erase( cmd );
2140 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2142 theCommand->Clear();
2146 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2147 addCmd->RemoveArgs();
2148 addCmd->SetArg( 1, hypID );
2150 addCmd->SetArg( 2, geomID );
2159 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2160 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2161 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2162 _pyID geom = theCommand->GetArg( 1 );
2163 theCommand->RemoveArgs();
2164 theCommand->SetArg( 1, hypID );
2165 if ( geom != GetGeom() )
2166 theCommand->SetArg( 2, geom );
2168 // remove hyp from myHypos
2169 myHypos.remove( hyp );
2171 // check for SubMesh order commands
2172 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2174 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2175 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2176 // commands are moved at the end of the script
2177 TCollection_AsciiString subIDs =
2178 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2179 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2180 list< _pyID >::iterator subID = idList.begin();
2181 for ( ; subID != idList.end(); ++subID )
2183 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2184 if ( !subMesh.IsNull() )
2185 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2188 // add accessor method if necessary
2191 if ( NeedMeshAccess( theCommand ))
2192 // apply theCommand to the mesh wrapped by smeshpy mesh
2193 AddMeshAccess( theCommand );
2197 //================================================================================
2199 * \brief Return True if addition of accesor method is needed
2201 //================================================================================
2203 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2205 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2206 // so no conversion is needed for them at all:
2207 static TStringSet sameMethods;
2208 if ( sameMethods.empty() ) {
2209 const char * names[] =
2210 { "ExportDAT","ExportUNV","ExportSTL", "RemoveGroup","RemoveGroupWithContents",
2211 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2212 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2213 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2214 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2215 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2216 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2217 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2218 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2219 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2220 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2221 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2222 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2223 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder",
2225 ,"" }; // <- mark of end
2226 sameMethods.Insert( names );
2229 return !sameMethods.Contains( theCommand->GetMethod() );
2232 //================================================================================
2234 * \brief Convert creation and addition of all algos and hypos
2236 //================================================================================
2238 void _pyMesh::Flush()
2241 // get the meshes this mesh depends on via hypotheses
2242 list< Handle(_pyMesh) > fatherMeshes;
2243 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2244 for ( ; hyp != myHypos.end(); ++hyp )
2245 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2246 myGeomNotInStudy = true;
2248 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2249 for ( ; m != fatherMeshes.end(); ++m )
2250 addFatherMesh( *m );
2251 // if ( removedGeom )
2252 // SetRemovedFromStudy(); // as referred geometry not in study
2254 if ( myGeomNotInStudy )
2257 list < Handle(_pyCommand) >::iterator cmd;
2259 // try to convert algo addition like this:
2260 // mesh.AddHypothesis( geom, ALGO ) --> ALGO = mesh.Algo()
2261 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2263 Handle(_pyCommand) addCmd = *cmd;
2265 _pyID algoID = addCmd->GetArg( 2 );
2266 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2267 if ( algo.IsNull() || !algo->IsAlgo() )
2270 // check and create new algorithm instance if it is already wrapped
2271 if ( algo->IsWrapped() ) {
2272 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2273 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2274 TCollection_AsciiString( " = " ) + theGen->GetID() +
2275 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2276 TCollection_AsciiString( "\" )" );
2278 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2279 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2280 if ( !newAlgo.IsNull() ) {
2281 newAlgo->Assign( algo, this->GetID() );
2282 newAlgo->SetCreationCmd( newCmd );
2284 // set algorithm creation
2285 theGen->SetCommandBefore( newCmd, addCmd );
2286 myHypos.push_back( newAlgo );
2287 if ( !myLastComputeCmd.IsNull() &&
2288 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2289 newAlgo->MeshComputed( myLastComputeCmd );
2294 _pyID geom = addCmd->GetArg( 1 );
2295 bool isLocalAlgo = ( geom != GetGeom() );
2298 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2300 // wrapped algo is created after mesh creation
2301 GetCreationCmd()->AddDependantCmd( addCmd );
2303 if ( isLocalAlgo ) {
2304 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2305 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2306 TCollection_AsciiString( "geom=" ) + geom );
2307 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2308 list < Handle(_pySubMesh) >::iterator smIt;
2309 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2310 Handle(_pySubMesh) subMesh = *smIt;
2311 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2312 if ( geom == subCmd->GetArg( 1 )) {
2313 subCmd->SetObject( algo->GetID() );
2314 subCmd->RemoveArgs();
2315 subMesh->SetCreator( algo );
2320 else // KO - ALGO was already created
2322 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2323 addCmd->RemoveArgs();
2324 addCmd->SetArg( 1, algoID );
2326 addCmd->SetArg( 2, geom );
2327 myNotConvertedAddHypCmds.push_back( addCmd );
2331 // try to convert hypo addition like this:
2332 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2333 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2335 Handle(_pyCommand) addCmd = *cmd;
2336 _pyID hypID = addCmd->GetArg( 2 );
2337 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2338 if ( hyp.IsNull() || hyp->IsAlgo() )
2340 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2342 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2343 _pyID geom = addCmd->GetArg( 1 );
2344 addCmd->RemoveArgs();
2345 addCmd->SetArg( 1, hypID );
2346 if ( geom != GetGeom() )
2347 addCmd->SetArg( 2, geom );
2348 myNotConvertedAddHypCmds.push_back( addCmd );
2352 myAddHypCmds.clear();
2353 mySubmeshes.clear();
2356 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2357 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2361 //================================================================================
2363 * \brief Sets myIsPublished of me and of all objects depending on me.
2365 //================================================================================
2367 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2369 _pyObject::SetRemovedFromStudy(isRemoved);
2371 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2372 for ( ; sm != mySubmeshes.end(); ++sm )
2373 (*sm)->SetRemovedFromStudy(isRemoved);
2375 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2376 for ( ; gr != myGroups.end(); ++gr )
2377 (*gr)->SetRemovedFromStudy(isRemoved);
2379 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2380 for ( ; m != myChildMeshes.end(); ++m )
2381 (*m)->SetRemovedFromStudy(isRemoved);
2383 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2384 for ( ; e != myEditors.end(); ++e )
2385 (*e)->SetRemovedFromStudy(isRemoved);
2388 //================================================================================
2390 * \brief Return true if none of myChildMeshes is in study
2392 //================================================================================
2394 bool _pyMesh::CanClear()
2399 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2400 for ( ; m != myChildMeshes.end(); ++m )
2401 if ( !(*m)->CanClear() )
2407 //================================================================================
2409 * \brief Clear my commands and commands of mesh editor
2411 //================================================================================
2413 void _pyMesh::ClearCommands()
2419 // mark all sub-objects as not removed, except child meshes
2420 list< Handle(_pyMesh) > children;
2421 children.swap( myChildMeshes );
2422 SetRemovedFromStudy( false );
2423 children.swap( myChildMeshes );
2427 _pyObject::ClearCommands();
2429 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2430 for ( ; sm != mySubmeshes.end(); ++sm )
2431 (*sm)->ClearCommands();
2433 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2434 for ( ; gr != myGroups.end(); ++gr )
2435 (*gr)->ClearCommands();
2437 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2438 for ( ; e != myEditors.end(); ++e )
2439 (*e)->ClearCommands();
2442 //================================================================================
2444 * \brief Add a father mesh by ID
2446 //================================================================================
2448 void _pyMesh::addFatherMesh( const _pyID& meshID )
2450 if ( !meshID.IsEmpty() && meshID != GetID() )
2451 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2454 //================================================================================
2456 * \brief Add a father mesh
2458 //================================================================================
2460 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2462 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2464 //myFatherMeshes.push_back( mesh );
2465 mesh->myChildMeshes.push_back( this );
2467 // protect last Compute() from clearing by the next Compute()
2468 mesh->myLastComputeCmd.Nullify();
2472 //================================================================================
2474 * \brief MeshEditor convert its commands to ones of mesh
2476 //================================================================================
2478 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2479 _pyObject( theCreationCmd )
2481 myMesh = theCreationCmd->GetObject();
2482 myCreationCmdStr = theCreationCmd->GetString();
2483 theCreationCmd->Clear();
2485 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2486 if ( !mesh.IsNull() )
2487 mesh->AddEditor( this );
2490 //================================================================================
2492 * \brief convert its commands to ones of mesh
2494 //================================================================================
2496 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2498 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2499 // commands calling these methods are converted to calls of Mesh methods without
2500 // additional modifs, only object is changed from MeshEditor to Mesh.
2501 static TStringSet sameMethods;
2502 if ( sameMethods.empty() ) {
2503 const char * names[] = {
2504 "RemoveElements","RemoveNodes","RemoveOrphanNodes","RemoveNodeWithReconnection",
2505 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2506 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","AddNodeOnSegment",
2507 "MoveNode", "MoveClosestNodeToPoint","InverseDiag","DeleteDiag","AddNodeOnFace",
2508 "Reorient","ReorientObject","Reorient2DBy3D","Reorient2DByNeighbours",
2509 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2510 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2511 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2512 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2513 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2514 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2515 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2516 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2517 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject","Offset",
2518 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2519 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2520 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2521 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2522 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2523 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2524 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2525 "MakeBoundaryElements", "MakeBoundaryOfEachElement", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2526 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2527 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2528 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2529 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2530 ,"" }; // <- mark of the end
2531 sameMethods.Insert( names );
2534 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2535 TStringMap diffMethods;
2536 if ( diffMethods.empty() ) {
2537 const char * orig2newName[] = {
2538 // original name --------------> new name
2539 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2540 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2541 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2542 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2543 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2544 ""};// <- mark of the end
2545 diffMethods.Insert( orig2newName );
2548 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2549 // only by last two arguments
2550 static TStringSet diffLastTwoArgsMethods;
2551 if (diffLastTwoArgsMethods.empty() ) {
2552 const char * names[] = {
2553 "MirrorMakeGroups","MirrorObjectMakeGroups",
2554 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2555 "RotateMakeGroups","RotateObjectMakeGroups",
2556 ""};// <- mark of the end
2557 diffLastTwoArgsMethods.Insert( names );
2560 // only a method name is to change?
2561 const TCollection_AsciiString & method = theCommand->GetMethod();
2562 bool isPyMeshMethod = sameMethods.Contains( method );
2563 if ( !isPyMeshMethod )
2565 TCollection_AsciiString newMethod = diffMethods.Value( method );
2566 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2567 theCommand->SetMethod( newMethod );
2569 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2570 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2572 isPyMeshMethod = true;
2573 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2574 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2577 if ( !isPyMeshMethod )
2579 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2580 // functions with the flag "theMakeGroups = True" like:
2581 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2582 int pos = method.Search("MakeGroups");
2585 isPyMeshMethod = true;
2586 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2587 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2589 // 1. Remove "MakeGroups" from the Command
2590 TCollection_AsciiString aMethod = theCommand->GetMethod();
2591 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2594 pos = pos-2; //Remove "0D" from the Command too
2595 aMethod.Trunc(pos-1);
2596 theCommand->SetMethod(aMethod);
2598 // 2. And add last "True" argument(s)
2599 while(nbArgsToAdd--)
2600 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2601 if( is0DmethId || is0DmethObj )
2602 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2606 // ExtrusionSweep0D() -> ExtrusionSweep()
2607 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2608 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2609 method == "ExtrusionSweepObject0D" ))
2611 isPyMeshMethod = true;
2612 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2613 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2614 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2617 // DoubleNode...New(...) -> DoubleNode...(...,True)
2618 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2619 method == "DoubleNodeElemGroupsNew" ||
2620 method == "DoubleNodeGroupNew" ||
2621 method == "DoubleNodeGroupsNew" ||
2622 method == "DoubleNodeElemGroup2New" ||
2623 method == "DoubleNodeElemGroups2New"))
2625 isPyMeshMethod = true;
2626 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2627 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2628 if ( excessLen == 3 )
2630 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2632 else if ( theCommand->GetArg(4) == "0" ||
2633 theCommand->GetArg(5) == "0" )
2635 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2636 // Group = DoubleNodeGroup2New(,,,False, True)
2637 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2638 theCommand->SetResultValue( groupID );
2641 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2642 // FindElementsByPoint(x, y, z, elementType, meshPart)
2643 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2645 isPyMeshMethod = true;
2646 theCommand->SetMethod( "FindElementsByPoint" );
2647 // make the 1st arg be the last one
2648 _pyID partID = theCommand->GetArg( 1 );
2649 int nbArgs = theCommand->GetNbArgs();
2650 for ( int i = 2; i <= nbArgs; ++i )
2651 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2652 theCommand->SetArg( nbArgs, partID );
2654 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2655 if ( !isPyMeshMethod && method == "Reorient2D" )
2657 isPyMeshMethod = true;
2658 _AString mesh = theCommand->GetArg( 1 );
2659 _AString dir = theCommand->GetArg( 2 );
2660 _AString face = theCommand->GetArg( 3 );
2661 _AString point = theCommand->GetArg( 4 );
2662 theCommand->RemoveArgs();
2663 theCommand->SetArg( 1, mesh );
2664 theCommand->SetArg( 2, dir );
2665 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2666 theCommand->SetArg( 3, point );
2668 theCommand->SetArg( 3, face );
2671 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2673 isPyMeshMethod = true;
2674 int crit_arg = theCommand->GetNbArgs();
2675 const _AString& crit = theCommand->GetArg(crit_arg);
2676 if (crit.Search("MaxElementLength2D") != -1)
2677 theCommand->SetArg(crit_arg, "");
2680 if ( isPyMeshMethod )
2682 theCommand->SetObject( myMesh );
2686 // editor creation command is needed only if any editor function is called
2687 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2688 if ( !myCreationCmdStr.IsEmpty() ) {
2689 GetCreationCmd()->GetString() = myCreationCmdStr;
2690 myCreationCmdStr.Clear();
2695 //================================================================================
2697 * \brief Return true if my mesh can be removed
2699 //================================================================================
2701 bool _pyMeshEditor::CanClear()
2703 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2704 return mesh.IsNull() ? true : mesh->CanClear();
2707 //================================================================================
2709 * \brief _pyHypothesis constructor
2710 * \param theCreationCmd -
2712 //================================================================================
2714 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2715 _pyObject( theCreationCmd ), myCurCrMethod(0)
2717 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2720 //================================================================================
2722 * \brief Creates algorithm or hypothesis
2723 * \param theCreationCmd - The engine command creating a hypothesis
2724 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2726 //================================================================================
2728 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2730 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2731 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2733 Handle(_pyHypothesis) hyp, algo;
2736 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2737 if ( hypTypeQuoted.IsEmpty() )
2740 TCollection_AsciiString hypType =
2741 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2743 algo = new _pyAlgorithm( theCreationCmd );
2744 hyp = new _pyHypothesis( theCreationCmd );
2746 if ( hypType == "NumberOfSegments" ) {
2747 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2748 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2749 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2750 hyp->AddArgMethod( "SetNumberOfSegments" );
2751 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2752 hyp->AddArgMethod( "SetScaleFactor" );
2753 hyp->AddArgMethod( "SetReversedEdges" );
2754 // same for ""CompositeSegment_1D:
2755 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2756 hyp->AddArgMethod( "SetNumberOfSegments" );
2757 hyp->AddArgMethod( "SetScaleFactor" );
2758 hyp->AddArgMethod( "SetReversedEdges" );
2760 else if ( hypType == "SegmentLengthAroundVertex" ) {
2761 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2762 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2763 hyp->AddArgMethod( "SetLength" );
2764 // same for ""CompositeSegment_1D:
2765 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2766 hyp->AddArgMethod( "SetLength" );
2768 else if ( hypType == "LayerDistribution2D" ) {
2769 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2770 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2772 else if ( hypType == "LayerDistribution" ) {
2773 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2774 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2776 else if ( hypType == "CartesianParameters3D" ) {
2777 hyp = new _pyComplexParamHypo( theCreationCmd );
2778 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2779 for ( int iArg = 0; iArg < 4; ++iArg )
2780 hyp->setCreationArg( iArg+1, "[]");
2781 hyp->AddAccumulativeMethod( "SetGrid" );
2782 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2786 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2789 return algo->IsValid() ? algo : hyp;
2792 //================================================================================
2794 * \brief Returns true if addition of this hypothesis to a given mesh can be
2795 * wrapped into hypothesis creation
2797 //================================================================================
2799 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2801 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2803 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2804 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2810 //================================================================================
2812 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2813 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2814 * \param theAlgo - The algo that can create this hypo
2815 * \retval bool - false if the command can't be converted
2817 //================================================================================
2819 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2820 const _pyID& theMesh)
2822 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2824 if ( !IsWrappable( theMesh ))
2827 myGeom = theCmd->GetArg( 1 );
2829 Handle(_pyHypothesis) algo;
2831 // find algo created on myGeom in theMesh
2832 algo = theGen->FindAlgo( myGeom, theMesh, this );
2833 if ( algo.IsNull() )
2835 // attach hypothesis creation command to be after algo creation command
2836 // because it can be new created instance of algorithm
2837 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2841 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2842 theCmd->SetResultValue( GetID() );
2843 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2844 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2845 // set args (geom will be set by _pyMesh calling this method)
2846 theCmd->RemoveArgs();
2847 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2848 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2849 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2851 theCmd->SetArg( i+1, "[]");
2853 // set a new creation command
2854 GetCreationCmd()->Clear();
2855 // replace creation command by wrapped instance
2856 // please note, that hypothesis attaches to algo creation command (see upper)
2857 SetCreationCmd( theCmd );
2860 // clear commands setting arg values
2861 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2862 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2865 // set unknown arg commands after hypo creation
2866 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2867 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2868 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2869 afterCmd->AddDependantCmd( *cmd );
2875 //================================================================================
2877 * \brief Remember hypothesis parameter values
2878 * \param theCommand - The called hypothesis method
2880 //================================================================================
2882 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2884 ASSERT( !myIsAlgo );
2885 if ( !theGen->IsToKeepAllCommands() )
2886 rememberCmdOfParameter( theCommand );
2888 bool usedCommand = false;
2889 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2890 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2892 CreationMethod& crMethod = type2meth->second;
2893 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2894 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2896 myArgCommands.push_back( theCommand );
2898 while ( crMethod.myArgs.size() < i+1 )
2899 crMethod.myArgs.push_back( "None" );
2900 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2905 myUnusedCommands.push_back( theCommand );
2908 //================================================================================
2910 * \brief Finish conversion
2912 //================================================================================
2914 void _pyHypothesis::Flush()
2918 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2919 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2920 // Add access to a wrapped mesh
2921 theGen->AddMeshAccessorMethod( *cmd );
2922 // Add access to a wrapped algorithm
2923 theGen->AddAlgoAccessorMethod( *cmd );
2925 cmd = myUnusedCommands.begin();
2926 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2927 // Add access to a wrapped mesh
2928 theGen->AddMeshAccessorMethod( *cmd );
2929 // Add access to a wrapped algorithm
2930 theGen->AddAlgoAccessorMethod( *cmd );
2933 // forget previous hypothesis modifications
2934 myArgCommands.clear();
2935 myUnusedCommands.clear();
2938 //================================================================================
2940 * \brief clear creation, arg and unknown commands
2942 //================================================================================
2944 void _pyHypothesis::ClearAllCommands()
2946 GetCreationCmd()->Clear();
2947 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2948 for ( ; cmd != myArgCommands.end(); ++cmd )
2950 cmd = myUnusedCommands.begin();
2951 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2956 //================================================================================
2958 * \brief Assign fields of theOther to me except myIsWrapped
2960 //================================================================================
2962 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2963 const _pyID& theMesh )
2965 // myCreationCmd = theOther->myCreationCmd;
2966 myIsAlgo = theOther->myIsAlgo;
2967 myIsWrapped = false;
2968 myGeom = theOther->myGeom;
2970 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2971 myAccumulativeMethods = theOther->myAccumulativeMethods;
2972 //myUnusedCommands = theOther->myUnusedCommands;
2973 // init myCurCrMethod
2974 GetCreationMethod( theOther->GetAlgoType() );
2977 //================================================================================
2979 * \brief Analyze my erasability depending on myReferredObjs
2981 //================================================================================
2983 bool _pyHypothesis::CanClear()
2987 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2988 for ( ; obj != myReferredObjs.end(); ++obj )
2989 if ( (*obj)->CanClear() )
2996 //================================================================================
2998 * \brief Clear my commands depending on usage by meshes
3000 //================================================================================
3002 void _pyHypothesis::ClearCommands()
3004 // if ( !theGen->IsToKeepAllCommands() )
3006 // bool isUsed = false;
3007 // int lastComputeOrder = 0;
3008 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
3009 // for ( ; cmd != myComputeCmds.end(); ++cmd )
3010 // if ( ! (*cmd)->IsEmpty() )
3013 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
3014 // lastComputeOrder = (*cmd)->GetOrderNb();
3018 // SetRemovedFromStudy( true );
3022 // // clear my commands invoked after lastComputeOrder
3023 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3024 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3026 // // list< Handle(_pyCommand)> & cmds = m2c->second;
3027 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
3028 // // cmds.back()->Clear();
3032 _pyObject::ClearCommands();
3035 //================================================================================
3037 * \brief Find arguments that are objects like mesh, group, geometry
3038 * \param meshes - referred meshes (directly or indirrectly)
3039 * \retval bool - false if a referred geometry is not in the study
3041 //================================================================================
3043 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3045 if ( IsAlgo() ) return true;
3047 bool geomPublished = true;
3048 vector< _AString > args;
3049 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3050 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3052 CreationMethod& crMethod = type2meth->second;
3053 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3055 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3056 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3057 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3058 args.push_back( (*cmd)->GetArg( nb ));
3061 for ( size_t i = 0; i < args.size(); ++i )
3063 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3064 if ( idList.empty() && !args[ i ].IsEmpty() )
3065 idList.push_back( args[ i ]);
3066 list< _pyID >::iterator id = idList.begin();
3067 for ( ; id != idList.end(); ++id )
3069 Handle(_pyObject) obj = theGen->FindObject( *id );
3070 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3073 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3074 geomPublished = false;
3078 myReferredObjs.push_back( obj );
3079 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3080 if ( !mesh.IsNull() )
3081 meshes.push_back( mesh );
3082 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3083 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3084 obj->SetRemovedFromStudy( false );
3088 return geomPublished;
3091 //================================================================================
3093 * \brief Remember theCommand setting a parameter
3095 //================================================================================
3097 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3099 // parameters are discriminated by method name
3100 _AString method = theCommand->GetMethod();
3101 if ( myAccumulativeMethods.count( method ))
3102 return; // this method adds values and not override the previous value
3104 // discriminate commands setting different parameters via one method
3105 // by passing parameter names like e.g. SetOption("size", "0.2")
3106 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3107 theCommand->GetNbArgs() > 1 )
3109 // mangle method by appending a 1st textual arg
3110 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3112 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3113 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3114 if ( !isalpha( arg.Value(2))) continue;
3119 // parameters are discriminated by method name
3120 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3121 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3123 cmds.back()->Clear(); // previous parameter value has not been used
3124 cmds.back() = theCommand;
3128 cmds.push_back( theCommand );
3132 //================================================================================
3134 * \brief Return true if a setting parameter command ha been used to compute mesh
3136 //================================================================================
3138 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3139 _pyCommand::TAddr avoidComputeAddr ) const
3141 bool isUsed = false;
3142 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3143 myComputeAddr2Cmds.begin();
3144 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3146 if ( addr2cmds->first == avoidComputeAddr ) continue;
3147 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3148 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3153 //================================================================================
3155 * \brief Save commands setting parameters as they are used for a mesh computation
3157 //================================================================================
3159 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3161 myComputeCmds.push_back( theComputeCmd );
3162 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3164 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3165 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3166 savedCmds.push_back( m2c->second.back() );
3169 //================================================================================
3171 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3173 //================================================================================
3175 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3177 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3179 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3180 for ( ; cmd != savedCmds.end(); ++cmd )
3182 // check if a cmd has been used to compute another mesh
3183 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3185 // check if a cmd is a sole command setting its parameter;
3186 // don't use method name for search as it can change
3187 map<_AString, list<Handle(_pyCommand)> >::iterator m2cmds = myMeth2Commands.begin();
3188 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3190 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3191 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3192 if ( cmdIt != cmds.end() )
3194 if ( cmds.back() != *cmd )
3196 cmds.erase( cmdIt );
3203 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3206 //================================================================================
3208 * \brief Sets an argNb-th argument of current creation command
3209 * \param argNb - argument index countered from 1
3211 //================================================================================
3213 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3215 if ( myCurCrMethod )
3217 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3218 myCurCrMethod->myArgs.push_back( "None" );
3219 if ( arg.IsEmpty() )
3220 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3222 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3227 //================================================================================
3229 * \brief Remember hypothesis parameter values
3230 * \param theCommand - The called hypothesis method
3232 //================================================================================
3234 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3236 if ( GetAlgoType() == "Cartesian_3D" )
3238 // CartesianParameters3D hyp
3240 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3241 theCommand->GetMethod() == "SetToAddEdges" )
3243 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3244 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3245 myArgCommands.push_back( theCommand );
3248 if ( theCommand->GetMethod() == "SetGrid" ||
3249 theCommand->GetMethod() == "SetGridSpacing" )
3251 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3252 int iArg = axis.Value(1) - '0';
3253 if ( theCommand->GetMethod() == "SetGrid" )
3255 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3259 myCurCrMethod->myArgs[ iArg ] = "[ ";
3260 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3261 myCurCrMethod->myArgs[ iArg ] += ", ";
3262 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3263 myCurCrMethod->myArgs[ iArg ] += "]";
3265 myArgCommands.push_back( theCommand );
3266 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3267 // accumulative, else, if the creation
3268 // is not converted, commands for axes 1 and 2 are lost
3273 if( theCommand->GetMethod() == "SetLength" )
3275 // NOW it is OBSOLETE
3276 // ex: hyp.SetLength(start, 1)
3277 // hyp.SetLength(end, 0)
3278 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3279 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3280 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3281 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3283 CreationMethod& crMethod = type2meth->second;
3284 while ( (int) crMethod.myArgs.size() < i+1 )
3285 crMethod.myArgs.push_back( "[]" );
3286 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3288 myArgCommands.push_back( theCommand );
3292 _pyHypothesis::Process( theCommand );
3295 //================================================================================
3297 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3299 //================================================================================
3301 void _pyComplexParamHypo::Flush()
3303 list < Handle(_pyCommand) >::iterator cmd;
3306 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3307 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3311 // if ( GetAlgoType() == "Cartesian_3D" )
3313 // _pyID algo = myCreationCmd->GetObject();
3314 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3316 // if ( IsWrapped() )
3318 // StructToList( *cmd, /*checkMethod=*/false );
3319 // const _AString & method = (*cmd)->GetMethod();
3320 // if ( method == "SetFixedPoint" )
3321 // (*cmd)->SetObject( algo );
3327 //================================================================================
3329 * \brief Convert methods of 1D hypotheses to my own methods
3330 * \param theCommand - The called hypothesis method
3332 //================================================================================
3334 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3336 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3339 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3340 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3341 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3343 // TCollection_AsciiString cmd =
3344 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3345 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3346 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3349 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3351 // // 1D hypo is already set, so distribution changes and the old
3352 // // 1D hypo is thrown away
3353 // my1dHyp->ClearAllCommands();
3356 // //my1dHyp->SetRemovedFromStudy( false );
3358 // if ( !myArgCommands.empty() )
3359 // myArgCommands.back()->Clear();
3360 myCurCrMethod->myArgs.push_back( hyp1dID );
3361 myArgCommands.push_back( theCommand );
3364 //================================================================================
3367 * \param theAdditionCmd - command to be converted
3368 * \param theMesh - mesh instance
3369 * \retval bool - status
3371 //================================================================================
3373 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3374 const _pyID& theMesh)
3376 myIsWrapped = false;
3378 if ( my1dHyp.IsNull() )
3381 // set "SetLayerDistribution()" after addition cmd
3382 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3384 _pyID geom = theAdditionCmd->GetArg( 1 );
3386 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3387 if ( !algo.IsNull() )
3389 my1dHyp->SetMesh( theMesh );
3390 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3391 algo->GetAlgoType().ToCString());
3392 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3395 // clear "SetLayerDistribution()" cmd
3396 myArgCommands.back()->Clear();
3398 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3400 // find RadialPrism algo created on <geom> for theMesh
3401 GetCreationCmd()->SetObject( algo->GetID() );
3402 GetCreationCmd()->SetMethod( myAlgoMethod );
3403 GetCreationCmd()->RemoveArgs();
3404 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3410 //================================================================================
3414 //================================================================================
3416 void _pyLayerDistributionHypo::Flush()
3418 // as creation of 1D hyp was written later then it's edition,
3419 // we need to find all it's edition calls and process them
3420 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3422 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3424 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3425 if ( hyp1dID.IsEmpty() ) continue;
3427 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3429 // make a new name for 1D hyp = "HypType" + "_Distribution"
3431 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3433 if ( prevNewName.IsEmpty() ) continue;
3434 newName = prevNewName;
3438 if ( hyp1d->IsWrapped() ) {
3439 newName = hyp1d->GetCreationCmd()->GetMethod();
3442 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3443 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3445 newName += "_Distribution";
3446 prevNewName = newName;
3448 hyp1d->GetCreationCmd()->SetResultValue( newName );
3450 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3451 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3452 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3453 const _pyID& objID = (*cmdIt)->GetObject();
3454 if ( objID == hyp1dID ) {
3455 if ( !hyp1d.IsNull() )
3457 hyp1d->Process( *cmdIt );
3458 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3460 ( *cmdIt )->SetObject( newName );
3463 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3464 (*cmd)->SetArg( 1, newName );
3468 //================================================================================
3470 * \brief additionally to Addition2Creation, clears SetDistrType() command
3471 * \param theCmd - AddHypothesis() command
3472 * \param theMesh - mesh to which a hypothesis is added
3473 * \retval bool - conversion result
3475 //================================================================================
3477 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3478 const _pyID& theMesh)
3480 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3481 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3482 bool scaleDistrType = false;
3483 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3484 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3485 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3486 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3487 scaleDistrType = true;
3490 else if ( !scaleDistrType ) {
3491 // distribution type changed: remove scale factor from args
3492 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3493 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3495 CreationMethod& crMethod = type2meth->second;
3496 if ( crMethod.myArgs.size() == 2 )
3497 crMethod.myArgs.pop_back();
3504 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3507 //================================================================================
3509 * \brief remove repeated commands defining distribution
3511 //================================================================================
3513 void _pyNumberOfSegmentsHyp::Flush()
3515 // find number of the last SetDistrType() command
3516 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3517 int distrTypeNb = 0;
3518 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3519 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3520 if ( cmd != myUnusedCommands.rbegin() )
3521 distrTypeNb = (*cmd)->GetOrderNb();
3523 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3526 // clear commands before the last SetDistrType()
3527 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3528 set< int > treatedCmdNbs; // avoid treating same cmd twice
3529 for ( int i = 0; i < 2; ++i ) {
3530 set<TCollection_AsciiString> uniqueMethods;
3531 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3532 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3534 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3535 continue;// avoid treating same cmd twice
3536 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3537 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3538 if ( !clear || method == "SetNumberOfSegments" ) {
3539 bool isNewInSet = uniqueMethods.insert( method ).second;
3540 clear = !isNewInSet;
3549 //================================================================================
3551 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3552 * into regular1D.LengthNearVertex( length, vertex )
3553 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3554 * \param theMesh - The mesh needing this hypo
3555 * \retval bool - false if the command can't be converted
3557 //================================================================================
3559 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3560 const _pyID& theMeshID)
3562 if ( IsWrappable( theMeshID )) {
3564 _pyID vertex = theCmd->GetArg( 1 );
3566 // the problem here is that segment algo can be not found
3567 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3568 // geometry where segment algorithm is assigned
3569 _pyID geom = vertex;
3570 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3571 while ( algo.IsNull() && !geom.IsEmpty()) {
3572 // try to find geom as a father of <vertex>
3573 geom = FatherID( geom );
3574 algo = theGen->FindAlgo( geom, theMeshID, this );
3576 if ( algo.IsNull() || geom.IsEmpty() )
3577 return false; // also possible to find geom as brother of veretex...
3579 // set geom instead of vertex
3580 theCmd->SetArg( 1, geom );
3582 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3583 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3584 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3586 // set vertex as a second arg
3587 theCmd->SetArg( 2, vertex );
3595 //================================================================================
3597 * \brief _pyAlgorithm constructor
3598 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3600 //================================================================================
3602 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3603 : _pyHypothesis( theCreationCmd )
3608 //================================================================================
3610 * \brief Convert the command adding an algorithm to mesh
3611 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3612 * \param theMesh - The mesh needing this algo
3613 * \retval bool - false if the command can't be converted
3615 //================================================================================
3617 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3618 const _pyID& theMeshID)
3620 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3621 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3622 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3628 //================================================================================
3630 * \brief Return starting position of a part of python command
3631 * \param thePartIndex - The index of command part
3632 * \retval int - Part position
3634 //================================================================================
3636 int _pyCommand::GetBegPos( int thePartIndex ) const
3640 if ( myBegPos.Length() < thePartIndex )
3642 ASSERT( thePartIndex > 0 );
3643 return myBegPos( thePartIndex );
3646 //================================================================================
3648 * \brief Store starting position of a part of python command
3649 * \param thePartIndex - The index of command part
3650 * \param thePosition - Part position
3652 //================================================================================
3654 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3656 while ( myBegPos.Length() < thePartIndex )
3657 myBegPos.Append( UNKNOWN );
3658 ASSERT( thePartIndex > 0 );
3659 myBegPos( thePartIndex ) = thePosition;
3662 //================================================================================
3664 * \brief Returns whitespace symbols at the line beginning
3665 * \retval TCollection_AsciiString - result
3667 //================================================================================
3669 TCollection_AsciiString _pyCommand::GetIndentation()
3672 //while ( end <= Length() && isblank( myString.Value( end )))
3673 //ANA: isblank() function isn't provided in VC2010 compiler
3674 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3676 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3679 //================================================================================
3681 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3682 * \retval const TCollection_AsciiString & - ResultValue substring
3684 //================================================================================
3686 const TCollection_AsciiString & _pyCommand::GetResultValue()
3688 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3690 SetBegPos( RESULT_IND, EMPTY );
3691 int begPos, endPos = myString.Location( "=", 1, Length() );
3695 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3696 if ( begPos < endPos )
3698 SetBegPos( RESULT_IND, begPos );
3700 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3701 myRes = myString.SubString( begPos, endPos );
3708 //================================================================================
3710 * \brief Return number of python command result value ResultValue = Obj.Meth()
3712 //================================================================================
3714 int _pyCommand::GetNbResultValues()
3717 return myResults.Length();
3721 //================================================================================
3723 * \brief Return substring of python command looking like
3724 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3725 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3727 //================================================================================
3728 const _AString& _pyCommand::GetResultValue(int res)
3730 if ( GetResultValue().IsEmpty() )
3731 return theEmptyString;
3733 if ( myResults.IsEmpty() )
3736 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3737 ++begPos; // skip [, else the whole list is returned
3738 while ( begPos < myRes.Length() ) {
3739 _AString result = GetWord( myRes, begPos, true );
3740 begPos += result.Length();
3742 // result.RemoveAll('[');
3743 // result.RemoveAll(']');
3748 myResults.Append( result );
3751 if ( res > 0 && res <= myResults.Length() )
3752 return myResults( res );
3753 return theEmptyString;
3756 //================================================================================
3758 * \brief Return substring of python command looking like ResVal = Object.Meth()
3759 * \retval const TCollection_AsciiString & - Object substring
3761 //================================================================================
3763 const TCollection_AsciiString & _pyCommand::GetObject()
3765 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3768 int begPos = GetBegPos( RESULT_IND );
3770 begPos = myString.Location( "=", 1, Length() ) + 1;
3771 // is '=' in the string argument (for example, name) or not
3772 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3773 for ( int i = 1; i < begPos-1; i++ )
3774 switch ( myString.Value( i )) {
3775 case '\'': nb[0]++; break;
3776 case '"' : nb[1]++; break;
3777 case '(' : nb[2]++; break;
3778 case ')' : nb[3]++; break;
3780 // if = is inside a string or a list
3781 // then get an object at the start of the command
3782 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3786 begPos += myRes.Length();
3788 myObj = GetWord( myString, begPos, true );
3789 if ( begPos != EMPTY )
3791 // check if object is complex,
3792 // so far consider case like "smesh.Method()"
3793 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3794 //if ( bracketPos==0 ) bracketPos = Length();
3795 int dotPos = begPos+myObj.Length();
3796 while ( dotPos+1 < bracketPos ) {
3797 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3802 if ( dotPos > begPos+myObj.Length() )
3803 myObj = myString.SubString( begPos, dotPos-1 );
3806 // 1st word after '=' is an object
3807 // else // no method -> no object
3813 SetBegPos( OBJECT_IND, begPos );
3819 //================================================================================
3821 * \brief Return substring of python command looking like ResVal = Obj.Method()
3822 * \retval const TCollection_AsciiString & - Method substring
3824 //================================================================================
3826 const TCollection_AsciiString & _pyCommand::GetMethod()
3828 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3831 int begPos = GetBegPos( OBJECT_IND );
3832 bool forward = true;
3834 begPos = myString.Location( "(", 1, Length() ) - 1;
3838 begPos += myObj.Length();
3841 myMeth = GetWord( myString, begPos, forward );
3842 SetBegPos( METHOD_IND, begPos );
3848 //================================================================================
3850 * \brief Returns true if there are brackets after the method
3852 //================================================================================
3854 bool _pyCommand::IsMethodCall()
3856 if ( GetMethod().IsEmpty() )
3858 if ( myString.StartsWith("#") )
3860 if ( myString.StartsWith("SHAPERSTUDY") ) // skip shaperstudy specific dump string analysis
3862 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3863 return ( s[0] == '(' || s[1] == '(' );
3866 //================================================================================
3868 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3869 * \retval const TCollection_AsciiString & - Arg<index> substring
3871 //================================================================================
3873 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3875 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3879 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3881 pos = myString.Location( "(", 1, Length() );
3885 // we are at or before '(', skip it if present
3887 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3888 if ( pos > Length() )
3892 SetBegPos( ARG1_IND, 0 ); // even no '('
3893 return theEmptyString;
3897 list< TCollection_AsciiString > separatorStack( 1, ",)");
3898 bool ignoreNesting = false;
3900 while ( pos <= Length() )
3902 const char chr = myString.Value( pos );
3904 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3906 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3908 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3910 TCollection_AsciiString arg;
3911 if ( pos-1 >= prevPos ) {
3912 arg = myString.SubString( prevPos, pos-1 );
3913 arg.RightAdjust(); // remove spaces
3916 if ( !arg.IsEmpty() || chr == ',' )
3918 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3919 myArgs.Append( arg );
3925 else // end of nesting args found
3927 separatorStack.pop_back();
3928 ignoreNesting = false;
3931 else if ( !ignoreNesting )
3934 case '(' : separatorStack.push_back(")"); break;
3935 case '[' : separatorStack.push_back("]"); break;
3936 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3937 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3944 if ( myArgs.Length() < index )
3945 return theEmptyString;
3946 return myArgs( index );
3949 //================================================================================
3951 * \brief Return position where arguments begin
3953 //================================================================================
3955 int _pyCommand::GetArgBeginning() const
3957 int pos = GetBegPos( ARG1_IND );
3958 if ( pos == UNKNOWN )
3960 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3961 if ( pos < 1 && Length() >= 4 )
3962 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3967 //================================================================================
3969 * \brief Check if char is a word part
3970 * \param c - The character to check
3971 * \retval bool - The check result
3973 //================================================================================
3975 static inline bool isWord(const char c, const bool dotIsWord)
3978 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3981 //================================================================================
3983 * \brief Looks for a word in the string and returns word's beginning
3984 * \param theString - The input string
3985 * \param theStartPos - The position to start the search, returning word's beginning
3986 * \param theForward - The search direction
3987 * \retval TCollection_AsciiString - The found word
3989 //================================================================================
3991 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3993 const bool theForward,
3994 const bool dotIsWord )
3996 int beg = theStartPos, end = theStartPos;
3997 theStartPos = EMPTY;
3998 if ( beg < 1 || beg > theString.Length() )
3999 return theEmptyString;
4001 if ( theForward ) { // search forward
4003 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
4005 if ( beg > theString.Length() )
4006 return theEmptyString; // no word found
4009 char begChar = theString.Value( beg );
4010 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
4011 char endChar = ( begChar == '[' ) ? ']' : begChar;
4012 // end is at the corresponding quoting mark or bracket
4013 while ( end < theString.Length() &&
4014 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
4018 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
4023 else { // search backward
4025 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
4028 return theEmptyString; // no word found
4030 char endChar = theString.Value( end );
4031 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
4032 char begChar = ( endChar == ']' ) ? '[' : endChar;
4033 // beg is at the corresponding quoting mark
4035 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
4039 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4045 //cout << theString << " ---- " << beg << " - " << end << endl;
4046 if ( end > theString.Length() )
4048 theStartPos = EMPTY;
4049 return theEmptyString;
4051 return theString.SubString( beg, end );
4054 //================================================================================
4056 * \brief Returns true if the string looks like a study entry
4058 //================================================================================
4060 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4062 if ( str.Length() < 5 ) return false;
4064 int nbColons = 0, isColon;
4065 for ( int i = 1; i <= str.Length(); ++i )
4067 char c = str.Value(i);
4068 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4070 nbColons += isColon;
4072 return nbColons > 2 && str.Length()-nbColons > 2;
4075 //================================================================================
4077 * \brief Returns true if the string looks like an object ID but not like a list,
4078 * string, command etc.
4080 //================================================================================
4082 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4084 if ( str.Length() < 1 ) return false;
4086 const char* s = str.ToCString();
4088 for ( int i = 0; i < str.Length(); ++i )
4089 if ( !IsIDChar( s[i] ))
4095 //================================================================================
4097 * \brief Finds entries in a string
4099 //================================================================================
4101 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4103 std::list< _pyID > resList;
4105 while ( ++pos <= str.Length() )
4107 if ( !isdigit( str.Value( pos ))) continue;
4108 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4111 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4112 _pyID entry = str.SubString( pos, end-1 );
4114 if ( IsStudyEntry( entry ))
4115 resList.push_back( entry );
4120 //================================================================================
4122 * \brief Look for position where not space char is
4123 * \param theString - The string
4124 * \param thePos - The position to search from and which returns result
4125 * \retval bool - false if there are only space after thePos in theString
4127 //================================================================================
4129 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4131 if ( thePos < 1 || thePos > theString.Length() )
4134 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4137 return thePos <= theString.Length();
4140 //================================================================================
4142 * \brief Modify a part of the command
4143 * \param thePartIndex - The index of the part
4144 * \param thePart - The new part string
4145 * \param theOldPart - The old part
4147 //================================================================================
4149 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4150 TCollection_AsciiString& theOldPart)
4152 int pos = GetBegPos( thePartIndex );
4153 if ( pos <= Length() && theOldPart != thePart)
4155 TCollection_AsciiString seperator;
4157 pos = GetBegPos( thePartIndex + 1 );
4158 if ( pos < 1 ) return;
4159 switch ( thePartIndex ) {
4160 case RESULT_IND: seperator = " = "; break;
4161 case OBJECT_IND: seperator = "."; break;
4162 case METHOD_IND: seperator = "()"; break;
4166 myString.Remove( pos, theOldPart.Length() );
4167 if ( !seperator.IsEmpty() )
4168 myString.Insert( pos , seperator );
4169 myString.Insert( pos, thePart );
4170 // update starting positions of the following parts
4171 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4172 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4173 if ( myBegPos( i ) > 0 )
4174 myBegPos( i ) += posDelta;
4176 theOldPart = thePart;
4180 //================================================================================
4182 * \brief Set argument
4183 * \param index - The argument index, it counts from 1
4184 * \param theArg - The argument string
4186 //================================================================================
4188 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4191 int argInd = ARG1_IND + index - 1;
4192 int pos = GetBegPos( argInd );
4193 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4195 // find a closing parenthesis
4196 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4197 int lastArgInd = GetNbArgs();
4198 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4199 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4204 while ( pos > 0 && myString.Value( pos ) != ')' )
4207 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4211 while ( myArgs.Length() < index ) {
4212 if ( myArgs.Length() )
4213 myString.Insert( pos++, "," );
4214 myArgs.Append("None");
4215 myString.Insert( pos, myArgs.Last() );
4216 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4217 pos += myArgs.Last().Length();
4220 SetPart( argInd, theArg, myArgs( index ));
4223 //================================================================================
4225 * \brief Empty arg list
4227 //================================================================================
4229 void _pyCommand::RemoveArgs()
4231 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4232 myString.Trunc( pos );
4235 if ( myBegPos.Length() >= ARG1_IND )
4236 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4239 //================================================================================
4241 * \brief Comment a python command
4243 //================================================================================
4245 void _pyCommand::Comment()
4247 if ( IsEmpty() ) return;
4250 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4251 if ( i <= Length() )
4253 myString.Insert( i, "#" );
4254 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4256 int begPos = GetBegPos( iPart );
4257 if ( begPos != UNKNOWN && begPos != EMPTY )
4258 SetBegPos( iPart, begPos + 1 );
4263 //================================================================================
4265 * \brief Set dependent commands after this one
4267 //================================================================================
4269 bool _pyCommand::SetDependentCmdsAfter() const
4271 bool orderChanged = false;
4272 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4273 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4274 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4275 orderChanged = true;
4276 theGen->SetCommandAfter( *cmd, this );
4277 (*cmd)->SetDependentCmdsAfter();
4280 return orderChanged;
4282 //================================================================================
4284 * \brief Insert accessor method after theObjectID
4285 * \param theObjectID - id of the accessed object
4286 * \param theAcsMethod - name of the method giving access to the object
4287 * \retval bool - false if theObjectID is not found in the command string
4289 //================================================================================
4291 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4293 if ( !theAcsMethod )
4295 // start object search from the object, i.e. ignore result
4297 int beg = GetBegPos( OBJECT_IND );
4298 if ( beg < 1 || beg > Length() )
4301 while (( beg = myString.Location( theObjectID, beg, Length() )))
4303 // check that theObjectID is not just a part of a longer ID
4304 int afterEnd = beg + theObjectID.Length();
4305 Standard_Character c = myString.Value( afterEnd );
4306 if ( !IsIDChar( c ))
4308 // check if accessor method already present
4310 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4312 int oldLen = Length();
4313 myString.Insert( afterEnd, (char*) theAcsMethod );
4314 myString.Insert( afterEnd, "." );
4315 // update starting positions of the parts following the modified one
4316 int posDelta = Length() - oldLen;
4317 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4318 if ( myBegPos( i ) > afterEnd )
4319 myBegPos( i ) += posDelta;
4324 beg = afterEnd; // is a part -> next search
4329 //================================================================================
4331 * \brief Creates pyObject
4333 //================================================================================
4335 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4336 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4341 //================================================================================
4343 * \brief Set up myID and myIsPublished
4345 //================================================================================
4347 void _pyObject::setID(const _pyID& theID)
4350 myIsPublished = !theGen->IsNotPublished( GetID() );
4353 //================================================================================
4355 * \brief Clear myCreationCmd and myProcessedCmds
4357 //================================================================================
4359 void _pyObject::ClearCommands()
4364 if ( !myCreationCmd.IsNull() )
4365 myCreationCmd->Clear();
4367 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4368 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4372 //================================================================================
4374 * \brief Return method name giving access to an interaface object wrapped by python class
4375 * \retval const char* - method name
4377 //================================================================================
4379 const char* _pyObject::AccessorMethod() const
4383 //================================================================================
4385 * \brief Return ID of a father
4387 //================================================================================
4389 _pyID _pyObject::FatherID(const _pyID & childID)
4391 int colPos = childID.SearchFromEnd(':');
4393 return childID.SubString( 1, colPos-1 );
4397 //================================================================================
4399 * \brief SelfEraser erases creation command if none of it's commands invoked
4400 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4402 //================================================================================
4404 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4405 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4407 myIsPublished = true; // prevent clearing as a not published
4408 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4411 //================================================================================
4413 * \brief SelfEraser erases creation command if none of it's commands invoked
4414 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4416 //================================================================================
4418 bool _pySelfEraser::CanClear()
4420 bool toErase = false;
4421 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4424 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4425 for ( ; cmd != myArgCmds.end(); ++cmd )
4426 nbArgUses += IsAliveCmd( *cmd );
4428 toErase = ( nbArgUses < 1 );
4433 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4434 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4435 for ( ; cmd != cmds.end(); )
4436 // check of cmd emptiness is not enough as object can change
4437 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4440 cmd = cmds.erase( cmd ); // save the cmd from clearing
4442 toErase = ( nbCalls < 1 );
4447 //================================================================================
4449 * \brief Check if a command is or can be cleared
4451 //================================================================================
4453 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4455 if ( theCmd->IsEmpty() )
4458 if ( !theGen->IsToKeepAllCommands() )
4460 const _pyID& objID = theCmd->GetObject();
4461 Handle( _pyObject ) obj = theGen->FindObject( objID );
4462 if ( !obj.IsNull() )
4463 return !obj->CanClear();
4468 //================================================================================
4470 * \brief SelfEraser erases creation command if none of it's commands invoked
4471 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4473 //================================================================================
4475 void _pySelfEraser::Flush()
4479 myIsPublished = false;
4480 _pyObject::ClearCommands();
4484 //================================================================================
4486 * \brief _pySubMesh constructor
4488 //================================================================================
4490 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4491 _pyObject(theCreationCmd)
4493 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4494 if ( toKeepAgrCmds )
4495 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4498 //================================================================================
4500 * \brief Return true if a sub-mesh can be used as argument of the given method
4502 //================================================================================
4504 bool _pySubMesh::CanBeArgOfMethod(const _AString& /*theMethodName*/)
4507 // names of all methods where a sub-mesh can be used as argument
4508 // static TStringSet methods;
4509 // if ( methods.empty() ) {
4510 // const char * names[] = {
4511 // // methods of SMESH_Gen
4513 // // methods of SMESH_Group
4515 // // methods of SMESH_Measurements
4517 // // methods of SMESH_Mesh
4518 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4520 // // methods of SMESH_MeshEditor
4521 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4522 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4523 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4524 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4525 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4526 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4527 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4528 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4529 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4530 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4531 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4532 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4533 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4534 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4535 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4536 // "" }; // <- mark of end
4537 // methods.Insert( names );
4539 // return methods.Contains( theMethodName );
4542 //================================================================================
4544 * \brief count invoked commands
4546 //================================================================================
4548 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4550 _pyObject::Process(theCommand); // count calls of Process()
4553 //================================================================================
4555 * \brief Move creation command depending on invoked commands
4557 //================================================================================
4559 void _pySubMesh::Flush()
4561 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4562 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4563 else if ( !myCreator.IsNull() )
4564 // move to be just after creator
4565 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4567 // move sub-mesh usage after creation cmd
4568 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4569 for ( ; cmd != myArgCmds.end(); ++cmd )
4570 if ( !(*cmd)->IsEmpty() )
4571 GetCreationCmd()->AddDependantCmd( *cmd );
4574 //================================================================================
4576 * \brief Creates _pyGroup
4578 //================================================================================
4580 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4581 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4583 if ( !id.IsEmpty() )
4586 myCanClearCreationCmd = true;
4588 const _AString& method = theCreationCmd->GetMethod();
4589 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4591 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4593 // ----------------------------------------------------------------------
4594 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4596 _pyID geom = theCreationCmd->GetArg( 3 );
4597 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4598 // next if(){...} section is commented
4599 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4600 // theCreationCmd->SetMethod( "Group" );
4601 // theCreationCmd->RemoveArgs();
4602 // theCreationCmd->SetArg( 1, geom );
4605 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4606 _pyID type = theCreationCmd->GetArg( 1 );
4607 _pyID name = theCreationCmd->GetArg( 2 );
4608 theCreationCmd->SetMethod( "GroupOnGeom" );
4609 theCreationCmd->RemoveArgs();
4610 theCreationCmd->SetArg( 1, geom );
4611 theCreationCmd->SetArg( 2, name );
4612 theCreationCmd->SetArg( 3, type );
4615 else if ( method == "CreateGroupFromFilter" )
4617 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4618 theCreationCmd->SetMethod( "GroupOnFilter" );
4620 _pyID filterID = theCreationCmd->GetArg(3);
4621 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4622 if ( !filter.IsNull())
4624 if ( !filter->GetNewID().IsEmpty() )
4625 theCreationCmd->SetArg( 3, filter->GetNewID() );
4626 //filter->AddUser( this );
4630 else if ( method == "GetGroups" )
4632 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4636 // theCreationCmd does something else apart from creation of this group
4637 // and thus it can't be cleared if this group is removed
4638 myCanClearCreationCmd = false;
4642 //================================================================================
4644 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4647 //================================================================================
4649 bool _pyGroup::CanClear()
4654 if ( !myCanClearCreationCmd &&
4655 !myCreationCmd.IsNull() &&
4656 myCreationCmd->GetMethod() == "GetGroups" )
4658 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4659 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4660 list< _pyID >::iterator grID = idList.begin();
4661 if ( GetID() == *grID )
4663 myCanClearCreationCmd = true;
4664 list< Handle(_pyGroup ) > groups;
4665 for ( ; grID != idList.end(); ++grID )
4667 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4668 if ( group.IsNull() ) continue;
4669 groups.push_back( group );
4670 if ( group->IsInStudy() )
4671 myCanClearCreationCmd = false;
4673 // set myCanClearCreationCmd == true to all groups
4674 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4675 for ( ; group != groups.end(); ++group )
4676 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4680 return myCanClearCreationCmd;
4683 //================================================================================
4685 * \brief set myCanClearCreationCmd = true if the main action of the creation
4686 * command is discarded
4688 //================================================================================
4690 void _pyGroup::RemovedWithContents()
4692 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4693 // via a created group
4694 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4695 // myCanClearCreationCmd = true;
4698 //================================================================================
4700 * \brief To convert creation of a group by filter
4702 //================================================================================
4704 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4706 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4707 // group = mesh.CreateEmptyGroup( elemType, groupName )
4708 // aFilter.SetMesh(mesh)
4709 // nbAdd = group.AddFrom( aFilter )
4710 Handle(_pyFilter) filter;
4711 if ( theCommand->GetMethod() == "AddFrom" )
4713 _pyID idSource = theCommand->GetArg(1);
4714 // check if idSource is a filter
4715 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4716 if ( !filter.IsNull() )
4718 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4719 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4720 while ( *cmdIt != theCommand ) ++cmdIt;
4721 while ( (*cmdIt)->GetOrderNb() != 1 )
4723 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4724 if ((setMeshCmd->GetObject() == idSource ||
4725 setMeshCmd->GetObject() == filter->GetNewID() )
4727 setMeshCmd->GetMethod() == "SetMesh")
4729 setMeshCmd->Clear();
4733 // replace 3 commands by one
4734 theCommand->Clear();
4735 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4736 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4737 if ( !filter->GetNewID().IsEmpty() )
4738 idSource = filter->GetNewID();
4739 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4740 makeGroupCmd->SetArg( 1, name );
4741 makeGroupCmd->SetArg( 2, idSource );
4742 filter->AddArgCmd( makeGroupCmd );
4745 else if ( theCommand->GetMethod() == "SetFilter" )
4747 // set new name of a filter or clear the command if the same filter is set
4748 _pyID filterID = theCommand->GetArg(1);
4749 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4750 if ( !myFilter.IsNull() && filter == myFilter )
4751 theCommand->Clear();
4752 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4753 theCommand->SetArg( 1, filter->GetNewID() );
4756 else if ( theCommand->GetMethod() == "GetFilter" )
4758 // GetFilter() returns a filter with other ID, make myFilter process
4759 // calls of the returned filter
4760 if ( !myFilter.IsNull() )
4762 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4763 theCommand->Clear();
4767 // if ( !filter.IsNull() )
4768 // filter->AddUser( this );
4770 theGen->AddMeshAccessorMethod( theCommand );
4773 //================================================================================
4775 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4777 //================================================================================
4779 void _pyGroup::Flush()
4781 if ( !theGen->IsToKeepAllCommands() &&
4782 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4784 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4788 //================================================================================
4790 * \brief Constructor of _pyFilter
4792 //================================================================================
4794 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4795 :_pyObject(theCreationCmd), myNewID( newID )
4797 //myIsPublished = true; // prevent clearing as a not published
4798 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4801 //================================================================================
4803 * \brief To convert creation of a filter by criteria and
4804 * to replace an old name by a new one
4806 //================================================================================
4808 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4810 if ( theCommand->GetObject() == GetID() )
4811 _pyObject::Process(theCommand); // count commands
4813 if ( !myNewID.IsEmpty() )
4814 theCommand->SetObject( myNewID );
4816 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4817 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4818 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4819 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4820 theCommand->GetMethod() == "SetCriteria")
4822 // aFilter.SetCriteria(aCriteria) ->
4823 // aFilter = smesh.GetFilterFromCriteria(criteria)
4824 if ( myNewID.IsEmpty() )
4825 theCommand->SetResultValue( GetID() );
4827 theCommand->SetResultValue( myNewID );
4828 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4829 theCommand->SetMethod( "GetFilterFromCriteria" );
4831 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4832 GetCreationCmd()->Clear();
4833 GetCreationCmd()->GetString() = theCommand->GetString();
4834 theCommand->Clear();
4835 theCommand->AddDependantCmd( GetCreationCmd() );
4836 // why swap? -- it's needed
4837 //GetCreationCmd()->Clear();
4839 else if ( theCommand->GetMethod() == "SetMesh" )
4841 if ( myMesh == theCommand->GetArg( 1 ))
4842 theCommand->Clear();
4844 myMesh = theCommand->GetArg( 1 );
4845 theGen->AddMeshAccessorMethod( theCommand );
4849 //================================================================================
4851 * \brief Set new filter name to the creation command and to myArgCmds
4853 //================================================================================
4855 void _pyFilter::Flush()
4857 if ( myNewID.IsEmpty() ) return;
4859 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4860 for ( ; cmd != myArgCmds.end(); ++cmd )
4861 if ( !(*cmd)->IsEmpty() )
4863 _AString cmdStr = (*cmd)->GetString();
4864 _AString id = GetID();
4865 int pos = cmdStr.Search( id );
4868 cmdStr.Remove( pos, id.Length() );
4869 cmdStr.Insert( pos, myNewID );
4872 (*cmd)->GetString() = cmdStr;
4875 if ( !GetCreationCmd()->IsEmpty() )
4876 GetCreationCmd()->SetResultValue( myNewID );
4879 //================================================================================
4881 * \brief Return true if all my users can be cleared
4883 //================================================================================
4885 bool _pyObject::CanClear()
4887 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4888 for ( ; cmd != myArgCmds.end(); ++cmd )
4889 if ( !(*cmd)->IsEmpty() )
4891 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4892 if ( !obj.IsNull() && !obj->CanClear() )
4895 return ( !myIsPublished );
4898 //================================================================================
4900 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4902 //================================================================================
4904 _pyHypothesisReader::_pyHypothesisReader()
4907 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4908 LDOMParser xmlParser;
4909 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4911 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4915 INFOS( xmlParser.GetError(data) );
4918 // <algorithm type="Regular_1D"
4919 // label-id="Wire discretisation"
4922 // <algo>Regular_1D=Segment()</algo>
4923 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4925 LDOM_Document xmlDoc = xmlParser.getDocument();
4926 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4927 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4929 LDOM_Node algoNode = algoNodeList.item( i );
4930 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4931 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4932 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4934 _AString text, algoType, method, arg;
4935 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4937 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4938 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4939 text = textNode.getNodeValue();
4940 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4941 algoType = algoCmd->GetResultValue();
4942 method = algoCmd->GetMethod();
4943 arg = algoCmd->GetArg(1);
4944 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4946 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4947 algo->SetConvMethodAndType( method, algoType );
4948 if ( !arg.IsEmpty() )
4949 algo->setCreationArg( 1, arg );
4951 myType2Hyp[ algoType ] = algo;
4955 if ( algoType.IsEmpty() ) continue;
4957 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4959 Handle( _pyHypothesis ) hyp;
4960 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4962 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4963 LDOM_Node textNode = pyHypoNode.getFirstChild();
4964 text = textNode.getNodeValue();
4965 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4966 hypType = hypoCmd->GetResultValue();
4967 method = hypoCmd->GetMethod();
4968 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4970 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4971 if ( type2hyp == myType2Hyp.end() )
4972 hyp = new _pyHypothesis( hypoCmd );
4974 hyp = type2hyp->second;
4975 hyp->SetConvMethodAndType( method, algoType );
4976 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4978 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4979 _AString argMethod = argCmd.GetMethod();
4980 _AString argNbText = argCmd.GetArg( 1 );
4981 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4982 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4984 hyp->AddArgMethod( argMethod,
4985 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4987 myType2Hyp[ hypType ] = hyp;
4991 // <hypothesis type="BLSURF_Parameters"
4995 // <accumulative-methods>
4996 // SetEnforcedVertex,
4997 // SetEnforcedVertexNamed
4998 // </accumulative-methods>
5002 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
5003 for ( int i = 0; i < hypNodeList.getLength(); ++i )
5005 LDOM_Node hypNode = hypNodeList.item( i );
5006 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
5007 _AString hypType = hypElem.getAttribute("type");
5008 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
5009 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
5011 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5012 if ( type2hyp == myType2Hyp.end() ) continue;
5014 LDOM_Node methNode = methNodeList.item( 0 );
5015 LDOM_Node textNode = methNode.getFirstChild();
5016 _AString text = textNode.getNodeValue();
5020 method = _pyCommand::GetWord( text, pos, /*forward= */true );
5021 pos += method.Length();
5022 type2hyp->second->AddAccumulativeMethod( method );
5024 while ( !method.IsEmpty() );
5027 } // loop on xmlPaths
5030 //================================================================================
5032 * \brief Returns a new hypothesis initialized according to the read information
5034 //================================================================================
5036 Handle(_pyHypothesis)
5037 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
5038 const Handle(_pyCommand)& creationCmd) const
5040 Handle(_pyHypothesis) resHyp, sampleHyp;
5042 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5043 if ( type2hyp != myType2Hyp.end() )
5044 sampleHyp = type2hyp->second;
5046 if ( sampleHyp.IsNull() )
5048 resHyp = new _pyHypothesis(creationCmd);
5052 if ( sampleHyp->IsAlgo() )
5053 resHyp = new _pyAlgorithm( creationCmd );
5055 resHyp = new _pyHypothesis(creationCmd);
5056 resHyp->Assign( sampleHyp, _pyID() );
5061 //================================================================================
5063 * \brief Adds an object ID to some family of IDs with a common prefix
5064 * \param [in] str - the object ID
5065 * \return bool - \c false if \a str does not have the same prefix as \a this family
5066 * (for internal usage)
5068 //================================================================================
5070 bool _pyStringFamily::Add( const char* str )
5072 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5073 return false; // expected prefix is missing
5075 str += _prefix.Length(); // skip _prefix
5077 // try to add to some of child falimies
5078 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5079 for ( ; itSub != _subFams.end(); ++itSub )
5080 if ( itSub->Add( str ))
5083 // no suitable family found - add str to _strings or create a new child family
5085 // look for a proper place within sorted _strings
5086 std::list< _AString >::iterator itStr = _strings.begin();
5087 while ( itStr != _strings.end() && itStr->IsLess( str ))
5089 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5090 return true; // same ID already kept
5092 const int minPrefixSize = 4;
5094 // count "smaller" strings with the same prefix
5096 std::list< _AString >::iterator itLess = itStr;
5097 while ( itLess != _strings.begin() )
5100 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5108 // itLess points to the 1st string with same prefix
5110 // count "greater" strings with the same prefix
5112 std::list< _AString >::iterator itMore = itStr;
5113 for ( ; itMore != _strings.end(); ++itMore )
5114 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5118 // itMore points to the 1st string with greater prefix
5120 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5122 int prefixSize = minPrefixSize;
5123 _AString newPrefix ( str, prefixSize );
5125 // look for a proper place within _subFams sorted by _prefix
5126 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5127 if ( !itSub->_prefix.IsLess( newPrefix ))
5130 // add the new _pyStringFamily
5131 itSub = _subFams.insert( itSub, _pyStringFamily());
5132 _pyStringFamily& newSubFam = *itSub;
5133 newSubFam._prefix = newPrefix;
5135 // pass this->_strings to newSubFam._strings
5136 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5137 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5138 newSubFam._strings.push_back( str + prefixSize );
5139 for ( ; nbMore > 0; --nbMore, ++itStr )
5140 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5142 _strings.erase( itLess, itMore );
5144 else // too few string to make a family for them
5146 _strings.insert( itStr, str );
5151 //================================================================================
5153 * \brief Finds an object ID in the command
5154 * \param [in] longStr - the command string
5155 * \param [out] subStr - the found object ID
5156 * \return bool - \c true if the object ID found
5158 //================================================================================
5160 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5162 const _AString& longStr = cmd->GetString();
5163 const char* s = longStr.ToCString();
5166 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5167 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5168 if ( argBeg < 4 || argBeg > longStr.Length() )
5170 for ( ; itSub != _subFams.end(); ++itSub )
5173 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5174 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5176 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5177 from = pos + len + itSub->_prefix.Length();
5182 from += itSub->_prefix.Length();
5185 // look among _strings
5186 std::list< _AString >::iterator itStr = _strings.begin();
5187 for ( ; itStr != _strings.end(); ++itStr )
5188 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5189 // check that object ID does not continue after len
5190 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5192 subStr.push_back( *itStr );
5198 //================================================================================
5200 * \brief Return remainder length of the object ID after my _prefix
5201 * \param [in] str - remainder of the command after my _prefix
5202 * \return int - length of the object ID or -1 if not found
5204 //================================================================================
5206 int _pyStringFamily::isIn( const char* str )
5208 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5210 for ( ; itSub != _subFams.end(); ++itSub )
5212 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5215 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5216 return itSub->_prefix.Length() + len;
5221 if ( !_strings.empty() )
5223 std::list< _AString >::iterator itStr = _strings.begin();
5224 bool firstEmpty = itStr->IsEmpty();
5227 for ( ; itStr != _strings.end(); ++itStr )
5229 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5232 len = itStr->Length();
5241 // check that object ID does not continue after len
5242 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5249 //================================================================================
5253 //================================================================================
5255 void _pyStringFamily::Print( int level )
5257 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5258 std::list< _AString >::iterator itStr = _strings.begin();
5259 for ( ; itStr != _strings.end(); ++itStr )
5260 cout << *itStr << " | ";
5262 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5263 for ( ; itSub != _subFams.end(); ++itSub )
5264 itSub->Print( level + 1 );
5266 cout << string( 70, '-' ) << endl;