1 // Copyright (C) 2007-2013 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.
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>
54 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
57 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
65 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
67 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
84 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
87 using SMESH::TPythonDump;
90 * \brief Container of commands into which the initial script is split.
91 * It also contains data coresponding to SMESH_Gen contents
93 static Handle(_pyGen) theGen;
95 static TCollection_AsciiString theEmptyString;
97 //#define DUMP_CONVERSION
99 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
100 #undef DUMP_CONVERSION
106 //================================================================================
108 * \brief Set of TCollection_AsciiString initialized by C array of C strings
110 //================================================================================
112 struct TStringSet: public set<TCollection_AsciiString>
115 * \brief Filling. The last string must be ""
117 void Insert(const char* names[]) {
118 for ( int i = 0; names[i][0] ; ++i )
119 insert( (char*) names[i] );
122 * \brief Check if a string is in
124 bool Contains(const TCollection_AsciiString& name ) {
125 return find( name ) != end();
129 //================================================================================
131 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
132 * Odd items of the C array are map keys, and even items are values
134 //================================================================================
136 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
139 * \brief Filling. The last string must be ""
141 void Insert(const char* names_values[]) {
142 for ( int i = 0; names_values[i][0] ; i += 2 )
143 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
146 * \brief Check if a string is in
148 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
149 map< _AString, _AString >::iterator it = find( name );
150 return it == end() ? "" : it->second;
154 //================================================================================
156 * \brief Returns a mesh by object
158 //================================================================================
160 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
164 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
165 return Handle(_pyMesh)::DownCast( obj );
166 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
167 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
168 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
169 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
171 return Handle(_pyMesh)();
174 //================================================================================
176 * \brief Check if objects used as args have been created by previous commands
178 //================================================================================
180 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
182 // either comment or erase a command including NotPublishedObjectName()
183 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
185 bool isResultPublished = false;
186 const int nbRes = cmd->GetNbResultValues();
187 for ( int i = 0; i < nbRes; i++ )
189 _pyID objID = cmd->GetResultValue( i+1 );
190 if ( cmd->IsStudyEntry( objID ))
191 isResultPublished = (! theGen->IsNotPublished( objID ));
192 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
194 if ( isResultPublished )
200 // check if an Object was created in the script
203 _pyID obj = cmd->GetObject();
204 if ( obj.Search( "print " ) == 1 )
205 return; // print statement
207 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
208 // remove an accessor method
209 obj = _pyCommand( obj ).GetObject();
211 const bool isMethodCall = cmd->IsMethodCall();
212 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
214 comment = "not created Object";
215 theGen->ObjectCreationRemoved( obj );
217 // check if a command has not created args
218 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
220 const _pyID& arg = cmd->GetArg( iArg );
221 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
223 list< _pyID > idList = cmd->GetStudyEntries( arg );
224 list< _pyID >::iterator id = idList.begin();
225 for ( ; id != idList.end(); ++id )
226 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
228 comment += *id + " has not been yet created";
231 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
232 // comment += arg + " has not been yet created";
234 // treat result objects
235 const _pyID& result = cmd->GetResultValue();
236 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
238 list< _pyID > idList = cmd->GetStudyEntries( result );
239 list< _pyID >::iterator id = idList.begin();
240 for ( ; id != idList.end(); ++id )
242 if ( comment.IsEmpty() )
243 presentObjects.insert( *id );
245 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
247 if ( idList.empty() && cmd->IsID( result ))
248 presentObjects.insert( result );
250 // comment the command
251 if ( !comment.IsEmpty() )
254 cmd->GetString() += " ### ";
255 cmd->GetString() += comment;
259 //================================================================================
261 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
263 //================================================================================
265 void fixFunctorType( TCollection_AsciiString& Type,
266 TCollection_AsciiString& Compare,
267 TCollection_AsciiString& UnaryOp,
268 TCollection_AsciiString& BinaryOp )
270 // The problem is that dumps of old studies created using filters becomes invalid
271 // when new items are inserted in the enum SMESH::FunctorType since values
272 // of this enum are dumped as integer values.
273 // This function corrects enum values of old studies given as args (Type,Compare,...)
274 // We can find out how to correct them by value of BinaryOp which can have only two
275 // values: FT_Undefined or FT_LogicalNOT.
276 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
277 // where PythonDump appeared
278 // v 3.0.0: FT_Undefined == 25
279 // v 3.1.0: FT_Undefined == 26, new items:
281 // v 4.1.2: FT_Undefined == 27, new items:
282 // - FT_BelongToGenSurface = 17
283 // v 5.1.1: FT_Undefined == 32, new items:
284 // - FT_FreeNodes = 10
285 // - FT_FreeFaces = 11
286 // - FT_LinearOrQuadratic = 23
287 // - FT_GroupColor = 24
288 // - FT_ElemGeomType = 25
289 // v 5.1.5: FT_Undefined == 33, new items:
290 // - FT_CoplanarFaces = 26
291 // v 6.2.0: FT_Undefined == 39, new items:
292 // - FT_MaxElementLength2D = 8
293 // - FT_MaxElementLength3D = 9
294 // - FT_BareBorderVolume = 25
295 // - FT_BareBorderFace = 26
296 // - FT_OverConstrainedVolume = 27
297 // - FT_OverConstrainedFace = 28
298 // v 6.5.0: FT_Undefined == 43, new items:
299 // - FT_EqualNodes = 14
300 // - FT_EqualEdges = 15
301 // - FT_EqualFaces = 16
302 // - FT_EqualVolumes = 17
303 // v 6.6.0: FT_Undefined == 44, new items:
304 // - FT_BallDiameter = 37
305 // v 6.7.1: FT_Undefined == 45, new items:
306 // - FT_EntityType = 36
307 // v 7.3.0: FT_Undefined == 46, new items:
308 // - FT_ConnectedElements = 39
310 // It's necessary to continue recording this history and to fill
311 // undef2newItems (see below) accordingly.
313 typedef map< int, vector< int > > TUndef2newItems;
314 static TUndef2newItems undef2newItems;
315 if ( undef2newItems.empty() )
317 undef2newItems[ 26 ].push_back( 7 );
318 undef2newItems[ 27 ].push_back( 17 );
319 { int items[] = { 10, 11, 23, 24, 25 };
320 undef2newItems[ 32 ].assign( items, items+5 ); }
321 undef2newItems[ 33 ].push_back( 26 );
322 { int items[] = { 8, 9, 25, 26, 27, 28 };
323 undef2newItems[ 39 ].assign( items, items+6 ); }
324 { int items[] = { 14, 15, 16, 17 };
325 undef2newItems[ 43 ].assign( items, items+4 ); }
326 undef2newItems[ 44 ].push_back( 37 );
327 undef2newItems[ 45 ].push_back( 36 );
328 undef2newItems[ 46 ].push_back( 39 );
330 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
333 int iType = Type.IntegerValue();
334 int iCompare = Compare.IntegerValue();
335 int iUnaryOp = UnaryOp.IntegerValue();
336 int iBinaryOp = BinaryOp.IntegerValue();
338 // find out integer value of FT_Undefined at the moment of dump
339 int oldUndefined = iBinaryOp;
340 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
343 // apply history to args
344 TUndef2newItems::const_iterator undef_items =
345 undef2newItems.upper_bound( oldUndefined );
346 if ( undef_items != undef2newItems.end() )
348 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
349 for ( ; undef_items != undef2newItems.end(); ++undef_items )
351 const vector< int > & addedItems = undef_items->second;
352 for ( size_t i = 0; i < addedItems.size(); ++i )
353 for ( int iArg = 0; iArg < 4; ++iArg )
355 int& arg = *pArg[iArg];
356 if ( arg >= addedItems[i] )
360 Type = TCollection_AsciiString( iType );
361 Compare = TCollection_AsciiString( iCompare );
362 UnaryOp = TCollection_AsciiString( iUnaryOp );
363 BinaryOp = TCollection_AsciiString( iBinaryOp );
367 //================================================================================
369 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
370 * arguments of a given command by a list "[x,y,z]" if the list is accesible
373 //================================================================================
375 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
377 static TStringSet methodsAcceptingList;
378 if ( methodsAcceptingList.empty() ) {
379 const char * methodNames[] = {
380 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
381 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
382 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
383 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
384 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
385 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
386 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
387 "Translate","TranslateMakeGroups","TranslateMakeMesh",
388 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
389 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
390 ,"" }; // <- mark of the end
391 methodsAcceptingList.Insert( methodNames );
393 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
395 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
397 const _AString & arg = theCommand->GetArg( i );
398 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
399 arg.Search( "SMESH.DirStruct" ) == 1 )
401 Handle(_pyCommand) workCmd = new _pyCommand( arg );
402 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
404 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
406 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
408 _AString newArg = "[ ";
409 newArg += ( workCmd->GetArg( 1 ) + ", " +
410 workCmd->GetArg( 2 ) + ", " +
411 workCmd->GetArg( 3 ) + " ]");
412 theCommand->SetArg( i, newArg );
418 //================================================================================
420 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
421 * a list "[id1,id2]" if the list is an accesible type of argument.
423 //================================================================================
425 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
427 static TStringSet methodsAcceptingList;
428 if ( methodsAcceptingList.empty() ) {
429 const char * methodNames[] = {
430 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
431 "ExportCGNS","ExportGMF",
432 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
433 "ScaleMakeGroups","Scale","ScaleMakeMesh",
434 "FindCoincidentNodesOnPartBut","DoubleElements"
435 ,"" }; // <- mark of the end
436 methodsAcceptingList.Insert( methodNames );
438 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
440 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
442 _pyCommand argCmd( theCommand->GetArg( i ));
443 if ( argCmd.GetMethod() == "GetIDSource" &&
444 argCmd.GetNbArgs() == 2 )
446 theCommand->SetArg( i, argCmd.GetArg( 1 ));
453 //================================================================================
455 * \brief Convert a python script using commands of smeshBuilder.py
456 * \param theScriptLines - Lines of the input script
457 * \param theEntry2AccessorMethod - returns method names to access to
458 * objects wrapped with python class
459 * \param theObjectNames - names of objects
460 * \param theRemovedObjIDs - entries of objects whose created commands were removed
461 * \param theHistoricalDump - true means to keep all commands, false means
462 * to exclude commands relating to objects removed from study
463 * \retval TCollection_AsciiString - Convertion result
465 //================================================================================
468 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
469 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
470 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
471 std::set< TCollection_AsciiString >& theRemovedObjIDs,
472 SALOMEDS::Study_ptr& theStudy,
473 const bool theToKeepAllCommands)
475 std::list< TCollection_AsciiString >::iterator lineIt;
476 // process notebook variables
478 SMESH_NoteBook aNoteBook;
480 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
481 aNoteBook.AddCommand( *lineIt );
483 theScriptLines.clear();
485 aNoteBook.ReplaceVariables();
487 aNoteBook.GetResultLines( theScriptLines );
490 // convert to smeshBuilder.py API
492 theGen = new _pyGen( theEntry2AccessorMethod,
496 theToKeepAllCommands );
498 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
499 theGen->AddCommand( *lineIt );
501 theScriptLines.clear();
505 #ifdef DUMP_CONVERSION
506 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
509 // clean commmands of removed objects depending on myIsPublished flag
510 theGen->ClearCommands();
512 // reorder commands after conversion
513 list< Handle(_pyCommand) >::iterator cmd;
516 orderChanges = false;
517 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
518 if ( (*cmd)->SetDependentCmdsAfter() )
520 } while ( orderChanges );
522 // concat commands back into a script
523 TCollection_AsciiString aPrevCmd;
524 set<_pyID> createdObjects;
525 createdObjects.insert( "smeshBuilder" );
526 createdObjects.insert( "smesh" );
527 createdObjects.insert( "theStudy" );
528 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
530 #ifdef DUMP_CONVERSION
531 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
533 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
534 CheckObjectPresence( *cmd, createdObjects );
535 if ( !(*cmd)->IsEmpty() ) {
536 aPrevCmd = (*cmd)->GetString();
537 theScriptLines.push_back( aPrevCmd );
546 //================================================================================
548 * \brief _pyGen constructor
550 //================================================================================
552 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
553 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
554 std::set< TCollection_AsciiString >& theRemovedObjIDs,
555 SALOMEDS::Study_ptr& theStudy,
556 const bool theToKeepAllCommands)
557 : _pyObject( new _pyCommand( "", 0 )),
559 myID2AccessorMethod( theEntry2AccessorMethod ),
560 myObjectNames( theObjectNames ),
561 myRemovedObjIDs( theRemovedObjIDs ),
563 myToKeepAllCommands( theToKeepAllCommands ),
564 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
565 myGeomIDNb(0), myGeomIDIndex(-1)
567 // make that GetID() to return TPythonDump::SMESHGenName()
568 GetCreationCmd()->Clear();
569 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
570 GetCreationCmd()->GetString() += "=";
572 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
573 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
577 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
578 if ( geomComp->_is_nil() ) return;
579 CORBA::String_var entry = geomComp->GetID();
582 // find a SMESH entry
584 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
585 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
586 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
589 // find 1st difference between smeshID and geomID
590 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
591 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
592 if ( geomID.Value( i ) != smeshID.Value( i ))
594 myGeomIDNb = geomID.Value( i );
600 //================================================================================
602 * \brief name of SMESH_Gen in smeshBuilder.py
604 //================================================================================
606 const char* _pyGen::AccessorMethod() const
608 return SMESH_2smeshpy::GenName();
611 //================================================================================
613 * \brief Convert a command using a specific converter
614 * \param theCommand - the command to convert
616 //================================================================================
618 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
620 // store theCommand in the sequence
621 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
623 Handle(_pyCommand) aCommand = myCommands.back();
624 #ifdef DUMP_CONVERSION
625 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
628 const _pyID& objID = aCommand->GetObject();
630 if ( objID.IsEmpty() )
633 // Prevent moving a command creating a sub-mesh to the end of the script
634 // if the sub-mesh is used in theCommand as argument
635 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
637 // PlaceSubmeshAfterItsCreation( aCommand );
640 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
641 StructToList( aCommand );
643 const TCollection_AsciiString& method = aCommand->GetMethod();
645 // not to erase _pySelfEraser's etc. used as args in some commands
647 #ifdef USE_STRING_FAMILY
648 std::list<_pyID> objIDs;
649 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
651 std::list<_pyID>::iterator objID = objIDs.begin();
652 for ( ; objID != objIDs.end(); ++objID )
654 Handle(_pyObject) obj = FindObject( *objID );
657 obj->AddArgCmd( aCommand );
658 //cout << objID << " found in " << theCommand << endl;
663 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
664 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
665 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
667 Handle(_pyObject) obj = FindObject( *id );
669 obj->AddArgCmd( aCommand );
674 // Find an object to process theCommand
677 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
679 this->Process( aCommand );
680 //addFilterUser( aCommand, theGen ); // protect filters from clearing
684 // SMESH_Mesh method?
685 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
686 if ( id_mesh != myMeshes.end() )
688 //id_mesh->second->AddProcessedCmd( aCommand );
690 // check for mesh editor object
691 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
692 _pyID editorID = aCommand->GetResultValue();
693 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
694 myMeshEditors.insert( make_pair( editorID, editor ));
697 // check for SubMesh objects
698 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
699 _pyID subMeshID = aCommand->GetResultValue();
700 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
701 AddObject( subMesh );
704 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
705 GetIDSourceToList( aCommand );
707 //addFilterUser( aCommand, theGen ); // protect filters from clearing
709 id_mesh->second->Process( aCommand );
710 id_mesh->second->AddProcessedCmd( aCommand );
714 // SMESH_MeshEditor method?
715 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
716 if ( id_editor != myMeshEditors.end() )
718 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
719 GetIDSourceToList( aCommand );
721 //addFilterUser( aCommand, theGen ); // protect filters from clearing
723 // some commands of SMESH_MeshEditor create meshes and groups
724 _pyID meshID, groups;
725 if ( method.Search("MakeMesh") != -1 )
726 meshID = aCommand->GetResultValue();
727 else if ( method == "MakeBoundaryMesh")
728 meshID = aCommand->GetResultValue(1);
729 else if ( method == "MakeBoundaryElements")
730 meshID = aCommand->GetResultValue(2);
732 if ( method.Search("MakeGroups") != -1 ||
733 method == "ExtrusionAlongPathX" ||
734 method == "ExtrusionAlongPathObjX" ||
735 method == "DoubleNodeGroupNew" ||
736 method == "DoubleNodeGroupsNew" ||
737 method == "DoubleNodeElemGroupNew" ||
738 method == "DoubleNodeElemGroupsNew"||
739 method == "DoubleNodeElemGroup2New"||
740 method == "DoubleNodeElemGroups2New"
742 groups = aCommand->GetResultValue();
743 else if ( method == "MakeBoundaryMesh" )
744 groups = aCommand->GetResultValue(2);
745 else if ( method == "MakeBoundaryElements")
746 groups = aCommand->GetResultValue(3);
747 else if ( method == "Create0DElementsOnAllNodes" &&
748 aCommand->GetArg(2).Length() > 2 ) // group name != ''
749 groups = aCommand->GetResultValue();
751 id_editor->second->Process( aCommand );
752 id_editor->second->AddProcessedCmd( aCommand );
755 if ( !meshID.IsEmpty() &&
756 !myMeshes.count( meshID ) &&
757 aCommand->IsStudyEntry( meshID ))
759 _AString processedCommand = aCommand->GetString();
760 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
761 CheckObjectIsReCreated( mesh );
762 myMeshes.insert( make_pair( meshID, mesh ));
764 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
767 if ( !groups.IsEmpty() )
769 if ( !aCommand->IsStudyEntry( meshID ))
770 meshID = id_editor->second->GetMesh();
771 Handle(_pyMesh) mesh = myMeshes[ meshID ];
773 list< _pyID > idList = aCommand->GetStudyEntries( groups );
774 list< _pyID >::iterator grID = idList.begin();
775 for ( ; grID != idList.end(); ++grID )
776 if ( !myObjects.count( *grID ))
778 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
780 if ( !mesh.IsNull() ) mesh->AddGroup( group );
784 } // SMESH_MeshEditor methods
786 // SMESH_Hypothesis method?
787 Handle(_pyHypothesis) hyp = FindHyp( objID );
788 if ( !hyp.IsNull() && !hyp->IsAlgo() )
790 hyp->Process( aCommand );
791 hyp->AddProcessedCmd( aCommand );
795 // aFilterManager.CreateFilter() ?
796 if ( aCommand->GetMethod() == "CreateFilter" )
798 // Set a more human readable name to a filter
799 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
800 _pyID newID, filterID = aCommand->GetResultValue();
801 int pos = filterID.Search( "0x" );
803 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
805 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
808 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
809 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
811 // create _pySelfEraser for functors
812 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
813 functor->IgnoreOwnCalls(); // to erase if not used as an argument
814 AddObject( functor );
817 // other object method?
818 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
819 if ( id_obj != myObjects.end() ) {
820 id_obj->second->Process( aCommand );
821 id_obj->second->AddProcessedCmd( aCommand );
825 // Add access to a wrapped mesh
826 AddMeshAccessorMethod( aCommand );
828 // Add access to a wrapped algorithm
829 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
831 // PAL12227. PythonDump was not updated at proper time; result is
832 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
833 // TypeError: __init__() takes exactly 11 arguments (10 given)
834 const char wrongCommand[] = "SMESH.Filter.Criterion(";
835 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
837 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
838 // there must be 10 arguments, 5-th arg ThresholdID is missing,
839 const int wrongNbArgs = 9, missingArg = 5;
840 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
842 for ( int i = wrongNbArgs; i > missingArg; --i )
843 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
844 tmpCmd.SetArg( missingArg, "''");
845 aCommand->GetString().Trunc( beg - 1 );
846 aCommand->GetString() += tmpCmd.GetString();
849 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
851 // instead of "SMESH.Filter.Criterion(
852 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
853 // 1 2 3 4 5 6 7 8 9 10
854 // in order to avoid the problem of type mismatch of long and FunctorType
855 const TCollection_AsciiString
856 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
857 TCollection_AsciiString
858 Type = aCommand->GetArg(1), // long
859 Compare = aCommand->GetArg(2), // long
860 Threshold = aCommand->GetArg(3), // double
861 ThresholdStr = aCommand->GetArg(4), // string
862 ThresholdID = aCommand->GetArg(5), // string
863 UnaryOp = aCommand->GetArg(6), // long
864 BinaryOp = aCommand->GetArg(7), // long
865 Tolerance = aCommand->GetArg(8), // double
866 TypeOfElement = aCommand->GetArg(9), // ElementType
867 Precision = aCommand->GetArg(10); // long
868 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
869 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
870 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
871 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
872 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
874 if ( Compare == "SMESH.FT_EqualTo" )
877 aCommand->RemoveArgs();
878 aCommand->SetObject( SMESH_2smeshpy::GenName() );
879 aCommand->SetMethod( "GetCriterion" );
881 aCommand->SetArg( 1, TypeOfElement );
882 aCommand->SetArg( 2, Type );
883 aCommand->SetArg( 3, Compare );
885 if ( Threshold.IsIntegerValue() )
887 int iGeom = Threshold.IntegerValue();
888 if ( Type == "SMESH.FT_ElemGeomType" )
890 // set SMESH.GeometryType instead of a numerical Threshold
891 const int nbTypes = SMESH::Geom_BALL+1;
892 const char* types[nbTypes] = {
893 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
894 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
895 "Geom_POLYHEDRA", "Geom_BALL" };
896 if ( -1 < iGeom && iGeom < nbTypes )
897 Threshold = SMESH + types[ iGeom ];
899 if (Type == "SMESH.FT_EntityType")
901 // set SMESH.EntityType instead of a numerical Threshold
902 const int nbTypes = SMESH::Entity_Ball+1;
903 const char* types[nbTypes] = {
904 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
905 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
906 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
907 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
908 "Entity_Pyramid", "Entity_Quad_Pyramid",
909 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
910 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
911 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
912 if ( -1 < iGeom && iGeom < nbTypes )
913 Threshold = SMESH + types[ iGeom ];
916 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
917 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
918 else if ( ThresholdStr.Length() != 2 )
919 aCommand->SetArg( 4, ThresholdStr );
920 else if ( ThresholdID.Length() != 2 )
921 aCommand->SetArg( 4, ThresholdID );
923 aCommand->SetArg( 4, Threshold );
924 // find the last not default arg
926 if ( Tolerance == dfltTol ) {
928 if ( BinaryOp == dfltFunctor ) {
930 if ( UnaryOp == dfltFunctor )
934 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
935 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
936 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
937 if ( Precision != dfltPreci )
939 TCollection_AsciiString crit = aCommand->GetResultValue();
940 aCommand->GetString() += "; ";
941 aCommand->GetString() += crit + ".Precision = " + Precision;
947 //================================================================================
949 * \brief Convert the command or remember it for later conversion
950 * \param theCommand - The python command calling a method of SMESH_Gen
952 //================================================================================
954 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
956 // there are methods to convert:
957 // CreateMesh( shape )
958 // Concatenate( [mesh1, ...], ... )
959 // CreateHypothesis( theHypType, theLibName )
960 // Compute( mesh, geom )
961 // Evaluate( mesh, geom )
963 TCollection_AsciiString method = theCommand->GetMethod();
965 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
967 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
971 if ( method == "CreateMeshesFromUNV" ||
972 method == "CreateMeshesFromSTL" ||
973 method == "CopyMesh" ) // command result is a mesh
975 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
979 if( method == "CreateMeshesFromMED" ||
980 method == "CreateMeshesFromSAUV"||
981 method == "CreateMeshesFromCGNS" ||
982 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
984 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
985 std::list< _pyID >::iterator meshID = meshIDs.begin();
986 for ( ; meshID != meshIDs.end(); ++meshID )
988 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
991 if ( method == "CreateMeshesFromGMF" )
993 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
994 // CreateMeshesFromGMF( theFileName )
995 _AString file = theCommand->GetArg(1);
996 theCommand->RemoveArgs();
997 theCommand->SetArg( 1, file );
1001 // CreateHypothesis()
1002 if ( method == "CreateHypothesis" )
1004 // issue 199929, remove standard library name (default parameter)
1005 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1006 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1007 // keep the first argument
1008 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1009 theCommand->RemoveArgs();
1010 theCommand->SetArg( 1, arg );
1013 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1014 CheckObjectIsReCreated( hyp );
1015 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1020 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1021 if ( method == "Compute" )
1023 const _pyID& meshID = theCommand->GetArg( 1 );
1024 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1025 if ( id_mesh != myMeshes.end() ) {
1026 theCommand->SetObject( meshID );
1027 theCommand->RemoveArgs();
1028 id_mesh->second->Process( theCommand );
1029 id_mesh->second->AddProcessedCmd( theCommand );
1034 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1035 if ( method == "Evaluate" )
1037 const _pyID& meshID = theCommand->GetArg( 1 );
1038 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1039 if ( id_mesh != myMeshes.end() ) {
1040 theCommand->SetObject( meshID );
1041 _pyID geom = theCommand->GetArg( 2 );
1042 theCommand->RemoveArgs();
1043 theCommand->SetArg( 1, geom );
1044 id_mesh->second->AddProcessedCmd( theCommand );
1049 // objects erasing creation command if no more its commands invoked:
1050 // SMESH_Pattern, FilterManager
1051 if ( method == "GetPattern" ||
1052 method == "CreateFilterManager" ||
1053 method == "CreateMeasurements" )
1055 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1056 if ( !AddObject( obj ) )
1057 theCommand->Clear(); // already created
1059 // Concatenate( [mesh1, ...], ... )
1060 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1062 if ( method == "ConcatenateWithGroups" ) {
1063 theCommand->SetMethod( "Concatenate" );
1064 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1066 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1068 AddMeshAccessorMethod( theCommand );
1070 else if ( method == "SetName" ) // SetName(obj,name)
1072 // store theCommand as one of object commands to erase it along with the object
1073 const _pyID& objID = theCommand->GetArg( 1 );
1074 Handle(_pyObject) obj = FindObject( objID );
1075 if ( !obj.IsNull() )
1076 obj->AddProcessedCmd( theCommand );
1079 // Replace name of SMESH_Gen
1081 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1082 static TStringSet smeshpyMethods;
1083 if ( smeshpyMethods.empty() ) {
1084 const char * names[] =
1085 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1086 "GetPattern","GetSubShapesId",
1087 "" }; // <- mark of array end
1088 smeshpyMethods.Insert( names );
1090 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1091 // smeshgen.Method() --> smesh.Method()
1092 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1094 // smeshgen.Method() --> smesh.Method()
1095 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1098 //================================================================================
1100 * \brief Convert the remembered commands
1102 //================================================================================
1104 void _pyGen::Flush()
1106 // create an empty command
1107 myLastCommand = new _pyCommand();
1109 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1110 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1111 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1113 if ( IsToKeepAllCommands() ) // historical dump
1115 // set myIsPublished = true to all objects
1116 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1117 id_mesh->second->SetRemovedFromStudy( false );
1118 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1119 id_hyp->second->SetRemovedFromStudy( false );
1120 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1121 id_obj->second->SetRemovedFromStudy( false );
1125 // let hypotheses find referred objects in order to prevent clearing
1126 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1127 list< Handle(_pyMesh) > fatherMeshes;
1128 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1129 if ( !id_hyp->second.IsNull() )
1130 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1132 // set myIsPublished = false to all objects depending on
1133 // meshes built on a removed geometry
1134 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1135 if ( id_mesh->second->IsNotGeomPublished() )
1136 id_mesh->second->SetRemovedFromStudy( true );
1139 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1140 if ( ! id_mesh->second.IsNull() )
1141 id_mesh->second->Flush();
1144 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1145 if ( !id_hyp->second.IsNull() ) {
1146 id_hyp->second->Flush();
1147 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1148 if ( !id_hyp->second->IsWrapped() )
1149 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1152 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1153 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1154 for ( ; robj != myOrderedObjects.rend(); ++robj )
1155 if ( ! robj->IsNull() )
1157 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1158 for ( ; obj != myOrderedObjects.end(); ++obj )
1159 if ( ! obj->IsNull() )
1162 myLastCommand->SetOrderNb( ++myNbCommands );
1163 myCommands.push_back( myLastCommand );
1166 //================================================================================
1168 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1169 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1171 //================================================================================
1173 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1175 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1176 // for ( ; id_obj != myObjects.end(); ++id_obj )
1178 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1179 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1181 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1182 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1184 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1185 // list< _pyID >::iterator id = idList.begin();
1186 // for ( ; id != idList.end(); ++id )
1187 // if ( id_obj->first == *id )
1188 // // _pySubMesh::Process() does what we need
1189 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1194 //================================================================================
1196 * \brief Clean commmands of removed objects depending on myIsPublished flag
1198 //================================================================================
1200 void _pyGen::ClearCommands()
1202 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1203 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1204 id_mesh->second->ClearCommands();
1206 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1207 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1208 if ( !id_hyp->second.IsNull() )
1209 id_hyp->second->ClearCommands();
1211 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1212 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1213 for ( ; robj != myOrderedObjects.rend(); ++robj )
1214 if ( ! robj->IsNull() )
1215 (*robj)->ClearCommands();
1216 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1217 for ( ; obj != myOrderedObjects.end(); ++obj )
1218 if ( ! obj->IsNull() )
1219 (*obj)->ClearCommands();
1222 //================================================================================
1224 * \brief Release mutual handles of objects
1226 //================================================================================
1230 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1231 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1232 id_mesh->second->Free();
1235 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1236 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1237 id_ed->second->Free();
1238 myMeshEditors.clear();
1240 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1241 for ( ; id_obj != myObjects.end(); ++id_obj )
1242 id_obj->second->Free();
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->Free();
1251 myFile2ExportedMesh.clear();
1253 //myKeepAgrCmdsIDs.Print();
1256 //================================================================================
1258 * \brief Add access method to mesh that is an argument
1259 * \param theCmd - command to add access method
1260 * \retval bool - true if added
1262 //================================================================================
1264 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1267 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1268 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1269 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1275 //================================================================================
1277 * \brief Add access method to algo that is an object or an argument
1278 * \param theCmd - command to add access method
1279 * \retval bool - true if added
1281 //================================================================================
1283 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1286 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1287 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1288 if ( !id_hyp->second.IsNull() &&
1289 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1290 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1291 id_hyp->second->AccessorMethod() ))
1297 //================================================================================
1299 * \brief Find hypothesis by ID (entry)
1300 * \param theHypID - The hypothesis ID
1301 * \retval Handle(_pyHypothesis) - The found hypothesis
1303 //================================================================================
1305 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1307 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1308 if ( id_hyp != myHypos.end() &&
1309 !id_hyp->second.IsNull() &&
1310 theHypID == id_hyp->second->GetID() )
1311 return id_hyp->second;
1312 return Handle(_pyHypothesis)();
1315 //================================================================================
1317 * \brief Find algorithm able to create a hypothesis
1318 * \param theGeom - The shape ID the algorithm was created on
1319 * \param theMesh - The mesh ID that created the algorithm
1320 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1321 * \retval Handle(_pyHypothesis) - The found algo
1323 //================================================================================
1325 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1326 const Handle(_pyHypothesis)& theHypothesis )
1328 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1329 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1330 if ( !id_hyp->second.IsNull() &&
1331 id_hyp->second->IsAlgo() &&
1332 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1333 id_hyp->second->GetGeom() == theGeom &&
1334 id_hyp->second->GetMesh() == theMesh )
1335 return id_hyp->second;
1336 return Handle(_pyHypothesis)();
1339 //================================================================================
1341 * \brief Find subMesh by ID (entry)
1342 * \param theSubMeshID - The subMesh ID
1343 * \retval Handle(_pySubMesh) - The found subMesh
1345 //================================================================================
1347 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1349 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1350 if ( id_subMesh != myObjects.end() )
1351 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1352 return Handle(_pySubMesh)();
1356 //================================================================================
1358 * \brief Change order of commands in the script
1359 * \param theCmd1 - One command
1360 * \param theCmd2 - Another command
1362 //================================================================================
1364 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1366 list< Handle(_pyCommand) >::iterator pos1, pos2;
1367 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1368 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1369 myCommands.insert( pos1, theCmd2 );
1370 myCommands.insert( pos2, theCmd1 );
1371 myCommands.erase( pos1 );
1372 myCommands.erase( pos2 );
1374 int nb1 = theCmd1->GetOrderNb();
1375 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1376 theCmd2->SetOrderNb( nb1 );
1377 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1378 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1381 //================================================================================
1383 * \brief Set one command after the other
1384 * \param theCmd - Command to move
1385 * \param theAfterCmd - Command ater which to insert the first one
1387 //================================================================================
1389 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1391 setNeighbourCommand( theCmd, theAfterCmd, true );
1394 //================================================================================
1396 * \brief Set one command before the other
1397 * \param theCmd - Command to move
1398 * \param theBeforeCmd - Command before which to insert the first one
1400 //================================================================================
1402 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1404 setNeighbourCommand( theCmd, theBeforeCmd, false );
1407 //================================================================================
1409 * \brief Set one command before or after the other
1410 * \param theCmd - Command to move
1411 * \param theOtherCmd - Command ater or before which to insert the first one
1413 //================================================================================
1415 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1416 Handle(_pyCommand)& theOtherCmd,
1417 const bool theIsAfter )
1419 list< Handle(_pyCommand) >::iterator pos;
1420 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1421 myCommands.erase( pos );
1422 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1423 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1426 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1427 (*pos)->SetOrderNb( i++ );
1430 //================================================================================
1432 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1434 //================================================================================
1436 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1438 // No more needed after adding _pyObject::myArgCommands
1440 // const char filterPrefix[] = "aFilter0x";
1441 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1444 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1446 // const _AString & arg = theCommand->GetArg( i );
1447 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1448 // if ( arg.Search( filterPrefix ) != 1 )
1451 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1452 // if ( !filter.IsNull() )
1454 // filter->AddUser( user );
1455 // if ( !filter->GetNewID().IsEmpty() )
1456 // theCommand->SetArg( i, filter->GetNewID() );
1461 //================================================================================
1463 * \brief Set command be last in list of commands
1464 * \param theCmd - Command to be last
1466 //================================================================================
1468 Handle(_pyCommand)& _pyGen::GetLastCommand()
1470 return myLastCommand;
1473 //================================================================================
1475 * \brief Set method to access to object wrapped with python class
1476 * \param theID - The wrapped object entry
1477 * \param theMethod - The accessor method
1479 //================================================================================
1481 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1483 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1486 //================================================================================
1488 * \brief Generated new ID for object and assign with existing name
1489 * \param theID - ID of existing object
1491 //================================================================================
1493 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1498 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1500 while ( myObjectNames.IsBound( aNewID ) );
1502 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1503 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1504 : _pyID( "A" ) + aNewID );
1508 //================================================================================
1510 * \brief Stores theObj in myObjects
1512 //================================================================================
1514 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1516 if ( theObj.IsNull() ) return false;
1518 CheckObjectIsReCreated( theObj );
1522 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1523 add = myMeshes.insert( make_pair( theObj->GetID(),
1524 Handle(_pyMesh)::DownCast( theObj ))).second;
1526 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1527 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1528 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1531 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1532 if ( add ) myOrderedObjects.push_back( theObj );
1537 //================================================================================
1539 * \brief Erases an existing object with the same ID. This method should be called
1540 * before storing theObj in _pyGen
1542 //================================================================================
1544 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1546 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1549 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1550 Handle(_pyObject) existing =
1551 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1552 if ( !existing.IsNull() && existing != theObj )
1554 existing->SetRemovedFromStudy( true );
1555 existing->ClearCommands();
1558 if ( myHypos.count( theObj->GetID() ))
1559 myHypos.erase( theObj->GetID() );
1561 else if ( myMeshes.count( theObj->GetID() ))
1563 myMeshes.erase( theObj->GetID() );
1565 else if ( myObjects.count( theObj->GetID() ))
1567 myObjects.erase( theObj->GetID() );
1572 //================================================================================
1574 * \brief Re-register an object with other ID to make it Process() commands of
1575 * other object having this ID
1577 //================================================================================
1579 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1581 if ( theObj.IsNull() ) return;
1583 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1584 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1586 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1587 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1590 myObjects.insert( make_pair( theID, theObj ));
1593 //================================================================================
1595 * \brief Finds a _pyObject by ID
1597 //================================================================================
1599 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1602 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1603 if ( id_obj != myObjects.end() )
1604 return id_obj->second;
1607 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1608 if ( id_obj != myMeshes.end() )
1609 return id_obj->second;
1612 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1613 // if ( id_obj != myMeshEditors.end() )
1614 // return id_obj->second;
1616 return Handle(_pyObject)();
1619 //================================================================================
1621 * \brief Check if a study entry is under GEOM component
1623 //================================================================================
1625 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1629 return ( myGeomIDIndex <= theObjID.Length() &&
1630 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1631 _pyCommand::IsStudyEntry( theObjID ));
1636 //================================================================================
1638 * \brief Returns true if an object is not present in a study
1640 //================================================================================
1642 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1644 if ( theObjID.IsEmpty() ) return false;
1646 if ( myObjectNames.IsBound( theObjID ))
1647 return false; // SMESH object is in study
1649 // either the SMESH object is not in study or it is a GEOM object
1650 if ( IsGeomObject( theObjID ))
1652 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1653 if ( so->_is_nil() ) return true;
1654 CORBA::Object_var obj = so->GetObject();
1655 return CORBA::is_nil( obj );
1657 return true; // SMESH object not in study
1660 //================================================================================
1662 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1663 * this object is not dumped
1664 * \param [in] theObjID - entry of the object whose creation command was eliminated
1666 //================================================================================
1668 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1670 myRemovedObjIDs.insert( theObjID );
1673 //================================================================================
1675 * \brief Return reader of hypotheses of plugins
1677 //================================================================================
1679 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1681 if (myHypReader.IsNull() )
1682 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1688 //================================================================================
1690 * \brief Mesh created by SMESH_Gen
1692 //================================================================================
1694 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1695 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1697 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1698 myGeomNotInStudy = true;
1700 // convert my creation command --> smeshpy.Mesh(...)
1701 Handle(_pyCommand) creationCmd = GetCreationCmd();
1702 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1703 creationCmd->SetMethod( "Mesh" );
1704 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1707 //================================================================================
1709 * \brief Mesh created by SMESH_MeshEditor
1711 //================================================================================
1713 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1714 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1716 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1718 // this mesh depends on the exported mesh
1719 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1720 if ( !file.IsEmpty() )
1722 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1723 addFatherMesh( exportData.myMesh );
1724 if ( !exportData.myLastComputeCmd.IsNull() )
1726 // restore cleared Compute() by which the exported mesh was generated
1727 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1728 // protect that Compute() cmd from clearing
1729 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1730 exportData.myMesh->myLastComputeCmd.Nullify();
1734 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1736 // this mesh depends on concatenated meshes
1737 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1738 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1739 list< _pyID >::iterator meshID = idList.begin();
1740 for ( ; meshID != idList.end(); ++meshID )
1741 addFatherMesh( *meshID );
1743 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1745 // this mesh depends on a copied IdSource
1746 const _pyID& objID = theCreationCmd->GetArg( 1 );
1747 addFatherMesh( objID );
1749 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1750 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1751 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1753 // this mesh depends on a source mesh
1754 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1755 const _pyID& meshID = theCreationCmd->GetObject();
1756 addFatherMesh( meshID );
1759 // convert my creation command
1760 Handle(_pyCommand) creationCmd = GetCreationCmd();
1761 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1762 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1765 //================================================================================
1767 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1768 * \param theCommand - Engine method called for this mesh
1770 //================================================================================
1772 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1774 // some methods of SMESH_Mesh interface needs special conversion
1775 // to methods of Mesh python class
1777 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1778 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1779 // 2. AddHypothesis(geom, hyp)
1780 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1781 // 3. CreateGroupFromGEOM(type, name, grp)
1782 // --> in Mesh.Group(grp, name="")
1783 // 4. ExportToMED(f, auto_groups, version)
1784 // --> in Mesh.ExportMED( f, auto_groups, version )
1787 const TCollection_AsciiString& method = theCommand->GetMethod();
1788 // ----------------------------------------------------------------------
1789 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1791 if ( !theGen->IsToKeepAllCommands() ) // !historical
1793 list< Handle(_pyHypothesis) >::iterator hyp;
1794 if ( !myLastComputeCmd.IsNull() )
1796 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1797 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1799 myLastComputeCmd->Clear();
1801 myLastComputeCmd = theCommand;
1803 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1804 (*hyp)->MeshComputed( myLastComputeCmd );
1808 // ----------------------------------------------------------------------
1809 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1811 if ( !theGen->IsToKeepAllCommands() ) // !historical
1814 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1815 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1816 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1818 if ( !myLastComputeCmd.IsNull() )
1820 list< Handle(_pyHypothesis) >::iterator hyp;
1821 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1822 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1824 myLastComputeCmd->Clear();
1827 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1828 for ( ; e != myEditors.end(); ++e )
1830 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1831 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1832 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1833 if ( !(*cmd)->IsEmpty() )
1835 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1839 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1842 // ----------------------------------------------------------------------
1843 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1844 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1845 if ( !subMesh.IsNull() ) {
1846 subMesh->SetCreator( this );
1847 mySubmeshes.push_back( subMesh );
1850 // ----------------------------------------------------------------------
1851 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1852 myAddHypCmds.push_back( theCommand );
1854 const _pyID& hypID = theCommand->GetArg( 2 );
1855 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1856 if ( !hyp.IsNull() ) {
1857 myHypos.push_back( hyp );
1858 if ( hyp->GetMesh().IsEmpty() )
1859 hyp->SetMesh( this->GetID() );
1862 // ----------------------------------------------------------------------
1863 else if ( method == "CreateGroup" ||
1864 method == "CreateGroupFromGEOM" ||
1865 method == "CreateGroupFromFilter" )
1867 Handle(_pyGroup) group = new _pyGroup( theCommand );
1868 myGroups.push_back( group );
1869 theGen->AddObject( group );
1871 // ----------------------------------------------------------------------
1872 // update list of groups
1873 else if ( method == "GetGroups" )
1875 bool allGroupsRemoved = true;
1876 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1877 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1878 list< _pyID >::iterator grID = idList.begin();
1879 const int nbGroupsBefore = myGroups.size();
1880 Handle(_pyObject) obj;
1881 for ( ; grID != idList.end(); ++grID )
1883 obj = theGen->FindObject( *grID );
1886 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1887 theGen->AddObject( group );
1888 myGroups.push_back( group );
1891 if ( !obj->CanClear() )
1892 allGroupsRemoved = false;
1894 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1895 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1897 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1899 // check if the preceding command is Compute();
1900 // if GetGroups() is just after Compute(), this can mean that the groups
1901 // were created by some algorithm and hence Compute() should not be discarded
1902 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1903 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1904 while ( (*cmd)->GetMethod() == "GetGroups" )
1906 if ( myLastComputeCmd == (*cmd))
1907 // protect last Compute() from clearing by the next Compute()
1908 myLastComputeCmd.Nullify();
1911 // ----------------------------------------------------------------------
1912 // notify a group about full removal
1913 else if ( method == "RemoveGroupWithContents" ||
1914 method == "RemoveGroup")
1916 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1917 const _pyID groupID = theCommand->GetArg( 1 );
1918 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1919 if ( !grp.IsNull() )
1921 if ( method == "RemoveGroupWithContents" )
1922 grp->RemovedWithContents();
1923 // to clear RemoveGroup() if the group creation is cleared
1924 grp->AddProcessedCmd( theCommand );
1928 // ----------------------------------------------------------------------
1929 else if ( theCommand->MethodStartsFrom( "Export" ))
1931 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1932 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1934 theCommand->SetMethod( "ExportMED" );
1935 if ( theCommand->GetNbArgs() == 5 )
1937 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1938 _AString autoDimension = theCommand->GetArg( 5 );
1939 theCommand->SetArg( 5, "None" );
1940 theCommand->SetArg( 6, autoDimension );
1943 else if ( method == "ExportCGNS" )
1944 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1945 _pyID partID = theCommand->GetArg( 1 );
1946 int nbArgs = theCommand->GetNbArgs();
1947 for ( int i = 2; i <= nbArgs; ++i )
1948 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1949 theCommand->SetArg( nbArgs, partID );
1951 else if ( method == "ExportGMF" )
1952 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1953 _pyID partID = theCommand->GetArg( 1 );
1954 _AString file = theCommand->GetArg( 2 );
1955 theCommand->RemoveArgs();
1956 theCommand->SetArg( 1, file );
1957 theCommand->SetArg( 2, partID );
1959 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1960 { // ExportPartTo*(part, ...) -> Export*(..., part)
1962 // remove "PartTo" from the method
1963 TCollection_AsciiString newMethod = method;
1964 newMethod.Remove( 7, 6 );
1965 theCommand->SetMethod( newMethod );
1966 // make the 1st arg be the last one (or last but one for ExportMED())
1967 _pyID partID = theCommand->GetArg( 1 );
1968 int nbArgs = theCommand->GetNbArgs() - (newMethod == "ExportMED");
1969 for ( int i = 2; i <= nbArgs; ++i )
1970 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1971 theCommand->SetArg( nbArgs, partID );
1973 // remember file name
1974 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1975 ExportedMeshData( this, myLastComputeCmd ));
1977 // ----------------------------------------------------------------------
1978 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1980 _pyID hypID = theCommand->GetArg( 2 );
1981 _pyID geomID = theCommand->GetArg( 1 );
1982 bool isLocal = ( geomID != GetGeom() );
1984 // check if this mesh still has corresponding addition command
1985 Handle(_pyCommand) addCmd;
1986 list< Handle(_pyCommand) >::iterator cmd;
1987 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1988 for ( int i = 0; i < 2; ++i )
1990 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1991 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1993 bool sameHyp = true;
1994 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1995 sameHyp = false; // other hyp
1996 if ( (*cmd)->GetNbArgs() == 2 &&
1997 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1998 sameHyp = false; // other geom
1999 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2000 sameHyp = false; // other geom
2004 cmd = addHypCmds.erase( cmd );
2005 if ( !theGen->IsToKeepAllCommands() && CanClear() ) {
2007 theCommand->Clear();
2016 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2017 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2018 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2019 _pyID geom = theCommand->GetArg( 1 );
2020 theCommand->RemoveArgs();
2021 theCommand->SetArg( 1, hypID );
2022 if ( geom != GetGeom() )
2023 theCommand->SetArg( 2, geom );
2025 // remove hyp from myHypos
2026 myHypos.remove( hyp );
2028 // check for SubMesh order commands
2029 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2031 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2032 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2033 // commands are moved at the end of the script
2034 TCollection_AsciiString subIDs =
2035 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2036 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2037 list< _pyID >::iterator subID = idList.begin();
2038 for ( ; subID != idList.end(); ++subID )
2040 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2041 if ( !subMesh.IsNull() )
2042 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2045 // add accessor method if necessary
2048 if ( NeedMeshAccess( theCommand ))
2049 // apply theCommand to the mesh wrapped by smeshpy mesh
2050 AddMeshAccess( theCommand );
2054 //================================================================================
2056 * \brief Return True if addition of accesor method is needed
2058 //================================================================================
2060 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2062 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2063 // so no conversion is needed for them at all:
2064 static TStringSet sameMethods;
2065 if ( sameMethods.empty() ) {
2066 const char * names[] =
2067 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2068 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
2069 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2070 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2071 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2072 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2073 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2074 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2075 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2076 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2077 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2078 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2079 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2080 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2081 ,"" }; // <- mark of end
2082 sameMethods.Insert( names );
2085 return !sameMethods.Contains( theCommand->GetMethod() );
2088 //================================================================================
2090 * \brief Convert creation and addition of all algos and hypos
2092 //================================================================================
2094 void _pyMesh::Flush()
2097 // get the meshes this mesh depends on via hypotheses
2098 list< Handle(_pyMesh) > fatherMeshes;
2099 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2100 for ( ; hyp != myHypos.end(); ++hyp )
2101 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2102 myGeomNotInStudy = true;
2104 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2105 for ( ; m != fatherMeshes.end(); ++m )
2106 addFatherMesh( *m );
2107 // if ( removedGeom )
2108 // SetRemovedFromStudy(); // as reffered geometry not in study
2110 if ( myGeomNotInStudy )
2113 list < Handle(_pyCommand) >::iterator cmd;
2115 // try to convert algo addition like this:
2116 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2117 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2119 Handle(_pyCommand) addCmd = *cmd;
2121 _pyID algoID = addCmd->GetArg( 2 );
2122 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2123 if ( algo.IsNull() || !algo->IsAlgo() )
2126 // check and create new algorithm instance if it is already wrapped
2127 if ( algo->IsWrapped() ) {
2128 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2129 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2130 TCollection_AsciiString( " = " ) + theGen->GetID() +
2131 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2132 TCollection_AsciiString( "\" )" );
2134 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2135 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2136 if ( !newAlgo.IsNull() ) {
2137 newAlgo->Assign( algo, this->GetID() );
2138 newAlgo->SetCreationCmd( newCmd );
2140 // set algorithm creation
2141 theGen->SetCommandBefore( newCmd, addCmd );
2142 myHypos.push_back( newAlgo );
2143 if ( !myLastComputeCmd.IsNull() &&
2144 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2145 newAlgo->MeshComputed( myLastComputeCmd );
2150 _pyID geom = addCmd->GetArg( 1 );
2151 bool isLocalAlgo = ( geom != GetGeom() );
2154 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2156 // wrapped algo is created after mesh creation
2157 GetCreationCmd()->AddDependantCmd( addCmd );
2159 if ( isLocalAlgo ) {
2160 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2161 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2162 TCollection_AsciiString( "geom=" ) + geom );
2163 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2164 list < Handle(_pySubMesh) >::iterator smIt;
2165 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2166 Handle(_pySubMesh) subMesh = *smIt;
2167 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2168 if ( geom == subCmd->GetArg( 1 )) {
2169 subCmd->SetObject( algo->GetID() );
2170 subCmd->RemoveArgs();
2171 subMesh->SetCreator( algo );
2176 else // KO - ALGO was already created
2178 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2179 addCmd->RemoveArgs();
2180 addCmd->SetArg( 1, algoID );
2182 addCmd->SetArg( 2, geom );
2183 myNotConvertedAddHypCmds.push_back( addCmd );
2187 // try to convert hypo addition like this:
2188 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2189 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2191 Handle(_pyCommand) addCmd = *cmd;
2192 _pyID hypID = addCmd->GetArg( 2 );
2193 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2194 if ( hyp.IsNull() || hyp->IsAlgo() )
2196 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2198 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2199 _pyID geom = addCmd->GetArg( 1 );
2200 addCmd->RemoveArgs();
2201 addCmd->SetArg( 1, hypID );
2202 if ( geom != GetGeom() )
2203 addCmd->SetArg( 2, geom );
2204 myNotConvertedAddHypCmds.push_back( addCmd );
2208 myAddHypCmds.clear();
2209 mySubmeshes.clear();
2212 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2213 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2217 //================================================================================
2219 * \brief Sets myIsPublished of me and of all objects depending on me.
2221 //================================================================================
2223 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2225 _pyObject::SetRemovedFromStudy(isRemoved);
2227 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2228 for ( ; sm != mySubmeshes.end(); ++sm )
2229 (*sm)->SetRemovedFromStudy(isRemoved);
2231 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2232 for ( ; gr != myGroups.end(); ++gr )
2233 (*gr)->SetRemovedFromStudy(isRemoved);
2235 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2236 for ( ; m != myChildMeshes.end(); ++m )
2237 (*m)->SetRemovedFromStudy(isRemoved);
2239 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2240 for ( ; e != myEditors.end(); ++e )
2241 (*e)->SetRemovedFromStudy(isRemoved);
2244 //================================================================================
2246 * \brief Return true if none of myChildMeshes is in study
2248 //================================================================================
2250 bool _pyMesh::CanClear()
2255 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2256 for ( ; m != myChildMeshes.end(); ++m )
2257 if ( !(*m)->CanClear() )
2263 //================================================================================
2265 * \brief Clear my commands and commands of mesh editor
2267 //================================================================================
2269 void _pyMesh::ClearCommands()
2275 // mark all sub-objects as not removed, except child meshes
2276 list< Handle(_pyMesh) > children;
2277 children.swap( myChildMeshes );
2278 SetRemovedFromStudy( false );
2279 children.swap( myChildMeshes );
2283 _pyObject::ClearCommands();
2285 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2286 for ( ; sm != mySubmeshes.end(); ++sm )
2287 (*sm)->ClearCommands();
2289 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2290 for ( ; gr != myGroups.end(); ++gr )
2291 (*gr)->ClearCommands();
2293 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2294 for ( ; e != myEditors.end(); ++e )
2295 (*e)->ClearCommands();
2298 //================================================================================
2300 * \brief Add a father mesh by ID
2302 //================================================================================
2304 void _pyMesh::addFatherMesh( const _pyID& meshID )
2306 if ( !meshID.IsEmpty() && meshID != GetID() )
2307 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2310 //================================================================================
2312 * \brief Add a father mesh
2314 //================================================================================
2316 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2318 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2320 //myFatherMeshes.push_back( mesh );
2321 mesh->myChildMeshes.push_back( this );
2323 // protect last Compute() from clearing by the next Compute()
2324 mesh->myLastComputeCmd.Nullify();
2328 //================================================================================
2330 * \brief MeshEditor convert its commands to ones of mesh
2332 //================================================================================
2334 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2335 _pyObject( theCreationCmd )
2337 myMesh = theCreationCmd->GetObject();
2338 myCreationCmdStr = theCreationCmd->GetString();
2339 theCreationCmd->Clear();
2341 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2342 if ( !mesh.IsNull() )
2343 mesh->AddEditor( this );
2346 //================================================================================
2348 * \brief convert its commands to ones of mesh
2350 //================================================================================
2352 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2354 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2355 // commands calling these methods are converted to calls of Mesh methods without
2356 // additional modifs, only object is changed from MeshEditor to Mesh.
2357 static TStringSet sameMethods;
2358 if ( sameMethods.empty() ) {
2359 const char * names[] = {
2360 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2361 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2362 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2363 "MoveNode", "MoveClosestNodeToPoint",
2364 "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2365 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2366 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2367 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2368 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2369 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2370 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2371 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2372 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2373 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2374 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2375 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2376 "GetLastCreatedElems",
2377 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2378 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2379 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2380 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2381 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2382 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2383 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2384 ,"" }; // <- mark of the end
2385 sameMethods.Insert( names );
2388 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2389 TStringMap diffMethods;
2390 if ( diffMethods.empty() ) {
2391 const char * orig2newName[] = {
2392 // original name --------------> new name
2393 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2394 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2395 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2396 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2397 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2398 ""};// <- mark of the end
2399 diffMethods.Insert( orig2newName );
2402 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2403 // only by last two arguments
2404 static TStringSet diffLastTwoArgsMethods;
2405 if (diffLastTwoArgsMethods.empty() ) {
2406 const char * names[] = {
2407 "MirrorMakeGroups","MirrorObjectMakeGroups",
2408 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2409 "RotateMakeGroups","RotateObjectMakeGroups",
2410 ""};// <- mark of the end
2411 diffLastTwoArgsMethods.Insert( names );
2414 // only a method name is to change?
2415 const TCollection_AsciiString & method = theCommand->GetMethod();
2416 bool isPyMeshMethod = sameMethods.Contains( method );
2417 if ( !isPyMeshMethod )
2419 TCollection_AsciiString newMethod = diffMethods.Value( method );
2420 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2421 theCommand->SetMethod( newMethod );
2423 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2424 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2426 isPyMeshMethod = true;
2427 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2428 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2431 if ( !isPyMeshMethod )
2433 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2434 // functions with the flag "theMakeGroups = True" like:
2435 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2436 int pos = method.Search("MakeGroups");
2439 isPyMeshMethod = true;
2440 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2441 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2443 // 1. Remove "MakeGroups" from the Command
2444 TCollection_AsciiString aMethod = theCommand->GetMethod();
2445 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2448 pos = pos-2; //Remove "0D" from the Command too
2449 aMethod.Trunc(pos-1);
2450 theCommand->SetMethod(aMethod);
2452 // 2. And add last "True" argument(s)
2453 while(nbArgsToAdd--)
2454 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2455 if( is0DmethId || is0DmethObj )
2456 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2460 // ExtrusionSweep0D() -> ExtrusionSweep()
2461 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2462 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2463 method == "ExtrusionSweepObject0D" ))
2465 isPyMeshMethod = true;
2466 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2467 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2468 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2471 // DoubleNode...New(...) -> DoubleNode...(...,True)
2472 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2473 method == "DoubleNodeElemGroupsNew" ||
2474 method == "DoubleNodeGroupNew" ||
2475 method == "DoubleNodeGroupsNew" ||
2476 method == "DoubleNodeElemGroup2New" ||
2477 method == "DoubleNodeElemGroups2New"))
2479 isPyMeshMethod = true;
2480 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2481 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2482 if ( excessLen == 3 )
2484 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2486 else if ( theCommand->GetArg(4) == "0" ||
2487 theCommand->GetArg(5) == "0" )
2489 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2490 // Group = DoubleNodeGroup2New(,,,False, True)
2491 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2492 theCommand->SetResultValue( groupID );
2495 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2496 // FindElementsByPoint(x, y, z, elementType, meshPart)
2497 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2499 isPyMeshMethod = true;
2500 theCommand->SetMethod( "FindElementsByPoint" );
2501 // make the 1st arg be the last one
2502 _pyID partID = theCommand->GetArg( 1 );
2503 int nbArgs = theCommand->GetNbArgs();
2504 for ( int i = 2; i <= nbArgs; ++i )
2505 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2506 theCommand->SetArg( nbArgs, partID );
2508 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2509 if ( !isPyMeshMethod && method == "Reorient2D" )
2511 isPyMeshMethod = true;
2512 _AString mesh = theCommand->GetArg( 1 );
2513 _AString dir = theCommand->GetArg( 2 );
2514 _AString face = theCommand->GetArg( 3 );
2515 _AString point = theCommand->GetArg( 4 );
2516 theCommand->RemoveArgs();
2517 theCommand->SetArg( 1, mesh );
2518 theCommand->SetArg( 2, dir );
2519 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2520 theCommand->SetArg( 3, point );
2522 theCommand->SetArg( 3, face );
2525 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2527 isPyMeshMethod = true;
2528 int crit_arg = theCommand->GetNbArgs();
2529 const _AString& crit = theCommand->GetArg(crit_arg);
2530 if (crit.Search("MaxElementLength2D") != -1)
2531 theCommand->SetArg(crit_arg, "");
2534 if ( isPyMeshMethod )
2536 theCommand->SetObject( myMesh );
2540 // editor creation command is needed only if any editor function is called
2541 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2542 if ( !myCreationCmdStr.IsEmpty() ) {
2543 GetCreationCmd()->GetString() = myCreationCmdStr;
2544 myCreationCmdStr.Clear();
2549 //================================================================================
2551 * \brief Return true if my mesh can be removed
2553 //================================================================================
2555 bool _pyMeshEditor::CanClear()
2557 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2558 return mesh.IsNull() ? true : mesh->CanClear();
2561 //================================================================================
2563 * \brief _pyHypothesis constructor
2564 * \param theCreationCmd -
2566 //================================================================================
2568 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2569 _pyObject( theCreationCmd ), myCurCrMethod(0)
2571 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2574 //================================================================================
2576 * \brief Creates algorithm or hypothesis
2577 * \param theCreationCmd - The engine command creating a hypothesis
2578 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2580 //================================================================================
2582 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2584 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2585 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2587 Handle(_pyHypothesis) hyp, algo;
2590 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2591 if ( hypTypeQuoted.IsEmpty() )
2594 TCollection_AsciiString hypType =
2595 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2597 algo = new _pyAlgorithm( theCreationCmd );
2598 hyp = new _pyHypothesis( theCreationCmd );
2600 if ( hypType == "NumberOfSegments" ) {
2601 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2602 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2603 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2604 hyp->AddArgMethod( "SetNumberOfSegments" );
2605 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2606 hyp->AddArgMethod( "SetScaleFactor" );
2607 hyp->AddArgMethod( "SetReversedEdges" );
2608 // same for ""CompositeSegment_1D:
2609 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2610 hyp->AddArgMethod( "SetNumberOfSegments" );
2611 hyp->AddArgMethod( "SetScaleFactor" );
2612 hyp->AddArgMethod( "SetReversedEdges" );
2614 else if ( hypType == "SegmentLengthAroundVertex" ) {
2615 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2616 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2617 hyp->AddArgMethod( "SetLength" );
2618 // same for ""CompositeSegment_1D:
2619 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2620 hyp->AddArgMethod( "SetLength" );
2622 else if ( hypType == "LayerDistribution2D" ) {
2623 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2624 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2626 else if ( hypType == "LayerDistribution" ) {
2627 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2628 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2630 else if ( hypType == "CartesianParameters3D" ) {
2631 hyp = new _pyComplexParamHypo( theCreationCmd );
2632 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2633 for ( int iArg = 0; iArg < 4; ++iArg )
2634 hyp->setCreationArg( iArg+1, "[]");
2635 hyp->AddAccumulativeMethod( "SetGrid" );
2636 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2640 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2643 return algo->IsValid() ? algo : hyp;
2646 //================================================================================
2648 * \brief Returns true if addition of this hypothesis to a given mesh can be
2649 * wrapped into hypothesis creation
2651 //================================================================================
2653 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2655 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2657 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2658 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2664 //================================================================================
2666 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2667 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2668 * \param theAlgo - The algo that can create this hypo
2669 * \retval bool - false if the command cant be converted
2671 //================================================================================
2673 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2674 const _pyID& theMesh)
2676 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2678 if ( !IsWrappable( theMesh ))
2681 myGeom = theCmd->GetArg( 1 );
2683 Handle(_pyHypothesis) algo;
2685 // find algo created on myGeom in theMesh
2686 algo = theGen->FindAlgo( myGeom, theMesh, this );
2687 if ( algo.IsNull() )
2689 // attach hypothesis creation command to be after algo creation command
2690 // because it can be new created instance of algorithm
2691 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2695 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2696 theCmd->SetResultValue( GetID() );
2697 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2698 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2699 // set args (geom will be set by _pyMesh calling this method)
2700 theCmd->RemoveArgs();
2701 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2702 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2703 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2705 theCmd->SetArg( i+1, "[]");
2707 // set a new creation command
2708 GetCreationCmd()->Clear();
2709 // replace creation command by wrapped instance
2710 // please note, that hypothesis attaches to algo creation command (see upper)
2711 SetCreationCmd( theCmd );
2714 // clear commands setting arg values
2715 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2716 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2719 // set unknown arg commands after hypo creation
2720 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2721 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2722 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2723 afterCmd->AddDependantCmd( *cmd );
2729 //================================================================================
2731 * \brief Remember hypothesis parameter values
2732 * \param theCommand - The called hypothesis method
2734 //================================================================================
2736 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2738 ASSERT( !myIsAlgo );
2739 if ( !theGen->IsToKeepAllCommands() )
2740 rememberCmdOfParameter( theCommand );
2742 bool usedCommand = false;
2743 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2744 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2746 CreationMethod& crMethod = type2meth->second;
2747 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2748 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2750 myArgCommands.push_back( theCommand );
2752 while ( crMethod.myArgs.size() < i+1 )
2753 crMethod.myArgs.push_back( "[]" );
2754 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2759 myUnusedCommands.push_back( theCommand );
2762 //================================================================================
2764 * \brief Finish conversion
2766 //================================================================================
2768 void _pyHypothesis::Flush()
2772 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2773 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2774 // Add access to a wrapped mesh
2775 theGen->AddMeshAccessorMethod( *cmd );
2776 // Add access to a wrapped algorithm
2777 theGen->AddAlgoAccessorMethod( *cmd );
2779 cmd = myUnusedCommands.begin();
2780 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2781 // Add access to a wrapped mesh
2782 theGen->AddMeshAccessorMethod( *cmd );
2783 // Add access to a wrapped algorithm
2784 theGen->AddAlgoAccessorMethod( *cmd );
2787 // forget previous hypothesis modifications
2788 myArgCommands.clear();
2789 myUnusedCommands.clear();
2792 //================================================================================
2794 * \brief clear creation, arg and unkown commands
2796 //================================================================================
2798 void _pyHypothesis::ClearAllCommands()
2800 GetCreationCmd()->Clear();
2801 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2802 for ( ; cmd != myArgCommands.end(); ++cmd )
2804 cmd = myUnusedCommands.begin();
2805 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2810 //================================================================================
2812 * \brief Assign fields of theOther to me except myIsWrapped
2814 //================================================================================
2816 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2817 const _pyID& theMesh )
2819 // myCreationCmd = theOther->myCreationCmd;
2820 myIsAlgo = theOther->myIsAlgo;
2821 myIsWrapped = false;
2822 myGeom = theOther->myGeom;
2824 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2825 myAccumulativeMethods = theOther->myAccumulativeMethods;
2826 //myUnusedCommands = theOther->myUnusedCommands;
2827 // init myCurCrMethod
2828 GetCreationMethod( theOther->GetAlgoType() );
2831 //================================================================================
2833 * \brief Analyze my erasability depending on myReferredObjs
2835 //================================================================================
2837 bool _pyHypothesis::CanClear()
2841 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2842 for ( ; obj != myReferredObjs.end(); ++obj )
2843 if ( (*obj)->CanClear() )
2850 //================================================================================
2852 * \brief Clear my commands depending on usage by meshes
2854 //================================================================================
2856 void _pyHypothesis::ClearCommands()
2858 // if ( !theGen->IsToKeepAllCommands() )
2860 // bool isUsed = false;
2861 // int lastComputeOrder = 0;
2862 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2863 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2864 // if ( ! (*cmd)->IsEmpty() )
2867 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2868 // lastComputeOrder = (*cmd)->GetOrderNb();
2872 // SetRemovedFromStudy( true );
2876 // // clear my commands invoked after lastComputeOrder
2877 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2878 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2880 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2881 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2882 // // cmds.back()->Clear();
2886 _pyObject::ClearCommands();
2889 //================================================================================
2891 * \brief Find arguments that are objects like mesh, group, geometry
2892 * \param meshes - referred meshes (directly or indirrectly)
2893 * \retval bool - false if a referred geometry is not in the study
2895 //================================================================================
2897 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2899 if ( IsAlgo() ) return true;
2901 bool geomPublished = true;
2902 vector< _AString > args;
2903 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2904 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2906 CreationMethod& crMethod = type2meth->second;
2907 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2909 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2910 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2911 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2912 args.push_back( (*cmd)->GetArg( nb ));
2915 for ( size_t i = 0; i < args.size(); ++i )
2917 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2918 if ( idList.empty() && !args[ i ].IsEmpty() )
2919 idList.push_back( args[ i ]);
2920 list< _pyID >::iterator id = idList.begin();
2921 for ( ; id != idList.end(); ++id )
2923 Handle(_pyObject) obj = theGen->FindObject( *id );
2924 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2927 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2928 geomPublished = false;
2932 myReferredObjs.push_back( obj );
2933 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2934 if ( !mesh.IsNull() )
2935 meshes.push_back( mesh );
2936 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2937 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2938 obj->SetRemovedFromStudy( false );
2942 return geomPublished;
2945 //================================================================================
2947 * \brief Remember theCommand setting a parameter
2949 //================================================================================
2951 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2953 // parameters are discriminated by method name
2954 _AString method = theCommand->GetMethod();
2955 if ( myAccumulativeMethods.count( method ))
2956 return; // this method adds values and not override the previus value
2958 // discriminate commands setting different parameters via one method
2959 // by passing parameter names like e.g. SetOption("size", "0.2")
2960 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2961 theCommand->GetNbArgs() > 1 )
2963 // mangle method by appending a 1st textual arg
2964 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2966 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2967 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2968 if ( !isalpha( arg.Value(2))) continue;
2973 // parameters are discriminated by method name
2974 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2975 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2977 cmds.back()->Clear(); // previous parameter value has not been used
2978 cmds.back() = theCommand;
2982 cmds.push_back( theCommand );
2986 //================================================================================
2988 * \brief Return true if a setting parameter command ha been used to compute mesh
2990 //================================================================================
2992 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2993 _pyCommand::TAddr avoidComputeAddr ) const
2995 bool isUsed = false;
2996 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2997 myComputeAddr2Cmds.begin();
2998 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3000 if ( addr2cmds->first == avoidComputeAddr ) continue;
3001 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3002 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3007 //================================================================================
3009 * \brief Save commands setting parameters as they are used for a mesh computation
3011 //================================================================================
3013 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3015 myComputeCmds.push_back( theComputeCmd );
3016 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3018 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3019 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3020 savedCmds.push_back( m2c->second.back() );
3023 //================================================================================
3025 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3027 //================================================================================
3029 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3031 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3033 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3034 for ( ; cmd != savedCmds.end(); ++cmd )
3036 // check if a cmd has been used to compute another mesh
3037 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3039 // check if a cmd is a sole command setting its parameter;
3040 // don't use method name for search as it can change
3041 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3042 m2cmds = myMeth2Commands.begin();
3043 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3045 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3046 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3047 if ( cmdIt != cmds.end() )
3049 if ( cmds.back() != *cmd )
3051 cmds.erase( cmdIt );
3058 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3061 //================================================================================
3063 * \brief Sets an argNb-th argument of current creation command
3064 * \param argNb - argument index countered from 1
3066 //================================================================================
3068 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3070 if ( myCurCrMethod )
3072 while ( myCurCrMethod->myArgs.size() < argNb )
3073 myCurCrMethod->myArgs.push_back( "None" );
3074 if ( arg.IsEmpty() )
3075 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3077 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3082 //================================================================================
3084 * \brief Remember hypothesis parameter values
3085 * \param theCommand - The called hypothesis method
3087 //================================================================================
3089 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3091 if ( GetAlgoType() == "Cartesian_3D" )
3093 // CartesianParameters3D hyp
3095 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3096 theCommand->GetMethod() == "SetToAddEdges" )
3098 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3099 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3100 myArgCommands.push_back( theCommand );
3103 if ( theCommand->GetMethod() == "SetGrid" ||
3104 theCommand->GetMethod() == "SetGridSpacing" )
3106 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3107 int iArg = axis.Value(1) - '0';
3108 if ( theCommand->GetMethod() == "SetGrid" )
3110 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3114 myCurCrMethod->myArgs[ iArg ] = "[ ";
3115 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3116 myCurCrMethod->myArgs[ iArg ] += ", ";
3117 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3118 myCurCrMethod->myArgs[ iArg ] += "]";
3120 myArgCommands.push_back( theCommand );
3121 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3122 // accumulative, else, if the creation
3123 // is not converted, commands for axes 1 and 2 are lost
3128 if( theCommand->GetMethod() == "SetLength" )
3130 // NOW it is OBSOLETE
3131 // ex: hyp.SetLength(start, 1)
3132 // hyp.SetLength(end, 0)
3133 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3134 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3135 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3136 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3138 CreationMethod& crMethod = type2meth->second;
3139 while ( crMethod.myArgs.size() < i+1 )
3140 crMethod.myArgs.push_back( "[]" );
3141 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3143 myArgCommands.push_back( theCommand );
3147 _pyHypothesis::Process( theCommand );
3150 //================================================================================
3152 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3154 //================================================================================
3156 void _pyComplexParamHypo::Flush()
3160 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
3161 for ( ; cmd != myUnusedCommands.end(); ++cmd )
3162 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3165 if ( GetAlgoType() == "Cartesian_3D" )
3167 _pyID algo = myCreationCmd->GetObject();
3168 for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3170 StructToList( *cmd, /*checkMethod=*/false );
3171 (*cmd)->SetObject( algo );
3177 //================================================================================
3179 * \brief Convert methods of 1D hypotheses to my own methods
3180 * \param theCommand - The called hypothesis method
3182 //================================================================================
3184 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3186 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3189 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3190 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3191 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3193 // TCollection_AsciiString cmd =
3194 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3195 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3196 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3199 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3201 // // 1D hypo is already set, so distribution changes and the old
3202 // // 1D hypo is thrown away
3203 // my1dHyp->ClearAllCommands();
3206 // //my1dHyp->SetRemovedFromStudy( false );
3208 // if ( !myArgCommands.empty() )
3209 // myArgCommands.back()->Clear();
3210 myCurCrMethod->myArgs.push_back( hyp1dID );
3211 myArgCommands.push_back( theCommand );
3214 //================================================================================
3217 * \param theAdditionCmd - command to be converted
3218 * \param theMesh - mesh instance
3219 * \retval bool - status
3221 //================================================================================
3223 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3224 const _pyID& theMesh)
3226 myIsWrapped = false;
3228 if ( my1dHyp.IsNull() )
3231 // set "SetLayerDistribution()" after addition cmd
3232 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3234 _pyID geom = theAdditionCmd->GetArg( 1 );
3236 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3237 if ( !algo.IsNull() )
3239 my1dHyp->SetMesh( theMesh );
3240 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3241 algo->GetAlgoType().ToCString());
3242 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3245 // clear "SetLayerDistribution()" cmd
3246 myArgCommands.back()->Clear();
3248 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3250 // find RadialPrism algo created on <geom> for theMesh
3251 GetCreationCmd()->SetObject( algo->GetID() );
3252 GetCreationCmd()->SetMethod( myAlgoMethod );
3253 GetCreationCmd()->RemoveArgs();
3254 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3260 //================================================================================
3264 //================================================================================
3266 void _pyLayerDistributionHypo::Flush()
3268 // as creation of 1D hyp was written later then it's edition,
3269 // we need to find all it's edition calls and process them
3270 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3272 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3274 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3275 if ( hyp1dID.IsEmpty() ) continue;
3277 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3279 // make a new name for 1D hyp = "HypType" + "_Distribution"
3281 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3283 if ( prevNewName.IsEmpty() ) continue;
3284 newName = prevNewName;
3288 if ( hyp1d->IsWrapped() ) {
3289 newName = hyp1d->GetCreationCmd()->GetMethod();
3292 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3293 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3295 newName += "_Distribution";
3296 prevNewName = newName;
3298 hyp1d->GetCreationCmd()->SetResultValue( newName );
3300 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3301 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3302 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3303 const _pyID& objID = (*cmdIt)->GetObject();
3304 if ( objID == hyp1dID ) {
3305 if ( !hyp1d.IsNull() )
3307 hyp1d->Process( *cmdIt );
3308 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3310 ( *cmdIt )->SetObject( newName );
3313 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3314 (*cmd)->SetArg( 1, newName );
3318 //================================================================================
3320 * \brief additionally to Addition2Creation, clears SetDistrType() command
3321 * \param theCmd - AddHypothesis() command
3322 * \param theMesh - mesh to which a hypothesis is added
3323 * \retval bool - convertion result
3325 //================================================================================
3327 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3328 const _pyID& theMesh)
3330 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3331 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3332 bool scaleDistrType = false;
3333 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3334 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3335 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3336 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3337 scaleDistrType = true;
3340 else if ( !scaleDistrType ) {
3341 // distribution type changed: remove scale factor from args
3342 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3343 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3345 CreationMethod& crMethod = type2meth->second;
3346 if ( crMethod.myArgs.size() == 2 )
3347 crMethod.myArgs.pop_back();
3354 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3357 //================================================================================
3359 * \brief remove repeated commands defining distribution
3361 //================================================================================
3363 void _pyNumberOfSegmentsHyp::Flush()
3365 // find number of the last SetDistrType() command
3366 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3367 int distrTypeNb = 0;
3368 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3369 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3370 if ( cmd != myUnusedCommands.rbegin() )
3371 distrTypeNb = (*cmd)->GetOrderNb();
3373 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3376 // clear commands before the last SetDistrType()
3377 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3378 set< int > treatedCmdNbs; // avoid treating same cmd twice
3379 for ( int i = 0; i < 2; ++i ) {
3380 set<TCollection_AsciiString> uniqueMethods;
3381 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3382 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3384 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3385 continue;// avoid treating same cmd twice
3386 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3387 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3388 if ( !clear || method == "SetNumberOfSegments" ) {
3389 bool isNewInSet = uniqueMethods.insert( method ).second;
3390 clear = !isNewInSet;
3399 //================================================================================
3401 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3402 * into regular1D.LengthNearVertex( length, vertex )
3403 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3404 * \param theMesh - The mesh needing this hypo
3405 * \retval bool - false if the command cant be converted
3407 //================================================================================
3409 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3410 const _pyID& theMeshID)
3412 if ( IsWrappable( theMeshID )) {
3414 _pyID vertex = theCmd->GetArg( 1 );
3416 // the problem here is that segment algo will not be found
3417 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3418 // geometry where segment algorithm is assigned
3419 Handle(_pyHypothesis) algo;
3420 _pyID geom = vertex;
3421 while ( algo.IsNull() && !geom.IsEmpty()) {
3422 // try to find geom as a father of <vertex>
3423 geom = FatherID( geom );
3424 algo = theGen->FindAlgo( geom, theMeshID, this );
3426 if ( algo.IsNull() )
3427 return false; // also possible to find geom as brother of veretex...
3428 // set geom instead of vertex
3429 theCmd->SetArg( 1, geom );
3431 // set vertex as a second arg
3432 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3433 setCreationArg( 2, vertex );
3435 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3436 // theMeshID.LengthNearVertex( length, vertex )
3437 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3442 //================================================================================
3444 * \brief _pyAlgorithm constructor
3445 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3447 //================================================================================
3449 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3450 : _pyHypothesis( theCreationCmd )
3455 //================================================================================
3457 * \brief Convert the command adding an algorithm to mesh
3458 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3459 * \param theMesh - The mesh needing this algo
3460 * \retval bool - false if the command cant be converted
3462 //================================================================================
3464 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3465 const _pyID& theMeshID)
3467 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3468 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3469 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3475 //================================================================================
3477 * \brief Return starting position of a part of python command
3478 * \param thePartIndex - The index of command part
3479 * \retval int - Part position
3481 //================================================================================
3483 int _pyCommand::GetBegPos( int thePartIndex ) const
3487 if ( myBegPos.Length() < thePartIndex )
3489 ASSERT( thePartIndex > 0 );
3490 return myBegPos( thePartIndex );
3493 //================================================================================
3495 * \brief Store starting position of a part of python command
3496 * \param thePartIndex - The index of command part
3497 * \param thePosition - Part position
3499 //================================================================================
3501 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3503 while ( myBegPos.Length() < thePartIndex )
3504 myBegPos.Append( UNKNOWN );
3505 ASSERT( thePartIndex > 0 );
3506 myBegPos( thePartIndex ) = thePosition;
3509 //================================================================================
3511 * \brief Returns whitespace symbols at the line beginning
3512 * \retval TCollection_AsciiString - result
3514 //================================================================================
3516 TCollection_AsciiString _pyCommand::GetIndentation()
3519 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3520 GetWord( myString, end, true );
3522 end = GetBegPos( RESULT_IND );
3523 return myString.SubString( 1, Max( end - 1, 1 ));
3526 //================================================================================
3528 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3529 * \retval const TCollection_AsciiString & - ResultValue substring
3531 //================================================================================
3533 const TCollection_AsciiString & _pyCommand::GetResultValue()
3535 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3537 SetBegPos( RESULT_IND, EMPTY );
3538 int begPos, endPos = myString.Location( "=", 1, Length() );
3542 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3543 if ( begPos < endPos )
3545 SetBegPos( RESULT_IND, begPos );
3547 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3548 myRes = myString.SubString( begPos, endPos );
3555 //================================================================================
3557 * \brief Return number of python command result value ResultValue = Obj.Meth()
3559 //================================================================================
3561 int _pyCommand::GetNbResultValues()
3564 return myResults.Length();
3568 //================================================================================
3570 * \brief Return substring of python command looking like
3571 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3572 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3574 //================================================================================
3575 const _AString& _pyCommand::GetResultValue(int res)
3577 if ( GetResultValue().IsEmpty() )
3578 return theEmptyString;
3580 if ( myResults.IsEmpty() )
3583 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3584 ++begPos; // skip [, else the whole list is returned
3585 while ( begPos < myRes.Length() ) {
3586 _AString result = GetWord( myRes, begPos, true );
3587 begPos += result.Length();
3589 // result.RemoveAll('[');
3590 // result.RemoveAll(']');
3595 myResults.Append( result );
3598 if ( res > 0 && res <= myResults.Length() )
3599 return myResults( res );
3600 return theEmptyString;
3603 //================================================================================
3605 * \brief Return substring of python command looking like ResVal = Object.Meth()
3606 * \retval const TCollection_AsciiString & - Object substring
3608 //================================================================================
3610 const TCollection_AsciiString & _pyCommand::GetObject()
3612 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3615 int begPos = GetBegPos( RESULT_IND );
3617 begPos = myString.Location( "=", 1, Length() ) + 1;
3618 // is '=' in the string argument (for example, name) or not
3619 int nb1 = 0; // number of ' character at the left of =
3620 int nb2 = 0; // number of " character at the left of =
3621 for ( int i = 1; i < begPos-1; i++ ) {
3622 if ( myString.Value( i )=='\'' )
3624 else if ( myString.Value( i )=='"' )
3627 // if number of ' or " is not divisible by 2,
3628 // then get an object at the start of the command
3629 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3633 begPos += myRes.Length();
3635 myObj = GetWord( myString, begPos, true );
3636 if ( begPos != EMPTY )
3638 // check if object is complex,
3639 // so far consider case like "smesh.Method()"
3640 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3641 //if ( bracketPos==0 ) bracketPos = Length();
3642 int dotPos = begPos+myObj.Length();
3643 while ( dotPos+1 < bracketPos ) {
3644 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3649 if ( dotPos > begPos+myObj.Length() )
3650 myObj = myString.SubString( begPos, dotPos-1 );
3653 // 1st word after '=' is an object
3654 // else // no method -> no object
3660 SetBegPos( OBJECT_IND, begPos );
3666 //================================================================================
3668 * \brief Return substring of python command looking like ResVal = Obj.Method()
3669 * \retval const TCollection_AsciiString & - Method substring
3671 //================================================================================
3673 const TCollection_AsciiString & _pyCommand::GetMethod()
3675 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3678 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3679 bool forward = true;
3681 begPos = myString.Location( "(", 1, Length() ) - 1;
3685 myMeth = GetWord( myString, begPos, forward );
3686 SetBegPos( METHOD_IND, begPos );
3692 //================================================================================
3694 * \brief Returns true if there are brackets after the method
3696 //================================================================================
3698 bool _pyCommand::IsMethodCall()
3700 if ( GetMethod().IsEmpty() )
3702 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3703 return ( s[0] == '(' || s[1] == '(' );
3706 //================================================================================
3708 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3709 * \retval const TCollection_AsciiString & - Arg<index> substring
3711 //================================================================================
3713 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3715 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3719 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3721 pos = myString.Location( "(", 1, Length() );
3725 // we are at or before '(', skip it if present
3727 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3728 if ( pos > Length() )
3732 SetBegPos( ARG1_IND, 0 ); // even no '('
3733 return theEmptyString;
3737 list< TCollection_AsciiString > separatorStack( 1, ",)");
3738 bool ignoreNesting = false;
3740 while ( pos <= Length() )
3742 const char chr = myString.Value( pos );
3744 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3746 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3748 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3750 TCollection_AsciiString arg;
3751 if ( pos-1 >= prevPos ) {
3752 arg = myString.SubString( prevPos, pos-1 );
3753 arg.RightAdjust(); // remove spaces
3756 if ( !arg.IsEmpty() || chr == ',' )
3758 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3759 myArgs.Append( arg );
3765 else // end of nesting args found
3767 separatorStack.pop_back();
3768 ignoreNesting = false;
3771 else if ( !ignoreNesting )
3774 case '(' : separatorStack.push_back(")"); break;
3775 case '[' : separatorStack.push_back("]"); break;
3776 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3777 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3784 if ( myArgs.Length() < index )
3785 return theEmptyString;
3786 return myArgs( index );
3789 //================================================================================
3791 * \brief Return position where arguments begin
3793 //================================================================================
3795 int _pyCommand::GetArgBeginning() const
3797 int pos = GetBegPos( ARG1_IND );
3798 if ( pos == UNKNOWN )
3800 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3802 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3807 //================================================================================
3809 * \brief Check if char is a word part
3810 * \param c - The character to check
3811 * \retval bool - The check result
3813 //================================================================================
3815 static inline bool isWord(const char c, const bool dotIsWord)
3818 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3821 //================================================================================
3823 * \brief Looks for a word in the string and returns word's beginning
3824 * \param theString - The input string
3825 * \param theStartPos - The position to start the search, returning word's beginning
3826 * \param theForward - The search direction
3827 * \retval TCollection_AsciiString - The found word
3829 //================================================================================
3831 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3833 const bool theForward,
3834 const bool dotIsWord )
3836 int beg = theStartPos, end = theStartPos;
3837 theStartPos = EMPTY;
3838 if ( beg < 1 || beg > theString.Length() )
3839 return theEmptyString;
3841 if ( theForward ) { // search forward
3843 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3845 if ( beg > theString.Length() )
3846 return theEmptyString; // no word found
3849 char begChar = theString.Value( beg );
3850 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3851 char endChar = ( begChar == '[' ) ? ']' : begChar;
3852 // end is at the corresponding quoting mark or bracket
3853 while ( end < theString.Length() &&
3854 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3858 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3863 else { // search backward
3865 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3868 return theEmptyString; // no word found
3870 char endChar = theString.Value( end );
3871 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3872 char begChar = ( endChar == ']' ) ? '[' : endChar;
3873 // beg is at the corresponding quoting mark
3875 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3879 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3885 //cout << theString << " ---- " << beg << " - " << end << endl;
3886 return theString.SubString( beg, end );
3889 //================================================================================
3891 * \brief Returns true if the string looks like a study entry
3893 //================================================================================
3895 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3897 if ( str.Length() < 5 ) return false;
3899 int nbColons = 0, isColon;
3900 for ( int i = 1; i <= str.Length(); ++i )
3902 char c = str.Value(i);
3903 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3905 nbColons += isColon;
3907 return nbColons > 2 && str.Length()-nbColons > 2;
3910 //================================================================================
3912 * \brief Returns true if the string looks like an object ID but not like a list,
3913 * string, command etc.
3915 //================================================================================
3917 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3919 if ( str.Length() < 1 ) return false;
3921 const char* s = str.ToCString();
3923 for ( int i = 0; i < str.Length(); ++i )
3924 if ( !IsIDChar( s[i] ))
3930 //================================================================================
3932 * \brief Finds entries in a sting
3934 //================================================================================
3936 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3938 std::list< _pyID > resList;
3940 while ( ++pos <= str.Length() )
3942 if ( !isdigit( str.Value( pos ))) continue;
3943 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3946 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3947 _pyID entry = str.SubString( pos, end-1 );
3949 if ( IsStudyEntry( entry ))
3950 resList.push_back( entry );
3955 //================================================================================
3957 * \brief Look for position where not space char is
3958 * \param theString - The string
3959 * \param thePos - The position to search from and which returns result
3960 * \retval bool - false if there are only space after thePos in theString
3962 //================================================================================
3964 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3966 if ( thePos < 1 || thePos > theString.Length() )
3969 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3972 return thePos <= theString.Length();
3975 //================================================================================
3977 * \brief Modify a part of the command
3978 * \param thePartIndex - The index of the part
3979 * \param thePart - The new part string
3980 * \param theOldPart - The old part
3982 //================================================================================
3984 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3985 TCollection_AsciiString& theOldPart)
3987 int pos = GetBegPos( thePartIndex );
3988 if ( pos <= Length() && theOldPart != thePart)
3990 TCollection_AsciiString seperator;
3992 pos = GetBegPos( thePartIndex + 1 );
3993 if ( pos < 1 ) return;
3994 switch ( thePartIndex ) {
3995 case RESULT_IND: seperator = " = "; break;
3996 case OBJECT_IND: seperator = "."; break;
3997 case METHOD_IND: seperator = "()"; break;
4001 myString.Remove( pos, theOldPart.Length() );
4002 if ( !seperator.IsEmpty() )
4003 myString.Insert( pos , seperator );
4004 myString.Insert( pos, thePart );
4005 // update starting positions of the following parts
4006 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4007 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4008 if ( myBegPos( i ) > 0 )
4009 myBegPos( i ) += posDelta;
4011 theOldPart = thePart;
4015 //================================================================================
4017 * \brief Set agrument
4018 * \param index - The argument index, it counts from 1
4019 * \param theArg - The argument string
4021 //================================================================================
4023 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4026 int argInd = ARG1_IND + index - 1;
4027 int pos = GetBegPos( argInd );
4028 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4030 // find a closing parenthesis
4031 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4032 int lastArgInd = GetNbArgs();
4033 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4034 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4039 while ( pos > 0 && myString.Value( pos ) != ')' )
4042 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4046 while ( myArgs.Length() < index ) {
4047 if ( myArgs.Length() )
4048 myString.Insert( pos++, "," );
4049 myArgs.Append("None");
4050 myString.Insert( pos, myArgs.Last() );
4051 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4052 pos += myArgs.Last().Length();
4055 SetPart( argInd, theArg, myArgs( index ));
4058 //================================================================================
4060 * \brief Empty arg list
4062 //================================================================================
4064 void _pyCommand::RemoveArgs()
4066 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4067 myString.Trunc( pos );
4070 if ( myBegPos.Length() >= ARG1_IND )
4071 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4074 //================================================================================
4076 * \brief Comment a python command
4078 //================================================================================
4080 void _pyCommand::Comment()
4082 if ( IsEmpty() ) return;
4085 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4086 if ( i <= Length() )
4088 myString.Insert( i, "#" );
4089 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4091 int begPos = GetBegPos( iPart );
4092 if ( begPos != UNKNOWN && begPos != EMPTY )
4093 SetBegPos( iPart, begPos + 1 );
4098 //================================================================================
4100 * \brief Set dependent commands after this one
4102 //================================================================================
4104 bool _pyCommand::SetDependentCmdsAfter() const
4106 bool orderChanged = false;
4107 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4108 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4109 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4110 orderChanged = true;
4111 theGen->SetCommandAfter( *cmd, this );
4112 (*cmd)->SetDependentCmdsAfter();
4115 return orderChanged;
4117 //================================================================================
4119 * \brief Insert accessor method after theObjectID
4120 * \param theObjectID - id of the accessed object
4121 * \param theAcsMethod - name of the method giving access to the object
4122 * \retval bool - false if theObjectID is not found in the command string
4124 //================================================================================
4126 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4128 if ( !theAcsMethod )
4130 // start object search from the object, i.e. ignore result
4132 int beg = GetBegPos( OBJECT_IND );
4133 if ( beg < 1 || beg > Length() )
4136 while (( beg = myString.Location( theObjectID, beg, Length() )))
4138 // check that theObjectID is not just a part of a longer ID
4139 int afterEnd = beg + theObjectID.Length();
4140 Standard_Character c = myString.Value( afterEnd );
4141 if ( !IsIDChar( c ))
4143 // check if accessor method already present
4145 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4147 int oldLen = Length();
4148 myString.Insert( afterEnd, (char*) theAcsMethod );
4149 myString.Insert( afterEnd, "." );
4150 // update starting positions of the parts following the modified one
4151 int posDelta = Length() - oldLen;
4152 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4153 if ( myBegPos( i ) > afterEnd )
4154 myBegPos( i ) += posDelta;
4159 beg = afterEnd; // is a part -> next search
4164 //================================================================================
4166 * \brief Creates pyObject
4168 //================================================================================
4170 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4171 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4176 //================================================================================
4178 * \brief Set up myID and myIsPublished
4180 //================================================================================
4182 void _pyObject::setID(const _pyID& theID)
4185 myIsPublished = !theGen->IsNotPublished( GetID() );
4188 //================================================================================
4190 * \brief Clear myCreationCmd and myProcessedCmds
4192 //================================================================================
4194 void _pyObject::ClearCommands()
4199 if ( !myCreationCmd.IsNull() )
4200 myCreationCmd->Clear();
4202 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4203 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4207 //================================================================================
4209 * \brief Return method name giving access to an interaface object wrapped by python class
4210 * \retval const char* - method name
4212 //================================================================================
4214 const char* _pyObject::AccessorMethod() const
4218 //================================================================================
4220 * \brief Return ID of a father
4222 //================================================================================
4224 _pyID _pyObject::FatherID(const _pyID & childID)
4226 int colPos = childID.SearchFromEnd(':');
4228 return childID.SubString( 1, colPos-1 );
4232 //================================================================================
4234 * \brief SelfEraser erases creation command if none of it's commands invoked
4235 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4237 //================================================================================
4239 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4240 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4242 myIsPublished = true; // prevent clearing as a not published
4243 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4246 //================================================================================
4248 * \brief SelfEraser erases creation command if none of it's commands invoked
4249 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4251 //================================================================================
4253 bool _pySelfEraser::CanClear()
4255 bool toErase = false;
4256 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4259 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4260 for ( ; cmd != myArgCmds.end(); ++cmd )
4261 nbArgUses += IsAliveCmd( *cmd );
4263 toErase = ( nbArgUses < 1 );
4268 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4269 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4270 for ( ; cmd != cmds.end(); )
4271 // check of cmd emptiness is not enough as object can change
4272 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4275 cmd = cmds.erase( cmd ); // save the cmd from clearing
4277 toErase = ( nbCalls < 1 );
4282 //================================================================================
4284 * \brief Check if a command is or can be cleared
4286 //================================================================================
4288 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4290 if ( theCmd->IsEmpty() )
4293 if ( !theGen->IsToKeepAllCommands() )
4295 const _pyID& objID = theCmd->GetObject();
4296 Handle( _pyObject ) obj = theGen->FindObject( objID );
4297 if ( !obj.IsNull() )
4298 return !obj->CanClear();
4303 //================================================================================
4305 * \brief SelfEraser erases creation command if none of it's commands invoked
4306 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4308 //================================================================================
4310 void _pySelfEraser::Flush()
4314 myIsPublished = false;
4315 _pyObject::ClearCommands();
4319 //================================================================================
4321 * \brief _pySubMesh constructor
4323 //================================================================================
4325 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4326 _pyObject(theCreationCmd)
4328 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4329 if ( toKeepAgrCmds )
4330 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4333 //================================================================================
4335 * \brief Return true if a sub-mesh can be used as argument of the given method
4337 //================================================================================
4339 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4342 // // names of all methods where a sub-mesh can be used as argument
4343 // static TStringSet methods;
4344 // if ( methods.empty() ) {
4345 // const char * names[] = {
4346 // // methods of SMESH_Gen
4348 // // methods of SMESH_Group
4350 // // methods of SMESH_Measurements
4352 // // methods of SMESH_Mesh
4353 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4355 // // methods of SMESH_MeshEditor
4356 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4357 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4358 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4359 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4360 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4361 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4362 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4363 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4364 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4365 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4366 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4367 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4368 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4369 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4370 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4371 // "" }; // <- mark of end
4372 // methods.Insert( names );
4374 // return methods.Contains( theMethodName );
4377 //================================================================================
4379 * \brief count invoked commands
4381 //================================================================================
4383 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4385 _pyObject::Process(theCommand); // count calls of Process()
4388 //================================================================================
4390 * \brief Move creation command depending on invoked commands
4392 //================================================================================
4394 void _pySubMesh::Flush()
4396 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4397 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4398 else if ( !myCreator.IsNull() )
4399 // move to be just after creator
4400 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4402 // move sub-mesh usage after creation cmd
4403 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4404 for ( ; cmd != myArgCmds.end(); ++cmd )
4405 if ( !(*cmd)->IsEmpty() )
4406 GetCreationCmd()->AddDependantCmd( *cmd );
4409 //================================================================================
4411 * \brief Creates _pyGroup
4413 //================================================================================
4415 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4416 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4418 if ( !id.IsEmpty() )
4421 myCanClearCreationCmd = true;
4423 const _AString& method = theCreationCmd->GetMethod();
4424 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4426 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4428 // ----------------------------------------------------------------------
4429 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4431 _pyID geom = theCreationCmd->GetArg( 3 );
4432 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4433 // next if(){...} section is commented
4434 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4435 // theCreationCmd->SetMethod( "Group" );
4436 // theCreationCmd->RemoveArgs();
4437 // theCreationCmd->SetArg( 1, geom );
4440 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4441 _pyID type = theCreationCmd->GetArg( 1 );
4442 _pyID name = theCreationCmd->GetArg( 2 );
4443 theCreationCmd->SetMethod( "GroupOnGeom" );
4444 theCreationCmd->RemoveArgs();
4445 theCreationCmd->SetArg( 1, geom );
4446 theCreationCmd->SetArg( 2, name );
4447 theCreationCmd->SetArg( 3, type );
4450 else if ( method == "CreateGroupFromFilter" )
4452 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4453 theCreationCmd->SetMethod( "GroupOnFilter" );
4455 _pyID filterID = theCreationCmd->GetArg(3);
4456 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4457 if ( !filter.IsNull())
4459 if ( !filter->GetNewID().IsEmpty() )
4460 theCreationCmd->SetArg( 3, filter->GetNewID() );
4461 //filter->AddUser( this );
4465 else if ( method == "GetGroups" )
4467 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4471 // theCreationCmd does something else apart from creation of this group
4472 // and thus it can't be cleared if this group is removed
4473 myCanClearCreationCmd = false;
4477 //================================================================================
4479 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4482 //================================================================================
4484 bool _pyGroup::CanClear()
4489 if ( !myCanClearCreationCmd &&
4490 !myCreationCmd.IsNull() &&
4491 myCreationCmd->GetMethod() == "GetGroups" )
4493 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4494 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4495 list< _pyID >::iterator grID = idList.begin();
4496 if ( GetID() == *grID )
4498 myCanClearCreationCmd = true;
4499 list< Handle(_pyGroup ) > groups;
4500 for ( ; grID != idList.end(); ++grID )
4502 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4503 if ( group.IsNull() ) continue;
4504 groups.push_back( group );
4505 if ( group->IsInStudy() )
4506 myCanClearCreationCmd = false;
4508 // set myCanClearCreationCmd == true to all groups
4509 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4510 for ( ; group != groups.end(); ++group )
4511 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4515 return myCanClearCreationCmd;
4518 //================================================================================
4520 * \brief set myCanClearCreationCmd = true if the main action of the creation
4521 * command is discarded
4523 //================================================================================
4525 void _pyGroup::RemovedWithContents()
4527 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4528 // via a created group
4529 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4530 // myCanClearCreationCmd = true;
4533 //================================================================================
4535 * \brief To convert creation of a group by filter
4537 //================================================================================
4539 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4541 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4542 // group = mesh.CreateEmptyGroup( elemType, groupName )
4543 // aFilter.SetMesh(mesh)
4544 // nbAdd = group.AddFrom( aFilter )
4545 Handle(_pyFilter) filter;
4546 if ( theCommand->GetMethod() == "AddFrom" )
4548 _pyID idSource = theCommand->GetArg(1);
4549 // check if idSource is a filter
4550 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4551 if ( !filter.IsNull() )
4553 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4554 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4555 while ( *cmdIt != theCommand ) ++cmdIt;
4556 while ( (*cmdIt)->GetOrderNb() != 1 )
4558 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4559 if ((setMeshCmd->GetObject() == idSource ||
4560 setMeshCmd->GetObject() == filter->GetNewID() )
4562 setMeshCmd->GetMethod() == "SetMesh")
4564 setMeshCmd->Clear();
4568 // replace 3 commands by one
4569 theCommand->Clear();
4570 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4571 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4572 if ( !filter->GetNewID().IsEmpty() )
4573 idSource = filter->GetNewID();
4574 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4575 makeGroupCmd->SetArg( 1, name );
4576 makeGroupCmd->SetArg( 2, idSource );
4577 filter->AddArgCmd( makeGroupCmd );
4580 else if ( theCommand->GetMethod() == "SetFilter" )
4582 // set new name of a filter or clear the command if the same filter is set
4583 _pyID filterID = theCommand->GetArg(1);
4584 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4585 if ( !myFilter.IsNull() && filter == myFilter )
4586 theCommand->Clear();
4587 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4588 theCommand->SetArg( 1, filter->GetNewID() );
4591 else if ( theCommand->GetMethod() == "GetFilter" )
4593 // GetFilter() returns a filter with other ID, make myFilter process
4594 // calls of the returned filter
4595 if ( !myFilter.IsNull() )
4597 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4598 theCommand->Clear();
4602 // if ( !filter.IsNull() )
4603 // filter->AddUser( this );
4605 theGen->AddMeshAccessorMethod( theCommand );
4608 //================================================================================
4610 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4612 //================================================================================
4614 void _pyGroup::Flush()
4616 if ( !theGen->IsToKeepAllCommands() &&
4617 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4619 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4623 //================================================================================
4625 * \brief Constructor of _pyFilter
4627 //================================================================================
4629 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4630 :_pyObject(theCreationCmd), myNewID( newID )
4632 //myIsPublished = true; // prevent clearing as a not published
4633 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4636 //================================================================================
4638 * \brief To convert creation of a filter by criteria and
4639 * to replace an old name by a new one
4641 //================================================================================
4643 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4645 if ( theCommand->GetObject() == GetID() )
4646 _pyObject::Process(theCommand); // count commands
4648 if ( !myNewID.IsEmpty() )
4649 theCommand->SetObject( myNewID );
4651 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4652 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4653 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4654 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4655 theCommand->GetMethod() == "SetCriteria")
4657 // aFilter.SetCriteria(aCriteria) ->
4658 // aFilter = smesh.GetFilterFromCriteria(criteria)
4659 if ( myNewID.IsEmpty() )
4660 theCommand->SetResultValue( GetID() );
4662 theCommand->SetResultValue( myNewID );
4663 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4664 theCommand->SetMethod( "GetFilterFromCriteria" );
4666 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4667 GetCreationCmd()->Clear();
4668 GetCreationCmd()->GetString() = theCommand->GetString();
4669 theCommand->Clear();
4670 theCommand->AddDependantCmd( GetCreationCmd() );
4671 // why swap? -- it's needed
4672 //GetCreationCmd()->Clear();
4674 else if ( theCommand->GetMethod() == "SetMesh" )
4676 if ( myMesh == theCommand->GetArg( 1 ))
4677 theCommand->Clear();
4679 myMesh = theCommand->GetArg( 1 );
4680 theGen->AddMeshAccessorMethod( theCommand );
4684 //================================================================================
4686 * \brief Set new filter name to the creation command and to myArgCmds
4688 //================================================================================
4690 void _pyFilter::Flush()
4692 if ( myNewID.IsEmpty() ) return;
4694 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4695 for ( ; cmd != myArgCmds.end(); ++cmd )
4696 if ( !(*cmd)->IsEmpty() )
4698 _AString cmdStr = (*cmd)->GetString();
4699 _AString id = GetID();
4700 int pos = cmdStr.Search( id );
4703 cmdStr.Remove( pos, id.Length() );
4704 cmdStr.Insert( pos, myNewID );
4707 (*cmd)->GetString() = cmdStr;
4710 if ( !GetCreationCmd()->IsEmpty() )
4711 GetCreationCmd()->SetResultValue( myNewID );
4714 //================================================================================
4716 * \brief Return true if all my users can be cleared
4718 //================================================================================
4720 bool _pyObject::CanClear()
4722 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4723 for ( ; cmd != myArgCmds.end(); ++cmd )
4724 if ( !(*cmd)->IsEmpty() )
4726 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4727 if ( !obj.IsNull() && !obj->CanClear() )
4730 return ( !myIsPublished );
4733 //================================================================================
4735 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4737 //================================================================================
4739 _pyHypothesisReader::_pyHypothesisReader()
4742 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4743 LDOMParser xmlParser;
4744 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4746 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4750 INFOS( xmlParser.GetError(data) );
4753 // <algorithm type="Regular_1D"
4754 // label-id="Wire discretisation"
4757 // <algo>Regular_1D=Segment()</algo>
4758 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4760 LDOM_Document xmlDoc = xmlParser.getDocument();
4761 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4762 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4764 LDOM_Node algoNode = algoNodeList.item( i );
4765 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4766 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4767 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4769 _AString text, algoType, method, arg;
4770 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4772 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4773 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4774 text = textNode.getNodeValue();
4775 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4776 algoType = algoCmd->GetResultValue();
4777 method = algoCmd->GetMethod();
4778 arg = algoCmd->GetArg(1);
4779 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4781 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4782 algo->SetConvMethodAndType( method, algoType );
4783 if ( !arg.IsEmpty() )
4784 algo->setCreationArg( 1, arg );
4786 myType2Hyp[ algoType ] = algo;
4790 if ( algoType.IsEmpty() ) continue;
4792 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4794 Handle( _pyHypothesis ) hyp;
4795 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4797 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4798 LDOM_Node textNode = pyHypoNode.getFirstChild();
4799 text = textNode.getNodeValue();
4800 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4801 hypType = hypoCmd->GetResultValue();
4802 method = hypoCmd->GetMethod();
4803 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4805 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4806 if ( type2hyp == myType2Hyp.end() )
4807 hyp = new _pyHypothesis( hypoCmd );
4809 hyp = type2hyp->second;
4810 hyp->SetConvMethodAndType( method, algoType );
4811 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4813 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4814 _AString argMethod = argCmd.GetMethod();
4815 _AString argNbText = argCmd.GetArg( 1 );
4816 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4817 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4819 hyp->AddArgMethod( argMethod,
4820 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4822 myType2Hyp[ hypType ] = hyp;
4826 // <hypothesis type="BLSURF_Parameters"
4830 // <accumulative-methods>
4831 // SetEnforcedVertex,
4832 // SetEnforcedVertexNamed
4833 // </accumulative-methods>
4837 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4838 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4840 LDOM_Node hypNode = hypNodeList.item( i );
4841 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4842 _AString hypType = hypElem.getAttribute("type");
4843 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4844 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4846 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4847 if ( type2hyp == myType2Hyp.end() ) continue;
4849 LDOM_Node methNode = methNodeList.item( 0 );
4850 LDOM_Node textNode = methNode.getFirstChild();
4851 _AString text = textNode.getNodeValue();
4855 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4856 pos += method.Length();
4857 type2hyp->second->AddAccumulativeMethod( method );
4859 while ( !method.IsEmpty() );
4862 } // loop on xmlPaths
4865 //================================================================================
4867 * \brief Returns a new hypothesis initialized according to the read information
4869 //================================================================================
4871 Handle(_pyHypothesis)
4872 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4873 const Handle(_pyCommand)& creationCmd) const
4875 Handle(_pyHypothesis) resHyp, sampleHyp;
4877 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4878 if ( type2hyp != myType2Hyp.end() )
4879 sampleHyp = type2hyp->second;
4881 if ( sampleHyp.IsNull() )
4883 resHyp = new _pyHypothesis(creationCmd);
4887 if ( sampleHyp->IsAlgo() )
4888 resHyp = new _pyAlgorithm( creationCmd );
4890 resHyp = new _pyHypothesis(creationCmd);
4891 resHyp->Assign( sampleHyp, _pyID() );
4896 //================================================================================
4898 * \brief Adds an object ID to some family of IDs with a common prefix
4899 * \param [in] str - the object ID
4900 * \return bool - \c false if \a str does not have the same prefix as \a this family
4901 * (for internal usage)
4903 //================================================================================
4905 bool _pyStringFamily::Add( const char* str )
4907 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4908 return false; // expected prefix is missing
4910 str += _prefix.Length(); // skip _prefix
4912 // try to add to some of child falimies
4913 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4914 for ( ; itSub != _subFams.end(); ++itSub )
4915 if ( itSub->Add( str ))
4918 // no suitable family found - add str to _strings or create a new child family
4920 // look for a proper place within sorted _strings
4921 std::list< _AString >::iterator itStr = _strings.begin();
4922 while ( itStr != _strings.end() && itStr->IsLess( str ))
4924 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4925 return true; // same ID already kept
4927 const int minPrefixSize = 4;
4929 // count "smaller" strings with the same prefix
4930 std::list< _AString >::iterator itLess = itStr; --itLess;
4932 for ( ; itLess != _strings.end(); --itLess )
4933 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4938 // count "greater" strings with the same prefix
4939 std::list< _AString >::iterator itMore = itStr;
4941 for ( ; itMore != _strings.end(); ++itMore )
4942 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4947 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4949 // look for a maximal prefix length
4950 // int lessPrefSize = 3, morePrefSize = 3;
4951 // if ( nbLess > 0 )
4952 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
4954 // if ( nbMore > 0 )
4955 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
4957 // int prefixSize = 3;
4958 // if ( nbLess == 0 )
4959 // prefixSize = morePrefSize;
4960 // else if ( nbMore == 0 )
4961 // prefixSize = lessPrefSize;
4963 // prefixSize = Min( lessPrefSize, morePrefSize );
4964 int prefixSize = minPrefixSize;
4965 _AString newPrefix ( str, prefixSize );
4967 // look for a proper place within _subFams sorted by _prefix
4968 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
4969 if ( !itSub->_prefix.IsLess( newPrefix ))
4972 // add the new _pyStringFamily
4973 itSub = _subFams.insert( itSub, _pyStringFamily());
4974 _pyStringFamily& newSubFam = *itSub;
4975 newSubFam._prefix = newPrefix;
4977 // pass this->_strings to newSubFam._strings
4978 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
4979 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4980 newSubFam._strings.push_back( str + prefixSize );
4981 for ( ; nbMore > 0; --nbMore, ++itStr )
4982 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4984 _strings.erase( itLess, ++itMore );
4986 else // to few string to make a family fot them
4988 _strings.insert( itStr, str );
4993 //================================================================================
4995 * \brief Finds an object ID in the command
4996 * \param [in] longStr - the command string
4997 * \param [out] subStr - the found object ID
4998 * \return bool - \c true if the object ID found
5000 //================================================================================
5002 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5004 const _AString& longStr = cmd->GetString();
5005 const char* s = longStr.ToCString();
5008 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5009 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5010 if ( argBeg < 4 || argBeg > longStr.Length() )
5012 for ( ; itSub != _subFams.end(); ++itSub )
5015 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5016 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5018 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5019 from = pos + len + itSub->_prefix.Length();
5024 from += itSub->_prefix.Length();
5027 // look among _strings
5028 std::list< _AString >::iterator itStr = _strings.begin();
5029 for ( ; itStr != _strings.end(); ++itStr )
5030 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5031 // check that object ID does not continue after len
5032 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5034 subStr.push_back( *itStr );
5040 //================================================================================
5042 * \brief Return remainder length of the object ID after my _prefix
5043 * \param [in] str - remainder of the command after my _prefix
5044 * \return int - length of the object ID or -1 if not found
5046 //================================================================================
5048 int _pyStringFamily::isIn( const char* str )
5050 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5052 for ( ; itSub != _subFams.end(); ++itSub )
5054 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5057 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5058 return itSub->_prefix.Length() + len;
5063 if ( !_strings.empty() )
5065 std::list< _AString >::iterator itStr = _strings.begin();
5066 bool firstEmpty = itStr->IsEmpty();
5069 for ( ; itStr != _strings.end(); ++itStr )
5071 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5074 len = itStr->Length();
5083 // check that object ID does not continue after len
5084 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5091 //================================================================================
5095 //================================================================================
5097 void _pyStringFamily::Print( int level )
5099 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5100 std::list< _AString >::iterator itStr = _strings.begin();
5101 for ( ; itStr != _strings.end(); ++itStr )
5102 cout << *itStr << " | ";
5104 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5105 for ( ; itSub != _subFams.end(); ++itSub )
5106 itSub->Print( level + 1 );
5108 cout << string( 70, '-' ) << endl;