1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
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 <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
53 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
71 using SMESH::TPythonDump;
74 * \brief Container of commands into which the initial script is split.
75 * It also contains data corresponding to SMESH_Gen contents
77 static Handle(_pyGen) theGen;
79 static TCollection_AsciiString theEmptyString;
81 //#define DUMP_CONVERSION
83 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
84 #undef DUMP_CONVERSION
90 //================================================================================
92 * \brief Set of TCollection_AsciiString initialized by C array of C strings
94 //================================================================================
96 struct TStringSet: public set<TCollection_AsciiString>
99 * \brief Filling. The last string must be ""
101 void Insert(const char* names[]) {
102 for ( int i = 0; names[i][0] ; ++i )
103 insert( (char*) names[i] );
106 * \brief Check if a string is in
108 bool Contains(const TCollection_AsciiString& name ) {
109 return find( name ) != end();
113 //================================================================================
115 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
116 * Odd items of the C array are map keys, and even items are values
118 //================================================================================
120 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
123 * \brief Filling. The last string must be ""
125 void Insert(const char* names_values[]) {
126 for ( int i = 0; names_values[i][0] ; i += 2 )
127 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
130 * \brief Check if a string is in
132 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
133 map< _AString, _AString >::iterator it = find( name );
134 return it == end() ? "" : it->second;
138 //================================================================================
140 * \brief Returns a mesh by object
142 //================================================================================
144 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
148 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
149 return Handle(_pyMesh)::DownCast( obj );
150 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
151 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
152 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
153 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
155 return Handle(_pyMesh)();
158 //================================================================================
160 * \brief Check if objects used as args have been created by previous commands
162 //================================================================================
164 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
166 // either comment or erase a command including NotPublishedObjectName()
167 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
169 bool isResultPublished = false;
170 const int nbRes = cmd->GetNbResultValues();
171 for ( int i = 0; i < nbRes; i++ )
173 _pyID objID = cmd->GetResultValue( i+1 );
174 if ( cmd->IsStudyEntry( objID ))
175 isResultPublished = (! theGen->IsNotPublished( objID ));
176 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
178 if ( isResultPublished )
184 // check if an Object was created in the script
187 _pyID obj = cmd->GetObject();
188 if ( obj.Search( "print " ) == 1 )
189 return; // print statement
191 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
192 // remove an accessor method
193 obj = _pyCommand( obj ).GetObject();
195 const bool isMethodCall = cmd->IsMethodCall();
196 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
198 comment = "not created Object";
199 theGen->ObjectCreationRemoved( obj );
201 // check if a command has not created args
202 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
204 const _pyID& arg = cmd->GetArg( iArg );
205 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
207 list< _pyID > idList = cmd->GetStudyEntries( arg );
208 list< _pyID >::iterator id = idList.begin();
209 for ( ; id != idList.end(); ++id )
210 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
212 comment += *id + " has not been yet created";
215 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
216 // comment += arg + " has not been yet created";
218 // treat result objects
219 const _pyID& result = cmd->GetResultValue();
220 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
222 list< _pyID > idList = cmd->GetStudyEntries( result );
223 list< _pyID >::iterator id = idList.begin();
224 for ( ; id != idList.end(); ++id )
226 if ( comment.IsEmpty() )
227 presentObjects.insert( *id );
229 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
231 if ( idList.empty() && cmd->IsID( result ))
232 presentObjects.insert( result );
234 // comment the command
235 if ( !comment.IsEmpty() )
238 cmd->GetString() += " ### ";
239 cmd->GetString() += comment;
243 //================================================================================
245 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
247 //================================================================================
249 void fixFunctorType( TCollection_AsciiString& Type,
250 TCollection_AsciiString& Compare,
251 TCollection_AsciiString& UnaryOp,
252 TCollection_AsciiString& BinaryOp )
254 // The problem is that dumps of old studies created using filters becomes invalid
255 // when new items are inserted in the enum SMESH::FunctorType since values
256 // of this enum are dumped as integer values.
257 // This function corrects enum values of old studies given as args (Type,Compare,...)
258 // We can find out how to correct them by value of BinaryOp which can have only two
259 // values: FT_Undefined or FT_LogicalNOT.
260 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
261 // where PythonDump appeared
262 // v 3.0.0: FT_Undefined == 25
263 // v 3.1.0: FT_Undefined == 26, new items:
265 // v 4.1.2: FT_Undefined == 27, new items:
266 // - FT_BelongToGenSurface = 17
267 // v 5.1.1: FT_Undefined == 32, new items:
268 // - FT_FreeNodes = 10
269 // - FT_FreeFaces = 11
270 // - FT_LinearOrQuadratic = 23
271 // - FT_GroupColor = 24
272 // - FT_ElemGeomType = 25
273 // v 5.1.5: FT_Undefined == 33, new items:
274 // - FT_CoplanarFaces = 26
275 // v 6.2.0: FT_Undefined == 39, new items:
276 // - FT_MaxElementLength2D = 8
277 // - FT_MaxElementLength3D = 9
278 // - FT_BareBorderVolume = 25
279 // - FT_BareBorderFace = 26
280 // - FT_OverConstrainedVolume = 27
281 // - FT_OverConstrainedFace = 28
282 // v 6.5.0: FT_Undefined == 43, new items:
283 // - FT_EqualNodes = 14
284 // - FT_EqualEdges = 15
285 // - FT_EqualFaces = 16
286 // - FT_EqualVolumes = 17
287 // v 6.6.0: FT_Undefined == 44, new items:
288 // - FT_BallDiameter = 37
289 // v 6.7.1: FT_Undefined == 45, new items:
290 // - FT_EntityType = 36
291 // v 7.3.0: FT_Undefined == 46, new items:
292 // - FT_ConnectedElements = 39
293 // v 7.6.0: FT_Undefined == 47, new items:
294 // - FT_BelongToMeshGroup = 22
295 // v 8.1.0: FT_Undefined == 48, new items:
296 // - FT_NodeConnectivityNumber= 22
297 // v 8.5.0: FT_Undefined == 49, new items:
298 // - FT_Deflection2D = 22
300 // It's necessary to continue recording this history and to fill
301 // undef2newItems (see below) accordingly.
303 typedef map< int, vector< int > > TUndef2newItems;
304 static TUndef2newItems undef2newItems;
305 if ( undef2newItems.empty() )
307 undef2newItems[ 26 ].push_back( 7 );
308 undef2newItems[ 27 ].push_back( 17 );
309 { int items[] = { 10, 11, 23, 24, 25 };
310 undef2newItems[ 32 ].assign( items, items+5 ); }
311 undef2newItems[ 33 ].push_back( 26 );
312 { int items[] = { 8, 9, 25, 26, 27, 28 };
313 undef2newItems[ 39 ].assign( items, items+6 ); }
314 { int items[] = { 14, 15, 16, 17 };
315 undef2newItems[ 43 ].assign( items, items+4 ); }
316 undef2newItems[ 44 ].push_back( 37 );
317 undef2newItems[ 45 ].push_back( 36 );
318 undef2newItems[ 46 ].push_back( 39 );
319 undef2newItems[ 47 ].push_back( 22 );
320 undef2newItems[ 48 ].push_back( 22 );
321 undef2newItems[ 49 ].push_back( 22 );
323 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
326 int iType = Type.IntegerValue();
327 int iCompare = Compare.IntegerValue();
328 int iUnaryOp = UnaryOp.IntegerValue();
329 int iBinaryOp = BinaryOp.IntegerValue();
331 // find out integer value of FT_Undefined at the moment of dump
332 int oldUndefined = iBinaryOp;
333 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
336 // apply history to args
337 TUndef2newItems::const_iterator undef_items =
338 undef2newItems.upper_bound( oldUndefined );
339 if ( undef_items != undef2newItems.end() )
341 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
342 for ( ; undef_items != undef2newItems.end(); ++undef_items )
344 const vector< int > & addedItems = undef_items->second;
345 for ( size_t i = 0; i < addedItems.size(); ++i )
346 for ( int iArg = 0; iArg < 4; ++iArg )
348 int& arg = *pArg[iArg];
349 if ( arg >= addedItems[i] )
353 Type = TCollection_AsciiString( iType );
354 Compare = TCollection_AsciiString( iCompare );
355 UnaryOp = TCollection_AsciiString( iUnaryOp );
356 BinaryOp = TCollection_AsciiString( iBinaryOp );
360 //================================================================================
362 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
363 * arguments of a given command by a list "[x,y,z]" if the list is accesible
366 //================================================================================
368 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
370 static TStringSet methodsAcceptingList;
371 if ( methodsAcceptingList.empty() ) {
372 const char * methodNames[] = {
373 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
374 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
375 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
376 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
377 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
378 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
379 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
380 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
381 "Translate","TranslateMakeGroups","TranslateMakeMesh",
382 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
383 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
384 ,"" }; // <- mark of the end
385 methodsAcceptingList.Insert( methodNames );
387 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
389 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
391 const _AString & arg = theCommand->GetArg( i );
392 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
393 arg.Search( "SMESH.DirStruct" ) == 1 )
395 Handle(_pyCommand) workCmd = new _pyCommand( arg );
396 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
398 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
400 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
402 _AString newArg = "[ ";
403 newArg += ( workCmd->GetArg( 1 ) + ", " +
404 workCmd->GetArg( 2 ) + ", " +
405 workCmd->GetArg( 3 ) + " ]");
406 theCommand->SetArg( i, newArg );
412 //================================================================================
414 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
415 * a list "[id1,id2]" if the list is an accesible type of argument.
417 //================================================================================
419 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
421 static TStringSet methodsAcceptingList;
422 if ( methodsAcceptingList.empty() ) {
423 const char * methodNames[] = {
424 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
425 "ExportCGNS","ExportGMF",
426 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
427 "ScaleMakeGroups","Scale","ScaleMakeMesh",
428 "FindCoincidentNodesOnPartBut","DoubleElements",
429 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
430 ,"" }; // <- mark of the end
431 methodsAcceptingList.Insert( methodNames );
433 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
435 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
437 _pyCommand argCmd( theCommand->GetArg( i ));
438 if ( argCmd.GetMethod() == "GetIDSource" &&
439 argCmd.GetNbArgs() == 2 )
441 theCommand->SetArg( i, argCmd.GetArg( 1 ));
448 //================================================================================
450 * \brief Convert a python script using commands of smeshBuilder.py
451 * \param theScriptLines - Lines of the input script
452 * \param theEntry2AccessorMethod - returns method names to access to
453 * objects wrapped with python class
454 * \param theObjectNames - names of objects
455 * \param theRemovedObjIDs - entries of objects whose created commands were removed
456 * \param theHistoricalDump - true means to keep all commands, false means
457 * to exclude commands relating to objects removed from study
458 * \retval TCollection_AsciiString - Conversion result
460 //================================================================================
463 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
464 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
465 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
466 std::set< TCollection_AsciiString >& theRemovedObjIDs,
467 SALOMEDS::Study_ptr& theStudy,
468 const bool theToKeepAllCommands)
470 std::list< TCollection_AsciiString >::iterator lineIt;
471 // process notebook variables
473 SMESH_NoteBook aNoteBook;
475 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
476 aNoteBook.AddCommand( *lineIt );
478 theScriptLines.clear();
480 aNoteBook.ReplaceVariables();
482 aNoteBook.GetResultLines( theScriptLines );
485 // convert to smeshBuilder.py API
487 theGen = new _pyGen( theEntry2AccessorMethod,
491 theToKeepAllCommands );
493 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
494 theGen->AddCommand( *lineIt );
496 theScriptLines.clear();
500 #ifdef DUMP_CONVERSION
501 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
504 // clean commands of removed objects depending on myIsPublished flag
505 theGen->ClearCommands();
507 // reorder commands after conversion
508 list< Handle(_pyCommand) >::iterator cmd;
511 orderChanges = false;
512 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
513 if ( (*cmd)->SetDependentCmdsAfter() )
515 } while ( orderChanges );
517 // concat commands back into a script
518 TCollection_AsciiString aPrevCmd;
519 set<_pyID> createdObjects;
520 createdObjects.insert( "smeshBuilder" );
521 createdObjects.insert( "smesh" );
522 createdObjects.insert( "theStudy" );
523 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
525 #ifdef DUMP_CONVERSION
526 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
528 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
529 CheckObjectPresence( *cmd, createdObjects );
530 if ( !(*cmd)->IsEmpty() ) {
531 aPrevCmd = (*cmd)->GetString();
532 theScriptLines.push_back( aPrevCmd );
541 //================================================================================
543 * \brief _pyGen constructor
545 //================================================================================
547 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
548 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
549 std::set< TCollection_AsciiString >& theRemovedObjIDs,
550 SALOMEDS::Study_ptr& theStudy,
551 const bool theToKeepAllCommands)
552 : _pyObject( new _pyCommand( "", 0 )),
554 myID2AccessorMethod( theEntry2AccessorMethod ),
555 myObjectNames( theObjectNames ),
556 myRemovedObjIDs( theRemovedObjIDs ),
558 myToKeepAllCommands( theToKeepAllCommands ),
559 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
560 myGeomIDNb(0), myGeomIDIndex(-1)
562 // make that GetID() to return TPythonDump::SMESHGenName()
563 GetCreationCmd()->Clear();
564 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
565 GetCreationCmd()->GetString() += "=";
567 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
568 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
572 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
573 if ( geomComp->_is_nil() ) return;
574 CORBA::String_var entry = geomComp->GetID();
577 // find a SMESH entry
579 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
580 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
581 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
584 // find 1st difference between smeshID and geomID
585 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
586 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
587 if ( geomID.Value( i ) != smeshID.Value( i ))
589 myGeomIDNb = geomID.Value( i );
595 //================================================================================
597 * \brief name of SMESH_Gen in smeshBuilder.py
599 //================================================================================
601 const char* _pyGen::AccessorMethod() const
603 return SMESH_2smeshpy::GenName();
606 //================================================================================
608 * \brief Convert a command using a specific converter
609 * \param theCommand - the command to convert
611 //================================================================================
613 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
615 // store theCommand in the sequence
616 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
618 Handle(_pyCommand) aCommand = myCommands.back();
619 #ifdef DUMP_CONVERSION
620 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
623 const _pyID& objID = aCommand->GetObject();
625 if ( objID.IsEmpty() )
628 // Prevent moving a command creating a sub-mesh to the end of the script
629 // if the sub-mesh is used in theCommand as argument
630 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
632 // PlaceSubmeshAfterItsCreation( aCommand );
635 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
636 StructToList( aCommand );
638 const TCollection_AsciiString& method = aCommand->GetMethod();
640 // not to erase _pySelfEraser's etc. used as args in some commands
642 #ifdef USE_STRING_FAMILY
643 std::list<_pyID> objIDs;
644 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
646 std::list<_pyID>::iterator objID = objIDs.begin();
647 for ( ; objID != objIDs.end(); ++objID )
649 Handle(_pyObject) obj = FindObject( *objID );
652 obj->AddArgCmd( aCommand );
653 //cout << objID << " found in " << theCommand << endl;
658 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
659 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
660 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
662 Handle(_pyObject) obj = FindObject( *id );
664 obj->AddArgCmd( aCommand );
669 // Find an object to process theCommand
672 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
674 this->Process( aCommand );
675 //addFilterUser( aCommand, theGen ); // protect filters from clearing
679 // SMESH_Mesh method?
680 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
681 if ( id_mesh != myMeshes.end() )
683 //id_mesh->second->AddProcessedCmd( aCommand );
685 // Wrap Export*() into try-except
686 if ( aCommand->MethodStartsFrom("Export"))
689 _AString indent = aCommand->GetIndentation();
690 _AString tryStr = indent + "try:";
691 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
692 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
693 _AString excStr = indent + "except:";
694 _AString msgStr = indent + "\tprint '"; msgStr += method + "() failed. Invalid file name?'";
696 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
698 aCommand->GetString() = newCmd;
699 aCommand->SetOrderNb( ++myNbCommands );
700 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
701 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
702 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
704 // check for mesh editor object
705 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
706 _pyID editorID = aCommand->GetResultValue();
707 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
708 myMeshEditors.insert( make_pair( editorID, editor ));
711 // check for SubMesh objects
712 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
713 _pyID subMeshID = aCommand->GetResultValue();
714 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
715 AddObject( subMesh );
718 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
719 GetIDSourceToList( aCommand );
721 //addFilterUser( aCommand, theGen ); // protect filters from clearing
723 id_mesh->second->Process( aCommand );
724 id_mesh->second->AddProcessedCmd( aCommand );
728 // SMESH_MeshEditor method?
729 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
730 if ( id_editor != myMeshEditors.end() )
732 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
733 GetIDSourceToList( aCommand );
735 //addFilterUser( aCommand, theGen ); // protect filters from clearing
737 // some commands of SMESH_MeshEditor create meshes and groups
738 _pyID meshID, groups;
739 if ( method.Search("MakeMesh") != -1 )
740 meshID = aCommand->GetResultValue();
741 else if ( method == "MakeBoundaryMesh")
742 meshID = aCommand->GetResultValue(1);
743 else if ( method == "MakeBoundaryElements")
744 meshID = aCommand->GetResultValue(2);
746 if ( method.Search("MakeGroups") != -1 ||
747 method == "ExtrusionAlongPathX" ||
748 method == "ExtrusionAlongPathObjX" ||
749 method == "DoubleNodeGroupNew" ||
750 method == "DoubleNodeGroupsNew" ||
751 method == "DoubleNodeElemGroupNew" ||
752 method == "DoubleNodeElemGroupsNew" ||
753 method == "DoubleNodeElemGroup2New" ||
754 method == "DoubleNodeElemGroups2New" ||
755 method == "AffectedElemGroupsInRegion"
757 groups = aCommand->GetResultValue();
758 else if ( method == "MakeBoundaryMesh" )
759 groups = aCommand->GetResultValue(2);
760 else if ( method == "MakeBoundaryElements")
761 groups = aCommand->GetResultValue(3);
762 else if ( method == "Create0DElementsOnAllNodes" &&
763 aCommand->GetArg(2).Length() > 2 ) // group name != ''
764 groups = aCommand->GetResultValue();
766 id_editor->second->Process( aCommand );
767 id_editor->second->AddProcessedCmd( aCommand );
770 if ( !meshID.IsEmpty() &&
771 !myMeshes.count( meshID ) &&
772 aCommand->IsStudyEntry( meshID ))
774 _AString processedCommand = aCommand->GetString();
775 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
776 CheckObjectIsReCreated( mesh );
777 myMeshes.insert( make_pair( meshID, mesh ));
779 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
782 if ( !groups.IsEmpty() )
784 if ( !aCommand->IsStudyEntry( meshID ))
785 meshID = id_editor->second->GetMesh();
786 Handle(_pyMesh) mesh = myMeshes[ meshID ];
788 list< _pyID > idList = aCommand->GetStudyEntries( groups );
789 list< _pyID >::iterator grID = idList.begin();
790 for ( ; grID != idList.end(); ++grID )
791 if ( !myObjects.count( *grID ))
793 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
795 if ( !mesh.IsNull() ) mesh->AddGroup( group );
799 } // SMESH_MeshEditor methods
801 // SMESH_Hypothesis method?
802 Handle(_pyHypothesis) hyp = FindHyp( objID );
803 if ( !hyp.IsNull() && !hyp->IsAlgo() )
805 hyp->Process( aCommand );
806 hyp->AddProcessedCmd( aCommand );
810 // aFilterManager.CreateFilter() ?
811 if ( aCommand->GetMethod() == "CreateFilter" )
813 // Set a more human readable name to a filter
814 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
815 _pyID newID, filterID = aCommand->GetResultValue();
816 int pos = filterID.Search( "0x" );
818 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
820 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
823 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
824 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
826 // create _pySelfEraser for functors
827 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
828 functor->IgnoreOwnCalls(); // to erase if not used as an argument
829 AddObject( functor );
832 // other object method?
833 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
834 if ( id_obj != myObjects.end() ) {
835 id_obj->second->Process( aCommand );
836 id_obj->second->AddProcessedCmd( aCommand );
840 // Add access to a wrapped mesh
841 AddMeshAccessorMethod( aCommand );
843 // Add access to a wrapped algorithm
844 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
846 // PAL12227. PythonDump was not updated at proper time; result is
847 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
848 // TypeError: __init__() takes exactly 11 arguments (10 given)
849 const char wrongCommand[] = "SMESH.Filter.Criterion(";
850 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
852 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
853 // there must be 10 arguments, 5-th arg ThresholdID is missing,
854 const int wrongNbArgs = 9, missingArg = 5;
855 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
857 for ( int i = wrongNbArgs; i > missingArg; --i )
858 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
859 tmpCmd.SetArg( missingArg, "''");
860 aCommand->GetString().Trunc( beg - 1 );
861 aCommand->GetString() += tmpCmd.GetString();
864 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
866 // instead of "SMESH.Filter.Criterion(
867 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
868 // 1 2 3 4 5 6 7 8 9 10
869 // in order to avoid the problem of type mismatch of long and FunctorType
870 const TCollection_AsciiString
871 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
872 TCollection_AsciiString
873 Type = aCommand->GetArg(1), // long
874 Compare = aCommand->GetArg(2), // long
875 Threshold = aCommand->GetArg(3), // double
876 ThresholdStr = aCommand->GetArg(4), // string
877 ThresholdID = aCommand->GetArg(5), // string
878 UnaryOp = aCommand->GetArg(6), // long
879 BinaryOp = aCommand->GetArg(7), // long
880 Tolerance = aCommand->GetArg(8), // double
881 TypeOfElement = aCommand->GetArg(9), // ElementType
882 Precision = aCommand->GetArg(10); // long
883 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
884 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
885 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
886 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
887 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
889 if ( Compare == "SMESH.FT_EqualTo" )
892 aCommand->RemoveArgs();
893 aCommand->SetObject( SMESH_2smeshpy::GenName() );
894 aCommand->SetMethod( "GetCriterion" );
896 aCommand->SetArg( 1, TypeOfElement );
897 aCommand->SetArg( 2, Type );
898 aCommand->SetArg( 3, Compare );
900 if ( Threshold.IsIntegerValue() )
902 int iGeom = Threshold.IntegerValue();
903 if ( Type == "SMESH.FT_ElemGeomType" )
905 // set SMESH.GeometryType instead of a numerical Threshold
906 const int nbTypes = SMESH::Geom_LAST;
907 const char* types[] = {
908 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
909 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
910 "Geom_POLYHEDRA", "Geom_BALL" };
911 if ( -1 < iGeom && iGeom < nbTypes )
912 Threshold = SMESH + types[ iGeom ];
914 // is types complete? (compilation failure mains that enum GeometryType changed)
915 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
918 if (Type == "SMESH.FT_EntityType")
920 // set SMESH.EntityType instead of a numerical Threshold
921 const int nbTypes = SMESH::Entity_Last;
922 const char* types[] = {
923 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
924 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
925 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
926 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
927 "Entity_Pyramid", "Entity_Quad_Pyramid",
928 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
929 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
930 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
931 if ( -1 < iGeom && iGeom < nbTypes )
932 Threshold = SMESH + types[ iGeom ];
934 // is 'types' complete? (compilation failure mains that enum EntityType changed)
935 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
939 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
940 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
941 else if ( ThresholdStr.Length() != 2 )
942 aCommand->SetArg( 4, ThresholdStr );
943 else if ( ThresholdID.Length() != 2 )
944 aCommand->SetArg( 4, ThresholdID );
946 aCommand->SetArg( 4, Threshold );
947 // find the last not default arg
949 if ( Tolerance == dfltTol ) {
951 if ( BinaryOp == dfltFunctor ) {
953 if ( UnaryOp == dfltFunctor )
957 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
958 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
959 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
960 if ( Precision != dfltPreci )
962 TCollection_AsciiString crit = aCommand->GetResultValue();
963 aCommand->GetString() += "; ";
964 aCommand->GetString() += crit + ".Precision = " + Precision;
970 //================================================================================
972 * \brief Convert the command or remember it for later conversion
973 * \param theCommand - The python command calling a method of SMESH_Gen
975 //================================================================================
977 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
979 // there are methods to convert:
980 // CreateMesh( shape )
981 // Concatenate( [mesh1, ...], ... )
982 // CreateHypothesis( theHypType, theLibName )
983 // Compute( mesh, geom )
984 // Evaluate( mesh, geom )
986 TCollection_AsciiString method = theCommand->GetMethod();
988 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
990 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
994 if ( method == "CreateMeshesFromUNV" ||
995 method == "CreateMeshesFromSTL" ||
996 method == "CopyMesh" ) // command result is a mesh
998 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1002 if( method == "CreateMeshesFromMED" ||
1003 method == "CreateMeshesFromSAUV"||
1004 method == "CreateMeshesFromCGNS" ||
1005 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1007 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1008 std::list< _pyID >::iterator meshID = meshIDs.begin();
1009 for ( ; meshID != meshIDs.end(); ++meshID )
1011 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1014 if ( method == "CreateMeshesFromGMF" )
1016 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1017 // CreateMeshesFromGMF( theFileName )
1018 _AString file = theCommand->GetArg(1);
1019 theCommand->RemoveArgs();
1020 theCommand->SetArg( 1, file );
1024 // CreateHypothesis()
1025 if ( method == "CreateHypothesis" )
1027 // issue 199929, remove standard library name (default parameter)
1028 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1029 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1030 // keep the first argument
1031 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1032 theCommand->RemoveArgs();
1033 theCommand->SetArg( 1, arg );
1036 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1037 CheckObjectIsReCreated( hyp );
1038 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1043 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1044 if ( method == "Compute" )
1046 const _pyID& meshID = theCommand->GetArg( 1 );
1047 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1048 if ( id_mesh != myMeshes.end() ) {
1049 theCommand->SetObject( meshID );
1050 theCommand->RemoveArgs();
1051 id_mesh->second->Process( theCommand );
1052 id_mesh->second->AddProcessedCmd( theCommand );
1057 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1058 if ( method == "Evaluate" )
1060 const _pyID& meshID = theCommand->GetArg( 1 );
1061 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1062 if ( id_mesh != myMeshes.end() ) {
1063 theCommand->SetObject( meshID );
1064 _pyID geom = theCommand->GetArg( 2 );
1065 theCommand->RemoveArgs();
1066 theCommand->SetArg( 1, geom );
1067 id_mesh->second->AddProcessedCmd( theCommand );
1072 // objects erasing creation command if no more its commands invoked:
1073 // SMESH_Pattern, FilterManager
1074 if ( method == "GetPattern" ||
1075 method == "CreateFilterManager" ||
1076 method == "CreateMeasurements" )
1078 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1079 if ( !AddObject( obj ) )
1080 theCommand->Clear(); // already created
1082 // Concatenate( [mesh1, ...], ... )
1083 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1085 if ( method == "ConcatenateWithGroups" ) {
1086 theCommand->SetMethod( "Concatenate" );
1087 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1089 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1091 AddMeshAccessorMethod( theCommand );
1093 else if ( method == "SetName" ) // SetName(obj,name)
1095 // store theCommand as one of object commands to erase it along with the object
1096 const _pyID& objID = theCommand->GetArg( 1 );
1097 Handle(_pyObject) obj = FindObject( objID );
1098 if ( !obj.IsNull() )
1099 obj->AddProcessedCmd( theCommand );
1102 // Replace name of SMESH_Gen
1104 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1105 static TStringSet smeshpyMethods;
1106 if ( smeshpyMethods.empty() ) {
1107 const char * names[] =
1108 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1109 "GetPattern","GetSubShapesId",
1110 "" }; // <- mark of array end
1111 smeshpyMethods.Insert( names );
1113 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1114 // smeshgen.Method() --> smesh.Method()
1115 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1117 // smeshgen.Method() --> smesh.Method()
1118 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1121 //================================================================================
1123 * \brief Convert the remembered commands
1125 //================================================================================
1127 void _pyGen::Flush()
1129 // create an empty command
1130 myLastCommand = new _pyCommand();
1132 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1133 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1134 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1136 if ( IsToKeepAllCommands() ) // historical dump
1138 // set myIsPublished = true to all objects
1139 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1140 id_mesh->second->SetRemovedFromStudy( false );
1141 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1142 id_hyp->second->SetRemovedFromStudy( false );
1143 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1144 id_obj->second->SetRemovedFromStudy( false );
1148 // let hypotheses find referred objects in order to prevent clearing
1149 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1150 list< Handle(_pyMesh) > fatherMeshes;
1151 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1152 if ( !id_hyp->second.IsNull() )
1153 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1155 // set myIsPublished = false to all objects depending on
1156 // meshes built on a removed geometry
1157 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1158 if ( id_mesh->second->IsNotGeomPublished() )
1159 id_mesh->second->SetRemovedFromStudy( true );
1162 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1163 if ( ! id_mesh->second.IsNull() )
1164 id_mesh->second->Flush();
1167 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1168 if ( !id_hyp->second.IsNull() ) {
1169 id_hyp->second->Flush();
1170 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1171 if ( !id_hyp->second->IsWrapped() )
1172 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1175 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1176 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1177 for ( ; robj != myOrderedObjects.rend(); ++robj )
1178 if ( ! robj->IsNull() )
1180 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1181 for ( ; obj != myOrderedObjects.end(); ++obj )
1182 if ( ! obj->IsNull() )
1185 myLastCommand->SetOrderNb( ++myNbCommands );
1186 myCommands.push_back( myLastCommand );
1189 //================================================================================
1191 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1192 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1194 //================================================================================
1196 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1198 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1199 // for ( ; id_obj != myObjects.end(); ++id_obj )
1201 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1202 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1204 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1205 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1207 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1208 // list< _pyID >::iterator id = idList.begin();
1209 // for ( ; id != idList.end(); ++id )
1210 // if ( id_obj->first == *id )
1211 // // _pySubMesh::Process() does what we need
1212 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1217 //================================================================================
1219 * \brief Clean commands of removed objects depending on myIsPublished flag
1221 //================================================================================
1223 void _pyGen::ClearCommands()
1225 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1226 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1227 id_mesh->second->ClearCommands();
1229 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1230 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1231 if ( !id_hyp->second.IsNull() )
1232 id_hyp->second->ClearCommands();
1234 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1235 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1236 for ( ; robj != myOrderedObjects.rend(); ++robj )
1237 if ( ! robj->IsNull() )
1238 (*robj)->ClearCommands();
1239 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1240 for ( ; obj != myOrderedObjects.end(); ++obj )
1241 if ( ! obj->IsNull() )
1242 (*obj)->ClearCommands();
1245 //================================================================================
1247 * \brief Release mutual handles of objects
1249 //================================================================================
1253 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1254 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1255 id_mesh->second->Free();
1258 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1259 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1260 id_ed->second->Free();
1261 myMeshEditors.clear();
1263 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1264 for ( ; id_obj != myObjects.end(); ++id_obj )
1265 id_obj->second->Free();
1268 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1269 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1270 if ( !id_hyp->second.IsNull() )
1271 id_hyp->second->Free();
1274 myFile2ExportedMesh.clear();
1276 //myKeepAgrCmdsIDs.Print();
1279 //================================================================================
1281 * \brief Add access method to mesh that is an argument
1282 * \param theCmd - command to add access method
1283 * \retval bool - true if added
1285 //================================================================================
1287 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1290 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1291 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1292 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1298 //================================================================================
1300 * \brief Add access method to algo that is an object or an argument
1301 * \param theCmd - command to add access method
1302 * \retval bool - true if added
1304 //================================================================================
1306 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1309 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1310 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1311 if ( !id_hyp->second.IsNull() &&
1312 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1313 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1314 id_hyp->second->AccessorMethod() ))
1320 //================================================================================
1322 * \brief Find hypothesis by ID (entry)
1323 * \param theHypID - The hypothesis ID
1324 * \retval Handle(_pyHypothesis) - The found hypothesis
1326 //================================================================================
1328 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1330 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1331 if ( id_hyp != myHypos.end() &&
1332 !id_hyp->second.IsNull() &&
1333 theHypID == id_hyp->second->GetID() )
1334 return id_hyp->second;
1335 return Handle(_pyHypothesis)();
1338 //================================================================================
1340 * \brief Find algorithm able to create a hypothesis
1341 * \param theGeom - The shape ID the algorithm was created on
1342 * \param theMesh - The mesh ID that created the algorithm
1343 * \param theHypothesis - The hypothesis the algorithm should be able to create
1344 * \retval Handle(_pyHypothesis) - The found algo
1346 //================================================================================
1348 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1349 const Handle(_pyHypothesis)& theHypothesis )
1351 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1352 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1353 if ( !id_hyp->second.IsNull() &&
1354 id_hyp->second->IsAlgo() &&
1355 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1356 id_hyp->second->GetGeom() == theGeom &&
1357 id_hyp->second->GetMesh() == theMesh )
1358 return id_hyp->second;
1359 return Handle(_pyHypothesis)();
1362 //================================================================================
1364 * \brief Find subMesh by ID (entry)
1365 * \param theSubMeshID - The subMesh ID
1366 * \retval Handle(_pySubMesh) - The found subMesh
1368 //================================================================================
1370 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1372 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1373 if ( id_subMesh != myObjects.end() )
1374 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1375 return Handle(_pySubMesh)();
1379 //================================================================================
1381 * \brief Change order of commands in the script
1382 * \param theCmd1 - One command
1383 * \param theCmd2 - Another command
1385 //================================================================================
1387 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1389 list< Handle(_pyCommand) >::iterator pos1, pos2;
1390 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1391 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1392 myCommands.insert( pos1, theCmd2 );
1393 myCommands.insert( pos2, theCmd1 );
1394 myCommands.erase( pos1 );
1395 myCommands.erase( pos2 );
1397 int nb1 = theCmd1->GetOrderNb();
1398 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1399 theCmd2->SetOrderNb( nb1 );
1400 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1401 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1404 //================================================================================
1406 * \brief Set one command after the other
1407 * \param theCmd - Command to move
1408 * \param theAfterCmd - Command ater which to insert the first one
1410 //================================================================================
1412 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1414 setNeighbourCommand( theCmd, theAfterCmd, true );
1417 //================================================================================
1419 * \brief Set one command before the other
1420 * \param theCmd - Command to move
1421 * \param theBeforeCmd - Command before which to insert the first one
1423 //================================================================================
1425 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1427 setNeighbourCommand( theCmd, theBeforeCmd, false );
1430 //================================================================================
1432 * \brief Set one command before or after the other
1433 * \param theCmd - Command to move
1434 * \param theOtherCmd - Command ater or before which to insert the first one
1436 //================================================================================
1438 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1439 Handle(_pyCommand)& theOtherCmd,
1440 const bool theIsAfter )
1442 list< Handle(_pyCommand) >::iterator pos;
1443 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1444 myCommands.erase( pos );
1445 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1446 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1449 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1450 (*pos)->SetOrderNb( i++ );
1453 //================================================================================
1455 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1457 //================================================================================
1459 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1461 // No more needed after adding _pyObject::myArgCommands
1463 // const char filterPrefix[] = "aFilter0x";
1464 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1467 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1469 // const _AString & arg = theCommand->GetArg( i );
1470 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1471 // if ( arg.Search( filterPrefix ) != 1 )
1474 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1475 // if ( !filter.IsNull() )
1477 // filter->AddUser( user );
1478 // if ( !filter->GetNewID().IsEmpty() )
1479 // theCommand->SetArg( i, filter->GetNewID() );
1484 //================================================================================
1486 * \brief Set command be last in list of commands
1487 * \param theCmd - Command to be last
1489 //================================================================================
1491 Handle(_pyCommand)& _pyGen::GetLastCommand()
1493 return myLastCommand;
1496 //================================================================================
1498 * \brief Set method to access to object wrapped with python class
1499 * \param theID - The wrapped object entry
1500 * \param theMethod - The accessor method
1502 //================================================================================
1504 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1506 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1509 //================================================================================
1511 * \brief Generated new ID for object and assign with existing name
1512 * \param theID - ID of existing object
1514 //================================================================================
1516 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1521 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1523 while ( myObjectNames.IsBound( aNewID ) );
1525 if ( myObjectNames.IsBound( theID ) )
1526 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1528 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1532 //================================================================================
1534 * \brief Stores theObj in myObjects
1536 //================================================================================
1538 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1540 if ( theObj.IsNull() ) return false;
1542 CheckObjectIsReCreated( theObj );
1546 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1547 add = myMeshes.insert( make_pair( theObj->GetID(),
1548 Handle(_pyMesh)::DownCast( theObj ))).second;
1550 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1551 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1552 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1555 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1556 if ( add ) myOrderedObjects.push_back( theObj );
1561 //================================================================================
1563 * \brief Erases an existing object with the same ID. This method should be called
1564 * before storing theObj in _pyGen
1566 //================================================================================
1568 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1570 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1573 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1574 Handle(_pyObject) existing;
1576 existing = FindHyp( theObj->GetID() );
1578 existing = FindObject( theObj->GetID() );
1579 if ( !existing.IsNull() && existing != theObj )
1581 existing->SetRemovedFromStudy( true );
1582 existing->ClearCommands();
1585 if ( myHypos.count( theObj->GetID() ))
1586 myHypos.erase( theObj->GetID() );
1588 else if ( myMeshes.count( theObj->GetID() ))
1590 myMeshes.erase( theObj->GetID() );
1592 else if ( myObjects.count( theObj->GetID() ))
1594 myObjects.erase( theObj->GetID() );
1599 //================================================================================
1601 * \brief Re-register an object with other ID to make it Process() commands of
1602 * other object having this ID
1604 //================================================================================
1606 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1608 if ( theObj.IsNull() ) return;
1610 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1611 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1613 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1614 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1617 myObjects.insert( make_pair( theID, theObj ));
1620 //================================================================================
1622 * \brief Finds a _pyObject by ID
1624 //================================================================================
1626 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1629 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1630 if ( id_obj != myObjects.end() )
1631 return id_obj->second;
1634 _pyGen* me = const_cast< _pyGen* >( this );
1635 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1636 if ( id_obj != myMeshes.end() )
1637 return id_obj->second;
1640 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1641 // if ( id_obj != myMeshEditors.end() )
1642 // return id_obj->second;
1644 return Handle(_pyObject)();
1647 //================================================================================
1649 * \brief Check if a study entry is under GEOM component
1651 //================================================================================
1653 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1657 return ( myGeomIDIndex <= theObjID.Length() &&
1658 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1659 _pyCommand::IsStudyEntry( theObjID ));
1664 //================================================================================
1666 * \brief Returns true if an object is not present in a study
1668 //================================================================================
1670 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1672 if ( theObjID.IsEmpty() ) return false;
1674 if ( myObjectNames.IsBound( theObjID ))
1675 return false; // SMESH object is in study
1677 // either the SMESH object is not in study or it is a GEOM object
1678 if ( IsGeomObject( theObjID ))
1680 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1681 if ( so->_is_nil() ) return true;
1682 CORBA::Object_var obj = so->GetObject();
1683 return CORBA::is_nil( obj );
1685 return true; // SMESH object not in study
1688 //================================================================================
1690 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1691 * this object is not dumped
1692 * \param [in] theObjID - entry of the object whose creation command was eliminated
1694 //================================================================================
1696 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1698 myRemovedObjIDs.insert( theObjID );
1701 //================================================================================
1703 * \brief Return reader of hypotheses of plugins
1705 //================================================================================
1707 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1709 if (myHypReader.IsNull() )
1710 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1716 //================================================================================
1718 * \brief Mesh created by SMESH_Gen
1720 //================================================================================
1722 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1723 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1725 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1726 myGeomNotInStudy = true;
1728 // convert my creation command --> smeshpy.Mesh(...)
1729 Handle(_pyCommand) creationCmd = GetCreationCmd();
1730 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1731 creationCmd->SetMethod( "Mesh" );
1732 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1735 //================================================================================
1737 * \brief Mesh created by SMESH_MeshEditor
1739 //================================================================================
1741 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1742 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1744 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1746 // this mesh depends on the exported mesh
1747 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1748 if ( !file.IsEmpty() )
1750 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1751 addFatherMesh( exportData.myMesh );
1752 if ( !exportData.myLastComputeCmd.IsNull() )
1754 // restore cleared Compute() by which the exported mesh was generated
1755 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1756 // protect that Compute() cmd from clearing
1757 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1758 exportData.myMesh->myLastComputeCmd.Nullify();
1762 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1764 // this mesh depends on concatenated meshes
1765 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1766 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1767 list< _pyID >::iterator meshID = idList.begin();
1768 for ( ; meshID != idList.end(); ++meshID )
1769 addFatherMesh( *meshID );
1771 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1773 // this mesh depends on a copied IdSource
1774 const _pyID& objID = theCreationCmd->GetArg( 1 );
1775 addFatherMesh( objID );
1777 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1778 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1779 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1781 // this mesh depends on a source mesh
1782 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1783 const _pyID& meshID = theCreationCmd->GetObject();
1784 addFatherMesh( meshID );
1787 // convert my creation command
1788 Handle(_pyCommand) creationCmd = GetCreationCmd();
1789 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1790 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1793 //================================================================================
1795 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1796 * \param theCommand - Engine method called for this mesh
1798 //================================================================================
1800 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1802 // some methods of SMESH_Mesh interface needs special conversion
1803 // to methods of Mesh python class
1805 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1806 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1807 // 2. AddHypothesis(geom, hyp)
1808 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1809 // 3. CreateGroupFromGEOM(type, name, grp)
1810 // --> in Mesh.Group(grp, name="")
1811 // 4. ExportToMED(f, auto_groups, version)
1812 // --> in Mesh.ExportMED( f, auto_groups, version )
1815 const TCollection_AsciiString& method = theCommand->GetMethod();
1816 // ----------------------------------------------------------------------
1817 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1819 if ( !theGen->IsToKeepAllCommands() ) // !historical
1821 list< Handle(_pyHypothesis) >::iterator hyp;
1822 if ( !myLastComputeCmd.IsNull() )
1824 // check if the previously computed mesh has been edited,
1825 // if so then we do not clear the previous Compute()
1826 bool toClear = true;
1827 if ( myLastComputeCmd->GetMethod() == "Compute" )
1829 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1830 for ( ; e != myEditors.end() && toClear; ++e )
1832 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1833 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1834 if ( cmd != cmds.rend() &&
1835 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1841 // clear hyp commands called before myLastComputeCmd
1842 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1843 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1845 myLastComputeCmd->Clear();
1848 myLastComputeCmd = theCommand;
1850 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1851 (*hyp)->MeshComputed( myLastComputeCmd );
1855 // ----------------------------------------------------------------------
1856 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1858 if ( !theGen->IsToKeepAllCommands() ) // !historical
1861 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1862 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1863 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1865 if ( !myLastComputeCmd.IsNull() )
1867 list< Handle(_pyHypothesis) >::iterator hyp;
1868 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1869 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1871 myLastComputeCmd->Clear();
1874 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1875 for ( ; e != myEditors.end(); ++e )
1877 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1878 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1879 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1880 if ( !(*cmd)->IsEmpty() )
1882 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1886 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1889 // ----------------------------------------------------------------------
1890 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1891 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1892 if ( !subMesh.IsNull() ) {
1893 subMesh->SetCreator( this );
1894 mySubmeshes.push_back( subMesh );
1897 // ----------------------------------------------------------------------
1898 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1899 theCommand->Clear();
1901 // ----------------------------------------------------------------------
1902 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1903 myAddHypCmds.push_back( theCommand );
1905 const _pyID& hypID = theCommand->GetArg( 2 );
1906 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1907 if ( !hyp.IsNull() ) {
1908 myHypos.push_back( hyp );
1909 if ( hyp->GetMesh().IsEmpty() )
1910 hyp->SetMesh( this->GetID() );
1913 // ----------------------------------------------------------------------
1914 else if ( method == "CreateGroup" ||
1915 method == "CreateGroupFromGEOM" ||
1916 method == "CreateGroupFromFilter" ||
1917 method == "CreateDimGroup" )
1919 Handle(_pyGroup) group = new _pyGroup( theCommand );
1920 myGroups.push_back( group );
1921 theGen->AddObject( group );
1923 // ----------------------------------------------------------------------
1924 // update list of groups
1925 else if ( method == "GetGroups" )
1927 bool allGroupsRemoved = true;
1928 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1929 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1930 list< _pyID >::iterator grID = idList.begin();
1931 const size_t nbGroupsBefore = myGroups.size();
1932 Handle(_pyObject) obj;
1933 for ( ; grID != idList.end(); ++grID )
1935 obj = theGen->FindObject( *grID );
1938 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1939 theGen->AddObject( group );
1940 myGroups.push_back( group );
1943 if ( !obj->CanClear() )
1944 allGroupsRemoved = false;
1946 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1947 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1949 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1951 // check if the preceding command is Compute();
1952 // if GetGroups() is just after Compute(), this can mean that the groups
1953 // were created by some algorithm and hence Compute() should not be discarded
1954 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1955 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1956 while ( (*cmd)->GetMethod() == "GetGroups" )
1958 if ( myLastComputeCmd == (*cmd))
1959 // protect last Compute() from clearing by the next Compute()
1960 myLastComputeCmd.Nullify();
1963 // ----------------------------------------------------------------------
1964 // notify a group about full removal
1965 else if ( method == "RemoveGroupWithContents" ||
1966 method == "RemoveGroup")
1968 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1969 const _pyID groupID = theCommand->GetArg( 1 );
1970 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1971 if ( !grp.IsNull() )
1973 if ( method == "RemoveGroupWithContents" )
1974 grp->RemovedWithContents();
1975 // to clear RemoveGroup() if the group creation is cleared
1976 grp->AddProcessedCmd( theCommand );
1980 // ----------------------------------------------------------------------
1981 else if ( theCommand->MethodStartsFrom( "Export" ))
1983 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1984 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1986 theCommand->SetMethod( "ExportMED" );
1987 if ( theCommand->GetNbArgs() == 5 )
1989 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1990 _AString autoDimension = theCommand->GetArg( 5 );
1991 theCommand->SetArg( 5, "None" );
1992 theCommand->SetArg( 6, autoDimension );
1995 else if ( method == "ExportCGNS" )
1996 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1997 _pyID partID = theCommand->GetArg( 1 );
1998 int nbArgs = theCommand->GetNbArgs();
1999 for ( int i = 2; i <= nbArgs; ++i )
2000 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2001 theCommand->SetArg( nbArgs, partID );
2003 else if ( method == "ExportGMF" )
2004 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2005 _pyID partID = theCommand->GetArg( 1 );
2006 _AString file = theCommand->GetArg( 2 );
2007 theCommand->RemoveArgs();
2008 theCommand->SetArg( 1, file );
2009 theCommand->SetArg( 2, partID );
2011 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2012 { // ExportPartTo*(part, ...) -> Export*(..., part)
2014 // remove "PartTo" from the method
2015 TCollection_AsciiString newMethod = method;
2016 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2017 theCommand->SetMethod( newMethod );
2018 // make the 1st arg be the last one (or last but three for ExportMED())
2019 _pyID partID = theCommand->GetArg( 1 );
2020 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2021 for ( int i = 2; i <= nbArgs; ++i )
2022 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2023 theCommand->SetArg( nbArgs, partID );
2025 // remember file name
2026 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2027 ExportedMeshData( this, myLastComputeCmd ));
2029 // ----------------------------------------------------------------------
2030 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2032 _pyID hypID = theCommand->GetArg( 2 );
2033 _pyID geomID = theCommand->GetArg( 1 );
2034 bool isLocal = ( geomID != GetGeom() );
2036 // check if this mesh still has corresponding addition command
2037 Handle(_pyCommand) addCmd;
2038 list< Handle(_pyCommand) >::iterator cmd;
2039 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2040 for ( int i = 0; i < 2; ++i )
2042 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2043 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2045 bool sameHyp = true;
2046 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2047 sameHyp = false; // other hyp
2048 if ( (*cmd)->GetNbArgs() == 2 &&
2049 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2050 sameHyp = false; // other geom
2051 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2052 sameHyp = false; // other geom
2056 cmd = addHypCmds.erase( cmd );
2057 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2059 theCommand->Clear();
2063 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2064 addCmd->RemoveArgs();
2065 addCmd->SetArg( 1, hypID );
2067 addCmd->SetArg( 2, geomID );
2076 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2077 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2078 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2079 _pyID geom = theCommand->GetArg( 1 );
2080 theCommand->RemoveArgs();
2081 theCommand->SetArg( 1, hypID );
2082 if ( geom != GetGeom() )
2083 theCommand->SetArg( 2, geom );
2085 // remove hyp from myHypos
2086 myHypos.remove( hyp );
2088 // check for SubMesh order commands
2089 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2091 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2092 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2093 // commands are moved at the end of the script
2094 TCollection_AsciiString subIDs =
2095 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2096 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2097 list< _pyID >::iterator subID = idList.begin();
2098 for ( ; subID != idList.end(); ++subID )
2100 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2101 if ( !subMesh.IsNull() )
2102 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2105 // add accessor method if necessary
2108 if ( NeedMeshAccess( theCommand ))
2109 // apply theCommand to the mesh wrapped by smeshpy mesh
2110 AddMeshAccess( theCommand );
2114 //================================================================================
2116 * \brief Return True if addition of accesor method is needed
2118 //================================================================================
2120 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2122 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2123 // so no conversion is needed for them at all:
2124 static TStringSet sameMethods;
2125 if ( sameMethods.empty() ) {
2126 const char * names[] =
2127 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2128 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2129 "ClearLog","GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2130 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2131 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2132 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2133 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2134 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2135 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2136 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2137 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2138 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2139 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2140 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2141 ,"" }; // <- mark of end
2142 sameMethods.Insert( names );
2145 return !sameMethods.Contains( theCommand->GetMethod() );
2148 //================================================================================
2150 * \brief Convert creation and addition of all algos and hypos
2152 //================================================================================
2154 void _pyMesh::Flush()
2157 // get the meshes this mesh depends on via hypotheses
2158 list< Handle(_pyMesh) > fatherMeshes;
2159 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2160 for ( ; hyp != myHypos.end(); ++hyp )
2161 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2162 myGeomNotInStudy = true;
2164 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2165 for ( ; m != fatherMeshes.end(); ++m )
2166 addFatherMesh( *m );
2167 // if ( removedGeom )
2168 // SetRemovedFromStudy(); // as referred geometry not in study
2170 if ( myGeomNotInStudy )
2173 list < Handle(_pyCommand) >::iterator cmd;
2175 // try to convert algo addition like this:
2176 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2177 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2179 Handle(_pyCommand) addCmd = *cmd;
2181 _pyID algoID = addCmd->GetArg( 2 );
2182 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2183 if ( algo.IsNull() || !algo->IsAlgo() )
2186 // check and create new algorithm instance if it is already wrapped
2187 if ( algo->IsWrapped() ) {
2188 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2189 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2190 TCollection_AsciiString( " = " ) + theGen->GetID() +
2191 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2192 TCollection_AsciiString( "\" )" );
2194 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2195 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2196 if ( !newAlgo.IsNull() ) {
2197 newAlgo->Assign( algo, this->GetID() );
2198 newAlgo->SetCreationCmd( newCmd );
2200 // set algorithm creation
2201 theGen->SetCommandBefore( newCmd, addCmd );
2202 myHypos.push_back( newAlgo );
2203 if ( !myLastComputeCmd.IsNull() &&
2204 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2205 newAlgo->MeshComputed( myLastComputeCmd );
2210 _pyID geom = addCmd->GetArg( 1 );
2211 bool isLocalAlgo = ( geom != GetGeom() );
2214 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2216 // wrapped algo is created after mesh creation
2217 GetCreationCmd()->AddDependantCmd( addCmd );
2219 if ( isLocalAlgo ) {
2220 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2221 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2222 TCollection_AsciiString( "geom=" ) + geom );
2223 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2224 list < Handle(_pySubMesh) >::iterator smIt;
2225 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2226 Handle(_pySubMesh) subMesh = *smIt;
2227 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2228 if ( geom == subCmd->GetArg( 1 )) {
2229 subCmd->SetObject( algo->GetID() );
2230 subCmd->RemoveArgs();
2231 subMesh->SetCreator( algo );
2236 else // KO - ALGO was already created
2238 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2239 addCmd->RemoveArgs();
2240 addCmd->SetArg( 1, algoID );
2242 addCmd->SetArg( 2, geom );
2243 myNotConvertedAddHypCmds.push_back( addCmd );
2247 // try to convert hypo addition like this:
2248 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2249 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2251 Handle(_pyCommand) addCmd = *cmd;
2252 _pyID hypID = addCmd->GetArg( 2 );
2253 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2254 if ( hyp.IsNull() || hyp->IsAlgo() )
2256 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2258 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2259 _pyID geom = addCmd->GetArg( 1 );
2260 addCmd->RemoveArgs();
2261 addCmd->SetArg( 1, hypID );
2262 if ( geom != GetGeom() )
2263 addCmd->SetArg( 2, geom );
2264 myNotConvertedAddHypCmds.push_back( addCmd );
2268 myAddHypCmds.clear();
2269 mySubmeshes.clear();
2272 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2273 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2277 //================================================================================
2279 * \brief Sets myIsPublished of me and of all objects depending on me.
2281 //================================================================================
2283 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2285 _pyObject::SetRemovedFromStudy(isRemoved);
2287 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2288 for ( ; sm != mySubmeshes.end(); ++sm )
2289 (*sm)->SetRemovedFromStudy(isRemoved);
2291 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2292 for ( ; gr != myGroups.end(); ++gr )
2293 (*gr)->SetRemovedFromStudy(isRemoved);
2295 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2296 for ( ; m != myChildMeshes.end(); ++m )
2297 (*m)->SetRemovedFromStudy(isRemoved);
2299 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2300 for ( ; e != myEditors.end(); ++e )
2301 (*e)->SetRemovedFromStudy(isRemoved);
2304 //================================================================================
2306 * \brief Return true if none of myChildMeshes is in study
2308 //================================================================================
2310 bool _pyMesh::CanClear()
2315 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2316 for ( ; m != myChildMeshes.end(); ++m )
2317 if ( !(*m)->CanClear() )
2323 //================================================================================
2325 * \brief Clear my commands and commands of mesh editor
2327 //================================================================================
2329 void _pyMesh::ClearCommands()
2335 // mark all sub-objects as not removed, except child meshes
2336 list< Handle(_pyMesh) > children;
2337 children.swap( myChildMeshes );
2338 SetRemovedFromStudy( false );
2339 children.swap( myChildMeshes );
2343 _pyObject::ClearCommands();
2345 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2346 for ( ; sm != mySubmeshes.end(); ++sm )
2347 (*sm)->ClearCommands();
2349 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2350 for ( ; gr != myGroups.end(); ++gr )
2351 (*gr)->ClearCommands();
2353 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2354 for ( ; e != myEditors.end(); ++e )
2355 (*e)->ClearCommands();
2358 //================================================================================
2360 * \brief Add a father mesh by ID
2362 //================================================================================
2364 void _pyMesh::addFatherMesh( const _pyID& meshID )
2366 if ( !meshID.IsEmpty() && meshID != GetID() )
2367 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2370 //================================================================================
2372 * \brief Add a father mesh
2374 //================================================================================
2376 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2378 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2380 //myFatherMeshes.push_back( mesh );
2381 mesh->myChildMeshes.push_back( this );
2383 // protect last Compute() from clearing by the next Compute()
2384 mesh->myLastComputeCmd.Nullify();
2388 //================================================================================
2390 * \brief MeshEditor convert its commands to ones of mesh
2392 //================================================================================
2394 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2395 _pyObject( theCreationCmd )
2397 myMesh = theCreationCmd->GetObject();
2398 myCreationCmdStr = theCreationCmd->GetString();
2399 theCreationCmd->Clear();
2401 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2402 if ( !mesh.IsNull() )
2403 mesh->AddEditor( this );
2406 //================================================================================
2408 * \brief convert its commands to ones of mesh
2410 //================================================================================
2412 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2414 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2415 // commands calling these methods are converted to calls of Mesh methods without
2416 // additional modifs, only object is changed from MeshEditor to Mesh.
2417 static TStringSet sameMethods;
2418 if ( sameMethods.empty() ) {
2419 const char * names[] = {
2420 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2421 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2422 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2423 "MoveNode", "MoveClosestNodeToPoint",
2424 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2425 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2426 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2427 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2428 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2429 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2430 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2431 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2432 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2433 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2434 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2435 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2436 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2437 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2438 "GetLastCreatedElems",
2439 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2440 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2441 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2442 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2443 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2444 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2445 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2446 ,"" }; // <- mark of the end
2447 sameMethods.Insert( names );
2450 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2451 TStringMap diffMethods;
2452 if ( diffMethods.empty() ) {
2453 const char * orig2newName[] = {
2454 // original name --------------> new name
2455 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2456 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2457 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2458 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2459 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2460 ""};// <- mark of the end
2461 diffMethods.Insert( orig2newName );
2464 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2465 // only by last two arguments
2466 static TStringSet diffLastTwoArgsMethods;
2467 if (diffLastTwoArgsMethods.empty() ) {
2468 const char * names[] = {
2469 "MirrorMakeGroups","MirrorObjectMakeGroups",
2470 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2471 "RotateMakeGroups","RotateObjectMakeGroups",
2472 ""};// <- mark of the end
2473 diffLastTwoArgsMethods.Insert( names );
2476 // only a method name is to change?
2477 const TCollection_AsciiString & method = theCommand->GetMethod();
2478 bool isPyMeshMethod = sameMethods.Contains( method );
2479 if ( !isPyMeshMethod )
2481 TCollection_AsciiString newMethod = diffMethods.Value( method );
2482 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2483 theCommand->SetMethod( newMethod );
2485 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2486 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2488 isPyMeshMethod = true;
2489 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2490 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2493 if ( !isPyMeshMethod )
2495 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2496 // functions with the flag "theMakeGroups = True" like:
2497 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2498 int pos = method.Search("MakeGroups");
2501 isPyMeshMethod = true;
2502 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2503 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2505 // 1. Remove "MakeGroups" from the Command
2506 TCollection_AsciiString aMethod = theCommand->GetMethod();
2507 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2510 pos = pos-2; //Remove "0D" from the Command too
2511 aMethod.Trunc(pos-1);
2512 theCommand->SetMethod(aMethod);
2514 // 2. And add last "True" argument(s)
2515 while(nbArgsToAdd--)
2516 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2517 if( is0DmethId || is0DmethObj )
2518 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2522 // ExtrusionSweep0D() -> ExtrusionSweep()
2523 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2524 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2525 method == "ExtrusionSweepObject0D" ))
2527 isPyMeshMethod = true;
2528 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2529 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2530 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2533 // DoubleNode...New(...) -> DoubleNode...(...,True)
2534 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2535 method == "DoubleNodeElemGroupsNew" ||
2536 method == "DoubleNodeGroupNew" ||
2537 method == "DoubleNodeGroupsNew" ||
2538 method == "DoubleNodeElemGroup2New" ||
2539 method == "DoubleNodeElemGroups2New"))
2541 isPyMeshMethod = true;
2542 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2543 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2544 if ( excessLen == 3 )
2546 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2548 else if ( theCommand->GetArg(4) == "0" ||
2549 theCommand->GetArg(5) == "0" )
2551 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2552 // Group = DoubleNodeGroup2New(,,,False, True)
2553 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2554 theCommand->SetResultValue( groupID );
2557 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2558 // FindElementsByPoint(x, y, z, elementType, meshPart)
2559 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2561 isPyMeshMethod = true;
2562 theCommand->SetMethod( "FindElementsByPoint" );
2563 // make the 1st arg be the last one
2564 _pyID partID = theCommand->GetArg( 1 );
2565 int nbArgs = theCommand->GetNbArgs();
2566 for ( int i = 2; i <= nbArgs; ++i )
2567 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2568 theCommand->SetArg( nbArgs, partID );
2570 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2571 if ( !isPyMeshMethod && method == "Reorient2D" )
2573 isPyMeshMethod = true;
2574 _AString mesh = theCommand->GetArg( 1 );
2575 _AString dir = theCommand->GetArg( 2 );
2576 _AString face = theCommand->GetArg( 3 );
2577 _AString point = theCommand->GetArg( 4 );
2578 theCommand->RemoveArgs();
2579 theCommand->SetArg( 1, mesh );
2580 theCommand->SetArg( 2, dir );
2581 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2582 theCommand->SetArg( 3, point );
2584 theCommand->SetArg( 3, face );
2587 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2589 isPyMeshMethod = true;
2590 int crit_arg = theCommand->GetNbArgs();
2591 const _AString& crit = theCommand->GetArg(crit_arg);
2592 if (crit.Search("MaxElementLength2D") != -1)
2593 theCommand->SetArg(crit_arg, "");
2596 if ( isPyMeshMethod )
2598 theCommand->SetObject( myMesh );
2602 // editor creation command is needed only if any editor function is called
2603 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2604 if ( !myCreationCmdStr.IsEmpty() ) {
2605 GetCreationCmd()->GetString() = myCreationCmdStr;
2606 myCreationCmdStr.Clear();
2611 //================================================================================
2613 * \brief Return true if my mesh can be removed
2615 //================================================================================
2617 bool _pyMeshEditor::CanClear()
2619 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2620 return mesh.IsNull() ? true : mesh->CanClear();
2623 //================================================================================
2625 * \brief _pyHypothesis constructor
2626 * \param theCreationCmd -
2628 //================================================================================
2630 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2631 _pyObject( theCreationCmd ), myCurCrMethod(0)
2633 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2636 //================================================================================
2638 * \brief Creates algorithm or hypothesis
2639 * \param theCreationCmd - The engine command creating a hypothesis
2640 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2642 //================================================================================
2644 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2646 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2647 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2649 Handle(_pyHypothesis) hyp, algo;
2652 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2653 if ( hypTypeQuoted.IsEmpty() )
2656 TCollection_AsciiString hypType =
2657 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2659 algo = new _pyAlgorithm( theCreationCmd );
2660 hyp = new _pyHypothesis( theCreationCmd );
2662 if ( hypType == "NumberOfSegments" ) {
2663 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2664 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2665 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2666 hyp->AddArgMethod( "SetNumberOfSegments" );
2667 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2668 hyp->AddArgMethod( "SetScaleFactor" );
2669 hyp->AddArgMethod( "SetReversedEdges" );
2670 // same for ""CompositeSegment_1D:
2671 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2672 hyp->AddArgMethod( "SetNumberOfSegments" );
2673 hyp->AddArgMethod( "SetScaleFactor" );
2674 hyp->AddArgMethod( "SetReversedEdges" );
2676 else if ( hypType == "SegmentLengthAroundVertex" ) {
2677 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2678 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2679 hyp->AddArgMethod( "SetLength" );
2680 // same for ""CompositeSegment_1D:
2681 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2682 hyp->AddArgMethod( "SetLength" );
2684 else if ( hypType == "LayerDistribution2D" ) {
2685 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2686 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2688 else if ( hypType == "LayerDistribution" ) {
2689 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2690 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2692 else if ( hypType == "CartesianParameters3D" ) {
2693 hyp = new _pyComplexParamHypo( theCreationCmd );
2694 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2695 for ( int iArg = 0; iArg < 4; ++iArg )
2696 hyp->setCreationArg( iArg+1, "[]");
2697 hyp->AddAccumulativeMethod( "SetGrid" );
2698 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2702 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2705 return algo->IsValid() ? algo : hyp;
2708 //================================================================================
2710 * \brief Returns true if addition of this hypothesis to a given mesh can be
2711 * wrapped into hypothesis creation
2713 //================================================================================
2715 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2717 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2719 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2720 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2726 //================================================================================
2728 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2729 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2730 * \param theAlgo - The algo that can create this hypo
2731 * \retval bool - false if the command can't be converted
2733 //================================================================================
2735 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2736 const _pyID& theMesh)
2738 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2740 if ( !IsWrappable( theMesh ))
2743 myGeom = theCmd->GetArg( 1 );
2745 Handle(_pyHypothesis) algo;
2747 // find algo created on myGeom in theMesh
2748 algo = theGen->FindAlgo( myGeom, theMesh, this );
2749 if ( algo.IsNull() )
2751 // attach hypothesis creation command to be after algo creation command
2752 // because it can be new created instance of algorithm
2753 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2757 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2758 theCmd->SetResultValue( GetID() );
2759 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2760 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2761 // set args (geom will be set by _pyMesh calling this method)
2762 theCmd->RemoveArgs();
2763 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2764 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2765 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2767 theCmd->SetArg( i+1, "[]");
2769 // set a new creation command
2770 GetCreationCmd()->Clear();
2771 // replace creation command by wrapped instance
2772 // please note, that hypothesis attaches to algo creation command (see upper)
2773 SetCreationCmd( theCmd );
2776 // clear commands setting arg values
2777 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2778 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2781 // set unknown arg commands after hypo creation
2782 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2783 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2784 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2785 afterCmd->AddDependantCmd( *cmd );
2791 //================================================================================
2793 * \brief Remember hypothesis parameter values
2794 * \param theCommand - The called hypothesis method
2796 //================================================================================
2798 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2800 ASSERT( !myIsAlgo );
2801 if ( !theGen->IsToKeepAllCommands() )
2802 rememberCmdOfParameter( theCommand );
2804 bool usedCommand = false;
2805 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2806 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2808 CreationMethod& crMethod = type2meth->second;
2809 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2810 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2812 myArgCommands.push_back( theCommand );
2814 while ( crMethod.myArgs.size() < i+1 )
2815 crMethod.myArgs.push_back( "None" );
2816 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2821 myUnusedCommands.push_back( theCommand );
2824 //================================================================================
2826 * \brief Finish conversion
2828 //================================================================================
2830 void _pyHypothesis::Flush()
2834 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2835 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2836 // Add access to a wrapped mesh
2837 theGen->AddMeshAccessorMethod( *cmd );
2838 // Add access to a wrapped algorithm
2839 theGen->AddAlgoAccessorMethod( *cmd );
2841 cmd = myUnusedCommands.begin();
2842 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2843 // Add access to a wrapped mesh
2844 theGen->AddMeshAccessorMethod( *cmd );
2845 // Add access to a wrapped algorithm
2846 theGen->AddAlgoAccessorMethod( *cmd );
2849 // forget previous hypothesis modifications
2850 myArgCommands.clear();
2851 myUnusedCommands.clear();
2854 //================================================================================
2856 * \brief clear creation, arg and unknown commands
2858 //================================================================================
2860 void _pyHypothesis::ClearAllCommands()
2862 GetCreationCmd()->Clear();
2863 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2864 for ( ; cmd != myArgCommands.end(); ++cmd )
2866 cmd = myUnusedCommands.begin();
2867 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2872 //================================================================================
2874 * \brief Assign fields of theOther to me except myIsWrapped
2876 //================================================================================
2878 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2879 const _pyID& theMesh )
2881 // myCreationCmd = theOther->myCreationCmd;
2882 myIsAlgo = theOther->myIsAlgo;
2883 myIsWrapped = false;
2884 myGeom = theOther->myGeom;
2886 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2887 myAccumulativeMethods = theOther->myAccumulativeMethods;
2888 //myUnusedCommands = theOther->myUnusedCommands;
2889 // init myCurCrMethod
2890 GetCreationMethod( theOther->GetAlgoType() );
2893 //================================================================================
2895 * \brief Analyze my erasability depending on myReferredObjs
2897 //================================================================================
2899 bool _pyHypothesis::CanClear()
2903 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2904 for ( ; obj != myReferredObjs.end(); ++obj )
2905 if ( (*obj)->CanClear() )
2912 //================================================================================
2914 * \brief Clear my commands depending on usage by meshes
2916 //================================================================================
2918 void _pyHypothesis::ClearCommands()
2920 // if ( !theGen->IsToKeepAllCommands() )
2922 // bool isUsed = false;
2923 // int lastComputeOrder = 0;
2924 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2925 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2926 // if ( ! (*cmd)->IsEmpty() )
2929 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2930 // lastComputeOrder = (*cmd)->GetOrderNb();
2934 // SetRemovedFromStudy( true );
2938 // // clear my commands invoked after lastComputeOrder
2939 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2940 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2942 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2943 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2944 // // cmds.back()->Clear();
2948 _pyObject::ClearCommands();
2951 //================================================================================
2953 * \brief Find arguments that are objects like mesh, group, geometry
2954 * \param meshes - referred meshes (directly or indirrectly)
2955 * \retval bool - false if a referred geometry is not in the study
2957 //================================================================================
2959 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2961 if ( IsAlgo() ) return true;
2963 bool geomPublished = true;
2964 vector< _AString > args;
2965 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2966 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2968 CreationMethod& crMethod = type2meth->second;
2969 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2971 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2972 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2973 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2974 args.push_back( (*cmd)->GetArg( nb ));
2977 for ( size_t i = 0; i < args.size(); ++i )
2979 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2980 if ( idList.empty() && !args[ i ].IsEmpty() )
2981 idList.push_back( args[ i ]);
2982 list< _pyID >::iterator id = idList.begin();
2983 for ( ; id != idList.end(); ++id )
2985 Handle(_pyObject) obj = theGen->FindObject( *id );
2986 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2989 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2990 geomPublished = false;
2994 myReferredObjs.push_back( obj );
2995 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2996 if ( !mesh.IsNull() )
2997 meshes.push_back( mesh );
2998 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2999 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3000 obj->SetRemovedFromStudy( false );
3004 return geomPublished;
3007 //================================================================================
3009 * \brief Remember theCommand setting a parameter
3011 //================================================================================
3013 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3015 // parameters are discriminated by method name
3016 _AString method = theCommand->GetMethod();
3017 if ( myAccumulativeMethods.count( method ))
3018 return; // this method adds values and not override the previus value
3020 // discriminate commands setting different parameters via one method
3021 // by passing parameter names like e.g. SetOption("size", "0.2")
3022 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3023 theCommand->GetNbArgs() > 1 )
3025 // mangle method by appending a 1st textual arg
3026 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3028 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3029 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3030 if ( !isalpha( arg.Value(2))) continue;
3035 // parameters are discriminated by method name
3036 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3037 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3039 cmds.back()->Clear(); // previous parameter value has not been used
3040 cmds.back() = theCommand;
3044 cmds.push_back( theCommand );
3048 //================================================================================
3050 * \brief Return true if a setting parameter command ha been used to compute mesh
3052 //================================================================================
3054 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3055 _pyCommand::TAddr avoidComputeAddr ) const
3057 bool isUsed = false;
3058 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3059 myComputeAddr2Cmds.begin();
3060 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3062 if ( addr2cmds->first == avoidComputeAddr ) continue;
3063 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3064 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3069 //================================================================================
3071 * \brief Save commands setting parameters as they are used for a mesh computation
3073 //================================================================================
3075 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3077 myComputeCmds.push_back( theComputeCmd );
3078 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3080 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3081 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3082 savedCmds.push_back( m2c->second.back() );
3085 //================================================================================
3087 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3089 //================================================================================
3091 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3093 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3095 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3096 for ( ; cmd != savedCmds.end(); ++cmd )
3098 // check if a cmd has been used to compute another mesh
3099 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3101 // check if a cmd is a sole command setting its parameter;
3102 // don't use method name for search as it can change
3103 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3104 m2cmds = myMeth2Commands.begin();
3105 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3107 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3108 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3109 if ( cmdIt != cmds.end() )
3111 if ( cmds.back() != *cmd )
3113 cmds.erase( cmdIt );
3120 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3123 //================================================================================
3125 * \brief Sets an argNb-th argument of current creation command
3126 * \param argNb - argument index countered from 1
3128 //================================================================================
3130 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3132 if ( myCurCrMethod )
3134 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3135 myCurCrMethod->myArgs.push_back( "None" );
3136 if ( arg.IsEmpty() )
3137 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3139 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3144 //================================================================================
3146 * \brief Remember hypothesis parameter values
3147 * \param theCommand - The called hypothesis method
3149 //================================================================================
3151 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3153 if ( GetAlgoType() == "Cartesian_3D" )
3155 // CartesianParameters3D hyp
3157 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3158 theCommand->GetMethod() == "SetToAddEdges" )
3160 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3161 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3162 myArgCommands.push_back( theCommand );
3165 if ( theCommand->GetMethod() == "SetGrid" ||
3166 theCommand->GetMethod() == "SetGridSpacing" )
3168 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3169 int iArg = axis.Value(1) - '0';
3170 if ( theCommand->GetMethod() == "SetGrid" )
3172 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3176 myCurCrMethod->myArgs[ iArg ] = "[ ";
3177 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3178 myCurCrMethod->myArgs[ iArg ] += ", ";
3179 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3180 myCurCrMethod->myArgs[ iArg ] += "]";
3182 myArgCommands.push_back( theCommand );
3183 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3184 // accumulative, else, if the creation
3185 // is not converted, commands for axes 1 and 2 are lost
3190 if( theCommand->GetMethod() == "SetLength" )
3192 // NOW it is OBSOLETE
3193 // ex: hyp.SetLength(start, 1)
3194 // hyp.SetLength(end, 0)
3195 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3196 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3197 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3198 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3200 CreationMethod& crMethod = type2meth->second;
3201 while ( (int) crMethod.myArgs.size() < i+1 )
3202 crMethod.myArgs.push_back( "[]" );
3203 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3205 myArgCommands.push_back( theCommand );
3209 _pyHypothesis::Process( theCommand );
3212 //================================================================================
3214 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3216 //================================================================================
3218 void _pyComplexParamHypo::Flush()
3220 list < Handle(_pyCommand) >::iterator cmd;
3223 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3224 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3228 // if ( GetAlgoType() == "Cartesian_3D" )
3230 // _pyID algo = myCreationCmd->GetObject();
3231 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3233 // if ( IsWrapped() )
3235 // StructToList( *cmd, /*checkMethod=*/false );
3236 // const _AString & method = (*cmd)->GetMethod();
3237 // if ( method == "SetFixedPoint" )
3238 // (*cmd)->SetObject( algo );
3244 //================================================================================
3246 * \brief Convert methods of 1D hypotheses to my own methods
3247 * \param theCommand - The called hypothesis method
3249 //================================================================================
3251 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3253 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3256 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3257 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3258 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3260 // TCollection_AsciiString cmd =
3261 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3262 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3263 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3266 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3268 // // 1D hypo is already set, so distribution changes and the old
3269 // // 1D hypo is thrown away
3270 // my1dHyp->ClearAllCommands();
3273 // //my1dHyp->SetRemovedFromStudy( false );
3275 // if ( !myArgCommands.empty() )
3276 // myArgCommands.back()->Clear();
3277 myCurCrMethod->myArgs.push_back( hyp1dID );
3278 myArgCommands.push_back( theCommand );
3281 //================================================================================
3284 * \param theAdditionCmd - command to be converted
3285 * \param theMesh - mesh instance
3286 * \retval bool - status
3288 //================================================================================
3290 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3291 const _pyID& theMesh)
3293 myIsWrapped = false;
3295 if ( my1dHyp.IsNull() )
3298 // set "SetLayerDistribution()" after addition cmd
3299 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3301 _pyID geom = theAdditionCmd->GetArg( 1 );
3303 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3304 if ( !algo.IsNull() )
3306 my1dHyp->SetMesh( theMesh );
3307 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3308 algo->GetAlgoType().ToCString());
3309 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3312 // clear "SetLayerDistribution()" cmd
3313 myArgCommands.back()->Clear();
3315 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3317 // find RadialPrism algo created on <geom> for theMesh
3318 GetCreationCmd()->SetObject( algo->GetID() );
3319 GetCreationCmd()->SetMethod( myAlgoMethod );
3320 GetCreationCmd()->RemoveArgs();
3321 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3327 //================================================================================
3331 //================================================================================
3333 void _pyLayerDistributionHypo::Flush()
3335 // as creation of 1D hyp was written later then it's edition,
3336 // we need to find all it's edition calls and process them
3337 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3339 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3341 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3342 if ( hyp1dID.IsEmpty() ) continue;
3344 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3346 // make a new name for 1D hyp = "HypType" + "_Distribution"
3348 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3350 if ( prevNewName.IsEmpty() ) continue;
3351 newName = prevNewName;
3355 if ( hyp1d->IsWrapped() ) {
3356 newName = hyp1d->GetCreationCmd()->GetMethod();
3359 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3360 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3362 newName += "_Distribution";
3363 prevNewName = newName;
3365 hyp1d->GetCreationCmd()->SetResultValue( newName );
3367 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3368 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3369 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3370 const _pyID& objID = (*cmdIt)->GetObject();
3371 if ( objID == hyp1dID ) {
3372 if ( !hyp1d.IsNull() )
3374 hyp1d->Process( *cmdIt );
3375 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3377 ( *cmdIt )->SetObject( newName );
3380 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3381 (*cmd)->SetArg( 1, newName );
3385 //================================================================================
3387 * \brief additionally to Addition2Creation, clears SetDistrType() command
3388 * \param theCmd - AddHypothesis() command
3389 * \param theMesh - mesh to which a hypothesis is added
3390 * \retval bool - conversion result
3392 //================================================================================
3394 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3395 const _pyID& theMesh)
3397 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3398 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3399 bool scaleDistrType = false;
3400 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3401 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3402 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3403 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3404 scaleDistrType = true;
3407 else if ( !scaleDistrType ) {
3408 // distribution type changed: remove scale factor from args
3409 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3410 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3412 CreationMethod& crMethod = type2meth->second;
3413 if ( crMethod.myArgs.size() == 2 )
3414 crMethod.myArgs.pop_back();
3421 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3424 //================================================================================
3426 * \brief remove repeated commands defining distribution
3428 //================================================================================
3430 void _pyNumberOfSegmentsHyp::Flush()
3432 // find number of the last SetDistrType() command
3433 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3434 int distrTypeNb = 0;
3435 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3436 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3437 if ( cmd != myUnusedCommands.rbegin() )
3438 distrTypeNb = (*cmd)->GetOrderNb();
3440 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3443 // clear commands before the last SetDistrType()
3444 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3445 set< int > treatedCmdNbs; // avoid treating same cmd twice
3446 for ( int i = 0; i < 2; ++i ) {
3447 set<TCollection_AsciiString> uniqueMethods;
3448 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3449 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3451 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3452 continue;// avoid treating same cmd twice
3453 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3454 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3455 if ( !clear || method == "SetNumberOfSegments" ) {
3456 bool isNewInSet = uniqueMethods.insert( method ).second;
3457 clear = !isNewInSet;
3466 //================================================================================
3468 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3469 * into regular1D.LengthNearVertex( length, vertex )
3470 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3471 * \param theMesh - The mesh needing this hypo
3472 * \retval bool - false if the command can't be converted
3474 //================================================================================
3476 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3477 const _pyID& theMeshID)
3479 if ( IsWrappable( theMeshID )) {
3481 _pyID vertex = theCmd->GetArg( 1 );
3483 // the problem here is that segment algo can be not found
3484 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3485 // geometry where segment algorithm is assigned
3486 _pyID geom = vertex;
3487 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3488 while ( algo.IsNull() && !geom.IsEmpty()) {
3489 // try to find geom as a father of <vertex>
3490 geom = FatherID( geom );
3491 algo = theGen->FindAlgo( geom, theMeshID, this );
3493 if ( algo.IsNull() || geom.IsEmpty() )
3494 return false; // also possible to find geom as brother of veretex...
3496 // set geom instead of vertex
3497 theCmd->SetArg( 1, geom );
3499 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3500 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3501 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3503 // set vertex as a second arg
3504 theCmd->SetArg( 2, vertex );
3512 //================================================================================
3514 * \brief _pyAlgorithm constructor
3515 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3517 //================================================================================
3519 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3520 : _pyHypothesis( theCreationCmd )
3525 //================================================================================
3527 * \brief Convert the command adding an algorithm to mesh
3528 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3529 * \param theMesh - The mesh needing this algo
3530 * \retval bool - false if the command can't be converted
3532 //================================================================================
3534 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3535 const _pyID& theMeshID)
3537 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3538 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3539 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3545 //================================================================================
3547 * \brief Return starting position of a part of python command
3548 * \param thePartIndex - The index of command part
3549 * \retval int - Part position
3551 //================================================================================
3553 int _pyCommand::GetBegPos( int thePartIndex ) const
3557 if ( myBegPos.Length() < thePartIndex )
3559 ASSERT( thePartIndex > 0 );
3560 return myBegPos( thePartIndex );
3563 //================================================================================
3565 * \brief Store starting position of a part of python command
3566 * \param thePartIndex - The index of command part
3567 * \param thePosition - Part position
3569 //================================================================================
3571 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3573 while ( myBegPos.Length() < thePartIndex )
3574 myBegPos.Append( UNKNOWN );
3575 ASSERT( thePartIndex > 0 );
3576 myBegPos( thePartIndex ) = thePosition;
3579 //================================================================================
3581 * \brief Returns whitespace symbols at the line beginning
3582 * \retval TCollection_AsciiString - result
3584 //================================================================================
3586 TCollection_AsciiString _pyCommand::GetIndentation()
3589 //while ( end <= Length() && isblank( myString.Value( end )))
3590 //ANA: isblank() function isn't provided in VC2010 compiler
3591 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3593 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3596 //================================================================================
3598 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3599 * \retval const TCollection_AsciiString & - ResultValue substring
3601 //================================================================================
3603 const TCollection_AsciiString & _pyCommand::GetResultValue()
3605 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3607 SetBegPos( RESULT_IND, EMPTY );
3608 int begPos, endPos = myString.Location( "=", 1, Length() );
3612 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3613 if ( begPos < endPos )
3615 SetBegPos( RESULT_IND, begPos );
3617 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3618 myRes = myString.SubString( begPos, endPos );
3625 //================================================================================
3627 * \brief Return number of python command result value ResultValue = Obj.Meth()
3629 //================================================================================
3631 int _pyCommand::GetNbResultValues()
3634 return myResults.Length();
3638 //================================================================================
3640 * \brief Return substring of python command looking like
3641 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3642 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3644 //================================================================================
3645 const _AString& _pyCommand::GetResultValue(int res)
3647 if ( GetResultValue().IsEmpty() )
3648 return theEmptyString;
3650 if ( myResults.IsEmpty() )
3653 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3654 ++begPos; // skip [, else the whole list is returned
3655 while ( begPos < myRes.Length() ) {
3656 _AString result = GetWord( myRes, begPos, true );
3657 begPos += result.Length();
3659 // result.RemoveAll('[');
3660 // result.RemoveAll(']');
3665 myResults.Append( result );
3668 if ( res > 0 && res <= myResults.Length() )
3669 return myResults( res );
3670 return theEmptyString;
3673 //================================================================================
3675 * \brief Return substring of python command looking like ResVal = Object.Meth()
3676 * \retval const TCollection_AsciiString & - Object substring
3678 //================================================================================
3680 const TCollection_AsciiString & _pyCommand::GetObject()
3682 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3685 int begPos = GetBegPos( RESULT_IND );
3687 begPos = myString.Location( "=", 1, Length() ) + 1;
3688 // is '=' in the string argument (for example, name) or not
3689 int nb1 = 0; // number of ' character at the left of =
3690 int nb2 = 0; // number of " character at the left of =
3691 for ( int i = 1; i < begPos-1; i++ ) {
3692 if ( myString.Value( i )=='\'' )
3694 else if ( myString.Value( i )=='"' )
3697 // if number of ' or " is not divisible by 2,
3698 // then get an object at the start of the command
3699 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3703 begPos += myRes.Length();
3705 myObj = GetWord( myString, begPos, true );
3706 if ( begPos != EMPTY )
3708 // check if object is complex,
3709 // so far consider case like "smesh.Method()"
3710 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3711 //if ( bracketPos==0 ) bracketPos = Length();
3712 int dotPos = begPos+myObj.Length();
3713 while ( dotPos+1 < bracketPos ) {
3714 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3719 if ( dotPos > begPos+myObj.Length() )
3720 myObj = myString.SubString( begPos, dotPos-1 );
3723 // 1st word after '=' is an object
3724 // else // no method -> no object
3730 SetBegPos( OBJECT_IND, begPos );
3736 //================================================================================
3738 * \brief Return substring of python command looking like ResVal = Obj.Method()
3739 * \retval const TCollection_AsciiString & - Method substring
3741 //================================================================================
3743 const TCollection_AsciiString & _pyCommand::GetMethod()
3745 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3748 int begPos = GetBegPos( OBJECT_IND );
3749 bool forward = true;
3751 begPos = myString.Location( "(", 1, Length() ) - 1;
3755 begPos += myObj.Length();
3758 myMeth = GetWord( myString, begPos, forward );
3759 SetBegPos( METHOD_IND, begPos );
3765 //================================================================================
3767 * \brief Returns true if there are brackets after the method
3769 //================================================================================
3771 bool _pyCommand::IsMethodCall()
3773 if ( GetMethod().IsEmpty() )
3775 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3776 return ( s[0] == '(' || s[1] == '(' );
3779 //================================================================================
3781 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3782 * \retval const TCollection_AsciiString & - Arg<index> substring
3784 //================================================================================
3786 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3788 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3792 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3794 pos = myString.Location( "(", 1, Length() );
3798 // we are at or before '(', skip it if present
3800 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3801 if ( pos > Length() )
3805 SetBegPos( ARG1_IND, 0 ); // even no '('
3806 return theEmptyString;
3810 list< TCollection_AsciiString > separatorStack( 1, ",)");
3811 bool ignoreNesting = false;
3813 while ( pos <= Length() )
3815 const char chr = myString.Value( pos );
3817 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3819 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3821 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3823 TCollection_AsciiString arg;
3824 if ( pos-1 >= prevPos ) {
3825 arg = myString.SubString( prevPos, pos-1 );
3826 arg.RightAdjust(); // remove spaces
3829 if ( !arg.IsEmpty() || chr == ',' )
3831 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3832 myArgs.Append( arg );
3838 else // end of nesting args found
3840 separatorStack.pop_back();
3841 ignoreNesting = false;
3844 else if ( !ignoreNesting )
3847 case '(' : separatorStack.push_back(")"); break;
3848 case '[' : separatorStack.push_back("]"); break;
3849 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3850 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3857 if ( myArgs.Length() < index )
3858 return theEmptyString;
3859 return myArgs( index );
3862 //================================================================================
3864 * \brief Return position where arguments begin
3866 //================================================================================
3868 int _pyCommand::GetArgBeginning() const
3870 int pos = GetBegPos( ARG1_IND );
3871 if ( pos == UNKNOWN )
3873 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3875 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3880 //================================================================================
3882 * \brief Check if char is a word part
3883 * \param c - The character to check
3884 * \retval bool - The check result
3886 //================================================================================
3888 static inline bool isWord(const char c, const bool dotIsWord)
3891 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3894 //================================================================================
3896 * \brief Looks for a word in the string and returns word's beginning
3897 * \param theString - The input string
3898 * \param theStartPos - The position to start the search, returning word's beginning
3899 * \param theForward - The search direction
3900 * \retval TCollection_AsciiString - The found word
3902 //================================================================================
3904 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3906 const bool theForward,
3907 const bool dotIsWord )
3909 int beg = theStartPos, end = theStartPos;
3910 theStartPos = EMPTY;
3911 if ( beg < 1 || beg > theString.Length() )
3912 return theEmptyString;
3914 if ( theForward ) { // search forward
3916 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3918 if ( beg > theString.Length() )
3919 return theEmptyString; // no word found
3922 char begChar = theString.Value( beg );
3923 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3924 char endChar = ( begChar == '[' ) ? ']' : begChar;
3925 // end is at the corresponding quoting mark or bracket
3926 while ( end < theString.Length() &&
3927 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3931 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3936 else { // search backward
3938 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3941 return theEmptyString; // no word found
3943 char endChar = theString.Value( end );
3944 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3945 char begChar = ( endChar == ']' ) ? '[' : endChar;
3946 // beg is at the corresponding quoting mark
3948 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3952 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3958 //cout << theString << " ---- " << beg << " - " << end << endl;
3959 return theString.SubString( beg, end );
3962 //================================================================================
3964 * \brief Returns true if the string looks like a study entry
3966 //================================================================================
3968 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3970 if ( str.Length() < 5 ) return false;
3972 int nbColons = 0, isColon;
3973 for ( int i = 1; i <= str.Length(); ++i )
3975 char c = str.Value(i);
3976 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3978 nbColons += isColon;
3980 return nbColons > 2 && str.Length()-nbColons > 2;
3983 //================================================================================
3985 * \brief Returns true if the string looks like an object ID but not like a list,
3986 * string, command etc.
3988 //================================================================================
3990 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3992 if ( str.Length() < 1 ) return false;
3994 const char* s = str.ToCString();
3996 for ( int i = 0; i < str.Length(); ++i )
3997 if ( !IsIDChar( s[i] ))
4003 //================================================================================
4005 * \brief Finds entries in a sting
4007 //================================================================================
4009 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4011 std::list< _pyID > resList;
4013 while ( ++pos <= str.Length() )
4015 if ( !isdigit( str.Value( pos ))) continue;
4016 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4019 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4020 _pyID entry = str.SubString( pos, end-1 );
4022 if ( IsStudyEntry( entry ))
4023 resList.push_back( entry );
4028 //================================================================================
4030 * \brief Look for position where not space char is
4031 * \param theString - The string
4032 * \param thePos - The position to search from and which returns result
4033 * \retval bool - false if there are only space after thePos in theString
4035 //================================================================================
4037 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4039 if ( thePos < 1 || thePos > theString.Length() )
4042 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4045 return thePos <= theString.Length();
4048 //================================================================================
4050 * \brief Modify a part of the command
4051 * \param thePartIndex - The index of the part
4052 * \param thePart - The new part string
4053 * \param theOldPart - The old part
4055 //================================================================================
4057 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4058 TCollection_AsciiString& theOldPart)
4060 int pos = GetBegPos( thePartIndex );
4061 if ( pos <= Length() && theOldPart != thePart)
4063 TCollection_AsciiString seperator;
4065 pos = GetBegPos( thePartIndex + 1 );
4066 if ( pos < 1 ) return;
4067 switch ( thePartIndex ) {
4068 case RESULT_IND: seperator = " = "; break;
4069 case OBJECT_IND: seperator = "."; break;
4070 case METHOD_IND: seperator = "()"; break;
4074 myString.Remove( pos, theOldPart.Length() );
4075 if ( !seperator.IsEmpty() )
4076 myString.Insert( pos , seperator );
4077 myString.Insert( pos, thePart );
4078 // update starting positions of the following parts
4079 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4080 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4081 if ( myBegPos( i ) > 0 )
4082 myBegPos( i ) += posDelta;
4084 theOldPart = thePart;
4088 //================================================================================
4090 * \brief Set argument
4091 * \param index - The argument index, it counts from 1
4092 * \param theArg - The argument string
4094 //================================================================================
4096 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4099 int argInd = ARG1_IND + index - 1;
4100 int pos = GetBegPos( argInd );
4101 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4103 // find a closing parenthesis
4104 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4105 int lastArgInd = GetNbArgs();
4106 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4107 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4112 while ( pos > 0 && myString.Value( pos ) != ')' )
4115 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4119 while ( myArgs.Length() < index ) {
4120 if ( myArgs.Length() )
4121 myString.Insert( pos++, "," );
4122 myArgs.Append("None");
4123 myString.Insert( pos, myArgs.Last() );
4124 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4125 pos += myArgs.Last().Length();
4128 SetPart( argInd, theArg, myArgs( index ));
4131 //================================================================================
4133 * \brief Empty arg list
4135 //================================================================================
4137 void _pyCommand::RemoveArgs()
4139 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4140 myString.Trunc( pos );
4143 if ( myBegPos.Length() >= ARG1_IND )
4144 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4147 //================================================================================
4149 * \brief Comment a python command
4151 //================================================================================
4153 void _pyCommand::Comment()
4155 if ( IsEmpty() ) return;
4158 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4159 if ( i <= Length() )
4161 myString.Insert( i, "#" );
4162 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4164 int begPos = GetBegPos( iPart );
4165 if ( begPos != UNKNOWN && begPos != EMPTY )
4166 SetBegPos( iPart, begPos + 1 );
4171 //================================================================================
4173 * \brief Set dependent commands after this one
4175 //================================================================================
4177 bool _pyCommand::SetDependentCmdsAfter() const
4179 bool orderChanged = false;
4180 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4181 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4182 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4183 orderChanged = true;
4184 theGen->SetCommandAfter( *cmd, this );
4185 (*cmd)->SetDependentCmdsAfter();
4188 return orderChanged;
4190 //================================================================================
4192 * \brief Insert accessor method after theObjectID
4193 * \param theObjectID - id of the accessed object
4194 * \param theAcsMethod - name of the method giving access to the object
4195 * \retval bool - false if theObjectID is not found in the command string
4197 //================================================================================
4199 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4201 if ( !theAcsMethod )
4203 // start object search from the object, i.e. ignore result
4205 int beg = GetBegPos( OBJECT_IND );
4206 if ( beg < 1 || beg > Length() )
4209 while (( beg = myString.Location( theObjectID, beg, Length() )))
4211 // check that theObjectID is not just a part of a longer ID
4212 int afterEnd = beg + theObjectID.Length();
4213 Standard_Character c = myString.Value( afterEnd );
4214 if ( !IsIDChar( c ))
4216 // check if accessor method already present
4218 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4220 int oldLen = Length();
4221 myString.Insert( afterEnd, (char*) theAcsMethod );
4222 myString.Insert( afterEnd, "." );
4223 // update starting positions of the parts following the modified one
4224 int posDelta = Length() - oldLen;
4225 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4226 if ( myBegPos( i ) > afterEnd )
4227 myBegPos( i ) += posDelta;
4232 beg = afterEnd; // is a part -> next search
4237 //================================================================================
4239 * \brief Creates pyObject
4241 //================================================================================
4243 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4244 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4249 //================================================================================
4251 * \brief Set up myID and myIsPublished
4253 //================================================================================
4255 void _pyObject::setID(const _pyID& theID)
4258 myIsPublished = !theGen->IsNotPublished( GetID() );
4261 //================================================================================
4263 * \brief Clear myCreationCmd and myProcessedCmds
4265 //================================================================================
4267 void _pyObject::ClearCommands()
4272 if ( !myCreationCmd.IsNull() )
4273 myCreationCmd->Clear();
4275 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4276 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4280 //================================================================================
4282 * \brief Return method name giving access to an interaface object wrapped by python class
4283 * \retval const char* - method name
4285 //================================================================================
4287 const char* _pyObject::AccessorMethod() const
4291 //================================================================================
4293 * \brief Return ID of a father
4295 //================================================================================
4297 _pyID _pyObject::FatherID(const _pyID & childID)
4299 int colPos = childID.SearchFromEnd(':');
4301 return childID.SubString( 1, colPos-1 );
4305 //================================================================================
4307 * \brief SelfEraser erases creation command if none of it's commands invoked
4308 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4310 //================================================================================
4312 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4313 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4315 myIsPublished = true; // prevent clearing as a not published
4316 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4319 //================================================================================
4321 * \brief SelfEraser erases creation command if none of it's commands invoked
4322 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4324 //================================================================================
4326 bool _pySelfEraser::CanClear()
4328 bool toErase = false;
4329 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4332 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4333 for ( ; cmd != myArgCmds.end(); ++cmd )
4334 nbArgUses += IsAliveCmd( *cmd );
4336 toErase = ( nbArgUses < 1 );
4341 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4342 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4343 for ( ; cmd != cmds.end(); )
4344 // check of cmd emptiness is not enough as object can change
4345 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4348 cmd = cmds.erase( cmd ); // save the cmd from clearing
4350 toErase = ( nbCalls < 1 );
4355 //================================================================================
4357 * \brief Check if a command is or can be cleared
4359 //================================================================================
4361 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4363 if ( theCmd->IsEmpty() )
4366 if ( !theGen->IsToKeepAllCommands() )
4368 const _pyID& objID = theCmd->GetObject();
4369 Handle( _pyObject ) obj = theGen->FindObject( objID );
4370 if ( !obj.IsNull() )
4371 return !obj->CanClear();
4376 //================================================================================
4378 * \brief SelfEraser erases creation command if none of it's commands invoked
4379 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4381 //================================================================================
4383 void _pySelfEraser::Flush()
4387 myIsPublished = false;
4388 _pyObject::ClearCommands();
4392 //================================================================================
4394 * \brief _pySubMesh constructor
4396 //================================================================================
4398 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4399 _pyObject(theCreationCmd)
4401 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4402 if ( toKeepAgrCmds )
4403 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4406 //================================================================================
4408 * \brief Return true if a sub-mesh can be used as argument of the given method
4410 //================================================================================
4412 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4415 // names of all methods where a sub-mesh can be used as argument
4416 // static TStringSet methods;
4417 // if ( methods.empty() ) {
4418 // const char * names[] = {
4419 // // methods of SMESH_Gen
4421 // // methods of SMESH_Group
4423 // // methods of SMESH_Measurements
4425 // // methods of SMESH_Mesh
4426 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4428 // // methods of SMESH_MeshEditor
4429 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4430 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4431 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4432 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4433 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4434 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4435 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4436 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4437 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4438 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4439 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4440 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4441 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4442 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4443 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4444 // "" }; // <- mark of end
4445 // methods.Insert( names );
4447 // return methods.Contains( theMethodName );
4450 //================================================================================
4452 * \brief count invoked commands
4454 //================================================================================
4456 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4458 _pyObject::Process(theCommand); // count calls of Process()
4461 //================================================================================
4463 * \brief Move creation command depending on invoked commands
4465 //================================================================================
4467 void _pySubMesh::Flush()
4469 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4470 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4471 else if ( !myCreator.IsNull() )
4472 // move to be just after creator
4473 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4475 // move sub-mesh usage after creation cmd
4476 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4477 for ( ; cmd != myArgCmds.end(); ++cmd )
4478 if ( !(*cmd)->IsEmpty() )
4479 GetCreationCmd()->AddDependantCmd( *cmd );
4482 //================================================================================
4484 * \brief Creates _pyGroup
4486 //================================================================================
4488 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4489 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4491 if ( !id.IsEmpty() )
4494 myCanClearCreationCmd = true;
4496 const _AString& method = theCreationCmd->GetMethod();
4497 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4499 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4501 // ----------------------------------------------------------------------
4502 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4504 _pyID geom = theCreationCmd->GetArg( 3 );
4505 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4506 // next if(){...} section is commented
4507 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4508 // theCreationCmd->SetMethod( "Group" );
4509 // theCreationCmd->RemoveArgs();
4510 // theCreationCmd->SetArg( 1, geom );
4513 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4514 _pyID type = theCreationCmd->GetArg( 1 );
4515 _pyID name = theCreationCmd->GetArg( 2 );
4516 theCreationCmd->SetMethod( "GroupOnGeom" );
4517 theCreationCmd->RemoveArgs();
4518 theCreationCmd->SetArg( 1, geom );
4519 theCreationCmd->SetArg( 2, name );
4520 theCreationCmd->SetArg( 3, type );
4523 else if ( method == "CreateGroupFromFilter" )
4525 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4526 theCreationCmd->SetMethod( "GroupOnFilter" );
4528 _pyID filterID = theCreationCmd->GetArg(3);
4529 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4530 if ( !filter.IsNull())
4532 if ( !filter->GetNewID().IsEmpty() )
4533 theCreationCmd->SetArg( 3, filter->GetNewID() );
4534 //filter->AddUser( this );
4538 else if ( method == "GetGroups" )
4540 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4544 // theCreationCmd does something else apart from creation of this group
4545 // and thus it can't be cleared if this group is removed
4546 myCanClearCreationCmd = false;
4550 //================================================================================
4552 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4555 //================================================================================
4557 bool _pyGroup::CanClear()
4562 if ( !myCanClearCreationCmd &&
4563 !myCreationCmd.IsNull() &&
4564 myCreationCmd->GetMethod() == "GetGroups" )
4566 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4567 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4568 list< _pyID >::iterator grID = idList.begin();
4569 if ( GetID() == *grID )
4571 myCanClearCreationCmd = true;
4572 list< Handle(_pyGroup ) > groups;
4573 for ( ; grID != idList.end(); ++grID )
4575 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4576 if ( group.IsNull() ) continue;
4577 groups.push_back( group );
4578 if ( group->IsInStudy() )
4579 myCanClearCreationCmd = false;
4581 // set myCanClearCreationCmd == true to all groups
4582 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4583 for ( ; group != groups.end(); ++group )
4584 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4588 return myCanClearCreationCmd;
4591 //================================================================================
4593 * \brief set myCanClearCreationCmd = true if the main action of the creation
4594 * command is discarded
4596 //================================================================================
4598 void _pyGroup::RemovedWithContents()
4600 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4601 // via a created group
4602 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4603 // myCanClearCreationCmd = true;
4606 //================================================================================
4608 * \brief To convert creation of a group by filter
4610 //================================================================================
4612 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4614 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4615 // group = mesh.CreateEmptyGroup( elemType, groupName )
4616 // aFilter.SetMesh(mesh)
4617 // nbAdd = group.AddFrom( aFilter )
4618 Handle(_pyFilter) filter;
4619 if ( theCommand->GetMethod() == "AddFrom" )
4621 _pyID idSource = theCommand->GetArg(1);
4622 // check if idSource is a filter
4623 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4624 if ( !filter.IsNull() )
4626 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4627 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4628 while ( *cmdIt != theCommand ) ++cmdIt;
4629 while ( (*cmdIt)->GetOrderNb() != 1 )
4631 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4632 if ((setMeshCmd->GetObject() == idSource ||
4633 setMeshCmd->GetObject() == filter->GetNewID() )
4635 setMeshCmd->GetMethod() == "SetMesh")
4637 setMeshCmd->Clear();
4641 // replace 3 commands by one
4642 theCommand->Clear();
4643 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4644 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4645 if ( !filter->GetNewID().IsEmpty() )
4646 idSource = filter->GetNewID();
4647 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4648 makeGroupCmd->SetArg( 1, name );
4649 makeGroupCmd->SetArg( 2, idSource );
4650 filter->AddArgCmd( makeGroupCmd );
4653 else if ( theCommand->GetMethod() == "SetFilter" )
4655 // set new name of a filter or clear the command if the same filter is set
4656 _pyID filterID = theCommand->GetArg(1);
4657 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4658 if ( !myFilter.IsNull() && filter == myFilter )
4659 theCommand->Clear();
4660 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4661 theCommand->SetArg( 1, filter->GetNewID() );
4664 else if ( theCommand->GetMethod() == "GetFilter" )
4666 // GetFilter() returns a filter with other ID, make myFilter process
4667 // calls of the returned filter
4668 if ( !myFilter.IsNull() )
4670 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4671 theCommand->Clear();
4675 // if ( !filter.IsNull() )
4676 // filter->AddUser( this );
4678 theGen->AddMeshAccessorMethod( theCommand );
4681 //================================================================================
4683 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4685 //================================================================================
4687 void _pyGroup::Flush()
4689 if ( !theGen->IsToKeepAllCommands() &&
4690 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4692 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4696 //================================================================================
4698 * \brief Constructor of _pyFilter
4700 //================================================================================
4702 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4703 :_pyObject(theCreationCmd), myNewID( newID )
4705 //myIsPublished = true; // prevent clearing as a not published
4706 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4709 //================================================================================
4711 * \brief To convert creation of a filter by criteria and
4712 * to replace an old name by a new one
4714 //================================================================================
4716 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4718 if ( theCommand->GetObject() == GetID() )
4719 _pyObject::Process(theCommand); // count commands
4721 if ( !myNewID.IsEmpty() )
4722 theCommand->SetObject( myNewID );
4724 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4725 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4726 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4727 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4728 theCommand->GetMethod() == "SetCriteria")
4730 // aFilter.SetCriteria(aCriteria) ->
4731 // aFilter = smesh.GetFilterFromCriteria(criteria)
4732 if ( myNewID.IsEmpty() )
4733 theCommand->SetResultValue( GetID() );
4735 theCommand->SetResultValue( myNewID );
4736 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4737 theCommand->SetMethod( "GetFilterFromCriteria" );
4739 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4740 GetCreationCmd()->Clear();
4741 GetCreationCmd()->GetString() = theCommand->GetString();
4742 theCommand->Clear();
4743 theCommand->AddDependantCmd( GetCreationCmd() );
4744 // why swap? -- it's needed
4745 //GetCreationCmd()->Clear();
4747 else if ( theCommand->GetMethod() == "SetMesh" )
4749 if ( myMesh == theCommand->GetArg( 1 ))
4750 theCommand->Clear();
4752 myMesh = theCommand->GetArg( 1 );
4753 theGen->AddMeshAccessorMethod( theCommand );
4757 //================================================================================
4759 * \brief Set new filter name to the creation command and to myArgCmds
4761 //================================================================================
4763 void _pyFilter::Flush()
4765 if ( myNewID.IsEmpty() ) return;
4767 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4768 for ( ; cmd != myArgCmds.end(); ++cmd )
4769 if ( !(*cmd)->IsEmpty() )
4771 _AString cmdStr = (*cmd)->GetString();
4772 _AString id = GetID();
4773 int pos = cmdStr.Search( id );
4776 cmdStr.Remove( pos, id.Length() );
4777 cmdStr.Insert( pos, myNewID );
4780 (*cmd)->GetString() = cmdStr;
4783 if ( !GetCreationCmd()->IsEmpty() )
4784 GetCreationCmd()->SetResultValue( myNewID );
4787 //================================================================================
4789 * \brief Return true if all my users can be cleared
4791 //================================================================================
4793 bool _pyObject::CanClear()
4795 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4796 for ( ; cmd != myArgCmds.end(); ++cmd )
4797 if ( !(*cmd)->IsEmpty() )
4799 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4800 if ( !obj.IsNull() && !obj->CanClear() )
4803 return ( !myIsPublished );
4806 //================================================================================
4808 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4810 //================================================================================
4812 _pyHypothesisReader::_pyHypothesisReader()
4815 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4816 LDOMParser xmlParser;
4817 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4819 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4823 INFOS( xmlParser.GetError(data) );
4826 // <algorithm type="Regular_1D"
4827 // label-id="Wire discretisation"
4830 // <algo>Regular_1D=Segment()</algo>
4831 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4833 LDOM_Document xmlDoc = xmlParser.getDocument();
4834 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4835 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4837 LDOM_Node algoNode = algoNodeList.item( i );
4838 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4839 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4840 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4842 _AString text, algoType, method, arg;
4843 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4845 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4846 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4847 text = textNode.getNodeValue();
4848 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4849 algoType = algoCmd->GetResultValue();
4850 method = algoCmd->GetMethod();
4851 arg = algoCmd->GetArg(1);
4852 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4854 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4855 algo->SetConvMethodAndType( method, algoType );
4856 if ( !arg.IsEmpty() )
4857 algo->setCreationArg( 1, arg );
4859 myType2Hyp[ algoType ] = algo;
4863 if ( algoType.IsEmpty() ) continue;
4865 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4867 Handle( _pyHypothesis ) hyp;
4868 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4870 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4871 LDOM_Node textNode = pyHypoNode.getFirstChild();
4872 text = textNode.getNodeValue();
4873 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4874 hypType = hypoCmd->GetResultValue();
4875 method = hypoCmd->GetMethod();
4876 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4878 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4879 if ( type2hyp == myType2Hyp.end() )
4880 hyp = new _pyHypothesis( hypoCmd );
4882 hyp = type2hyp->second;
4883 hyp->SetConvMethodAndType( method, algoType );
4884 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4886 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4887 _AString argMethod = argCmd.GetMethod();
4888 _AString argNbText = argCmd.GetArg( 1 );
4889 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4890 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4892 hyp->AddArgMethod( argMethod,
4893 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4895 myType2Hyp[ hypType ] = hyp;
4899 // <hypothesis type="BLSURF_Parameters"
4903 // <accumulative-methods>
4904 // SetEnforcedVertex,
4905 // SetEnforcedVertexNamed
4906 // </accumulative-methods>
4910 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4911 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4913 LDOM_Node hypNode = hypNodeList.item( i );
4914 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4915 _AString hypType = hypElem.getAttribute("type");
4916 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4917 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4919 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4920 if ( type2hyp == myType2Hyp.end() ) continue;
4922 LDOM_Node methNode = methNodeList.item( 0 );
4923 LDOM_Node textNode = methNode.getFirstChild();
4924 _AString text = textNode.getNodeValue();
4928 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4929 pos += method.Length();
4930 type2hyp->second->AddAccumulativeMethod( method );
4932 while ( !method.IsEmpty() );
4935 } // loop on xmlPaths
4938 //================================================================================
4940 * \brief Returns a new hypothesis initialized according to the read information
4942 //================================================================================
4944 Handle(_pyHypothesis)
4945 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4946 const Handle(_pyCommand)& creationCmd) const
4948 Handle(_pyHypothesis) resHyp, sampleHyp;
4950 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4951 if ( type2hyp != myType2Hyp.end() )
4952 sampleHyp = type2hyp->second;
4954 if ( sampleHyp.IsNull() )
4956 resHyp = new _pyHypothesis(creationCmd);
4960 if ( sampleHyp->IsAlgo() )
4961 resHyp = new _pyAlgorithm( creationCmd );
4963 resHyp = new _pyHypothesis(creationCmd);
4964 resHyp->Assign( sampleHyp, _pyID() );
4969 //================================================================================
4971 * \brief Adds an object ID to some family of IDs with a common prefix
4972 * \param [in] str - the object ID
4973 * \return bool - \c false if \a str does not have the same prefix as \a this family
4974 * (for internal usage)
4976 //================================================================================
4978 bool _pyStringFamily::Add( const char* str )
4980 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4981 return false; // expected prefix is missing
4983 str += _prefix.Length(); // skip _prefix
4985 // try to add to some of child falimies
4986 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4987 for ( ; itSub != _subFams.end(); ++itSub )
4988 if ( itSub->Add( str ))
4991 // no suitable family found - add str to _strings or create a new child family
4993 // look for a proper place within sorted _strings
4994 std::list< _AString >::iterator itStr = _strings.begin();
4995 while ( itStr != _strings.end() && itStr->IsLess( str ))
4997 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4998 return true; // same ID already kept
5000 const int minPrefixSize = 4;
5002 // count "smaller" strings with the same prefix
5003 std::list< _AString >::iterator itLess = itStr; --itLess;
5005 for ( ; itLess != _strings.end(); --itLess )
5006 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5011 // count "greater" strings with the same prefix
5012 std::list< _AString >::iterator itMore = itStr;
5014 for ( ; itMore != _strings.end(); ++itMore )
5015 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5020 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5022 // look for a maximal prefix length
5023 // int lessPrefSize = 3, morePrefSize = 3;
5024 // if ( nbLess > 0 )
5025 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5027 // if ( nbMore > 0 )
5028 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5030 // int prefixSize = 3;
5031 // if ( nbLess == 0 )
5032 // prefixSize = morePrefSize;
5033 // else if ( nbMore == 0 )
5034 // prefixSize = lessPrefSize;
5036 // prefixSize = Min( lessPrefSize, morePrefSize );
5037 int prefixSize = minPrefixSize;
5038 _AString newPrefix ( str, prefixSize );
5040 // look for a proper place within _subFams sorted by _prefix
5041 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5042 if ( !itSub->_prefix.IsLess( newPrefix ))
5045 // add the new _pyStringFamily
5046 itSub = _subFams.insert( itSub, _pyStringFamily());
5047 _pyStringFamily& newSubFam = *itSub;
5048 newSubFam._prefix = newPrefix;
5050 // pass this->_strings to newSubFam._strings
5051 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5052 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5053 newSubFam._strings.push_back( str + prefixSize );
5054 for ( ; nbMore > 0; --nbMore, ++itStr )
5055 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5057 _strings.erase( itLess, ++itMore );
5059 else // too few string to make a family for them
5061 _strings.insert( itStr, str );
5066 //================================================================================
5068 * \brief Finds an object ID in the command
5069 * \param [in] longStr - the command string
5070 * \param [out] subStr - the found object ID
5071 * \return bool - \c true if the object ID found
5073 //================================================================================
5075 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5077 const _AString& longStr = cmd->GetString();
5078 const char* s = longStr.ToCString();
5081 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5082 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5083 if ( argBeg < 4 || argBeg > longStr.Length() )
5085 for ( ; itSub != _subFams.end(); ++itSub )
5088 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5089 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5091 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5092 from = pos + len + itSub->_prefix.Length();
5097 from += itSub->_prefix.Length();
5100 // look among _strings
5101 std::list< _AString >::iterator itStr = _strings.begin();
5102 for ( ; itStr != _strings.end(); ++itStr )
5103 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5104 // check that object ID does not continue after len
5105 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5107 subStr.push_back( *itStr );
5113 //================================================================================
5115 * \brief Return remainder length of the object ID after my _prefix
5116 * \param [in] str - remainder of the command after my _prefix
5117 * \return int - length of the object ID or -1 if not found
5119 //================================================================================
5121 int _pyStringFamily::isIn( const char* str )
5123 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5125 for ( ; itSub != _subFams.end(); ++itSub )
5127 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5130 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5131 return itSub->_prefix.Length() + len;
5136 if ( !_strings.empty() )
5138 std::list< _AString >::iterator itStr = _strings.begin();
5139 bool firstEmpty = itStr->IsEmpty();
5142 for ( ; itStr != _strings.end(); ++itStr )
5144 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5147 len = itStr->Length();
5156 // check that object ID does not continue after len
5157 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5164 //================================================================================
5168 //================================================================================
5170 void _pyStringFamily::Print( int level )
5172 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5173 std::list< _AString >::iterator itStr = _strings.begin();
5174 for ( ; itStr != _strings.end(); ++itStr )
5175 cout << *itStr << " | ";
5177 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5178 for ( ; itSub != _subFams.end(); ++itSub )
5179 itSub->Print( level + 1 );
5181 cout << string( 70, '-' ) << endl;