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
299 // v 9.3.0: FT_Undefined == 50, new items:
300 // - FT_Length3D = 22
302 // It's necessary to continue recording this history and to fill
303 // undef2newItems (see below) accordingly.
305 typedef map< int, vector< int > > TUndef2newItems;
306 static TUndef2newItems undef2newItems;
307 if ( undef2newItems.empty() )
309 undef2newItems[ 26 ].push_back( 7 );
310 undef2newItems[ 27 ].push_back( 17 );
311 { int items[] = { 10, 11, 23, 24, 25 };
312 undef2newItems[ 32 ].assign( items, items+5 ); }
313 undef2newItems[ 33 ].push_back( 26 );
314 { int items[] = { 8, 9, 25, 26, 27, 28 };
315 undef2newItems[ 39 ].assign( items, items+6 ); }
316 { int items[] = { 14, 15, 16, 17 };
317 undef2newItems[ 43 ].assign( items, items+4 ); }
318 undef2newItems[ 44 ].push_back( 37 );
319 undef2newItems[ 45 ].push_back( 36 );
320 undef2newItems[ 46 ].push_back( 39 );
321 undef2newItems[ 47 ].push_back( 22 );
322 undef2newItems[ 48 ].push_back( 22 );
323 undef2newItems[ 49 ].push_back( 22 );
324 undef2newItems[ 50 ].push_back( 22 );
326 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
329 int iType = Type.IntegerValue();
330 int iCompare = Compare.IntegerValue();
331 int iUnaryOp = UnaryOp.IntegerValue();
332 int iBinaryOp = BinaryOp.IntegerValue();
334 // find out integer value of FT_Undefined at the moment of dump
335 int oldUndefined = iBinaryOp;
336 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
339 // apply history to args
340 TUndef2newItems::const_iterator undef_items =
341 undef2newItems.upper_bound( oldUndefined );
342 if ( undef_items != undef2newItems.end() )
344 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
345 for ( ; undef_items != undef2newItems.end(); ++undef_items )
347 const vector< int > & addedItems = undef_items->second;
348 for ( size_t i = 0; i < addedItems.size(); ++i )
349 for ( int iArg = 0; iArg < 4; ++iArg )
351 int& arg = *pArg[iArg];
352 if ( arg >= addedItems[i] )
356 Type = TCollection_AsciiString( iType );
357 Compare = TCollection_AsciiString( iCompare );
358 UnaryOp = TCollection_AsciiString( iUnaryOp );
359 BinaryOp = TCollection_AsciiString( iBinaryOp );
363 //================================================================================
365 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
366 * arguments of a given command by a list "[x,y,z]" if the list is accessible
369 //================================================================================
371 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
373 static TStringSet methodsAcceptingList;
374 if ( methodsAcceptingList.empty() ) {
375 const char * methodNames[] = {
376 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
377 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
378 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
379 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
380 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
381 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
382 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
383 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
384 "Translate","TranslateMakeGroups","TranslateMakeMesh",
385 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
386 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
387 ,"" }; // <- mark of the end
388 methodsAcceptingList.Insert( methodNames );
390 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
392 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
394 const _AString & arg = theCommand->GetArg( i );
395 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
396 arg.Search( "SMESH.DirStruct" ) == 1 )
398 Handle(_pyCommand) workCmd = new _pyCommand( arg );
399 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
401 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
403 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
405 _AString newArg = "[ ";
406 newArg += ( workCmd->GetArg( 1 ) + ", " +
407 workCmd->GetArg( 2 ) + ", " +
408 workCmd->GetArg( 3 ) + " ]");
409 theCommand->SetArg( i, newArg );
415 //================================================================================
417 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
418 * a list "[id1,id2]" if the list is an accessible type of argument.
420 //================================================================================
422 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
424 static TStringSet methodsAcceptingList;
425 if ( methodsAcceptingList.empty() ) {
426 const char * methodNames[] = {
427 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
428 "ExportCGNS","ExportGMF",
429 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
430 "ScaleMakeGroups","Scale","ScaleMakeMesh",
431 "FindCoincidentNodesOnPartBut","DoubleElements",
432 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
433 ,"" }; // <- mark of the end
434 methodsAcceptingList.Insert( methodNames );
436 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
438 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
440 _pyCommand argCmd( theCommand->GetArg( i ));
441 if ( argCmd.GetMethod() == "GetIDSource" &&
442 argCmd.GetNbArgs() == 2 )
444 theCommand->SetArg( i, argCmd.GetArg( 1 ));
450 bool _FilterArg( const _AString& theArg )
452 static std::list<_AString> filteredArgs;
453 static bool initialized = false;
454 if ( !initialized ) {
456 filteredArgs.push_back( "SMESH.MED_V2_1" );
457 filteredArgs.push_back( "SMESH.MED_V2_2" );
459 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
463 //================================================================================
465 * \brief Convert a python script using commands of smeshBuilder.py
466 * \param theScriptLines - Lines of the input script
467 * \param theEntry2AccessorMethod - returns method names to access to
468 * objects wrapped with python class
469 * \param theObjectNames - names of objects
470 * \param theRemovedObjIDs - entries of objects whose created commands were removed
471 * \param theHistoricalDump - true means to keep all commands, false means
472 * to exclude commands relating to objects removed from study
473 * \retval TCollection_AsciiString - Conversion result
475 //================================================================================
478 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
479 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
480 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
481 std::set< TCollection_AsciiString >& theRemovedObjIDs,
482 const bool theToKeepAllCommands)
484 std::list< TCollection_AsciiString >::iterator lineIt;
485 // process notebook variables
487 SMESH_NoteBook aNoteBook;
489 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
490 aNoteBook.AddCommand( *lineIt );
492 theScriptLines.clear();
494 aNoteBook.ReplaceVariables();
496 aNoteBook.GetResultLines( theScriptLines );
499 // convert to smeshBuilder.py API
501 theGen = new _pyGen( theEntry2AccessorMethod,
504 theToKeepAllCommands );
506 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
507 theGen->AddCommand( *lineIt );
509 theScriptLines.clear();
513 #ifdef DUMP_CONVERSION
514 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
517 // clean commands of removed objects depending on myIsPublished flag
518 theGen->ClearCommands();
520 // reorder commands after conversion
521 list< Handle(_pyCommand) >::iterator cmd;
524 orderChanges = false;
525 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
526 if ( (*cmd)->SetDependentCmdsAfter() )
528 } while ( orderChanges );
530 // concat commands back into a script
531 TCollection_AsciiString aPrevCmd;
532 set<_pyID> createdObjects;
533 createdObjects.insert( "smeshBuilder" );
534 createdObjects.insert( "smesh" );
535 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
537 #ifdef DUMP_CONVERSION
538 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
540 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
541 CheckObjectPresence( *cmd, createdObjects );
542 if ( !(*cmd)->IsEmpty() ) {
543 aPrevCmd = (*cmd)->GetString();
544 theScriptLines.push_back( aPrevCmd );
553 //================================================================================
555 * \brief _pyGen constructor
557 //================================================================================
559 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
560 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
561 std::set< TCollection_AsciiString >& theRemovedObjIDs,
562 const bool theToKeepAllCommands)
563 : _pyObject( new _pyCommand( "", 0 )),
565 myID2AccessorMethod( theEntry2AccessorMethod ),
566 myObjectNames( theObjectNames ),
567 myRemovedObjIDs( theRemovedObjIDs ),
569 myToKeepAllCommands( theToKeepAllCommands ),
570 myGeomIDNb(0), myGeomIDIndex(-1)
572 // make that GetID() to return TPythonDump::SMESHGenName()
573 GetCreationCmd()->Clear();
574 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
575 GetCreationCmd()->GetString() += "=";
577 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
578 if ( !theObjectNames.IsEmpty() )
582 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->FindComponent("GEOM");
583 if ( geomComp->_is_nil() ) return;
584 CORBA::String_var entry = geomComp->GetID();
587 // find a SMESH entry
589 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
590 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
591 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
594 // find 1st difference between smeshID and geomID
595 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
596 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
597 if ( geomID.Value( i ) != smeshID.Value( i ))
599 myGeomIDNb = geomID.Value( i );
605 //================================================================================
607 * \brief name of SMESH_Gen in smeshBuilder.py
609 //================================================================================
611 const char* _pyGen::AccessorMethod() const
613 return SMESH_2smeshpy::GenName();
616 //================================================================================
618 * \brief Convert a command using a specific converter
619 * \param theCommand - the command to convert
621 //================================================================================
623 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
625 // store theCommand in the sequence
626 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
628 Handle(_pyCommand) aCommand = myCommands.back();
629 #ifdef DUMP_CONVERSION
630 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
633 const _pyID& objID = aCommand->GetObject();
635 if ( objID.IsEmpty() )
638 // Prevent moving a command creating a sub-mesh to the end of the script
639 // if the sub-mesh is used in theCommand as argument
640 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
642 // PlaceSubmeshAfterItsCreation( aCommand );
645 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
646 StructToList( aCommand );
648 const TCollection_AsciiString& method = aCommand->GetMethod();
650 // not to erase _pySelfEraser's etc. used as args in some commands
652 #ifdef USE_STRING_FAMILY
653 std::list<_pyID> objIDs;
654 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
656 std::list<_pyID>::iterator objID = objIDs.begin();
657 for ( ; objID != objIDs.end(); ++objID )
659 Handle(_pyObject) obj = FindObject( *objID );
662 obj->AddArgCmd( aCommand );
663 //cout << objID << " found in " << theCommand << endl;
668 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
669 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
670 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
672 Handle(_pyObject) obj = FindObject( *id );
674 obj->AddArgCmd( aCommand );
679 // Find an object to process theCommand
682 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
684 this->Process( aCommand );
685 //addFilterUser( aCommand, theGen ); // protect filters from clearing
689 // SMESH_Mesh method?
690 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
691 if ( id_mesh != myMeshes.end() )
693 //id_mesh->second->AddProcessedCmd( aCommand );
695 // Wrap Export*() into try-except
696 if ( aCommand->MethodStartsFrom("Export"))
699 _AString indent = aCommand->GetIndentation();
700 _AString tryStr = indent + "try:";
701 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
702 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
703 _AString excStr = indent + "except:";
704 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
706 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
708 aCommand->GetString() = newCmd;
709 aCommand->SetOrderNb( ++myNbCommands );
710 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
711 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
712 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
714 // check for mesh editor object
715 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
716 _pyID editorID = aCommand->GetResultValue();
717 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
718 myMeshEditors.insert( make_pair( editorID, editor ));
721 // check for SubMesh objects
722 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
723 _pyID subMeshID = aCommand->GetResultValue();
724 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
725 AddObject( subMesh );
728 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
729 GetIDSourceToList( aCommand );
731 //addFilterUser( aCommand, theGen ); // protect filters from clearing
733 id_mesh->second->Process( aCommand );
734 id_mesh->second->AddProcessedCmd( aCommand );
738 // SMESH_MeshEditor method?
739 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
740 if ( id_editor != myMeshEditors.end() )
742 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
743 GetIDSourceToList( aCommand );
745 //addFilterUser( aCommand, theGen ); // protect filters from clearing
747 // some commands of SMESH_MeshEditor create meshes and groups
748 _pyID meshID, groups;
749 if ( method.Search("MakeMesh") != -1 )
750 meshID = aCommand->GetResultValue();
751 else if ( method == "MakeBoundaryMesh")
752 meshID = aCommand->GetResultValue(1);
753 else if ( method == "MakeBoundaryElements")
754 meshID = aCommand->GetResultValue(2);
756 if ( method.Search("MakeGroups") != -1 ||
757 method == "ExtrusionAlongPathX" ||
758 method == "ExtrusionAlongPathObjX" ||
759 method == "DoubleNodeGroupNew" ||
760 method == "DoubleNodeGroupsNew" ||
761 method == "DoubleNodeElemGroupNew" ||
762 method == "DoubleNodeElemGroupsNew" ||
763 method == "DoubleNodeElemGroup2New" ||
764 method == "DoubleNodeElemGroups2New" ||
765 method == "AffectedElemGroupsInRegion"
767 groups = aCommand->GetResultValue();
768 else if ( method == "MakeBoundaryMesh" )
769 groups = aCommand->GetResultValue(2);
770 else if ( method == "MakeBoundaryElements")
771 groups = aCommand->GetResultValue(3);
772 else if ( method == "Create0DElementsOnAllNodes" &&
773 aCommand->GetArg(2).Length() > 2 ) // group name != ''
774 groups = aCommand->GetResultValue();
776 id_editor->second->Process( aCommand );
777 id_editor->second->AddProcessedCmd( aCommand );
780 if ( !meshID.IsEmpty() &&
781 !myMeshes.count( meshID ) &&
782 aCommand->IsStudyEntry( meshID ))
784 _AString processedCommand = aCommand->GetString();
785 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
786 CheckObjectIsReCreated( mesh );
787 myMeshes.insert( make_pair( meshID, mesh ));
789 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
792 if ( !groups.IsEmpty() )
794 if ( !aCommand->IsStudyEntry( meshID ))
795 meshID = id_editor->second->GetMesh();
796 Handle(_pyMesh) mesh = myMeshes[ meshID ];
798 list< _pyID > idList = aCommand->GetStudyEntries( groups );
799 list< _pyID >::iterator grID = idList.begin();
800 for ( ; grID != idList.end(); ++grID )
801 if ( !myObjects.count( *grID ))
803 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
805 if ( !mesh.IsNull() ) mesh->AddGroup( group );
809 } // SMESH_MeshEditor methods
811 // SMESH_Hypothesis method?
812 Handle(_pyHypothesis) hyp = FindHyp( objID );
813 if ( !hyp.IsNull() && !hyp->IsAlgo() )
815 hyp->Process( aCommand );
816 hyp->AddProcessedCmd( aCommand );
820 // aFilterManager.CreateFilter() ?
821 if ( aCommand->GetMethod() == "CreateFilter" )
823 // Set a more human readable name to a filter
824 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
825 _pyID newID, filterID = aCommand->GetResultValue();
826 int pos = filterID.Search( "0x" );
828 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
830 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
833 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
834 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
836 // create _pySelfEraser for functors
837 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
838 functor->IgnoreOwnCalls(); // to erase if not used as an argument
839 AddObject( functor );
842 // other object method?
843 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
844 if ( id_obj != myObjects.end() ) {
845 id_obj->second->Process( aCommand );
846 id_obj->second->AddProcessedCmd( aCommand );
850 // Add access to a wrapped mesh
851 AddMeshAccessorMethod( aCommand );
853 // Add access to a wrapped algorithm
854 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
856 // PAL12227. PythonDump was not updated at proper time; result is
857 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
858 // TypeError: __init__() takes exactly 11 arguments (10 given)
859 const char wrongCommand[] = "SMESH.Filter.Criterion(";
860 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
862 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
863 // there must be 10 arguments, 5-th arg ThresholdID is missing,
864 const int wrongNbArgs = 9, missingArg = 5;
865 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
867 for ( int i = wrongNbArgs; i > missingArg; --i )
868 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
869 tmpCmd.SetArg( missingArg, "''");
870 aCommand->GetString().Trunc( beg - 1 );
871 aCommand->GetString() += tmpCmd.GetString();
874 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
876 // instead of "SMESH.Filter.Criterion(
877 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
878 // 1 2 3 4 5 6 7 8 9 10
879 // in order to avoid the problem of type mismatch of long and FunctorType
880 const TCollection_AsciiString
881 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
882 TCollection_AsciiString
883 Type = aCommand->GetArg(1), // long
884 Compare = aCommand->GetArg(2), // long
885 Threshold = aCommand->GetArg(3), // double
886 ThresholdStr = aCommand->GetArg(4), // string
887 ThresholdID = aCommand->GetArg(5), // string
888 UnaryOp = aCommand->GetArg(6), // long
889 BinaryOp = aCommand->GetArg(7), // long
890 Tolerance = aCommand->GetArg(8), // double
891 TypeOfElement = aCommand->GetArg(9), // ElementType
892 Precision = aCommand->GetArg(10); // long
893 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
894 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
895 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
896 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
897 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
899 if ( Compare == "SMESH.FT_EqualTo" )
902 aCommand->RemoveArgs();
903 aCommand->SetObject( SMESH_2smeshpy::GenName() );
904 aCommand->SetMethod( "GetCriterion" );
906 aCommand->SetArg( 1, TypeOfElement );
907 aCommand->SetArg( 2, Type );
908 aCommand->SetArg( 3, Compare );
910 if ( Threshold.IsIntegerValue() )
912 int iGeom = Threshold.IntegerValue();
913 if ( Type == "SMESH.FT_ElemGeomType" )
915 // set SMESH.GeometryType instead of a numerical Threshold
916 const int nbTypes = SMESH::Geom_LAST;
917 const char* types[] = {
918 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
919 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
920 "Geom_POLYHEDRA", "Geom_BALL" };
921 if ( -1 < iGeom && iGeom < nbTypes )
922 Threshold = SMESH + types[ iGeom ];
924 // is types complete? (compilation failure mains that enum GeometryType changed)
925 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
928 if (Type == "SMESH.FT_EntityType")
930 // set SMESH.EntityType instead of a numerical Threshold
931 const int nbTypes = SMESH::Entity_Last;
932 const char* types[] = {
933 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
934 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
935 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
936 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
937 "Entity_Pyramid", "Entity_Quad_Pyramid",
938 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
939 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
940 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
941 if ( -1 < iGeom && iGeom < nbTypes )
942 Threshold = SMESH + types[ iGeom ];
944 // is 'types' complete? (compilation failure mains that enum EntityType changed)
945 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
949 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
950 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
951 else if ( ThresholdStr.Length() != 2 )
952 aCommand->SetArg( 4, ThresholdStr );
953 else if ( ThresholdID.Length() != 2 )
954 aCommand->SetArg( 4, ThresholdID );
956 aCommand->SetArg( 4, Threshold );
957 // find the last not default arg
959 if ( Tolerance == dfltTol ) {
961 if ( BinaryOp == dfltFunctor ) {
963 if ( UnaryOp == dfltFunctor )
967 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
968 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
969 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
970 if ( Precision != dfltPreci )
972 TCollection_AsciiString crit = aCommand->GetResultValue();
973 aCommand->GetString() += "; ";
974 aCommand->GetString() += crit + ".Precision = " + Precision;
980 //================================================================================
982 * \brief Convert the command or remember it for later conversion
983 * \param theCommand - The python command calling a method of SMESH_Gen
985 //================================================================================
987 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
989 // there are methods to convert:
990 // CreateMesh( shape )
991 // Concatenate( [mesh1, ...], ... )
992 // CreateHypothesis( theHypType, theLibName )
993 // Compute( mesh, geom )
994 // Evaluate( mesh, geom )
996 TCollection_AsciiString method = theCommand->GetMethod();
998 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
1000 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1004 if ( method == "CreateMeshesFromUNV" ||
1005 method == "CreateMeshesFromSTL" ||
1006 method == "CopyMesh" ) // command result is a mesh
1008 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1012 if ( method == "CreateMeshesFromMED" ||
1013 method == "CreateMeshesFromSAUV"||
1014 method == "CreateMeshesFromCGNS" ||
1015 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1017 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1018 std::list< _pyID >::iterator meshID = meshIDs.begin();
1019 for ( ; meshID != meshIDs.end(); ++meshID )
1021 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1024 if ( method == "CreateMeshesFromGMF" )
1026 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1027 // CreateMeshesFromGMF( theFileName )
1028 _AString file = theCommand->GetArg(1);
1029 theCommand->RemoveArgs();
1030 theCommand->SetArg( 1, file );
1033 if ( method == "CopyMeshWithGeom" )
1035 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1036 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1040 // CreateHypothesis()
1041 if ( method == "CreateHypothesis" )
1043 // issue 199929, remove standard library name (default parameter)
1044 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1045 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1046 // keep the first argument
1047 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1048 theCommand->RemoveArgs();
1049 theCommand->SetArg( 1, arg );
1052 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1053 CheckObjectIsReCreated( hyp );
1054 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1059 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1060 if ( method == "Compute" )
1062 const _pyID& meshID = theCommand->GetArg( 1 );
1063 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1064 if ( id_mesh != myMeshes.end() ) {
1065 theCommand->SetObject( meshID );
1066 theCommand->RemoveArgs();
1067 id_mesh->second->Process( theCommand );
1068 id_mesh->second->AddProcessedCmd( theCommand );
1073 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1074 if ( method == "Evaluate" )
1076 const _pyID& meshID = theCommand->GetArg( 1 );
1077 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1078 if ( id_mesh != myMeshes.end() ) {
1079 theCommand->SetObject( meshID );
1080 _pyID geom = theCommand->GetArg( 2 );
1081 theCommand->RemoveArgs();
1082 theCommand->SetArg( 1, geom );
1083 id_mesh->second->AddProcessedCmd( theCommand );
1088 // objects erasing creation command if no more its commands invoked:
1089 // SMESH_Pattern, FilterManager
1090 if ( method == "GetPattern" ||
1091 method == "CreateFilterManager" ||
1092 method == "CreateMeasurements" )
1094 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1095 if ( !AddObject( obj ) )
1096 theCommand->Clear(); // already created
1098 // Concatenate( [mesh1, ...], ... )
1099 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1101 if ( method == "ConcatenateWithGroups" ) {
1102 theCommand->SetMethod( "Concatenate" );
1103 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1105 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1107 AddMeshAccessorMethod( theCommand );
1109 else if ( method == "SetName" ) // SetName(obj,name)
1111 // store theCommand as one of object commands to erase it along with the object
1112 const _pyID& objID = theCommand->GetArg( 1 );
1113 Handle(_pyObject) obj = FindObject( objID );
1114 if ( !obj.IsNull() )
1115 obj->AddProcessedCmd( theCommand );
1118 // Replace name of SMESH_Gen
1120 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1121 static TStringSet smeshpyMethods;
1122 if ( smeshpyMethods.empty() ) {
1123 const char * names[] =
1124 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1125 "GetPattern","GetSubShapesId",
1126 "" }; // <- mark of array end
1127 smeshpyMethods.Insert( names );
1129 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1130 // smeshgen.Method() --> smesh.Method()
1131 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1133 // smeshgen.Method() --> smesh.Method()
1134 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1137 //================================================================================
1139 * \brief Convert the remembered commands
1141 //================================================================================
1143 void _pyGen::Flush()
1145 // create an empty command
1146 myLastCommand = new _pyCommand();
1148 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1149 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1150 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1152 if ( IsToKeepAllCommands() ) // historical dump
1154 // set myIsPublished = true to all objects
1155 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1156 id_mesh->second->SetRemovedFromStudy( false );
1157 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1158 id_hyp->second->SetRemovedFromStudy( false );
1159 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1160 id_obj->second->SetRemovedFromStudy( false );
1164 // let hypotheses find referred objects in order to prevent clearing
1165 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1166 list< Handle(_pyMesh) > fatherMeshes;
1167 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1168 if ( !id_hyp->second.IsNull() )
1169 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1171 // set myIsPublished = false to all objects depending on
1172 // meshes built on a removed geometry
1173 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1174 if ( id_mesh->second->IsNotGeomPublished() )
1175 id_mesh->second->SetRemovedFromStudy( true );
1178 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1179 if ( ! id_mesh->second.IsNull() )
1180 id_mesh->second->Flush();
1183 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1184 if ( !id_hyp->second.IsNull() ) {
1185 id_hyp->second->Flush();
1186 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1187 if ( !id_hyp->second->IsWrapped() )
1188 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1191 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1192 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1193 for ( ; robj != myOrderedObjects.rend(); ++robj )
1194 if ( ! robj->IsNull() )
1196 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1197 for ( ; obj != myOrderedObjects.end(); ++obj )
1198 if ( ! obj->IsNull() )
1201 myLastCommand->SetOrderNb( ++myNbCommands );
1202 myCommands.push_back( myLastCommand );
1205 //================================================================================
1207 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1208 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1210 //================================================================================
1212 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1214 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1215 // for ( ; id_obj != myObjects.end(); ++id_obj )
1217 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1218 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1220 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1221 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1223 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1224 // list< _pyID >::iterator id = idList.begin();
1225 // for ( ; id != idList.end(); ++id )
1226 // if ( id_obj->first == *id )
1227 // // _pySubMesh::Process() does what we need
1228 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1233 //================================================================================
1235 * \brief Clean commands of removed objects depending on myIsPublished flag
1237 //================================================================================
1239 void _pyGen::ClearCommands()
1241 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1242 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1243 id_mesh->second->ClearCommands();
1245 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1246 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1247 if ( !id_hyp->second.IsNull() )
1248 id_hyp->second->ClearCommands();
1250 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1251 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1252 for ( ; robj != myOrderedObjects.rend(); ++robj )
1253 if ( ! robj->IsNull() )
1254 (*robj)->ClearCommands();
1255 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1256 for ( ; obj != myOrderedObjects.end(); ++obj )
1257 if ( ! obj->IsNull() )
1258 (*obj)->ClearCommands();
1261 //================================================================================
1263 * \brief Release mutual handles of objects
1265 //================================================================================
1269 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1270 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1271 id_mesh->second->Free();
1274 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1275 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1276 id_ed->second->Free();
1277 myMeshEditors.clear();
1279 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1280 for ( ; id_obj != myObjects.end(); ++id_obj )
1281 id_obj->second->Free();
1284 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1285 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1286 if ( !id_hyp->second.IsNull() )
1287 id_hyp->second->Free();
1290 myFile2ExportedMesh.clear();
1292 //myKeepAgrCmdsIDs.Print();
1295 //================================================================================
1297 * \brief Add access method to mesh that is an argument
1298 * \param theCmd - command to add access method
1299 * \retval bool - true if added
1301 //================================================================================
1303 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1306 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1307 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1308 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1314 //================================================================================
1316 * \brief Add access method to algo that is an object or an argument
1317 * \param theCmd - command to add access method
1318 * \retval bool - true if added
1320 //================================================================================
1322 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1325 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1326 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1327 if ( !id_hyp->second.IsNull() &&
1328 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1329 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1330 id_hyp->second->AccessorMethod() ))
1336 //================================================================================
1338 * \brief Find hypothesis by ID (entry)
1339 * \param theHypID - The hypothesis ID
1340 * \retval Handle(_pyHypothesis) - The found hypothesis
1342 //================================================================================
1344 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1346 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1347 if ( id_hyp != myHypos.end() &&
1348 !id_hyp->second.IsNull() &&
1349 theHypID == id_hyp->second->GetID() )
1350 return id_hyp->second;
1351 return Handle(_pyHypothesis)();
1354 //================================================================================
1356 * \brief Find algorithm able to create a hypothesis
1357 * \param theGeom - The shape ID the algorithm was created on
1358 * \param theMesh - The mesh ID that created the algorithm
1359 * \param theHypothesis - The hypothesis the algorithm should be able to create
1360 * \retval Handle(_pyHypothesis) - The found algo
1362 //================================================================================
1364 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1365 const Handle(_pyHypothesis)& theHypothesis )
1367 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1368 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1369 if ( !id_hyp->second.IsNull() &&
1370 id_hyp->second->IsAlgo() &&
1371 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1372 id_hyp->second->GetGeom() == theGeom &&
1373 id_hyp->second->GetMesh() == theMesh )
1374 return id_hyp->second;
1375 return Handle(_pyHypothesis)();
1378 //================================================================================
1380 * \brief Find subMesh by ID (entry)
1381 * \param theSubMeshID - The subMesh ID
1382 * \retval Handle(_pySubMesh) - The found subMesh
1384 //================================================================================
1386 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1388 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1389 if ( id_subMesh != myObjects.end() )
1390 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1391 return Handle(_pySubMesh)();
1395 //================================================================================
1397 * \brief Change order of commands in the script
1398 * \param theCmd1 - One command
1399 * \param theCmd2 - Another command
1401 //================================================================================
1403 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1405 list< Handle(_pyCommand) >::iterator pos1, pos2;
1406 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1407 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1408 myCommands.insert( pos1, theCmd2 );
1409 myCommands.insert( pos2, theCmd1 );
1410 myCommands.erase( pos1 );
1411 myCommands.erase( pos2 );
1413 int nb1 = theCmd1->GetOrderNb();
1414 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1415 theCmd2->SetOrderNb( nb1 );
1416 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1417 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1420 //================================================================================
1422 * \brief Set one command after the other
1423 * \param theCmd - Command to move
1424 * \param theAfterCmd - Command ater which to insert the first one
1426 //================================================================================
1428 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1430 setNeighbourCommand( theCmd, theAfterCmd, true );
1433 //================================================================================
1435 * \brief Set one command before the other
1436 * \param theCmd - Command to move
1437 * \param theBeforeCmd - Command before which to insert the first one
1439 //================================================================================
1441 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1443 setNeighbourCommand( theCmd, theBeforeCmd, false );
1446 //================================================================================
1448 * \brief Set one command before or after the other
1449 * \param theCmd - Command to move
1450 * \param theOtherCmd - Command ater or before which to insert the first one
1452 //================================================================================
1454 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1455 Handle(_pyCommand)& theOtherCmd,
1456 const bool theIsAfter )
1458 list< Handle(_pyCommand) >::iterator pos;
1459 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1460 myCommands.erase( pos );
1461 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1462 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1465 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1466 (*pos)->SetOrderNb( i++ );
1469 //================================================================================
1471 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1473 //================================================================================
1475 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1477 // No more needed after adding _pyObject::myArgCommands
1479 // const char filterPrefix[] = "aFilter0x";
1480 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1483 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1485 // const _AString & arg = theCommand->GetArg( i );
1486 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1487 // if ( arg.Search( filterPrefix ) != 1 )
1490 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1491 // if ( !filter.IsNull() )
1493 // filter->AddUser( user );
1494 // if ( !filter->GetNewID().IsEmpty() )
1495 // theCommand->SetArg( i, filter->GetNewID() );
1500 //================================================================================
1502 * \brief Set command be last in list of commands
1503 * \param theCmd - Command to be last
1505 //================================================================================
1507 Handle(_pyCommand)& _pyGen::GetLastCommand()
1509 return myLastCommand;
1512 //================================================================================
1514 * \brief Set method to access to object wrapped with python class
1515 * \param theID - The wrapped object entry
1516 * \param theMethod - The accessor method
1518 //================================================================================
1520 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1522 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1525 //================================================================================
1527 * \brief Generated new ID for object and assign with existing name
1528 * \param theID - ID of existing object
1530 //================================================================================
1532 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1537 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1539 while ( myObjectNames.IsBound( aNewID ) );
1541 if ( myObjectNames.IsBound( theID ) )
1542 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1544 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1548 //================================================================================
1550 * \brief Stores theObj in myObjects
1552 //================================================================================
1554 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1556 if ( theObj.IsNull() ) return false;
1558 CheckObjectIsReCreated( theObj );
1562 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1563 add = myMeshes.insert( make_pair( theObj->GetID(),
1564 Handle(_pyMesh)::DownCast( theObj ))).second;
1566 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1567 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1568 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1571 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1572 if ( add ) myOrderedObjects.push_back( theObj );
1577 //================================================================================
1579 * \brief Erases an existing object with the same ID. This method should be called
1580 * before storing theObj in _pyGen
1582 //================================================================================
1584 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1586 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1589 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1590 Handle(_pyObject) existing;
1592 existing = FindHyp( theObj->GetID() );
1594 existing = FindObject( theObj->GetID() );
1595 if ( !existing.IsNull() && existing != theObj )
1597 existing->SetRemovedFromStudy( true );
1598 existing->ClearCommands();
1601 if ( myHypos.count( theObj->GetID() ))
1602 myHypos.erase( theObj->GetID() );
1604 else if ( myMeshes.count( theObj->GetID() ))
1606 myMeshes.erase( theObj->GetID() );
1608 else if ( myObjects.count( theObj->GetID() ))
1610 myObjects.erase( theObj->GetID() );
1615 //================================================================================
1617 * \brief Re-register an object with other ID to make it Process() commands of
1618 * other object having this ID
1620 //================================================================================
1622 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1624 if ( theObj.IsNull() ) return;
1626 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1627 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1629 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1630 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1633 myObjects.insert( make_pair( theID, theObj ));
1636 //================================================================================
1638 * \brief Finds a _pyObject by ID
1640 //================================================================================
1642 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1645 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1646 if ( id_obj != myObjects.end() )
1647 return id_obj->second;
1650 _pyGen* me = const_cast< _pyGen* >( this );
1651 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1652 if ( id_obj != myMeshes.end() )
1653 return id_obj->second;
1656 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1657 // if ( id_obj != myMeshEditors.end() )
1658 // return id_obj->second;
1660 return Handle(_pyObject)();
1663 //================================================================================
1665 * \brief Check if a study entry is under GEOM component
1667 //================================================================================
1669 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1673 return ( myGeomIDIndex <= theObjID.Length() &&
1674 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1675 _pyCommand::IsStudyEntry( theObjID ));
1680 //================================================================================
1682 * \brief Returns true if an object is not present in a study
1684 //================================================================================
1686 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1688 if ( theObjID.IsEmpty() ) return false;
1690 if ( myObjectNames.IsBound( theObjID ))
1691 return false; // SMESH object is in study
1693 // either the SMESH object is not in study or it is a GEOM object
1694 if ( IsGeomObject( theObjID ))
1696 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1697 if ( so->_is_nil() ) return true;
1698 CORBA::Object_var obj = so->GetObject();
1699 return CORBA::is_nil( obj );
1701 return true; // SMESH object not in study
1704 //================================================================================
1706 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1707 * this object is not dumped
1708 * \param [in] theObjID - entry of the object whose creation command was eliminated
1710 //================================================================================
1712 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1714 myRemovedObjIDs.insert( theObjID );
1717 //================================================================================
1719 * \brief Return reader of hypotheses of plugins
1721 //================================================================================
1723 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1725 if (myHypReader.IsNull() )
1726 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1732 //================================================================================
1734 * \brief Mesh created by SMESH_Gen
1736 //================================================================================
1738 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1739 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1741 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1742 myGeomNotInStudy = true;
1744 // convert my creation command --> smeshpy.Mesh(...)
1745 Handle(_pyCommand) creationCmd = GetCreationCmd();
1746 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1747 creationCmd->SetMethod( "Mesh" );
1748 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1751 //================================================================================
1753 * \brief Mesh created by SMESH_MeshEditor
1755 //================================================================================
1757 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1758 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1760 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1762 // this mesh depends on the exported mesh
1763 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1764 if ( !file.IsEmpty() )
1766 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1767 addFatherMesh( exportData.myMesh );
1768 if ( !exportData.myLastComputeCmd.IsNull() )
1770 // restore cleared Compute() by which the exported mesh was generated
1771 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1772 // protect that Compute() cmd from clearing
1773 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1774 exportData.myMesh->myLastComputeCmd.Nullify();
1778 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1780 // this mesh depends on concatenated meshes
1781 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1782 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1783 list< _pyID >::iterator meshID = idList.begin();
1784 for ( ; meshID != idList.end(); ++meshID )
1785 addFatherMesh( *meshID );
1787 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1789 // this mesh depends on a copied IdSource
1790 const _pyID& objID = theCreationCmd->GetArg( 1 );
1791 addFatherMesh( objID );
1793 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1794 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1795 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1797 // this mesh depends on a source mesh
1798 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1799 const _pyID& meshID = theCreationCmd->GetObject();
1800 addFatherMesh( meshID );
1803 // convert my creation command
1804 Handle(_pyCommand) creationCmd = GetCreationCmd();
1805 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1806 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1809 //================================================================================
1811 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1812 * \param theCommand - Engine method called for this mesh
1814 //================================================================================
1816 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1818 // some methods of SMESH_Mesh interface needs special conversion
1819 // to methods of Mesh python class
1821 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1822 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1823 // 2. AddHypothesis(geom, hyp)
1824 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1825 // 3. CreateGroupFromGEOM(type, name, grp)
1826 // --> in Mesh.Group(grp, name="")
1827 // 4. ExportToMED(f, auto_groups, version)
1828 // --> in Mesh.ExportMED( f, auto_groups, version )
1831 const TCollection_AsciiString& method = theCommand->GetMethod();
1832 // ----------------------------------------------------------------------
1833 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1835 if ( !theGen->IsToKeepAllCommands() ) // !historical
1837 list< Handle(_pyHypothesis) >::iterator hyp;
1838 if ( !myLastComputeCmd.IsNull() )
1840 // check if the previously computed mesh has been edited,
1841 // if so then we do not clear the previous Compute()
1842 bool toClear = true;
1843 if ( myLastComputeCmd->GetMethod() == "Compute" )
1845 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1846 for ( ; e != myEditors.end() && toClear; ++e )
1848 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1849 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1850 if ( cmd != cmds.rend() &&
1851 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1857 // clear hyp commands called before myLastComputeCmd
1858 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1859 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1861 myLastComputeCmd->Clear();
1864 myLastComputeCmd = theCommand;
1866 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1867 (*hyp)->MeshComputed( myLastComputeCmd );
1871 // ----------------------------------------------------------------------
1872 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1874 if ( !theGen->IsToKeepAllCommands() ) // !historical
1877 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1878 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1879 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1881 if ( !myLastComputeCmd.IsNull() )
1883 list< Handle(_pyHypothesis) >::iterator hyp;
1884 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1885 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1887 myLastComputeCmd->Clear();
1890 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1891 for ( ; e != myEditors.end(); ++e )
1893 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1894 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1895 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1896 if ( !(*cmd)->IsEmpty() )
1898 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1902 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1905 // ----------------------------------------------------------------------
1906 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1907 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1908 if ( !subMesh.IsNull() ) {
1909 subMesh->SetCreator( this );
1910 mySubmeshes.push_back( subMesh );
1913 // ----------------------------------------------------------------------
1914 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1915 theCommand->Clear();
1917 // ----------------------------------------------------------------------
1918 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1919 myAddHypCmds.push_back( theCommand );
1921 const _pyID& hypID = theCommand->GetArg( 2 );
1922 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1923 if ( !hyp.IsNull() ) {
1924 myHypos.push_back( hyp );
1925 if ( hyp->GetMesh().IsEmpty() )
1926 hyp->SetMesh( this->GetID() );
1929 // ----------------------------------------------------------------------
1930 else if ( method == "CreateGroup" ||
1931 method == "CreateGroupFromGEOM" ||
1932 method == "CreateGroupFromFilter" ||
1933 method == "CreateDimGroup" )
1935 Handle(_pyGroup) group = new _pyGroup( theCommand );
1936 myGroups.push_back( group );
1937 theGen->AddObject( group );
1939 // ----------------------------------------------------------------------
1940 // update list of groups
1941 else if ( method == "GetGroups" )
1943 bool allGroupsRemoved = true;
1944 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1945 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1946 list< _pyID >::iterator grID = idList.begin();
1947 const size_t nbGroupsBefore = myGroups.size();
1948 Handle(_pyObject) obj;
1949 for ( ; grID != idList.end(); ++grID )
1951 obj = theGen->FindObject( *grID );
1954 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1955 theGen->AddObject( group );
1956 myGroups.push_back( group );
1959 if ( !obj->CanClear() )
1960 allGroupsRemoved = false;
1962 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1963 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1965 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1967 // check if the preceding command is Compute();
1968 // if GetGroups() is just after Compute(), this can mean that the groups
1969 // were created by some algorithm and hence Compute() should not be discarded
1970 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1971 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1972 while ( (*cmd)->GetMethod() == "GetGroups" )
1974 if ( myLastComputeCmd == (*cmd))
1975 // protect last Compute() from clearing by the next Compute()
1976 myLastComputeCmd.Nullify();
1979 // ----------------------------------------------------------------------
1980 // notify a group about full removal
1981 else if ( method == "RemoveGroupWithContents" ||
1982 method == "RemoveGroup")
1984 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1985 const _pyID groupID = theCommand->GetArg( 1 );
1986 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1987 if ( !grp.IsNull() )
1989 if ( method == "RemoveGroupWithContents" )
1990 grp->RemovedWithContents();
1991 // to clear RemoveGroup() if the group creation is cleared
1992 grp->AddProcessedCmd( theCommand );
1996 // ----------------------------------------------------------------------
1997 else if ( theCommand->MethodStartsFrom( "Export" ))
1999 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
2000 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
2001 method == "ExportMED" )
2003 theCommand->SetMethod( "ExportMED" );
2004 // filter out deprecated version parameter
2005 vector< _AString > args;
2006 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2007 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2008 args.push_back( theCommand->GetArg( i ) );
2010 theCommand->RemoveArgs();
2011 for ( unsigned int i = 0; i < args.size(); i++ )
2012 theCommand->SetArg( i+1, args[i] );
2013 if ( theCommand->GetNbArgs() == 4 )
2015 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2016 _AString autoDimension = theCommand->GetArg( 4 );
2017 theCommand->SetArg( 4, "None" );
2018 theCommand->SetArg( 5, autoDimension );
2021 else if ( method == "ExportCGNS" )
2022 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2023 _pyID partID = theCommand->GetArg( 1 );
2024 int nbArgs = theCommand->GetNbArgs();
2025 for ( int i = 2; i <= nbArgs; ++i )
2026 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2027 theCommand->SetArg( nbArgs, partID );
2029 else if ( method == "ExportGMF" )
2030 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2031 _pyID partID = theCommand->GetArg( 1 );
2032 _AString file = theCommand->GetArg( 2 );
2033 theCommand->RemoveArgs();
2034 theCommand->SetArg( 1, file );
2035 theCommand->SetArg( 2, partID );
2037 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2038 { // ExportPartTo*(part, ...) -> Export*(..., part)
2040 // remove "PartTo" from the method
2041 TCollection_AsciiString newMethod = method;
2042 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2043 theCommand->SetMethod( newMethod );
2044 // replace version parameter by minor
2045 std::list< _AString > args;
2046 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2047 if ( _FilterArg( theCommand->GetArg( i )))
2048 args.push_back( "minor=0");
2050 args.push_back( theCommand->GetArg( i ));
2052 // check the 1st arg meshPart, it must be SMESH_IDSource
2053 _AString meshPart = args.front();
2054 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2055 meshPart.Search( "Filter" ) > 0 ||
2056 meshPart.Search( "GetIDSource" ) > 0 ||
2057 meshPart.Search( "meshPart" ) > 0 )
2059 // set the 1st arg meshPart
2060 // - to 5th place for ExportMED command
2061 // - to last place for the rest commands
2062 std::list< _AString >::iterator newPos = args.end();
2063 if ( newMethod == "ExportMED" )
2064 std::advance( newPos = args.begin(), 5 );
2065 args.splice( newPos, args, args.begin() );
2067 std::list< _AString >::iterator a = args.begin();
2068 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2069 theCommand->SetArg( i, *a );
2071 // remember file name
2072 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2073 ExportedMeshData( this, myLastComputeCmd ));
2075 // ----------------------------------------------------------------------
2076 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2078 _pyID hypID = theCommand->GetArg( 2 );
2079 _pyID geomID = theCommand->GetArg( 1 );
2080 bool isLocal = ( geomID != GetGeom() );
2082 // check if this mesh still has corresponding addition command
2083 Handle(_pyCommand) addCmd;
2084 list< Handle(_pyCommand) >::iterator cmd;
2085 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2086 for ( int i = 0; i < 2; ++i )
2088 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2089 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2091 bool sameHyp = true;
2092 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2093 sameHyp = false; // other hyp
2094 if ( (*cmd)->GetNbArgs() == 2 &&
2095 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2096 sameHyp = false; // other geom
2097 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2098 sameHyp = false; // other geom
2102 cmd = addHypCmds.erase( cmd );
2103 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2105 theCommand->Clear();
2109 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2110 addCmd->RemoveArgs();
2111 addCmd->SetArg( 1, hypID );
2113 addCmd->SetArg( 2, geomID );
2122 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2123 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2124 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2125 _pyID geom = theCommand->GetArg( 1 );
2126 theCommand->RemoveArgs();
2127 theCommand->SetArg( 1, hypID );
2128 if ( geom != GetGeom() )
2129 theCommand->SetArg( 2, geom );
2131 // remove hyp from myHypos
2132 myHypos.remove( hyp );
2134 // check for SubMesh order commands
2135 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2137 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2138 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2139 // commands are moved at the end of the script
2140 TCollection_AsciiString subIDs =
2141 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2142 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2143 list< _pyID >::iterator subID = idList.begin();
2144 for ( ; subID != idList.end(); ++subID )
2146 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2147 if ( !subMesh.IsNull() )
2148 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2151 // add accessor method if necessary
2154 if ( NeedMeshAccess( theCommand ))
2155 // apply theCommand to the mesh wrapped by smeshpy mesh
2156 AddMeshAccess( theCommand );
2160 //================================================================================
2162 * \brief Return True if addition of accesor method is needed
2164 //================================================================================
2166 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2168 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2169 // so no conversion is needed for them at all:
2170 static TStringSet sameMethods;
2171 if ( sameMethods.empty() ) {
2172 const char * names[] =
2173 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2174 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2175 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2176 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2177 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2178 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2179 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2180 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2181 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2182 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2183 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2184 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2185 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2186 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2187 ,"" }; // <- mark of end
2188 sameMethods.Insert( names );
2191 return !sameMethods.Contains( theCommand->GetMethod() );
2194 //================================================================================
2196 * \brief Convert creation and addition of all algos and hypos
2198 //================================================================================
2200 void _pyMesh::Flush()
2203 // get the meshes this mesh depends on via hypotheses
2204 list< Handle(_pyMesh) > fatherMeshes;
2205 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2206 for ( ; hyp != myHypos.end(); ++hyp )
2207 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2208 myGeomNotInStudy = true;
2210 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2211 for ( ; m != fatherMeshes.end(); ++m )
2212 addFatherMesh( *m );
2213 // if ( removedGeom )
2214 // SetRemovedFromStudy(); // as referred geometry not in study
2216 if ( myGeomNotInStudy )
2219 list < Handle(_pyCommand) >::iterator cmd;
2221 // try to convert algo addition like this:
2222 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2223 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2225 Handle(_pyCommand) addCmd = *cmd;
2227 _pyID algoID = addCmd->GetArg( 2 );
2228 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2229 if ( algo.IsNull() || !algo->IsAlgo() )
2232 // check and create new algorithm instance if it is already wrapped
2233 if ( algo->IsWrapped() ) {
2234 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2235 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2236 TCollection_AsciiString( " = " ) + theGen->GetID() +
2237 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2238 TCollection_AsciiString( "\" )" );
2240 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2241 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2242 if ( !newAlgo.IsNull() ) {
2243 newAlgo->Assign( algo, this->GetID() );
2244 newAlgo->SetCreationCmd( newCmd );
2246 // set algorithm creation
2247 theGen->SetCommandBefore( newCmd, addCmd );
2248 myHypos.push_back( newAlgo );
2249 if ( !myLastComputeCmd.IsNull() &&
2250 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2251 newAlgo->MeshComputed( myLastComputeCmd );
2256 _pyID geom = addCmd->GetArg( 1 );
2257 bool isLocalAlgo = ( geom != GetGeom() );
2260 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2262 // wrapped algo is created after mesh creation
2263 GetCreationCmd()->AddDependantCmd( addCmd );
2265 if ( isLocalAlgo ) {
2266 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2267 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2268 TCollection_AsciiString( "geom=" ) + geom );
2269 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2270 list < Handle(_pySubMesh) >::iterator smIt;
2271 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2272 Handle(_pySubMesh) subMesh = *smIt;
2273 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2274 if ( geom == subCmd->GetArg( 1 )) {
2275 subCmd->SetObject( algo->GetID() );
2276 subCmd->RemoveArgs();
2277 subMesh->SetCreator( algo );
2282 else // KO - ALGO was already created
2284 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2285 addCmd->RemoveArgs();
2286 addCmd->SetArg( 1, algoID );
2288 addCmd->SetArg( 2, geom );
2289 myNotConvertedAddHypCmds.push_back( addCmd );
2293 // try to convert hypo addition like this:
2294 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2295 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2297 Handle(_pyCommand) addCmd = *cmd;
2298 _pyID hypID = addCmd->GetArg( 2 );
2299 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2300 if ( hyp.IsNull() || hyp->IsAlgo() )
2302 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2304 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2305 _pyID geom = addCmd->GetArg( 1 );
2306 addCmd->RemoveArgs();
2307 addCmd->SetArg( 1, hypID );
2308 if ( geom != GetGeom() )
2309 addCmd->SetArg( 2, geom );
2310 myNotConvertedAddHypCmds.push_back( addCmd );
2314 myAddHypCmds.clear();
2315 mySubmeshes.clear();
2318 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2319 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2323 //================================================================================
2325 * \brief Sets myIsPublished of me and of all objects depending on me.
2327 //================================================================================
2329 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2331 _pyObject::SetRemovedFromStudy(isRemoved);
2333 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2334 for ( ; sm != mySubmeshes.end(); ++sm )
2335 (*sm)->SetRemovedFromStudy(isRemoved);
2337 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2338 for ( ; gr != myGroups.end(); ++gr )
2339 (*gr)->SetRemovedFromStudy(isRemoved);
2341 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2342 for ( ; m != myChildMeshes.end(); ++m )
2343 (*m)->SetRemovedFromStudy(isRemoved);
2345 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2346 for ( ; e != myEditors.end(); ++e )
2347 (*e)->SetRemovedFromStudy(isRemoved);
2350 //================================================================================
2352 * \brief Return true if none of myChildMeshes is in study
2354 //================================================================================
2356 bool _pyMesh::CanClear()
2361 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2362 for ( ; m != myChildMeshes.end(); ++m )
2363 if ( !(*m)->CanClear() )
2369 //================================================================================
2371 * \brief Clear my commands and commands of mesh editor
2373 //================================================================================
2375 void _pyMesh::ClearCommands()
2381 // mark all sub-objects as not removed, except child meshes
2382 list< Handle(_pyMesh) > children;
2383 children.swap( myChildMeshes );
2384 SetRemovedFromStudy( false );
2385 children.swap( myChildMeshes );
2389 _pyObject::ClearCommands();
2391 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2392 for ( ; sm != mySubmeshes.end(); ++sm )
2393 (*sm)->ClearCommands();
2395 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2396 for ( ; gr != myGroups.end(); ++gr )
2397 (*gr)->ClearCommands();
2399 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2400 for ( ; e != myEditors.end(); ++e )
2401 (*e)->ClearCommands();
2404 //================================================================================
2406 * \brief Add a father mesh by ID
2408 //================================================================================
2410 void _pyMesh::addFatherMesh( const _pyID& meshID )
2412 if ( !meshID.IsEmpty() && meshID != GetID() )
2413 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2416 //================================================================================
2418 * \brief Add a father mesh
2420 //================================================================================
2422 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2424 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2426 //myFatherMeshes.push_back( mesh );
2427 mesh->myChildMeshes.push_back( this );
2429 // protect last Compute() from clearing by the next Compute()
2430 mesh->myLastComputeCmd.Nullify();
2434 //================================================================================
2436 * \brief MeshEditor convert its commands to ones of mesh
2438 //================================================================================
2440 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2441 _pyObject( theCreationCmd )
2443 myMesh = theCreationCmd->GetObject();
2444 myCreationCmdStr = theCreationCmd->GetString();
2445 theCreationCmd->Clear();
2447 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2448 if ( !mesh.IsNull() )
2449 mesh->AddEditor( this );
2452 //================================================================================
2454 * \brief convert its commands to ones of mesh
2456 //================================================================================
2458 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2460 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2461 // commands calling these methods are converted to calls of Mesh methods without
2462 // additional modifs, only object is changed from MeshEditor to Mesh.
2463 static TStringSet sameMethods;
2464 if ( sameMethods.empty() ) {
2465 const char * names[] = {
2466 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2467 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2468 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2469 "MoveNode", "MoveClosestNodeToPoint",
2470 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2471 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2472 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2473 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2474 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2475 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2476 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2477 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2478 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2479 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2480 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2481 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2482 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2483 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2484 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2485 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2486 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2487 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2488 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2489 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2490 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2491 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2492 ,"" }; // <- mark of the end
2493 sameMethods.Insert( names );
2496 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2497 TStringMap diffMethods;
2498 if ( diffMethods.empty() ) {
2499 const char * orig2newName[] = {
2500 // original name --------------> new name
2501 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2502 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2503 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2504 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2505 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2506 ""};// <- mark of the end
2507 diffMethods.Insert( orig2newName );
2510 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2511 // only by last two arguments
2512 static TStringSet diffLastTwoArgsMethods;
2513 if (diffLastTwoArgsMethods.empty() ) {
2514 const char * names[] = {
2515 "MirrorMakeGroups","MirrorObjectMakeGroups",
2516 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2517 "RotateMakeGroups","RotateObjectMakeGroups",
2518 ""};// <- mark of the end
2519 diffLastTwoArgsMethods.Insert( names );
2522 // only a method name is to change?
2523 const TCollection_AsciiString & method = theCommand->GetMethod();
2524 bool isPyMeshMethod = sameMethods.Contains( method );
2525 if ( !isPyMeshMethod )
2527 TCollection_AsciiString newMethod = diffMethods.Value( method );
2528 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2529 theCommand->SetMethod( newMethod );
2531 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2532 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2534 isPyMeshMethod = true;
2535 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2536 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2539 if ( !isPyMeshMethod )
2541 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2542 // functions with the flag "theMakeGroups = True" like:
2543 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2544 int pos = method.Search("MakeGroups");
2547 isPyMeshMethod = true;
2548 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2549 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2551 // 1. Remove "MakeGroups" from the Command
2552 TCollection_AsciiString aMethod = theCommand->GetMethod();
2553 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2556 pos = pos-2; //Remove "0D" from the Command too
2557 aMethod.Trunc(pos-1);
2558 theCommand->SetMethod(aMethod);
2560 // 2. And add last "True" argument(s)
2561 while(nbArgsToAdd--)
2562 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2563 if( is0DmethId || is0DmethObj )
2564 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2568 // ExtrusionSweep0D() -> ExtrusionSweep()
2569 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2570 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2571 method == "ExtrusionSweepObject0D" ))
2573 isPyMeshMethod = true;
2574 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2575 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2576 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2579 // DoubleNode...New(...) -> DoubleNode...(...,True)
2580 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2581 method == "DoubleNodeElemGroupsNew" ||
2582 method == "DoubleNodeGroupNew" ||
2583 method == "DoubleNodeGroupsNew" ||
2584 method == "DoubleNodeElemGroup2New" ||
2585 method == "DoubleNodeElemGroups2New"))
2587 isPyMeshMethod = true;
2588 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2589 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2590 if ( excessLen == 3 )
2592 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2594 else if ( theCommand->GetArg(4) == "0" ||
2595 theCommand->GetArg(5) == "0" )
2597 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2598 // Group = DoubleNodeGroup2New(,,,False, True)
2599 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2600 theCommand->SetResultValue( groupID );
2603 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2604 // FindElementsByPoint(x, y, z, elementType, meshPart)
2605 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2607 isPyMeshMethod = true;
2608 theCommand->SetMethod( "FindElementsByPoint" );
2609 // make the 1st arg be the last one
2610 _pyID partID = theCommand->GetArg( 1 );
2611 int nbArgs = theCommand->GetNbArgs();
2612 for ( int i = 2; i <= nbArgs; ++i )
2613 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2614 theCommand->SetArg( nbArgs, partID );
2616 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2617 if ( !isPyMeshMethod && method == "Reorient2D" )
2619 isPyMeshMethod = true;
2620 _AString mesh = theCommand->GetArg( 1 );
2621 _AString dir = theCommand->GetArg( 2 );
2622 _AString face = theCommand->GetArg( 3 );
2623 _AString point = theCommand->GetArg( 4 );
2624 theCommand->RemoveArgs();
2625 theCommand->SetArg( 1, mesh );
2626 theCommand->SetArg( 2, dir );
2627 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2628 theCommand->SetArg( 3, point );
2630 theCommand->SetArg( 3, face );
2633 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2635 isPyMeshMethod = true;
2636 int crit_arg = theCommand->GetNbArgs();
2637 const _AString& crit = theCommand->GetArg(crit_arg);
2638 if (crit.Search("MaxElementLength2D") != -1)
2639 theCommand->SetArg(crit_arg, "");
2642 if ( isPyMeshMethod )
2644 theCommand->SetObject( myMesh );
2648 // editor creation command is needed only if any editor function is called
2649 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2650 if ( !myCreationCmdStr.IsEmpty() ) {
2651 GetCreationCmd()->GetString() = myCreationCmdStr;
2652 myCreationCmdStr.Clear();
2657 //================================================================================
2659 * \brief Return true if my mesh can be removed
2661 //================================================================================
2663 bool _pyMeshEditor::CanClear()
2665 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2666 return mesh.IsNull() ? true : mesh->CanClear();
2669 //================================================================================
2671 * \brief _pyHypothesis constructor
2672 * \param theCreationCmd -
2674 //================================================================================
2676 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2677 _pyObject( theCreationCmd ), myCurCrMethod(0)
2679 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2682 //================================================================================
2684 * \brief Creates algorithm or hypothesis
2685 * \param theCreationCmd - The engine command creating a hypothesis
2686 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2688 //================================================================================
2690 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2692 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2693 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2695 Handle(_pyHypothesis) hyp, algo;
2698 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2699 if ( hypTypeQuoted.IsEmpty() )
2702 TCollection_AsciiString hypType =
2703 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2705 algo = new _pyAlgorithm( theCreationCmd );
2706 hyp = new _pyHypothesis( theCreationCmd );
2708 if ( hypType == "NumberOfSegments" ) {
2709 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2710 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2711 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2712 hyp->AddArgMethod( "SetNumberOfSegments" );
2713 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2714 hyp->AddArgMethod( "SetScaleFactor" );
2715 hyp->AddArgMethod( "SetReversedEdges" );
2716 // same for ""CompositeSegment_1D:
2717 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2718 hyp->AddArgMethod( "SetNumberOfSegments" );
2719 hyp->AddArgMethod( "SetScaleFactor" );
2720 hyp->AddArgMethod( "SetReversedEdges" );
2722 else if ( hypType == "SegmentLengthAroundVertex" ) {
2723 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2724 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2725 hyp->AddArgMethod( "SetLength" );
2726 // same for ""CompositeSegment_1D:
2727 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2728 hyp->AddArgMethod( "SetLength" );
2730 else if ( hypType == "LayerDistribution2D" ) {
2731 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2732 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2734 else if ( hypType == "LayerDistribution" ) {
2735 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2736 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2738 else if ( hypType == "CartesianParameters3D" ) {
2739 hyp = new _pyComplexParamHypo( theCreationCmd );
2740 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2741 for ( int iArg = 0; iArg < 4; ++iArg )
2742 hyp->setCreationArg( iArg+1, "[]");
2743 hyp->AddAccumulativeMethod( "SetGrid" );
2744 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2748 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2751 return algo->IsValid() ? algo : hyp;
2754 //================================================================================
2756 * \brief Returns true if addition of this hypothesis to a given mesh can be
2757 * wrapped into hypothesis creation
2759 //================================================================================
2761 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2763 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2765 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2766 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2772 //================================================================================
2774 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2775 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2776 * \param theAlgo - The algo that can create this hypo
2777 * \retval bool - false if the command can't be converted
2779 //================================================================================
2781 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2782 const _pyID& theMesh)
2784 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2786 if ( !IsWrappable( theMesh ))
2789 myGeom = theCmd->GetArg( 1 );
2791 Handle(_pyHypothesis) algo;
2793 // find algo created on myGeom in theMesh
2794 algo = theGen->FindAlgo( myGeom, theMesh, this );
2795 if ( algo.IsNull() )
2797 // attach hypothesis creation command to be after algo creation command
2798 // because it can be new created instance of algorithm
2799 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2803 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2804 theCmd->SetResultValue( GetID() );
2805 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2806 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2807 // set args (geom will be set by _pyMesh calling this method)
2808 theCmd->RemoveArgs();
2809 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2810 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2811 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2813 theCmd->SetArg( i+1, "[]");
2815 // set a new creation command
2816 GetCreationCmd()->Clear();
2817 // replace creation command by wrapped instance
2818 // please note, that hypothesis attaches to algo creation command (see upper)
2819 SetCreationCmd( theCmd );
2822 // clear commands setting arg values
2823 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2824 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2827 // set unknown arg commands after hypo creation
2828 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2829 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2830 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2831 afterCmd->AddDependantCmd( *cmd );
2837 //================================================================================
2839 * \brief Remember hypothesis parameter values
2840 * \param theCommand - The called hypothesis method
2842 //================================================================================
2844 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2846 ASSERT( !myIsAlgo );
2847 if ( !theGen->IsToKeepAllCommands() )
2848 rememberCmdOfParameter( theCommand );
2850 bool usedCommand = false;
2851 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2852 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2854 CreationMethod& crMethod = type2meth->second;
2855 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2856 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2858 myArgCommands.push_back( theCommand );
2860 while ( crMethod.myArgs.size() < i+1 )
2861 crMethod.myArgs.push_back( "None" );
2862 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2867 myUnusedCommands.push_back( theCommand );
2870 //================================================================================
2872 * \brief Finish conversion
2874 //================================================================================
2876 void _pyHypothesis::Flush()
2880 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2881 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2882 // Add access to a wrapped mesh
2883 theGen->AddMeshAccessorMethod( *cmd );
2884 // Add access to a wrapped algorithm
2885 theGen->AddAlgoAccessorMethod( *cmd );
2887 cmd = myUnusedCommands.begin();
2888 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2889 // Add access to a wrapped mesh
2890 theGen->AddMeshAccessorMethod( *cmd );
2891 // Add access to a wrapped algorithm
2892 theGen->AddAlgoAccessorMethod( *cmd );
2895 // forget previous hypothesis modifications
2896 myArgCommands.clear();
2897 myUnusedCommands.clear();
2900 //================================================================================
2902 * \brief clear creation, arg and unknown commands
2904 //================================================================================
2906 void _pyHypothesis::ClearAllCommands()
2908 GetCreationCmd()->Clear();
2909 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2910 for ( ; cmd != myArgCommands.end(); ++cmd )
2912 cmd = myUnusedCommands.begin();
2913 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2918 //================================================================================
2920 * \brief Assign fields of theOther to me except myIsWrapped
2922 //================================================================================
2924 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2925 const _pyID& theMesh )
2927 // myCreationCmd = theOther->myCreationCmd;
2928 myIsAlgo = theOther->myIsAlgo;
2929 myIsWrapped = false;
2930 myGeom = theOther->myGeom;
2932 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2933 myAccumulativeMethods = theOther->myAccumulativeMethods;
2934 //myUnusedCommands = theOther->myUnusedCommands;
2935 // init myCurCrMethod
2936 GetCreationMethod( theOther->GetAlgoType() );
2939 //================================================================================
2941 * \brief Analyze my erasability depending on myReferredObjs
2943 //================================================================================
2945 bool _pyHypothesis::CanClear()
2949 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2950 for ( ; obj != myReferredObjs.end(); ++obj )
2951 if ( (*obj)->CanClear() )
2958 //================================================================================
2960 * \brief Clear my commands depending on usage by meshes
2962 //================================================================================
2964 void _pyHypothesis::ClearCommands()
2966 // if ( !theGen->IsToKeepAllCommands() )
2968 // bool isUsed = false;
2969 // int lastComputeOrder = 0;
2970 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2971 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2972 // if ( ! (*cmd)->IsEmpty() )
2975 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2976 // lastComputeOrder = (*cmd)->GetOrderNb();
2980 // SetRemovedFromStudy( true );
2984 // // clear my commands invoked after lastComputeOrder
2985 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2986 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2988 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2989 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2990 // // cmds.back()->Clear();
2994 _pyObject::ClearCommands();
2997 //================================================================================
2999 * \brief Find arguments that are objects like mesh, group, geometry
3000 * \param meshes - referred meshes (directly or indirrectly)
3001 * \retval bool - false if a referred geometry is not in the study
3003 //================================================================================
3005 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3007 if ( IsAlgo() ) return true;
3009 bool geomPublished = true;
3010 vector< _AString > args;
3011 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3012 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3014 CreationMethod& crMethod = type2meth->second;
3015 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3017 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3018 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3019 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3020 args.push_back( (*cmd)->GetArg( nb ));
3023 for ( size_t i = 0; i < args.size(); ++i )
3025 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3026 if ( idList.empty() && !args[ i ].IsEmpty() )
3027 idList.push_back( args[ i ]);
3028 list< _pyID >::iterator id = idList.begin();
3029 for ( ; id != idList.end(); ++id )
3031 Handle(_pyObject) obj = theGen->FindObject( *id );
3032 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3035 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3036 geomPublished = false;
3040 myReferredObjs.push_back( obj );
3041 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3042 if ( !mesh.IsNull() )
3043 meshes.push_back( mesh );
3044 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3045 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3046 obj->SetRemovedFromStudy( false );
3050 return geomPublished;
3053 //================================================================================
3055 * \brief Remember theCommand setting a parameter
3057 //================================================================================
3059 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3061 // parameters are discriminated by method name
3062 _AString method = theCommand->GetMethod();
3063 if ( myAccumulativeMethods.count( method ))
3064 return; // this method adds values and not override the previous value
3066 // discriminate commands setting different parameters via one method
3067 // by passing parameter names like e.g. SetOption("size", "0.2")
3068 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3069 theCommand->GetNbArgs() > 1 )
3071 // mangle method by appending a 1st textual arg
3072 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3074 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3075 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3076 if ( !isalpha( arg.Value(2))) continue;
3081 // parameters are discriminated by method name
3082 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3083 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3085 cmds.back()->Clear(); // previous parameter value has not been used
3086 cmds.back() = theCommand;
3090 cmds.push_back( theCommand );
3094 //================================================================================
3096 * \brief Return true if a setting parameter command ha been used to compute mesh
3098 //================================================================================
3100 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3101 _pyCommand::TAddr avoidComputeAddr ) const
3103 bool isUsed = false;
3104 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3105 myComputeAddr2Cmds.begin();
3106 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3108 if ( addr2cmds->first == avoidComputeAddr ) continue;
3109 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3110 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3115 //================================================================================
3117 * \brief Save commands setting parameters as they are used for a mesh computation
3119 //================================================================================
3121 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3123 myComputeCmds.push_back( theComputeCmd );
3124 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3126 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3127 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3128 savedCmds.push_back( m2c->second.back() );
3131 //================================================================================
3133 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3135 //================================================================================
3137 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3139 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3141 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3142 for ( ; cmd != savedCmds.end(); ++cmd )
3144 // check if a cmd has been used to compute another mesh
3145 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3147 // check if a cmd is a sole command setting its parameter;
3148 // don't use method name for search as it can change
3149 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3150 m2cmds = myMeth2Commands.begin();
3151 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3153 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3154 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3155 if ( cmdIt != cmds.end() )
3157 if ( cmds.back() != *cmd )
3159 cmds.erase( cmdIt );
3166 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3169 //================================================================================
3171 * \brief Sets an argNb-th argument of current creation command
3172 * \param argNb - argument index countered from 1
3174 //================================================================================
3176 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3178 if ( myCurCrMethod )
3180 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3181 myCurCrMethod->myArgs.push_back( "None" );
3182 if ( arg.IsEmpty() )
3183 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3185 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3190 //================================================================================
3192 * \brief Remember hypothesis parameter values
3193 * \param theCommand - The called hypothesis method
3195 //================================================================================
3197 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3199 if ( GetAlgoType() == "Cartesian_3D" )
3201 // CartesianParameters3D hyp
3203 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3204 theCommand->GetMethod() == "SetToAddEdges" )
3206 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3207 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3208 myArgCommands.push_back( theCommand );
3211 if ( theCommand->GetMethod() == "SetGrid" ||
3212 theCommand->GetMethod() == "SetGridSpacing" )
3214 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3215 int iArg = axis.Value(1) - '0';
3216 if ( theCommand->GetMethod() == "SetGrid" )
3218 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3222 myCurCrMethod->myArgs[ iArg ] = "[ ";
3223 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3224 myCurCrMethod->myArgs[ iArg ] += ", ";
3225 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3226 myCurCrMethod->myArgs[ iArg ] += "]";
3228 myArgCommands.push_back( theCommand );
3229 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3230 // accumulative, else, if the creation
3231 // is not converted, commands for axes 1 and 2 are lost
3236 if( theCommand->GetMethod() == "SetLength" )
3238 // NOW it is OBSOLETE
3239 // ex: hyp.SetLength(start, 1)
3240 // hyp.SetLength(end, 0)
3241 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3242 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3243 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3244 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3246 CreationMethod& crMethod = type2meth->second;
3247 while ( (int) crMethod.myArgs.size() < i+1 )
3248 crMethod.myArgs.push_back( "[]" );
3249 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3251 myArgCommands.push_back( theCommand );
3255 _pyHypothesis::Process( theCommand );
3258 //================================================================================
3260 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3262 //================================================================================
3264 void _pyComplexParamHypo::Flush()
3266 list < Handle(_pyCommand) >::iterator cmd;
3269 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3270 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3274 // if ( GetAlgoType() == "Cartesian_3D" )
3276 // _pyID algo = myCreationCmd->GetObject();
3277 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3279 // if ( IsWrapped() )
3281 // StructToList( *cmd, /*checkMethod=*/false );
3282 // const _AString & method = (*cmd)->GetMethod();
3283 // if ( method == "SetFixedPoint" )
3284 // (*cmd)->SetObject( algo );
3290 //================================================================================
3292 * \brief Convert methods of 1D hypotheses to my own methods
3293 * \param theCommand - The called hypothesis method
3295 //================================================================================
3297 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3299 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3302 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3303 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3304 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3306 // TCollection_AsciiString cmd =
3307 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3308 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3309 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3312 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3314 // // 1D hypo is already set, so distribution changes and the old
3315 // // 1D hypo is thrown away
3316 // my1dHyp->ClearAllCommands();
3319 // //my1dHyp->SetRemovedFromStudy( false );
3321 // if ( !myArgCommands.empty() )
3322 // myArgCommands.back()->Clear();
3323 myCurCrMethod->myArgs.push_back( hyp1dID );
3324 myArgCommands.push_back( theCommand );
3327 //================================================================================
3330 * \param theAdditionCmd - command to be converted
3331 * \param theMesh - mesh instance
3332 * \retval bool - status
3334 //================================================================================
3336 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3337 const _pyID& theMesh)
3339 myIsWrapped = false;
3341 if ( my1dHyp.IsNull() )
3344 // set "SetLayerDistribution()" after addition cmd
3345 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3347 _pyID geom = theAdditionCmd->GetArg( 1 );
3349 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3350 if ( !algo.IsNull() )
3352 my1dHyp->SetMesh( theMesh );
3353 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3354 algo->GetAlgoType().ToCString());
3355 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3358 // clear "SetLayerDistribution()" cmd
3359 myArgCommands.back()->Clear();
3361 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3363 // find RadialPrism algo created on <geom> for theMesh
3364 GetCreationCmd()->SetObject( algo->GetID() );
3365 GetCreationCmd()->SetMethod( myAlgoMethod );
3366 GetCreationCmd()->RemoveArgs();
3367 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3373 //================================================================================
3377 //================================================================================
3379 void _pyLayerDistributionHypo::Flush()
3381 // as creation of 1D hyp was written later then it's edition,
3382 // we need to find all it's edition calls and process them
3383 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3385 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3387 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3388 if ( hyp1dID.IsEmpty() ) continue;
3390 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3392 // make a new name for 1D hyp = "HypType" + "_Distribution"
3394 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3396 if ( prevNewName.IsEmpty() ) continue;
3397 newName = prevNewName;
3401 if ( hyp1d->IsWrapped() ) {
3402 newName = hyp1d->GetCreationCmd()->GetMethod();
3405 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3406 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3408 newName += "_Distribution";
3409 prevNewName = newName;
3411 hyp1d->GetCreationCmd()->SetResultValue( newName );
3413 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3414 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3415 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3416 const _pyID& objID = (*cmdIt)->GetObject();
3417 if ( objID == hyp1dID ) {
3418 if ( !hyp1d.IsNull() )
3420 hyp1d->Process( *cmdIt );
3421 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3423 ( *cmdIt )->SetObject( newName );
3426 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3427 (*cmd)->SetArg( 1, newName );
3431 //================================================================================
3433 * \brief additionally to Addition2Creation, clears SetDistrType() command
3434 * \param theCmd - AddHypothesis() command
3435 * \param theMesh - mesh to which a hypothesis is added
3436 * \retval bool - conversion result
3438 //================================================================================
3440 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3441 const _pyID& theMesh)
3443 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3444 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3445 bool scaleDistrType = false;
3446 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3447 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3448 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3449 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3450 scaleDistrType = true;
3453 else if ( !scaleDistrType ) {
3454 // distribution type changed: remove scale factor from args
3455 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3456 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3458 CreationMethod& crMethod = type2meth->second;
3459 if ( crMethod.myArgs.size() == 2 )
3460 crMethod.myArgs.pop_back();
3467 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3470 //================================================================================
3472 * \brief remove repeated commands defining distribution
3474 //================================================================================
3476 void _pyNumberOfSegmentsHyp::Flush()
3478 // find number of the last SetDistrType() command
3479 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3480 int distrTypeNb = 0;
3481 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3482 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3483 if ( cmd != myUnusedCommands.rbegin() )
3484 distrTypeNb = (*cmd)->GetOrderNb();
3486 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3489 // clear commands before the last SetDistrType()
3490 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3491 set< int > treatedCmdNbs; // avoid treating same cmd twice
3492 for ( int i = 0; i < 2; ++i ) {
3493 set<TCollection_AsciiString> uniqueMethods;
3494 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3495 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3497 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3498 continue;// avoid treating same cmd twice
3499 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3500 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3501 if ( !clear || method == "SetNumberOfSegments" ) {
3502 bool isNewInSet = uniqueMethods.insert( method ).second;
3503 clear = !isNewInSet;
3512 //================================================================================
3514 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3515 * into regular1D.LengthNearVertex( length, vertex )
3516 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3517 * \param theMesh - The mesh needing this hypo
3518 * \retval bool - false if the command can't be converted
3520 //================================================================================
3522 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3523 const _pyID& theMeshID)
3525 if ( IsWrappable( theMeshID )) {
3527 _pyID vertex = theCmd->GetArg( 1 );
3529 // the problem here is that segment algo can be not found
3530 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3531 // geometry where segment algorithm is assigned
3532 _pyID geom = vertex;
3533 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3534 while ( algo.IsNull() && !geom.IsEmpty()) {
3535 // try to find geom as a father of <vertex>
3536 geom = FatherID( geom );
3537 algo = theGen->FindAlgo( geom, theMeshID, this );
3539 if ( algo.IsNull() || geom.IsEmpty() )
3540 return false; // also possible to find geom as brother of veretex...
3542 // set geom instead of vertex
3543 theCmd->SetArg( 1, geom );
3545 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3546 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3547 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3549 // set vertex as a second arg
3550 theCmd->SetArg( 2, vertex );
3558 //================================================================================
3560 * \brief _pyAlgorithm constructor
3561 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3563 //================================================================================
3565 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3566 : _pyHypothesis( theCreationCmd )
3571 //================================================================================
3573 * \brief Convert the command adding an algorithm to mesh
3574 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3575 * \param theMesh - The mesh needing this algo
3576 * \retval bool - false if the command can't be converted
3578 //================================================================================
3580 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3581 const _pyID& theMeshID)
3583 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3584 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3585 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3591 //================================================================================
3593 * \brief Return starting position of a part of python command
3594 * \param thePartIndex - The index of command part
3595 * \retval int - Part position
3597 //================================================================================
3599 int _pyCommand::GetBegPos( int thePartIndex ) const
3603 if ( myBegPos.Length() < thePartIndex )
3605 ASSERT( thePartIndex > 0 );
3606 return myBegPos( thePartIndex );
3609 //================================================================================
3611 * \brief Store starting position of a part of python command
3612 * \param thePartIndex - The index of command part
3613 * \param thePosition - Part position
3615 //================================================================================
3617 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3619 while ( myBegPos.Length() < thePartIndex )
3620 myBegPos.Append( UNKNOWN );
3621 ASSERT( thePartIndex > 0 );
3622 myBegPos( thePartIndex ) = thePosition;
3625 //================================================================================
3627 * \brief Returns whitespace symbols at the line beginning
3628 * \retval TCollection_AsciiString - result
3630 //================================================================================
3632 TCollection_AsciiString _pyCommand::GetIndentation()
3635 //while ( end <= Length() && isblank( myString.Value( end )))
3636 //ANA: isblank() function isn't provided in VC2010 compiler
3637 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3639 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3642 //================================================================================
3644 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3645 * \retval const TCollection_AsciiString & - ResultValue substring
3647 //================================================================================
3649 const TCollection_AsciiString & _pyCommand::GetResultValue()
3651 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3653 SetBegPos( RESULT_IND, EMPTY );
3654 int begPos, endPos = myString.Location( "=", 1, Length() );
3658 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3659 if ( begPos < endPos )
3661 SetBegPos( RESULT_IND, begPos );
3663 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3664 myRes = myString.SubString( begPos, endPos );
3671 //================================================================================
3673 * \brief Return number of python command result value ResultValue = Obj.Meth()
3675 //================================================================================
3677 int _pyCommand::GetNbResultValues()
3680 return myResults.Length();
3684 //================================================================================
3686 * \brief Return substring of python command looking like
3687 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3688 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3690 //================================================================================
3691 const _AString& _pyCommand::GetResultValue(int res)
3693 if ( GetResultValue().IsEmpty() )
3694 return theEmptyString;
3696 if ( myResults.IsEmpty() )
3699 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3700 ++begPos; // skip [, else the whole list is returned
3701 while ( begPos < myRes.Length() ) {
3702 _AString result = GetWord( myRes, begPos, true );
3703 begPos += result.Length();
3705 // result.RemoveAll('[');
3706 // result.RemoveAll(']');
3711 myResults.Append( result );
3714 if ( res > 0 && res <= myResults.Length() )
3715 return myResults( res );
3716 return theEmptyString;
3719 //================================================================================
3721 * \brief Return substring of python command looking like ResVal = Object.Meth()
3722 * \retval const TCollection_AsciiString & - Object substring
3724 //================================================================================
3726 const TCollection_AsciiString & _pyCommand::GetObject()
3728 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3731 int begPos = GetBegPos( RESULT_IND );
3733 begPos = myString.Location( "=", 1, Length() ) + 1;
3734 // is '=' in the string argument (for example, name) or not
3735 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3736 for ( int i = 1; i < begPos-1; i++ )
3737 switch ( myString.Value( i )) {
3738 case '\'': nb[0]++; break;
3739 case '"' : nb[1]++; break;
3740 case '(' : nb[2]++; break;
3741 case ')' : nb[3]++; break;
3743 // if = is inside a string or a list
3744 // then get an object at the start of the command
3745 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3749 begPos += myRes.Length();
3751 myObj = GetWord( myString, begPos, true );
3752 if ( begPos != EMPTY )
3754 // check if object is complex,
3755 // so far consider case like "smesh.Method()"
3756 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3757 //if ( bracketPos==0 ) bracketPos = Length();
3758 int dotPos = begPos+myObj.Length();
3759 while ( dotPos+1 < bracketPos ) {
3760 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3765 if ( dotPos > begPos+myObj.Length() )
3766 myObj = myString.SubString( begPos, dotPos-1 );
3769 // 1st word after '=' is an object
3770 // else // no method -> no object
3776 SetBegPos( OBJECT_IND, begPos );
3782 //================================================================================
3784 * \brief Return substring of python command looking like ResVal = Obj.Method()
3785 * \retval const TCollection_AsciiString & - Method substring
3787 //================================================================================
3789 const TCollection_AsciiString & _pyCommand::GetMethod()
3791 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3794 int begPos = GetBegPos( OBJECT_IND );
3795 bool forward = true;
3797 begPos = myString.Location( "(", 1, Length() ) - 1;
3801 begPos += myObj.Length();
3804 myMeth = GetWord( myString, begPos, forward );
3805 SetBegPos( METHOD_IND, begPos );
3811 //================================================================================
3813 * \brief Returns true if there are brackets after the method
3815 //================================================================================
3817 bool _pyCommand::IsMethodCall()
3819 if ( GetMethod().IsEmpty() )
3821 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3822 return ( s[0] == '(' || s[1] == '(' );
3825 //================================================================================
3827 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3828 * \retval const TCollection_AsciiString & - Arg<index> substring
3830 //================================================================================
3832 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3834 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3838 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3840 pos = myString.Location( "(", 1, Length() );
3844 // we are at or before '(', skip it if present
3846 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3847 if ( pos > Length() )
3851 SetBegPos( ARG1_IND, 0 ); // even no '('
3852 return theEmptyString;
3856 list< TCollection_AsciiString > separatorStack( 1, ",)");
3857 bool ignoreNesting = false;
3859 while ( pos <= Length() )
3861 const char chr = myString.Value( pos );
3863 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3865 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3867 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3869 TCollection_AsciiString arg;
3870 if ( pos-1 >= prevPos ) {
3871 arg = myString.SubString( prevPos, pos-1 );
3872 arg.RightAdjust(); // remove spaces
3875 if ( !arg.IsEmpty() || chr == ',' )
3877 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3878 myArgs.Append( arg );
3884 else // end of nesting args found
3886 separatorStack.pop_back();
3887 ignoreNesting = false;
3890 else if ( !ignoreNesting )
3893 case '(' : separatorStack.push_back(")"); break;
3894 case '[' : separatorStack.push_back("]"); break;
3895 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3896 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3903 if ( myArgs.Length() < index )
3904 return theEmptyString;
3905 return myArgs( index );
3908 //================================================================================
3910 * \brief Return position where arguments begin
3912 //================================================================================
3914 int _pyCommand::GetArgBeginning() const
3916 int pos = GetBegPos( ARG1_IND );
3917 if ( pos == UNKNOWN )
3919 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3921 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3926 //================================================================================
3928 * \brief Check if char is a word part
3929 * \param c - The character to check
3930 * \retval bool - The check result
3932 //================================================================================
3934 static inline bool isWord(const char c, const bool dotIsWord)
3937 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3940 //================================================================================
3942 * \brief Looks for a word in the string and returns word's beginning
3943 * \param theString - The input string
3944 * \param theStartPos - The position to start the search, returning word's beginning
3945 * \param theForward - The search direction
3946 * \retval TCollection_AsciiString - The found word
3948 //================================================================================
3950 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3952 const bool theForward,
3953 const bool dotIsWord )
3955 int beg = theStartPos, end = theStartPos;
3956 theStartPos = EMPTY;
3957 if ( beg < 1 || beg > theString.Length() )
3958 return theEmptyString;
3960 if ( theForward ) { // search forward
3962 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3964 if ( beg > theString.Length() )
3965 return theEmptyString; // no word found
3968 char begChar = theString.Value( beg );
3969 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3970 char endChar = ( begChar == '[' ) ? ']' : begChar;
3971 // end is at the corresponding quoting mark or bracket
3972 while ( end < theString.Length() &&
3973 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3977 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3982 else { // search backward
3984 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3987 return theEmptyString; // no word found
3989 char endChar = theString.Value( end );
3990 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3991 char begChar = ( endChar == ']' ) ? '[' : endChar;
3992 // beg is at the corresponding quoting mark
3994 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3998 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4004 //cout << theString << " ---- " << beg << " - " << end << endl;
4005 return theString.SubString( beg, end );
4008 //================================================================================
4010 * \brief Returns true if the string looks like a study entry
4012 //================================================================================
4014 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4016 if ( str.Length() < 5 ) return false;
4018 int nbColons = 0, isColon;
4019 for ( int i = 1; i <= str.Length(); ++i )
4021 char c = str.Value(i);
4022 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4024 nbColons += isColon;
4026 return nbColons > 2 && str.Length()-nbColons > 2;
4029 //================================================================================
4031 * \brief Returns true if the string looks like an object ID but not like a list,
4032 * string, command etc.
4034 //================================================================================
4036 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4038 if ( str.Length() < 1 ) return false;
4040 const char* s = str.ToCString();
4042 for ( int i = 0; i < str.Length(); ++i )
4043 if ( !IsIDChar( s[i] ))
4049 //================================================================================
4051 * \brief Finds entries in a string
4053 //================================================================================
4055 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4057 std::list< _pyID > resList;
4059 while ( ++pos <= str.Length() )
4061 if ( !isdigit( str.Value( pos ))) continue;
4062 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4065 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4066 _pyID entry = str.SubString( pos, end-1 );
4068 if ( IsStudyEntry( entry ))
4069 resList.push_back( entry );
4074 //================================================================================
4076 * \brief Look for position where not space char is
4077 * \param theString - The string
4078 * \param thePos - The position to search from and which returns result
4079 * \retval bool - false if there are only space after thePos in theString
4081 //================================================================================
4083 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4085 if ( thePos < 1 || thePos > theString.Length() )
4088 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4091 return thePos <= theString.Length();
4094 //================================================================================
4096 * \brief Modify a part of the command
4097 * \param thePartIndex - The index of the part
4098 * \param thePart - The new part string
4099 * \param theOldPart - The old part
4101 //================================================================================
4103 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4104 TCollection_AsciiString& theOldPart)
4106 int pos = GetBegPos( thePartIndex );
4107 if ( pos <= Length() && theOldPart != thePart)
4109 TCollection_AsciiString seperator;
4111 pos = GetBegPos( thePartIndex + 1 );
4112 if ( pos < 1 ) return;
4113 switch ( thePartIndex ) {
4114 case RESULT_IND: seperator = " = "; break;
4115 case OBJECT_IND: seperator = "."; break;
4116 case METHOD_IND: seperator = "()"; break;
4120 myString.Remove( pos, theOldPart.Length() );
4121 if ( !seperator.IsEmpty() )
4122 myString.Insert( pos , seperator );
4123 myString.Insert( pos, thePart );
4124 // update starting positions of the following parts
4125 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4126 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4127 if ( myBegPos( i ) > 0 )
4128 myBegPos( i ) += posDelta;
4130 theOldPart = thePart;
4134 //================================================================================
4136 * \brief Set argument
4137 * \param index - The argument index, it counts from 1
4138 * \param theArg - The argument string
4140 //================================================================================
4142 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4145 int argInd = ARG1_IND + index - 1;
4146 int pos = GetBegPos( argInd );
4147 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4149 // find a closing parenthesis
4150 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4151 int lastArgInd = GetNbArgs();
4152 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4153 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4158 while ( pos > 0 && myString.Value( pos ) != ')' )
4161 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4165 while ( myArgs.Length() < index ) {
4166 if ( myArgs.Length() )
4167 myString.Insert( pos++, "," );
4168 myArgs.Append("None");
4169 myString.Insert( pos, myArgs.Last() );
4170 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4171 pos += myArgs.Last().Length();
4174 SetPart( argInd, theArg, myArgs( index ));
4177 //================================================================================
4179 * \brief Empty arg list
4181 //================================================================================
4183 void _pyCommand::RemoveArgs()
4185 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4186 myString.Trunc( pos );
4189 if ( myBegPos.Length() >= ARG1_IND )
4190 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4193 //================================================================================
4195 * \brief Comment a python command
4197 //================================================================================
4199 void _pyCommand::Comment()
4201 if ( IsEmpty() ) return;
4204 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4205 if ( i <= Length() )
4207 myString.Insert( i, "#" );
4208 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4210 int begPos = GetBegPos( iPart );
4211 if ( begPos != UNKNOWN && begPos != EMPTY )
4212 SetBegPos( iPart, begPos + 1 );
4217 //================================================================================
4219 * \brief Set dependent commands after this one
4221 //================================================================================
4223 bool _pyCommand::SetDependentCmdsAfter() const
4225 bool orderChanged = false;
4226 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4227 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4228 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4229 orderChanged = true;
4230 theGen->SetCommandAfter( *cmd, this );
4231 (*cmd)->SetDependentCmdsAfter();
4234 return orderChanged;
4236 //================================================================================
4238 * \brief Insert accessor method after theObjectID
4239 * \param theObjectID - id of the accessed object
4240 * \param theAcsMethod - name of the method giving access to the object
4241 * \retval bool - false if theObjectID is not found in the command string
4243 //================================================================================
4245 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4247 if ( !theAcsMethod )
4249 // start object search from the object, i.e. ignore result
4251 int beg = GetBegPos( OBJECT_IND );
4252 if ( beg < 1 || beg > Length() )
4255 while (( beg = myString.Location( theObjectID, beg, Length() )))
4257 // check that theObjectID is not just a part of a longer ID
4258 int afterEnd = beg + theObjectID.Length();
4259 Standard_Character c = myString.Value( afterEnd );
4260 if ( !IsIDChar( c ))
4262 // check if accessor method already present
4264 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4266 int oldLen = Length();
4267 myString.Insert( afterEnd, (char*) theAcsMethod );
4268 myString.Insert( afterEnd, "." );
4269 // update starting positions of the parts following the modified one
4270 int posDelta = Length() - oldLen;
4271 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4272 if ( myBegPos( i ) > afterEnd )
4273 myBegPos( i ) += posDelta;
4278 beg = afterEnd; // is a part -> next search
4283 //================================================================================
4285 * \brief Creates pyObject
4287 //================================================================================
4289 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4290 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4295 //================================================================================
4297 * \brief Set up myID and myIsPublished
4299 //================================================================================
4301 void _pyObject::setID(const _pyID& theID)
4304 myIsPublished = !theGen->IsNotPublished( GetID() );
4307 //================================================================================
4309 * \brief Clear myCreationCmd and myProcessedCmds
4311 //================================================================================
4313 void _pyObject::ClearCommands()
4318 if ( !myCreationCmd.IsNull() )
4319 myCreationCmd->Clear();
4321 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4322 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4326 //================================================================================
4328 * \brief Return method name giving access to an interaface object wrapped by python class
4329 * \retval const char* - method name
4331 //================================================================================
4333 const char* _pyObject::AccessorMethod() const
4337 //================================================================================
4339 * \brief Return ID of a father
4341 //================================================================================
4343 _pyID _pyObject::FatherID(const _pyID & childID)
4345 int colPos = childID.SearchFromEnd(':');
4347 return childID.SubString( 1, colPos-1 );
4351 //================================================================================
4353 * \brief SelfEraser erases creation command if none of it's commands invoked
4354 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4356 //================================================================================
4358 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4359 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4361 myIsPublished = true; // prevent clearing as a not published
4362 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4365 //================================================================================
4367 * \brief SelfEraser erases creation command if none of it's commands invoked
4368 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4370 //================================================================================
4372 bool _pySelfEraser::CanClear()
4374 bool toErase = false;
4375 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4378 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4379 for ( ; cmd != myArgCmds.end(); ++cmd )
4380 nbArgUses += IsAliveCmd( *cmd );
4382 toErase = ( nbArgUses < 1 );
4387 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4388 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4389 for ( ; cmd != cmds.end(); )
4390 // check of cmd emptiness is not enough as object can change
4391 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4394 cmd = cmds.erase( cmd ); // save the cmd from clearing
4396 toErase = ( nbCalls < 1 );
4401 //================================================================================
4403 * \brief Check if a command is or can be cleared
4405 //================================================================================
4407 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4409 if ( theCmd->IsEmpty() )
4412 if ( !theGen->IsToKeepAllCommands() )
4414 const _pyID& objID = theCmd->GetObject();
4415 Handle( _pyObject ) obj = theGen->FindObject( objID );
4416 if ( !obj.IsNull() )
4417 return !obj->CanClear();
4422 //================================================================================
4424 * \brief SelfEraser erases creation command if none of it's commands invoked
4425 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4427 //================================================================================
4429 void _pySelfEraser::Flush()
4433 myIsPublished = false;
4434 _pyObject::ClearCommands();
4438 //================================================================================
4440 * \brief _pySubMesh constructor
4442 //================================================================================
4444 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4445 _pyObject(theCreationCmd)
4447 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4448 if ( toKeepAgrCmds )
4449 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4452 //================================================================================
4454 * \brief Return true if a sub-mesh can be used as argument of the given method
4456 //================================================================================
4458 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4461 // names of all methods where a sub-mesh can be used as argument
4462 // static TStringSet methods;
4463 // if ( methods.empty() ) {
4464 // const char * names[] = {
4465 // // methods of SMESH_Gen
4467 // // methods of SMESH_Group
4469 // // methods of SMESH_Measurements
4471 // // methods of SMESH_Mesh
4472 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4474 // // methods of SMESH_MeshEditor
4475 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4476 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4477 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4478 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4479 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4480 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4481 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4482 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4483 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4484 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4485 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4486 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4487 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4488 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4489 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4490 // "" }; // <- mark of end
4491 // methods.Insert( names );
4493 // return methods.Contains( theMethodName );
4496 //================================================================================
4498 * \brief count invoked commands
4500 //================================================================================
4502 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4504 _pyObject::Process(theCommand); // count calls of Process()
4507 //================================================================================
4509 * \brief Move creation command depending on invoked commands
4511 //================================================================================
4513 void _pySubMesh::Flush()
4515 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4516 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4517 else if ( !myCreator.IsNull() )
4518 // move to be just after creator
4519 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4521 // move sub-mesh usage after creation cmd
4522 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4523 for ( ; cmd != myArgCmds.end(); ++cmd )
4524 if ( !(*cmd)->IsEmpty() )
4525 GetCreationCmd()->AddDependantCmd( *cmd );
4528 //================================================================================
4530 * \brief Creates _pyGroup
4532 //================================================================================
4534 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4535 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4537 if ( !id.IsEmpty() )
4540 myCanClearCreationCmd = true;
4542 const _AString& method = theCreationCmd->GetMethod();
4543 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4545 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4547 // ----------------------------------------------------------------------
4548 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4550 _pyID geom = theCreationCmd->GetArg( 3 );
4551 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4552 // next if(){...} section is commented
4553 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4554 // theCreationCmd->SetMethod( "Group" );
4555 // theCreationCmd->RemoveArgs();
4556 // theCreationCmd->SetArg( 1, geom );
4559 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4560 _pyID type = theCreationCmd->GetArg( 1 );
4561 _pyID name = theCreationCmd->GetArg( 2 );
4562 theCreationCmd->SetMethod( "GroupOnGeom" );
4563 theCreationCmd->RemoveArgs();
4564 theCreationCmd->SetArg( 1, geom );
4565 theCreationCmd->SetArg( 2, name );
4566 theCreationCmd->SetArg( 3, type );
4569 else if ( method == "CreateGroupFromFilter" )
4571 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4572 theCreationCmd->SetMethod( "GroupOnFilter" );
4574 _pyID filterID = theCreationCmd->GetArg(3);
4575 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4576 if ( !filter.IsNull())
4578 if ( !filter->GetNewID().IsEmpty() )
4579 theCreationCmd->SetArg( 3, filter->GetNewID() );
4580 //filter->AddUser( this );
4584 else if ( method == "GetGroups" )
4586 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4590 // theCreationCmd does something else apart from creation of this group
4591 // and thus it can't be cleared if this group is removed
4592 myCanClearCreationCmd = false;
4596 //================================================================================
4598 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4601 //================================================================================
4603 bool _pyGroup::CanClear()
4608 if ( !myCanClearCreationCmd &&
4609 !myCreationCmd.IsNull() &&
4610 myCreationCmd->GetMethod() == "GetGroups" )
4612 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4613 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4614 list< _pyID >::iterator grID = idList.begin();
4615 if ( GetID() == *grID )
4617 myCanClearCreationCmd = true;
4618 list< Handle(_pyGroup ) > groups;
4619 for ( ; grID != idList.end(); ++grID )
4621 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4622 if ( group.IsNull() ) continue;
4623 groups.push_back( group );
4624 if ( group->IsInStudy() )
4625 myCanClearCreationCmd = false;
4627 // set myCanClearCreationCmd == true to all groups
4628 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4629 for ( ; group != groups.end(); ++group )
4630 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4634 return myCanClearCreationCmd;
4637 //================================================================================
4639 * \brief set myCanClearCreationCmd = true if the main action of the creation
4640 * command is discarded
4642 //================================================================================
4644 void _pyGroup::RemovedWithContents()
4646 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4647 // via a created group
4648 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4649 // myCanClearCreationCmd = true;
4652 //================================================================================
4654 * \brief To convert creation of a group by filter
4656 //================================================================================
4658 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4660 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4661 // group = mesh.CreateEmptyGroup( elemType, groupName )
4662 // aFilter.SetMesh(mesh)
4663 // nbAdd = group.AddFrom( aFilter )
4664 Handle(_pyFilter) filter;
4665 if ( theCommand->GetMethod() == "AddFrom" )
4667 _pyID idSource = theCommand->GetArg(1);
4668 // check if idSource is a filter
4669 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4670 if ( !filter.IsNull() )
4672 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4673 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4674 while ( *cmdIt != theCommand ) ++cmdIt;
4675 while ( (*cmdIt)->GetOrderNb() != 1 )
4677 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4678 if ((setMeshCmd->GetObject() == idSource ||
4679 setMeshCmd->GetObject() == filter->GetNewID() )
4681 setMeshCmd->GetMethod() == "SetMesh")
4683 setMeshCmd->Clear();
4687 // replace 3 commands by one
4688 theCommand->Clear();
4689 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4690 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4691 if ( !filter->GetNewID().IsEmpty() )
4692 idSource = filter->GetNewID();
4693 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4694 makeGroupCmd->SetArg( 1, name );
4695 makeGroupCmd->SetArg( 2, idSource );
4696 filter->AddArgCmd( makeGroupCmd );
4699 else if ( theCommand->GetMethod() == "SetFilter" )
4701 // set new name of a filter or clear the command if the same filter is set
4702 _pyID filterID = theCommand->GetArg(1);
4703 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4704 if ( !myFilter.IsNull() && filter == myFilter )
4705 theCommand->Clear();
4706 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4707 theCommand->SetArg( 1, filter->GetNewID() );
4710 else if ( theCommand->GetMethod() == "GetFilter" )
4712 // GetFilter() returns a filter with other ID, make myFilter process
4713 // calls of the returned filter
4714 if ( !myFilter.IsNull() )
4716 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4717 theCommand->Clear();
4721 // if ( !filter.IsNull() )
4722 // filter->AddUser( this );
4724 theGen->AddMeshAccessorMethod( theCommand );
4727 //================================================================================
4729 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4731 //================================================================================
4733 void _pyGroup::Flush()
4735 if ( !theGen->IsToKeepAllCommands() &&
4736 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4738 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4742 //================================================================================
4744 * \brief Constructor of _pyFilter
4746 //================================================================================
4748 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4749 :_pyObject(theCreationCmd), myNewID( newID )
4751 //myIsPublished = true; // prevent clearing as a not published
4752 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4755 //================================================================================
4757 * \brief To convert creation of a filter by criteria and
4758 * to replace an old name by a new one
4760 //================================================================================
4762 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4764 if ( theCommand->GetObject() == GetID() )
4765 _pyObject::Process(theCommand); // count commands
4767 if ( !myNewID.IsEmpty() )
4768 theCommand->SetObject( myNewID );
4770 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4771 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4772 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4773 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4774 theCommand->GetMethod() == "SetCriteria")
4776 // aFilter.SetCriteria(aCriteria) ->
4777 // aFilter = smesh.GetFilterFromCriteria(criteria)
4778 if ( myNewID.IsEmpty() )
4779 theCommand->SetResultValue( GetID() );
4781 theCommand->SetResultValue( myNewID );
4782 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4783 theCommand->SetMethod( "GetFilterFromCriteria" );
4785 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4786 GetCreationCmd()->Clear();
4787 GetCreationCmd()->GetString() = theCommand->GetString();
4788 theCommand->Clear();
4789 theCommand->AddDependantCmd( GetCreationCmd() );
4790 // why swap? -- it's needed
4791 //GetCreationCmd()->Clear();
4793 else if ( theCommand->GetMethod() == "SetMesh" )
4795 if ( myMesh == theCommand->GetArg( 1 ))
4796 theCommand->Clear();
4798 myMesh = theCommand->GetArg( 1 );
4799 theGen->AddMeshAccessorMethod( theCommand );
4803 //================================================================================
4805 * \brief Set new filter name to the creation command and to myArgCmds
4807 //================================================================================
4809 void _pyFilter::Flush()
4811 if ( myNewID.IsEmpty() ) return;
4813 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4814 for ( ; cmd != myArgCmds.end(); ++cmd )
4815 if ( !(*cmd)->IsEmpty() )
4817 _AString cmdStr = (*cmd)->GetString();
4818 _AString id = GetID();
4819 int pos = cmdStr.Search( id );
4822 cmdStr.Remove( pos, id.Length() );
4823 cmdStr.Insert( pos, myNewID );
4826 (*cmd)->GetString() = cmdStr;
4829 if ( !GetCreationCmd()->IsEmpty() )
4830 GetCreationCmd()->SetResultValue( myNewID );
4833 //================================================================================
4835 * \brief Return true if all my users can be cleared
4837 //================================================================================
4839 bool _pyObject::CanClear()
4841 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4842 for ( ; cmd != myArgCmds.end(); ++cmd )
4843 if ( !(*cmd)->IsEmpty() )
4845 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4846 if ( !obj.IsNull() && !obj->CanClear() )
4849 return ( !myIsPublished );
4852 //================================================================================
4854 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4856 //================================================================================
4858 _pyHypothesisReader::_pyHypothesisReader()
4861 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4862 LDOMParser xmlParser;
4863 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4865 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4869 INFOS( xmlParser.GetError(data) );
4872 // <algorithm type="Regular_1D"
4873 // label-id="Wire discretisation"
4876 // <algo>Regular_1D=Segment()</algo>
4877 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4879 LDOM_Document xmlDoc = xmlParser.getDocument();
4880 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4881 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4883 LDOM_Node algoNode = algoNodeList.item( i );
4884 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4885 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4886 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4888 _AString text, algoType, method, arg;
4889 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4891 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4892 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4893 text = textNode.getNodeValue();
4894 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4895 algoType = algoCmd->GetResultValue();
4896 method = algoCmd->GetMethod();
4897 arg = algoCmd->GetArg(1);
4898 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4900 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4901 algo->SetConvMethodAndType( method, algoType );
4902 if ( !arg.IsEmpty() )
4903 algo->setCreationArg( 1, arg );
4905 myType2Hyp[ algoType ] = algo;
4909 if ( algoType.IsEmpty() ) continue;
4911 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4913 Handle( _pyHypothesis ) hyp;
4914 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4916 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4917 LDOM_Node textNode = pyHypoNode.getFirstChild();
4918 text = textNode.getNodeValue();
4919 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4920 hypType = hypoCmd->GetResultValue();
4921 method = hypoCmd->GetMethod();
4922 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4924 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4925 if ( type2hyp == myType2Hyp.end() )
4926 hyp = new _pyHypothesis( hypoCmd );
4928 hyp = type2hyp->second;
4929 hyp->SetConvMethodAndType( method, algoType );
4930 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4932 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4933 _AString argMethod = argCmd.GetMethod();
4934 _AString argNbText = argCmd.GetArg( 1 );
4935 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4936 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4938 hyp->AddArgMethod( argMethod,
4939 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4941 myType2Hyp[ hypType ] = hyp;
4945 // <hypothesis type="BLSURF_Parameters"
4949 // <accumulative-methods>
4950 // SetEnforcedVertex,
4951 // SetEnforcedVertexNamed
4952 // </accumulative-methods>
4956 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4957 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4959 LDOM_Node hypNode = hypNodeList.item( i );
4960 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4961 _AString hypType = hypElem.getAttribute("type");
4962 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4963 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4965 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4966 if ( type2hyp == myType2Hyp.end() ) continue;
4968 LDOM_Node methNode = methNodeList.item( 0 );
4969 LDOM_Node textNode = methNode.getFirstChild();
4970 _AString text = textNode.getNodeValue();
4974 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4975 pos += method.Length();
4976 type2hyp->second->AddAccumulativeMethod( method );
4978 while ( !method.IsEmpty() );
4981 } // loop on xmlPaths
4984 //================================================================================
4986 * \brief Returns a new hypothesis initialized according to the read information
4988 //================================================================================
4990 Handle(_pyHypothesis)
4991 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4992 const Handle(_pyCommand)& creationCmd) const
4994 Handle(_pyHypothesis) resHyp, sampleHyp;
4996 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4997 if ( type2hyp != myType2Hyp.end() )
4998 sampleHyp = type2hyp->second;
5000 if ( sampleHyp.IsNull() )
5002 resHyp = new _pyHypothesis(creationCmd);
5006 if ( sampleHyp->IsAlgo() )
5007 resHyp = new _pyAlgorithm( creationCmd );
5009 resHyp = new _pyHypothesis(creationCmd);
5010 resHyp->Assign( sampleHyp, _pyID() );
5015 //================================================================================
5017 * \brief Adds an object ID to some family of IDs with a common prefix
5018 * \param [in] str - the object ID
5019 * \return bool - \c false if \a str does not have the same prefix as \a this family
5020 * (for internal usage)
5022 //================================================================================
5024 bool _pyStringFamily::Add( const char* str )
5026 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5027 return false; // expected prefix is missing
5029 str += _prefix.Length(); // skip _prefix
5031 // try to add to some of child falimies
5032 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5033 for ( ; itSub != _subFams.end(); ++itSub )
5034 if ( itSub->Add( str ))
5037 // no suitable family found - add str to _strings or create a new child family
5039 // look for a proper place within sorted _strings
5040 std::list< _AString >::iterator itStr = _strings.begin();
5041 while ( itStr != _strings.end() && itStr->IsLess( str ))
5043 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5044 return true; // same ID already kept
5046 const int minPrefixSize = 4;
5048 // count "smaller" strings with the same prefix
5049 std::list< _AString >::iterator itLess = itStr; --itLess;
5051 for ( ; itLess != _strings.end(); --itLess )
5052 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5057 // count "greater" strings with the same prefix
5058 std::list< _AString >::iterator itMore = itStr;
5060 for ( ; itMore != _strings.end(); ++itMore )
5061 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5066 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5068 // look for a maximal prefix length
5069 // int lessPrefSize = 3, morePrefSize = 3;
5070 // if ( nbLess > 0 )
5071 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5073 // if ( nbMore > 0 )
5074 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5076 // int prefixSize = 3;
5077 // if ( nbLess == 0 )
5078 // prefixSize = morePrefSize;
5079 // else if ( nbMore == 0 )
5080 // prefixSize = lessPrefSize;
5082 // prefixSize = Min( lessPrefSize, morePrefSize );
5083 int prefixSize = minPrefixSize;
5084 _AString newPrefix ( str, prefixSize );
5086 // look for a proper place within _subFams sorted by _prefix
5087 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5088 if ( !itSub->_prefix.IsLess( newPrefix ))
5091 // add the new _pyStringFamily
5092 itSub = _subFams.insert( itSub, _pyStringFamily());
5093 _pyStringFamily& newSubFam = *itSub;
5094 newSubFam._prefix = newPrefix;
5096 // pass this->_strings to newSubFam._strings
5097 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5098 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5099 newSubFam._strings.push_back( str + prefixSize );
5100 for ( ; nbMore > 0; --nbMore, ++itStr )
5101 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5103 _strings.erase( itLess, ++itMore );
5105 else // too few string to make a family for them
5107 _strings.insert( itStr, str );
5112 //================================================================================
5114 * \brief Finds an object ID in the command
5115 * \param [in] longStr - the command string
5116 * \param [out] subStr - the found object ID
5117 * \return bool - \c true if the object ID found
5119 //================================================================================
5121 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5123 const _AString& longStr = cmd->GetString();
5124 const char* s = longStr.ToCString();
5127 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5128 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5129 if ( argBeg < 4 || argBeg > longStr.Length() )
5131 for ( ; itSub != _subFams.end(); ++itSub )
5134 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5135 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5137 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5138 from = pos + len + itSub->_prefix.Length();
5143 from += itSub->_prefix.Length();
5146 // look among _strings
5147 std::list< _AString >::iterator itStr = _strings.begin();
5148 for ( ; itStr != _strings.end(); ++itStr )
5149 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5150 // check that object ID does not continue after len
5151 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5153 subStr.push_back( *itStr );
5159 //================================================================================
5161 * \brief Return remainder length of the object ID after my _prefix
5162 * \param [in] str - remainder of the command after my _prefix
5163 * \return int - length of the object ID or -1 if not found
5165 //================================================================================
5167 int _pyStringFamily::isIn( const char* str )
5169 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5171 for ( ; itSub != _subFams.end(); ++itSub )
5173 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5176 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5177 return itSub->_prefix.Length() + len;
5182 if ( !_strings.empty() )
5184 std::list< _AString >::iterator itStr = _strings.begin();
5185 bool firstEmpty = itStr->IsEmpty();
5188 for ( ; itStr != _strings.end(); ++itStr )
5190 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5193 len = itStr->Length();
5202 // check that object ID does not continue after len
5203 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5210 //================================================================================
5214 //================================================================================
5216 void _pyStringFamily::Print( int level )
5218 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5219 std::list< _AString >::iterator itStr = _strings.begin();
5220 for ( ; itStr != _strings.end(); ++itStr )
5221 cout << *itStr << " | ";
5223 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5224 for ( ; itSub != _subFams.end(); ++itSub )
5225 itSub->Print( level + 1 );
5227 cout << string( 70, '-' ) << endl;