1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
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 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
388 "Translate","TranslateMakeGroups","TranslateMakeMesh",
389 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
390 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
391 ,"" }; // <- mark of the end
392 methodsAcceptingList.Insert( methodNames );
394 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
396 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
398 const _AString & arg = theCommand->GetArg( i );
399 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
400 arg.Search( "SMESH.DirStruct" ) == 1 )
402 Handle(_pyCommand) workCmd = new _pyCommand( arg );
403 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
405 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
407 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
409 _AString newArg = "[ ";
410 newArg += ( workCmd->GetArg( 1 ) + ", " +
411 workCmd->GetArg( 2 ) + ", " +
412 workCmd->GetArg( 3 ) + " ]");
413 theCommand->SetArg( i, newArg );
419 //================================================================================
421 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
422 * a list "[id1,id2]" if the list is an accesible type of argument.
424 //================================================================================
426 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
428 static TStringSet methodsAcceptingList;
429 if ( methodsAcceptingList.empty() ) {
430 const char * methodNames[] = {
431 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
432 "ExportCGNS","ExportGMF",
433 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
434 "ScaleMakeGroups","Scale","ScaleMakeMesh",
435 "FindCoincidentNodesOnPartBut","DoubleElements",
436 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
437 ,"" }; // <- mark of the end
438 methodsAcceptingList.Insert( methodNames );
440 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
442 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
444 _pyCommand argCmd( theCommand->GetArg( i ));
445 if ( argCmd.GetMethod() == "GetIDSource" &&
446 argCmd.GetNbArgs() == 2 )
448 theCommand->SetArg( i, argCmd.GetArg( 1 ));
455 //================================================================================
457 * \brief Convert a python script using commands of smeshBuilder.py
458 * \param theScriptLines - Lines of the input script
459 * \param theEntry2AccessorMethod - returns method names to access to
460 * objects wrapped with python class
461 * \param theObjectNames - names of objects
462 * \param theRemovedObjIDs - entries of objects whose created commands were removed
463 * \param theHistoricalDump - true means to keep all commands, false means
464 * to exclude commands relating to objects removed from study
465 * \retval TCollection_AsciiString - Convertion result
467 //================================================================================
470 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
471 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
472 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
473 std::set< TCollection_AsciiString >& theRemovedObjIDs,
474 SALOMEDS::Study_ptr& theStudy,
475 const bool theToKeepAllCommands)
477 std::list< TCollection_AsciiString >::iterator lineIt;
478 // process notebook variables
480 SMESH_NoteBook aNoteBook;
482 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
483 aNoteBook.AddCommand( *lineIt );
485 theScriptLines.clear();
487 aNoteBook.ReplaceVariables();
489 aNoteBook.GetResultLines( theScriptLines );
492 // convert to smeshBuilder.py API
494 theGen = new _pyGen( theEntry2AccessorMethod,
498 theToKeepAllCommands );
500 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
501 theGen->AddCommand( *lineIt );
503 theScriptLines.clear();
507 #ifdef DUMP_CONVERSION
508 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
511 // clean commmands of removed objects depending on myIsPublished flag
512 theGen->ClearCommands();
514 // reorder commands after conversion
515 list< Handle(_pyCommand) >::iterator cmd;
518 orderChanges = false;
519 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
520 if ( (*cmd)->SetDependentCmdsAfter() )
522 } while ( orderChanges );
524 // concat commands back into a script
525 TCollection_AsciiString aPrevCmd;
526 set<_pyID> createdObjects;
527 createdObjects.insert( "smeshBuilder" );
528 createdObjects.insert( "smesh" );
529 createdObjects.insert( "theStudy" );
530 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
532 #ifdef DUMP_CONVERSION
533 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
535 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
536 CheckObjectPresence( *cmd, createdObjects );
537 if ( !(*cmd)->IsEmpty() ) {
538 aPrevCmd = (*cmd)->GetString();
539 theScriptLines.push_back( aPrevCmd );
548 //================================================================================
550 * \brief _pyGen constructor
552 //================================================================================
554 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
555 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
556 std::set< TCollection_AsciiString >& theRemovedObjIDs,
557 SALOMEDS::Study_ptr& theStudy,
558 const bool theToKeepAllCommands)
559 : _pyObject( new _pyCommand( "", 0 )),
561 myID2AccessorMethod( theEntry2AccessorMethod ),
562 myObjectNames( theObjectNames ),
563 myRemovedObjIDs( theRemovedObjIDs ),
565 myToKeepAllCommands( theToKeepAllCommands ),
566 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
567 myGeomIDNb(0), myGeomIDIndex(-1)
569 // make that GetID() to return TPythonDump::SMESHGenName()
570 GetCreationCmd()->Clear();
571 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
572 GetCreationCmd()->GetString() += "=";
574 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
575 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
579 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
580 if ( geomComp->_is_nil() ) return;
581 CORBA::String_var entry = geomComp->GetID();
584 // find a SMESH entry
586 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
587 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
588 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
591 // find 1st difference between smeshID and geomID
592 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
593 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
594 if ( geomID.Value( i ) != smeshID.Value( i ))
596 myGeomIDNb = geomID.Value( i );
602 //================================================================================
604 * \brief name of SMESH_Gen in smeshBuilder.py
606 //================================================================================
608 const char* _pyGen::AccessorMethod() const
610 return SMESH_2smeshpy::GenName();
613 //================================================================================
615 * \brief Convert a command using a specific converter
616 * \param theCommand - the command to convert
618 //================================================================================
620 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
622 // store theCommand in the sequence
623 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
625 Handle(_pyCommand) aCommand = myCommands.back();
626 #ifdef DUMP_CONVERSION
627 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
630 const _pyID& objID = aCommand->GetObject();
632 if ( objID.IsEmpty() )
635 // Prevent moving a command creating a sub-mesh to the end of the script
636 // if the sub-mesh is used in theCommand as argument
637 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
639 // PlaceSubmeshAfterItsCreation( aCommand );
642 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
643 StructToList( aCommand );
645 const TCollection_AsciiString& method = aCommand->GetMethod();
647 // not to erase _pySelfEraser's etc. used as args in some commands
649 #ifdef USE_STRING_FAMILY
650 std::list<_pyID> objIDs;
651 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
653 std::list<_pyID>::iterator objID = objIDs.begin();
654 for ( ; objID != objIDs.end(); ++objID )
656 Handle(_pyObject) obj = FindObject( *objID );
659 obj->AddArgCmd( aCommand );
660 //cout << objID << " found in " << theCommand << endl;
665 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
666 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
667 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
669 Handle(_pyObject) obj = FindObject( *id );
671 obj->AddArgCmd( aCommand );
676 // Find an object to process theCommand
679 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
681 this->Process( aCommand );
682 //addFilterUser( aCommand, theGen ); // protect filters from clearing
686 // SMESH_Mesh method?
687 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
688 if ( id_mesh != myMeshes.end() )
690 //id_mesh->second->AddProcessedCmd( aCommand );
692 // check for mesh editor object
693 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
694 _pyID editorID = aCommand->GetResultValue();
695 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
696 myMeshEditors.insert( make_pair( editorID, editor ));
699 // check for SubMesh objects
700 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
701 _pyID subMeshID = aCommand->GetResultValue();
702 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
703 AddObject( subMesh );
706 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
707 GetIDSourceToList( aCommand );
709 //addFilterUser( aCommand, theGen ); // protect filters from clearing
711 id_mesh->second->Process( aCommand );
712 id_mesh->second->AddProcessedCmd( aCommand );
716 // SMESH_MeshEditor method?
717 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
718 if ( id_editor != myMeshEditors.end() )
720 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
721 GetIDSourceToList( aCommand );
723 //addFilterUser( aCommand, theGen ); // protect filters from clearing
725 // some commands of SMESH_MeshEditor create meshes and groups
726 _pyID meshID, groups;
727 if ( method.Search("MakeMesh") != -1 )
728 meshID = aCommand->GetResultValue();
729 else if ( method == "MakeBoundaryMesh")
730 meshID = aCommand->GetResultValue(1);
731 else if ( method == "MakeBoundaryElements")
732 meshID = aCommand->GetResultValue(2);
734 if ( method.Search("MakeGroups") != -1 ||
735 method == "ExtrusionAlongPathX" ||
736 method == "ExtrusionAlongPathObjX" ||
737 method == "DoubleNodeGroupNew" ||
738 method == "DoubleNodeGroupsNew" ||
739 method == "DoubleNodeElemGroupNew" ||
740 method == "DoubleNodeElemGroupsNew"||
741 method == "DoubleNodeElemGroup2New"||
742 method == "DoubleNodeElemGroups2New"
744 groups = aCommand->GetResultValue();
745 else if ( method == "MakeBoundaryMesh" )
746 groups = aCommand->GetResultValue(2);
747 else if ( method == "MakeBoundaryElements")
748 groups = aCommand->GetResultValue(3);
749 else if ( method == "Create0DElementsOnAllNodes" &&
750 aCommand->GetArg(2).Length() > 2 ) // group name != ''
751 groups = aCommand->GetResultValue();
753 id_editor->second->Process( aCommand );
754 id_editor->second->AddProcessedCmd( aCommand );
757 if ( !meshID.IsEmpty() &&
758 !myMeshes.count( meshID ) &&
759 aCommand->IsStudyEntry( meshID ))
761 _AString processedCommand = aCommand->GetString();
762 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
763 CheckObjectIsReCreated( mesh );
764 myMeshes.insert( make_pair( meshID, mesh ));
766 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
769 if ( !groups.IsEmpty() )
771 if ( !aCommand->IsStudyEntry( meshID ))
772 meshID = id_editor->second->GetMesh();
773 Handle(_pyMesh) mesh = myMeshes[ meshID ];
775 list< _pyID > idList = aCommand->GetStudyEntries( groups );
776 list< _pyID >::iterator grID = idList.begin();
777 for ( ; grID != idList.end(); ++grID )
778 if ( !myObjects.count( *grID ))
780 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
782 if ( !mesh.IsNull() ) mesh->AddGroup( group );
786 } // SMESH_MeshEditor methods
788 // SMESH_Hypothesis method?
789 Handle(_pyHypothesis) hyp = FindHyp( objID );
790 if ( !hyp.IsNull() && !hyp->IsAlgo() )
792 hyp->Process( aCommand );
793 hyp->AddProcessedCmd( aCommand );
797 // aFilterManager.CreateFilter() ?
798 if ( aCommand->GetMethod() == "CreateFilter" )
800 // Set a more human readable name to a filter
801 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
802 _pyID newID, filterID = aCommand->GetResultValue();
803 int pos = filterID.Search( "0x" );
805 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
807 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
810 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
811 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
813 // create _pySelfEraser for functors
814 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
815 functor->IgnoreOwnCalls(); // to erase if not used as an argument
816 AddObject( functor );
819 // other object method?
820 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
821 if ( id_obj != myObjects.end() ) {
822 id_obj->second->Process( aCommand );
823 id_obj->second->AddProcessedCmd( aCommand );
827 // Add access to a wrapped mesh
828 AddMeshAccessorMethod( aCommand );
830 // Add access to a wrapped algorithm
831 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
833 // PAL12227. PythonDump was not updated at proper time; result is
834 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
835 // TypeError: __init__() takes exactly 11 arguments (10 given)
836 const char wrongCommand[] = "SMESH.Filter.Criterion(";
837 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
839 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
840 // there must be 10 arguments, 5-th arg ThresholdID is missing,
841 const int wrongNbArgs = 9, missingArg = 5;
842 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
844 for ( int i = wrongNbArgs; i > missingArg; --i )
845 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
846 tmpCmd.SetArg( missingArg, "''");
847 aCommand->GetString().Trunc( beg - 1 );
848 aCommand->GetString() += tmpCmd.GetString();
851 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
853 // instead of "SMESH.Filter.Criterion(
854 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
855 // 1 2 3 4 5 6 7 8 9 10
856 // in order to avoid the problem of type mismatch of long and FunctorType
857 const TCollection_AsciiString
858 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
859 TCollection_AsciiString
860 Type = aCommand->GetArg(1), // long
861 Compare = aCommand->GetArg(2), // long
862 Threshold = aCommand->GetArg(3), // double
863 ThresholdStr = aCommand->GetArg(4), // string
864 ThresholdID = aCommand->GetArg(5), // string
865 UnaryOp = aCommand->GetArg(6), // long
866 BinaryOp = aCommand->GetArg(7), // long
867 Tolerance = aCommand->GetArg(8), // double
868 TypeOfElement = aCommand->GetArg(9), // ElementType
869 Precision = aCommand->GetArg(10); // long
870 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
871 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
872 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
873 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
874 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
876 if ( Compare == "SMESH.FT_EqualTo" )
879 aCommand->RemoveArgs();
880 aCommand->SetObject( SMESH_2smeshpy::GenName() );
881 aCommand->SetMethod( "GetCriterion" );
883 aCommand->SetArg( 1, TypeOfElement );
884 aCommand->SetArg( 2, Type );
885 aCommand->SetArg( 3, Compare );
887 if ( Threshold.IsIntegerValue() )
889 int iGeom = Threshold.IntegerValue();
890 if ( Type == "SMESH.FT_ElemGeomType" )
892 // set SMESH.GeometryType instead of a numerical Threshold
893 const int nbTypes = SMESH::Geom_LAST;
894 const char* types[nbTypes] = {
895 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
896 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
897 "Geom_POLYHEDRA", "Geom_BALL" };
898 if ( -1 < iGeom && iGeom < nbTypes )
899 Threshold = SMESH + types[ iGeom ];
901 // is types complete? (compilation failure mains that enum GeometryType changed)
902 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ];
905 if (Type == "SMESH.FT_EntityType")
907 // set SMESH.EntityType instead of a numerical Threshold
908 const int nbTypes = SMESH::Entity_Last;
909 const char* types[nbTypes] = {
910 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
911 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
912 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
913 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
914 "Entity_Pyramid", "Entity_Quad_Pyramid",
915 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
916 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
917 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
918 if ( -1 < iGeom && iGeom < nbTypes )
919 Threshold = SMESH + types[ iGeom ];
921 // is types complete? (compilation failure mains that enum EntityType changed)
922 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ];
926 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
927 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
928 else if ( ThresholdStr.Length() != 2 )
929 aCommand->SetArg( 4, ThresholdStr );
930 else if ( ThresholdID.Length() != 2 )
931 aCommand->SetArg( 4, ThresholdID );
933 aCommand->SetArg( 4, Threshold );
934 // find the last not default arg
936 if ( Tolerance == dfltTol ) {
938 if ( BinaryOp == dfltFunctor ) {
940 if ( UnaryOp == dfltFunctor )
944 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
945 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
946 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
947 if ( Precision != dfltPreci )
949 TCollection_AsciiString crit = aCommand->GetResultValue();
950 aCommand->GetString() += "; ";
951 aCommand->GetString() += crit + ".Precision = " + Precision;
957 //================================================================================
959 * \brief Convert the command or remember it for later conversion
960 * \param theCommand - The python command calling a method of SMESH_Gen
962 //================================================================================
964 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
966 // there are methods to convert:
967 // CreateMesh( shape )
968 // Concatenate( [mesh1, ...], ... )
969 // CreateHypothesis( theHypType, theLibName )
970 // Compute( mesh, geom )
971 // Evaluate( mesh, geom )
973 TCollection_AsciiString method = theCommand->GetMethod();
975 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
977 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
981 if ( method == "CreateMeshesFromUNV" ||
982 method == "CreateMeshesFromSTL" ||
983 method == "CopyMesh" ) // command result is a mesh
985 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
989 if( method == "CreateMeshesFromMED" ||
990 method == "CreateMeshesFromSAUV"||
991 method == "CreateMeshesFromCGNS" ||
992 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
994 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
995 std::list< _pyID >::iterator meshID = meshIDs.begin();
996 for ( ; meshID != meshIDs.end(); ++meshID )
998 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1001 if ( method == "CreateMeshesFromGMF" )
1003 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1004 // CreateMeshesFromGMF( theFileName )
1005 _AString file = theCommand->GetArg(1);
1006 theCommand->RemoveArgs();
1007 theCommand->SetArg( 1, file );
1011 // CreateHypothesis()
1012 if ( method == "CreateHypothesis" )
1014 // issue 199929, remove standard library name (default parameter)
1015 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1016 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1017 // keep the first argument
1018 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1019 theCommand->RemoveArgs();
1020 theCommand->SetArg( 1, arg );
1023 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1024 CheckObjectIsReCreated( hyp );
1025 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1030 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1031 if ( method == "Compute" )
1033 const _pyID& meshID = theCommand->GetArg( 1 );
1034 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1035 if ( id_mesh != myMeshes.end() ) {
1036 theCommand->SetObject( meshID );
1037 theCommand->RemoveArgs();
1038 id_mesh->second->Process( theCommand );
1039 id_mesh->second->AddProcessedCmd( theCommand );
1044 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1045 if ( method == "Evaluate" )
1047 const _pyID& meshID = theCommand->GetArg( 1 );
1048 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1049 if ( id_mesh != myMeshes.end() ) {
1050 theCommand->SetObject( meshID );
1051 _pyID geom = theCommand->GetArg( 2 );
1052 theCommand->RemoveArgs();
1053 theCommand->SetArg( 1, geom );
1054 id_mesh->second->AddProcessedCmd( theCommand );
1059 // objects erasing creation command if no more its commands invoked:
1060 // SMESH_Pattern, FilterManager
1061 if ( method == "GetPattern" ||
1062 method == "CreateFilterManager" ||
1063 method == "CreateMeasurements" )
1065 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1066 if ( !AddObject( obj ) )
1067 theCommand->Clear(); // already created
1069 // Concatenate( [mesh1, ...], ... )
1070 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1072 if ( method == "ConcatenateWithGroups" ) {
1073 theCommand->SetMethod( "Concatenate" );
1074 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1076 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1078 AddMeshAccessorMethod( theCommand );
1080 else if ( method == "SetName" ) // SetName(obj,name)
1082 // store theCommand as one of object commands to erase it along with the object
1083 const _pyID& objID = theCommand->GetArg( 1 );
1084 Handle(_pyObject) obj = FindObject( objID );
1085 if ( !obj.IsNull() )
1086 obj->AddProcessedCmd( theCommand );
1089 // Replace name of SMESH_Gen
1091 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1092 static TStringSet smeshpyMethods;
1093 if ( smeshpyMethods.empty() ) {
1094 const char * names[] =
1095 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1096 "GetPattern","GetSubShapesId",
1097 "" }; // <- mark of array end
1098 smeshpyMethods.Insert( names );
1100 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1101 // smeshgen.Method() --> smesh.Method()
1102 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1104 // smeshgen.Method() --> smesh.Method()
1105 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1108 //================================================================================
1110 * \brief Convert the remembered commands
1112 //================================================================================
1114 void _pyGen::Flush()
1116 // create an empty command
1117 myLastCommand = new _pyCommand();
1119 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1120 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1121 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1123 if ( IsToKeepAllCommands() ) // historical dump
1125 // set myIsPublished = true to all objects
1126 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1127 id_mesh->second->SetRemovedFromStudy( false );
1128 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1129 id_hyp->second->SetRemovedFromStudy( false );
1130 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1131 id_obj->second->SetRemovedFromStudy( false );
1135 // let hypotheses find referred objects in order to prevent clearing
1136 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1137 list< Handle(_pyMesh) > fatherMeshes;
1138 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1139 if ( !id_hyp->second.IsNull() )
1140 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1142 // set myIsPublished = false to all objects depending on
1143 // meshes built on a removed geometry
1144 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1145 if ( id_mesh->second->IsNotGeomPublished() )
1146 id_mesh->second->SetRemovedFromStudy( true );
1149 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1150 if ( ! id_mesh->second.IsNull() )
1151 id_mesh->second->Flush();
1154 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1155 if ( !id_hyp->second.IsNull() ) {
1156 id_hyp->second->Flush();
1157 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1158 if ( !id_hyp->second->IsWrapped() )
1159 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1162 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1163 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1164 for ( ; robj != myOrderedObjects.rend(); ++robj )
1165 if ( ! robj->IsNull() )
1167 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1168 for ( ; obj != myOrderedObjects.end(); ++obj )
1169 if ( ! obj->IsNull() )
1172 myLastCommand->SetOrderNb( ++myNbCommands );
1173 myCommands.push_back( myLastCommand );
1176 //================================================================================
1178 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1179 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1181 //================================================================================
1183 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1185 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1186 // for ( ; id_obj != myObjects.end(); ++id_obj )
1188 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1189 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1191 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1192 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1194 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1195 // list< _pyID >::iterator id = idList.begin();
1196 // for ( ; id != idList.end(); ++id )
1197 // if ( id_obj->first == *id )
1198 // // _pySubMesh::Process() does what we need
1199 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1204 //================================================================================
1206 * \brief Clean commmands of removed objects depending on myIsPublished flag
1208 //================================================================================
1210 void _pyGen::ClearCommands()
1212 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1213 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1214 id_mesh->second->ClearCommands();
1216 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1217 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1218 if ( !id_hyp->second.IsNull() )
1219 id_hyp->second->ClearCommands();
1221 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1222 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1223 for ( ; robj != myOrderedObjects.rend(); ++robj )
1224 if ( ! robj->IsNull() )
1225 (*robj)->ClearCommands();
1226 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1227 for ( ; obj != myOrderedObjects.end(); ++obj )
1228 if ( ! obj->IsNull() )
1229 (*obj)->ClearCommands();
1232 //================================================================================
1234 * \brief Release mutual handles of objects
1236 //================================================================================
1240 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1241 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1242 id_mesh->second->Free();
1245 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1246 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1247 id_ed->second->Free();
1248 myMeshEditors.clear();
1250 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1251 for ( ; id_obj != myObjects.end(); ++id_obj )
1252 id_obj->second->Free();
1255 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1256 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1257 if ( !id_hyp->second.IsNull() )
1258 id_hyp->second->Free();
1261 myFile2ExportedMesh.clear();
1263 //myKeepAgrCmdsIDs.Print();
1266 //================================================================================
1268 * \brief Add access method to mesh that is an argument
1269 * \param theCmd - command to add access method
1270 * \retval bool - true if added
1272 //================================================================================
1274 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1277 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1278 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1279 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1285 //================================================================================
1287 * \brief Add access method to algo that is an object or an argument
1288 * \param theCmd - command to add access method
1289 * \retval bool - true if added
1291 //================================================================================
1293 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1296 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1297 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1298 if ( !id_hyp->second.IsNull() &&
1299 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1300 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1301 id_hyp->second->AccessorMethod() ))
1307 //================================================================================
1309 * \brief Find hypothesis by ID (entry)
1310 * \param theHypID - The hypothesis ID
1311 * \retval Handle(_pyHypothesis) - The found hypothesis
1313 //================================================================================
1315 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1317 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1318 if ( id_hyp != myHypos.end() &&
1319 !id_hyp->second.IsNull() &&
1320 theHypID == id_hyp->second->GetID() )
1321 return id_hyp->second;
1322 return Handle(_pyHypothesis)();
1325 //================================================================================
1327 * \brief Find algorithm able to create a hypothesis
1328 * \param theGeom - The shape ID the algorithm was created on
1329 * \param theMesh - The mesh ID that created the algorithm
1330 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1331 * \retval Handle(_pyHypothesis) - The found algo
1333 //================================================================================
1335 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1336 const Handle(_pyHypothesis)& theHypothesis )
1338 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1339 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1340 if ( !id_hyp->second.IsNull() &&
1341 id_hyp->second->IsAlgo() &&
1342 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1343 id_hyp->second->GetGeom() == theGeom &&
1344 id_hyp->second->GetMesh() == theMesh )
1345 return id_hyp->second;
1346 return Handle(_pyHypothesis)();
1349 //================================================================================
1351 * \brief Find subMesh by ID (entry)
1352 * \param theSubMeshID - The subMesh ID
1353 * \retval Handle(_pySubMesh) - The found subMesh
1355 //================================================================================
1357 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1359 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1360 if ( id_subMesh != myObjects.end() )
1361 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1362 return Handle(_pySubMesh)();
1366 //================================================================================
1368 * \brief Change order of commands in the script
1369 * \param theCmd1 - One command
1370 * \param theCmd2 - Another command
1372 //================================================================================
1374 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1376 list< Handle(_pyCommand) >::iterator pos1, pos2;
1377 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1378 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1379 myCommands.insert( pos1, theCmd2 );
1380 myCommands.insert( pos2, theCmd1 );
1381 myCommands.erase( pos1 );
1382 myCommands.erase( pos2 );
1384 int nb1 = theCmd1->GetOrderNb();
1385 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1386 theCmd2->SetOrderNb( nb1 );
1387 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1388 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1391 //================================================================================
1393 * \brief Set one command after the other
1394 * \param theCmd - Command to move
1395 * \param theAfterCmd - Command ater which to insert the first one
1397 //================================================================================
1399 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1401 setNeighbourCommand( theCmd, theAfterCmd, true );
1404 //================================================================================
1406 * \brief Set one command before the other
1407 * \param theCmd - Command to move
1408 * \param theBeforeCmd - Command before which to insert the first one
1410 //================================================================================
1412 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1414 setNeighbourCommand( theCmd, theBeforeCmd, false );
1417 //================================================================================
1419 * \brief Set one command before or after the other
1420 * \param theCmd - Command to move
1421 * \param theOtherCmd - Command ater or before which to insert the first one
1423 //================================================================================
1425 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1426 Handle(_pyCommand)& theOtherCmd,
1427 const bool theIsAfter )
1429 list< Handle(_pyCommand) >::iterator pos;
1430 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1431 myCommands.erase( pos );
1432 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1433 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1436 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1437 (*pos)->SetOrderNb( i++ );
1440 //================================================================================
1442 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1444 //================================================================================
1446 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1448 // No more needed after adding _pyObject::myArgCommands
1450 // const char filterPrefix[] = "aFilter0x";
1451 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1454 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1456 // const _AString & arg = theCommand->GetArg( i );
1457 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1458 // if ( arg.Search( filterPrefix ) != 1 )
1461 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1462 // if ( !filter.IsNull() )
1464 // filter->AddUser( user );
1465 // if ( !filter->GetNewID().IsEmpty() )
1466 // theCommand->SetArg( i, filter->GetNewID() );
1471 //================================================================================
1473 * \brief Set command be last in list of commands
1474 * \param theCmd - Command to be last
1476 //================================================================================
1478 Handle(_pyCommand)& _pyGen::GetLastCommand()
1480 return myLastCommand;
1483 //================================================================================
1485 * \brief Set method to access to object wrapped with python class
1486 * \param theID - The wrapped object entry
1487 * \param theMethod - The accessor method
1489 //================================================================================
1491 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1493 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1496 //================================================================================
1498 * \brief Generated new ID for object and assign with existing name
1499 * \param theID - ID of existing object
1501 //================================================================================
1503 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1508 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1510 while ( myObjectNames.IsBound( aNewID ) );
1512 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1513 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1514 : _pyID( "A" ) + aNewID );
1518 //================================================================================
1520 * \brief Stores theObj in myObjects
1522 //================================================================================
1524 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1526 if ( theObj.IsNull() ) return false;
1528 CheckObjectIsReCreated( theObj );
1532 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1533 add = myMeshes.insert( make_pair( theObj->GetID(),
1534 Handle(_pyMesh)::DownCast( theObj ))).second;
1536 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1537 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1538 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1541 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1542 if ( add ) myOrderedObjects.push_back( theObj );
1547 //================================================================================
1549 * \brief Erases an existing object with the same ID. This method should be called
1550 * before storing theObj in _pyGen
1552 //================================================================================
1554 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1556 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1559 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1560 Handle(_pyObject) existing =
1561 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1562 if ( !existing.IsNull() && existing != theObj )
1564 existing->SetRemovedFromStudy( true );
1565 existing->ClearCommands();
1568 if ( myHypos.count( theObj->GetID() ))
1569 myHypos.erase( theObj->GetID() );
1571 else if ( myMeshes.count( theObj->GetID() ))
1573 myMeshes.erase( theObj->GetID() );
1575 else if ( myObjects.count( theObj->GetID() ))
1577 myObjects.erase( theObj->GetID() );
1582 //================================================================================
1584 * \brief Re-register an object with other ID to make it Process() commands of
1585 * other object having this ID
1587 //================================================================================
1589 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1591 if ( theObj.IsNull() ) return;
1593 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1594 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1596 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1597 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1600 myObjects.insert( make_pair( theID, theObj ));
1603 //================================================================================
1605 * \brief Finds a _pyObject by ID
1607 //================================================================================
1609 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1612 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1613 if ( id_obj != myObjects.end() )
1614 return id_obj->second;
1617 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1618 if ( id_obj != myMeshes.end() )
1619 return id_obj->second;
1622 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1623 // if ( id_obj != myMeshEditors.end() )
1624 // return id_obj->second;
1626 return Handle(_pyObject)();
1629 //================================================================================
1631 * \brief Check if a study entry is under GEOM component
1633 //================================================================================
1635 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1639 return ( myGeomIDIndex <= theObjID.Length() &&
1640 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1641 _pyCommand::IsStudyEntry( theObjID ));
1646 //================================================================================
1648 * \brief Returns true if an object is not present in a study
1650 //================================================================================
1652 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1654 if ( theObjID.IsEmpty() ) return false;
1656 if ( myObjectNames.IsBound( theObjID ))
1657 return false; // SMESH object is in study
1659 // either the SMESH object is not in study or it is a GEOM object
1660 if ( IsGeomObject( theObjID ))
1662 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1663 if ( so->_is_nil() ) return true;
1664 CORBA::Object_var obj = so->GetObject();
1665 return CORBA::is_nil( obj );
1667 return true; // SMESH object not in study
1670 //================================================================================
1672 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1673 * this object is not dumped
1674 * \param [in] theObjID - entry of the object whose creation command was eliminated
1676 //================================================================================
1678 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1680 myRemovedObjIDs.insert( theObjID );
1683 //================================================================================
1685 * \brief Return reader of hypotheses of plugins
1687 //================================================================================
1689 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1691 if (myHypReader.IsNull() )
1692 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1698 //================================================================================
1700 * \brief Mesh created by SMESH_Gen
1702 //================================================================================
1704 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1705 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1707 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1708 myGeomNotInStudy = true;
1710 // convert my creation command --> smeshpy.Mesh(...)
1711 Handle(_pyCommand) creationCmd = GetCreationCmd();
1712 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1713 creationCmd->SetMethod( "Mesh" );
1714 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1717 //================================================================================
1719 * \brief Mesh created by SMESH_MeshEditor
1721 //================================================================================
1723 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1724 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1726 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1728 // this mesh depends on the exported mesh
1729 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1730 if ( !file.IsEmpty() )
1732 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1733 addFatherMesh( exportData.myMesh );
1734 if ( !exportData.myLastComputeCmd.IsNull() )
1736 // restore cleared Compute() by which the exported mesh was generated
1737 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1738 // protect that Compute() cmd from clearing
1739 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1740 exportData.myMesh->myLastComputeCmd.Nullify();
1744 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1746 // this mesh depends on concatenated meshes
1747 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1748 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1749 list< _pyID >::iterator meshID = idList.begin();
1750 for ( ; meshID != idList.end(); ++meshID )
1751 addFatherMesh( *meshID );
1753 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1755 // this mesh depends on a copied IdSource
1756 const _pyID& objID = theCreationCmd->GetArg( 1 );
1757 addFatherMesh( objID );
1759 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1760 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1761 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1763 // this mesh depends on a source mesh
1764 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1765 const _pyID& meshID = theCreationCmd->GetObject();
1766 addFatherMesh( meshID );
1769 // convert my creation command
1770 Handle(_pyCommand) creationCmd = GetCreationCmd();
1771 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1772 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1775 //================================================================================
1777 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1778 * \param theCommand - Engine method called for this mesh
1780 //================================================================================
1782 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1784 // some methods of SMESH_Mesh interface needs special conversion
1785 // to methods of Mesh python class
1787 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1788 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1789 // 2. AddHypothesis(geom, hyp)
1790 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1791 // 3. CreateGroupFromGEOM(type, name, grp)
1792 // --> in Mesh.Group(grp, name="")
1793 // 4. ExportToMED(f, auto_groups, version)
1794 // --> in Mesh.ExportMED( f, auto_groups, version )
1797 const TCollection_AsciiString& method = theCommand->GetMethod();
1798 // ----------------------------------------------------------------------
1799 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1801 if ( !theGen->IsToKeepAllCommands() ) // !historical
1803 list< Handle(_pyHypothesis) >::iterator hyp;
1804 if ( !myLastComputeCmd.IsNull() )
1806 // check if the previously computed mesh has been edited,
1807 // if so then we do not clear the previous Compute()
1808 bool toClear = true;
1809 if ( myLastComputeCmd->GetMethod() == "Compute" )
1811 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1812 for ( ; e != myEditors.end() && toClear; ++e )
1814 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1815 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1816 if ( cmd != cmds.rend() &&
1817 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1823 // clear hyp commands called before myLastComputeCmd
1824 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1825 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1827 myLastComputeCmd->Clear();
1830 myLastComputeCmd = theCommand;
1832 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1833 (*hyp)->MeshComputed( myLastComputeCmd );
1837 // ----------------------------------------------------------------------
1838 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1840 if ( !theGen->IsToKeepAllCommands() ) // !historical
1843 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1844 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1845 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1847 if ( !myLastComputeCmd.IsNull() )
1849 list< Handle(_pyHypothesis) >::iterator hyp;
1850 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1851 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1853 myLastComputeCmd->Clear();
1856 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1857 for ( ; e != myEditors.end(); ++e )
1859 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1860 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1861 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1862 if ( !(*cmd)->IsEmpty() )
1864 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1868 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1871 // ----------------------------------------------------------------------
1872 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1873 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1874 if ( !subMesh.IsNull() ) {
1875 subMesh->SetCreator( this );
1876 mySubmeshes.push_back( subMesh );
1879 // ----------------------------------------------------------------------
1880 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1881 myAddHypCmds.push_back( theCommand );
1883 const _pyID& hypID = theCommand->GetArg( 2 );
1884 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1885 if ( !hyp.IsNull() ) {
1886 myHypos.push_back( hyp );
1887 if ( hyp->GetMesh().IsEmpty() )
1888 hyp->SetMesh( this->GetID() );
1891 // ----------------------------------------------------------------------
1892 else if ( method == "CreateGroup" ||
1893 method == "CreateGroupFromGEOM" ||
1894 method == "CreateGroupFromFilter" )
1896 Handle(_pyGroup) group = new _pyGroup( theCommand );
1897 myGroups.push_back( group );
1898 theGen->AddObject( group );
1900 // ----------------------------------------------------------------------
1901 // update list of groups
1902 else if ( method == "GetGroups" )
1904 bool allGroupsRemoved = true;
1905 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1906 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1907 list< _pyID >::iterator grID = idList.begin();
1908 const int nbGroupsBefore = myGroups.size();
1909 Handle(_pyObject) obj;
1910 for ( ; grID != idList.end(); ++grID )
1912 obj = theGen->FindObject( *grID );
1915 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1916 theGen->AddObject( group );
1917 myGroups.push_back( group );
1920 if ( !obj->CanClear() )
1921 allGroupsRemoved = false;
1923 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1924 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1926 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1928 // check if the preceding command is Compute();
1929 // if GetGroups() is just after Compute(), this can mean that the groups
1930 // were created by some algorithm and hence Compute() should not be discarded
1931 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1932 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1933 while ( (*cmd)->GetMethod() == "GetGroups" )
1935 if ( myLastComputeCmd == (*cmd))
1936 // protect last Compute() from clearing by the next Compute()
1937 myLastComputeCmd.Nullify();
1940 // ----------------------------------------------------------------------
1941 // notify a group about full removal
1942 else if ( method == "RemoveGroupWithContents" ||
1943 method == "RemoveGroup")
1945 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1946 const _pyID groupID = theCommand->GetArg( 1 );
1947 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1948 if ( !grp.IsNull() )
1950 if ( method == "RemoveGroupWithContents" )
1951 grp->RemovedWithContents();
1952 // to clear RemoveGroup() if the group creation is cleared
1953 grp->AddProcessedCmd( theCommand );
1957 // ----------------------------------------------------------------------
1958 else if ( theCommand->MethodStartsFrom( "Export" ))
1960 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1961 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1963 theCommand->SetMethod( "ExportMED" );
1964 if ( theCommand->GetNbArgs() == 5 )
1966 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1967 _AString autoDimension = theCommand->GetArg( 5 );
1968 theCommand->SetArg( 5, "None" );
1969 theCommand->SetArg( 6, autoDimension );
1972 else if ( method == "ExportCGNS" )
1973 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1974 _pyID partID = theCommand->GetArg( 1 );
1975 int nbArgs = theCommand->GetNbArgs();
1976 for ( int i = 2; i <= nbArgs; ++i )
1977 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1978 theCommand->SetArg( nbArgs, partID );
1980 else if ( method == "ExportGMF" )
1981 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1982 _pyID partID = theCommand->GetArg( 1 );
1983 _AString file = theCommand->GetArg( 2 );
1984 theCommand->RemoveArgs();
1985 theCommand->SetArg( 1, file );
1986 theCommand->SetArg( 2, partID );
1988 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1989 { // ExportPartTo*(part, ...) -> Export*(..., part)
1991 // remove "PartTo" from the method
1992 TCollection_AsciiString newMethod = method;
1993 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
1994 theCommand->SetMethod( newMethod );
1995 // make the 1st arg be the last one (or last but three for ExportMED())
1996 _pyID partID = theCommand->GetArg( 1 );
1997 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
1998 for ( int i = 2; i <= nbArgs; ++i )
1999 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2000 theCommand->SetArg( nbArgs, partID );
2002 // remember file name
2003 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2004 ExportedMeshData( this, myLastComputeCmd ));
2006 // ----------------------------------------------------------------------
2007 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2009 _pyID hypID = theCommand->GetArg( 2 );
2010 _pyID geomID = theCommand->GetArg( 1 );
2011 bool isLocal = ( geomID != GetGeom() );
2013 // check if this mesh still has corresponding addition command
2014 Handle(_pyCommand) addCmd;
2015 list< Handle(_pyCommand) >::iterator cmd;
2016 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2017 for ( int i = 0; i < 2; ++i )
2019 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2020 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2022 bool sameHyp = true;
2023 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2024 sameHyp = false; // other hyp
2025 if ( (*cmd)->GetNbArgs() == 2 &&
2026 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2027 sameHyp = false; // other geom
2028 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2029 sameHyp = false; // other geom
2033 cmd = addHypCmds.erase( cmd );
2034 if ( !theGen->IsToKeepAllCommands() && CanClear() ) {
2036 theCommand->Clear();
2040 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2041 addCmd->RemoveArgs();
2042 addCmd->SetArg( 1, hypID );
2044 addCmd->SetArg( 2, geomID );
2053 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2054 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2055 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2056 _pyID geom = theCommand->GetArg( 1 );
2057 theCommand->RemoveArgs();
2058 theCommand->SetArg( 1, hypID );
2059 if ( geom != GetGeom() )
2060 theCommand->SetArg( 2, geom );
2062 // remove hyp from myHypos
2063 myHypos.remove( hyp );
2065 // check for SubMesh order commands
2066 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2068 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2069 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2070 // commands are moved at the end of the script
2071 TCollection_AsciiString subIDs =
2072 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2073 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2074 list< _pyID >::iterator subID = idList.begin();
2075 for ( ; subID != idList.end(); ++subID )
2077 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2078 if ( !subMesh.IsNull() )
2079 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2082 // add accessor method if necessary
2085 if ( NeedMeshAccess( theCommand ))
2086 // apply theCommand to the mesh wrapped by smeshpy mesh
2087 AddMeshAccess( theCommand );
2091 //================================================================================
2093 * \brief Return True if addition of accesor method is needed
2095 //================================================================================
2097 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2099 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2100 // so no conversion is needed for them at all:
2101 static TStringSet sameMethods;
2102 if ( sameMethods.empty() ) {
2103 const char * names[] =
2104 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2105 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2106 "ClearLog","GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2107 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2108 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2109 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2110 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2111 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2112 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2113 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2114 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2115 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2116 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2117 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2118 ,"" }; // <- mark of end
2119 sameMethods.Insert( names );
2122 return !sameMethods.Contains( theCommand->GetMethod() );
2125 //================================================================================
2127 * \brief Convert creation and addition of all algos and hypos
2129 //================================================================================
2131 void _pyMesh::Flush()
2134 // get the meshes this mesh depends on via hypotheses
2135 list< Handle(_pyMesh) > fatherMeshes;
2136 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2137 for ( ; hyp != myHypos.end(); ++hyp )
2138 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2139 myGeomNotInStudy = true;
2141 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2142 for ( ; m != fatherMeshes.end(); ++m )
2143 addFatherMesh( *m );
2144 // if ( removedGeom )
2145 // SetRemovedFromStudy(); // as reffered geometry not in study
2147 if ( myGeomNotInStudy )
2150 list < Handle(_pyCommand) >::iterator cmd;
2152 // try to convert algo addition like this:
2153 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2154 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2156 Handle(_pyCommand) addCmd = *cmd;
2158 _pyID algoID = addCmd->GetArg( 2 );
2159 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2160 if ( algo.IsNull() || !algo->IsAlgo() )
2163 // check and create new algorithm instance if it is already wrapped
2164 if ( algo->IsWrapped() ) {
2165 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2166 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2167 TCollection_AsciiString( " = " ) + theGen->GetID() +
2168 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2169 TCollection_AsciiString( "\" )" );
2171 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2172 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2173 if ( !newAlgo.IsNull() ) {
2174 newAlgo->Assign( algo, this->GetID() );
2175 newAlgo->SetCreationCmd( newCmd );
2177 // set algorithm creation
2178 theGen->SetCommandBefore( newCmd, addCmd );
2179 myHypos.push_back( newAlgo );
2180 if ( !myLastComputeCmd.IsNull() &&
2181 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2182 newAlgo->MeshComputed( myLastComputeCmd );
2187 _pyID geom = addCmd->GetArg( 1 );
2188 bool isLocalAlgo = ( geom != GetGeom() );
2191 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2193 // wrapped algo is created after mesh creation
2194 GetCreationCmd()->AddDependantCmd( addCmd );
2196 if ( isLocalAlgo ) {
2197 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2198 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2199 TCollection_AsciiString( "geom=" ) + geom );
2200 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2201 list < Handle(_pySubMesh) >::iterator smIt;
2202 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2203 Handle(_pySubMesh) subMesh = *smIt;
2204 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2205 if ( geom == subCmd->GetArg( 1 )) {
2206 subCmd->SetObject( algo->GetID() );
2207 subCmd->RemoveArgs();
2208 subMesh->SetCreator( algo );
2213 else // KO - ALGO was already created
2215 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2216 addCmd->RemoveArgs();
2217 addCmd->SetArg( 1, algoID );
2219 addCmd->SetArg( 2, geom );
2220 myNotConvertedAddHypCmds.push_back( addCmd );
2224 // try to convert hypo addition like this:
2225 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2226 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2228 Handle(_pyCommand) addCmd = *cmd;
2229 _pyID hypID = addCmd->GetArg( 2 );
2230 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2231 if ( hyp.IsNull() || hyp->IsAlgo() )
2233 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2235 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2236 _pyID geom = addCmd->GetArg( 1 );
2237 addCmd->RemoveArgs();
2238 addCmd->SetArg( 1, hypID );
2239 if ( geom != GetGeom() )
2240 addCmd->SetArg( 2, geom );
2241 myNotConvertedAddHypCmds.push_back( addCmd );
2245 myAddHypCmds.clear();
2246 mySubmeshes.clear();
2249 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2250 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2254 //================================================================================
2256 * \brief Sets myIsPublished of me and of all objects depending on me.
2258 //================================================================================
2260 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2262 _pyObject::SetRemovedFromStudy(isRemoved);
2264 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2265 for ( ; sm != mySubmeshes.end(); ++sm )
2266 (*sm)->SetRemovedFromStudy(isRemoved);
2268 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2269 for ( ; gr != myGroups.end(); ++gr )
2270 (*gr)->SetRemovedFromStudy(isRemoved);
2272 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2273 for ( ; m != myChildMeshes.end(); ++m )
2274 (*m)->SetRemovedFromStudy(isRemoved);
2276 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2277 for ( ; e != myEditors.end(); ++e )
2278 (*e)->SetRemovedFromStudy(isRemoved);
2281 //================================================================================
2283 * \brief Return true if none of myChildMeshes is in study
2285 //================================================================================
2287 bool _pyMesh::CanClear()
2292 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2293 for ( ; m != myChildMeshes.end(); ++m )
2294 if ( !(*m)->CanClear() )
2300 //================================================================================
2302 * \brief Clear my commands and commands of mesh editor
2304 //================================================================================
2306 void _pyMesh::ClearCommands()
2312 // mark all sub-objects as not removed, except child meshes
2313 list< Handle(_pyMesh) > children;
2314 children.swap( myChildMeshes );
2315 SetRemovedFromStudy( false );
2316 children.swap( myChildMeshes );
2320 _pyObject::ClearCommands();
2322 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2323 for ( ; sm != mySubmeshes.end(); ++sm )
2324 (*sm)->ClearCommands();
2326 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2327 for ( ; gr != myGroups.end(); ++gr )
2328 (*gr)->ClearCommands();
2330 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2331 for ( ; e != myEditors.end(); ++e )
2332 (*e)->ClearCommands();
2335 //================================================================================
2337 * \brief Add a father mesh by ID
2339 //================================================================================
2341 void _pyMesh::addFatherMesh( const _pyID& meshID )
2343 if ( !meshID.IsEmpty() && meshID != GetID() )
2344 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2347 //================================================================================
2349 * \brief Add a father mesh
2351 //================================================================================
2353 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2355 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2357 //myFatherMeshes.push_back( mesh );
2358 mesh->myChildMeshes.push_back( this );
2360 // protect last Compute() from clearing by the next Compute()
2361 mesh->myLastComputeCmd.Nullify();
2365 //================================================================================
2367 * \brief MeshEditor convert its commands to ones of mesh
2369 //================================================================================
2371 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2372 _pyObject( theCreationCmd )
2374 myMesh = theCreationCmd->GetObject();
2375 myCreationCmdStr = theCreationCmd->GetString();
2376 theCreationCmd->Clear();
2378 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2379 if ( !mesh.IsNull() )
2380 mesh->AddEditor( this );
2383 //================================================================================
2385 * \brief convert its commands to ones of mesh
2387 //================================================================================
2389 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2391 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2392 // commands calling these methods are converted to calls of Mesh methods without
2393 // additional modifs, only object is changed from MeshEditor to Mesh.
2394 static TStringSet sameMethods;
2395 if ( sameMethods.empty() ) {
2396 const char * names[] = {
2397 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2398 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2399 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2400 "MoveNode", "MoveClosestNodeToPoint",
2401 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2402 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2403 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2404 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2405 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2406 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2407 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2408 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2409 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2410 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2411 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2412 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2413 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2414 "GetLastCreatedElems",
2415 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2416 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2417 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2418 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2419 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2420 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2421 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2422 ,"" }; // <- mark of the end
2423 sameMethods.Insert( names );
2426 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2427 TStringMap diffMethods;
2428 if ( diffMethods.empty() ) {
2429 const char * orig2newName[] = {
2430 // original name --------------> new name
2431 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2432 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2433 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2434 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2435 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2436 ""};// <- mark of the end
2437 diffMethods.Insert( orig2newName );
2440 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2441 // only by last two arguments
2442 static TStringSet diffLastTwoArgsMethods;
2443 if (diffLastTwoArgsMethods.empty() ) {
2444 const char * names[] = {
2445 "MirrorMakeGroups","MirrorObjectMakeGroups",
2446 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2447 "RotateMakeGroups","RotateObjectMakeGroups",
2448 ""};// <- mark of the end
2449 diffLastTwoArgsMethods.Insert( names );
2452 // only a method name is to change?
2453 const TCollection_AsciiString & method = theCommand->GetMethod();
2454 bool isPyMeshMethod = sameMethods.Contains( method );
2455 if ( !isPyMeshMethod )
2457 TCollection_AsciiString newMethod = diffMethods.Value( method );
2458 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2459 theCommand->SetMethod( newMethod );
2461 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2462 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2464 isPyMeshMethod = true;
2465 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2466 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2469 if ( !isPyMeshMethod )
2471 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2472 // functions with the flag "theMakeGroups = True" like:
2473 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2474 int pos = method.Search("MakeGroups");
2477 isPyMeshMethod = true;
2478 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2479 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2481 // 1. Remove "MakeGroups" from the Command
2482 TCollection_AsciiString aMethod = theCommand->GetMethod();
2483 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2486 pos = pos-2; //Remove "0D" from the Command too
2487 aMethod.Trunc(pos-1);
2488 theCommand->SetMethod(aMethod);
2490 // 2. And add last "True" argument(s)
2491 while(nbArgsToAdd--)
2492 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2493 if( is0DmethId || is0DmethObj )
2494 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2498 // ExtrusionSweep0D() -> ExtrusionSweep()
2499 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2500 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2501 method == "ExtrusionSweepObject0D" ))
2503 isPyMeshMethod = true;
2504 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2505 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2506 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2509 // DoubleNode...New(...) -> DoubleNode...(...,True)
2510 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2511 method == "DoubleNodeElemGroupsNew" ||
2512 method == "DoubleNodeGroupNew" ||
2513 method == "DoubleNodeGroupsNew" ||
2514 method == "DoubleNodeElemGroup2New" ||
2515 method == "DoubleNodeElemGroups2New"))
2517 isPyMeshMethod = true;
2518 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2519 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2520 if ( excessLen == 3 )
2522 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2524 else if ( theCommand->GetArg(4) == "0" ||
2525 theCommand->GetArg(5) == "0" )
2527 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2528 // Group = DoubleNodeGroup2New(,,,False, True)
2529 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2530 theCommand->SetResultValue( groupID );
2533 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2534 // FindElementsByPoint(x, y, z, elementType, meshPart)
2535 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2537 isPyMeshMethod = true;
2538 theCommand->SetMethod( "FindElementsByPoint" );
2539 // make the 1st arg be the last one
2540 _pyID partID = theCommand->GetArg( 1 );
2541 int nbArgs = theCommand->GetNbArgs();
2542 for ( int i = 2; i <= nbArgs; ++i )
2543 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2544 theCommand->SetArg( nbArgs, partID );
2546 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2547 if ( !isPyMeshMethod && method == "Reorient2D" )
2549 isPyMeshMethod = true;
2550 _AString mesh = theCommand->GetArg( 1 );
2551 _AString dir = theCommand->GetArg( 2 );
2552 _AString face = theCommand->GetArg( 3 );
2553 _AString point = theCommand->GetArg( 4 );
2554 theCommand->RemoveArgs();
2555 theCommand->SetArg( 1, mesh );
2556 theCommand->SetArg( 2, dir );
2557 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2558 theCommand->SetArg( 3, point );
2560 theCommand->SetArg( 3, face );
2563 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2565 isPyMeshMethod = true;
2566 int crit_arg = theCommand->GetNbArgs();
2567 const _AString& crit = theCommand->GetArg(crit_arg);
2568 if (crit.Search("MaxElementLength2D") != -1)
2569 theCommand->SetArg(crit_arg, "");
2572 if ( isPyMeshMethod )
2574 theCommand->SetObject( myMesh );
2578 // editor creation command is needed only if any editor function is called
2579 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2580 if ( !myCreationCmdStr.IsEmpty() ) {
2581 GetCreationCmd()->GetString() = myCreationCmdStr;
2582 myCreationCmdStr.Clear();
2587 //================================================================================
2589 * \brief Return true if my mesh can be removed
2591 //================================================================================
2593 bool _pyMeshEditor::CanClear()
2595 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2596 return mesh.IsNull() ? true : mesh->CanClear();
2599 //================================================================================
2601 * \brief _pyHypothesis constructor
2602 * \param theCreationCmd -
2604 //================================================================================
2606 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2607 _pyObject( theCreationCmd ), myCurCrMethod(0)
2609 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2612 //================================================================================
2614 * \brief Creates algorithm or hypothesis
2615 * \param theCreationCmd - The engine command creating a hypothesis
2616 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2618 //================================================================================
2620 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2622 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2623 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2625 Handle(_pyHypothesis) hyp, algo;
2628 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2629 if ( hypTypeQuoted.IsEmpty() )
2632 TCollection_AsciiString hypType =
2633 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2635 algo = new _pyAlgorithm( theCreationCmd );
2636 hyp = new _pyHypothesis( theCreationCmd );
2638 if ( hypType == "NumberOfSegments" ) {
2639 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2640 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2641 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2642 hyp->AddArgMethod( "SetNumberOfSegments" );
2643 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2644 hyp->AddArgMethod( "SetScaleFactor" );
2645 hyp->AddArgMethod( "SetReversedEdges" );
2646 // same for ""CompositeSegment_1D:
2647 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2648 hyp->AddArgMethod( "SetNumberOfSegments" );
2649 hyp->AddArgMethod( "SetScaleFactor" );
2650 hyp->AddArgMethod( "SetReversedEdges" );
2652 else if ( hypType == "SegmentLengthAroundVertex" ) {
2653 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2654 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2655 hyp->AddArgMethod( "SetLength" );
2656 // same for ""CompositeSegment_1D:
2657 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2658 hyp->AddArgMethod( "SetLength" );
2660 else if ( hypType == "LayerDistribution2D" ) {
2661 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2662 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2664 else if ( hypType == "LayerDistribution" ) {
2665 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2666 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2668 else if ( hypType == "CartesianParameters3D" ) {
2669 hyp = new _pyComplexParamHypo( theCreationCmd );
2670 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2671 for ( int iArg = 0; iArg < 4; ++iArg )
2672 hyp->setCreationArg( iArg+1, "[]");
2673 hyp->AddAccumulativeMethod( "SetGrid" );
2674 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2678 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2681 return algo->IsValid() ? algo : hyp;
2684 //================================================================================
2686 * \brief Returns true if addition of this hypothesis to a given mesh can be
2687 * wrapped into hypothesis creation
2689 //================================================================================
2691 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2693 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2695 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2696 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2702 //================================================================================
2704 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2705 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2706 * \param theAlgo - The algo that can create this hypo
2707 * \retval bool - false if the command cant be converted
2709 //================================================================================
2711 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2712 const _pyID& theMesh)
2714 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2716 if ( !IsWrappable( theMesh ))
2719 myGeom = theCmd->GetArg( 1 );
2721 Handle(_pyHypothesis) algo;
2723 // find algo created on myGeom in theMesh
2724 algo = theGen->FindAlgo( myGeom, theMesh, this );
2725 if ( algo.IsNull() )
2727 // attach hypothesis creation command to be after algo creation command
2728 // because it can be new created instance of algorithm
2729 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2733 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2734 theCmd->SetResultValue( GetID() );
2735 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2736 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2737 // set args (geom will be set by _pyMesh calling this method)
2738 theCmd->RemoveArgs();
2739 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2740 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2741 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2743 theCmd->SetArg( i+1, "[]");
2745 // set a new creation command
2746 GetCreationCmd()->Clear();
2747 // replace creation command by wrapped instance
2748 // please note, that hypothesis attaches to algo creation command (see upper)
2749 SetCreationCmd( theCmd );
2752 // clear commands setting arg values
2753 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2754 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2757 // set unknown arg commands after hypo creation
2758 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2759 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2760 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2761 afterCmd->AddDependantCmd( *cmd );
2767 //================================================================================
2769 * \brief Remember hypothesis parameter values
2770 * \param theCommand - The called hypothesis method
2772 //================================================================================
2774 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2776 ASSERT( !myIsAlgo );
2777 if ( !theGen->IsToKeepAllCommands() )
2778 rememberCmdOfParameter( theCommand );
2780 bool usedCommand = false;
2781 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2782 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2784 CreationMethod& crMethod = type2meth->second;
2785 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2786 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2788 myArgCommands.push_back( theCommand );
2790 while ( crMethod.myArgs.size() < i+1 )
2791 crMethod.myArgs.push_back( "None" );
2792 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2797 myUnusedCommands.push_back( theCommand );
2800 //================================================================================
2802 * \brief Finish conversion
2804 //================================================================================
2806 void _pyHypothesis::Flush()
2810 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2811 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2812 // Add access to a wrapped mesh
2813 theGen->AddMeshAccessorMethod( *cmd );
2814 // Add access to a wrapped algorithm
2815 theGen->AddAlgoAccessorMethod( *cmd );
2817 cmd = myUnusedCommands.begin();
2818 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2819 // Add access to a wrapped mesh
2820 theGen->AddMeshAccessorMethod( *cmd );
2821 // Add access to a wrapped algorithm
2822 theGen->AddAlgoAccessorMethod( *cmd );
2825 // forget previous hypothesis modifications
2826 myArgCommands.clear();
2827 myUnusedCommands.clear();
2830 //================================================================================
2832 * \brief clear creation, arg and unkown commands
2834 //================================================================================
2836 void _pyHypothesis::ClearAllCommands()
2838 GetCreationCmd()->Clear();
2839 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2840 for ( ; cmd != myArgCommands.end(); ++cmd )
2842 cmd = myUnusedCommands.begin();
2843 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2848 //================================================================================
2850 * \brief Assign fields of theOther to me except myIsWrapped
2852 //================================================================================
2854 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2855 const _pyID& theMesh )
2857 // myCreationCmd = theOther->myCreationCmd;
2858 myIsAlgo = theOther->myIsAlgo;
2859 myIsWrapped = false;
2860 myGeom = theOther->myGeom;
2862 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2863 myAccumulativeMethods = theOther->myAccumulativeMethods;
2864 //myUnusedCommands = theOther->myUnusedCommands;
2865 // init myCurCrMethod
2866 GetCreationMethod( theOther->GetAlgoType() );
2869 //================================================================================
2871 * \brief Analyze my erasability depending on myReferredObjs
2873 //================================================================================
2875 bool _pyHypothesis::CanClear()
2879 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2880 for ( ; obj != myReferredObjs.end(); ++obj )
2881 if ( (*obj)->CanClear() )
2888 //================================================================================
2890 * \brief Clear my commands depending on usage by meshes
2892 //================================================================================
2894 void _pyHypothesis::ClearCommands()
2896 // if ( !theGen->IsToKeepAllCommands() )
2898 // bool isUsed = false;
2899 // int lastComputeOrder = 0;
2900 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2901 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2902 // if ( ! (*cmd)->IsEmpty() )
2905 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2906 // lastComputeOrder = (*cmd)->GetOrderNb();
2910 // SetRemovedFromStudy( true );
2914 // // clear my commands invoked after lastComputeOrder
2915 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2916 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2918 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2919 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2920 // // cmds.back()->Clear();
2924 _pyObject::ClearCommands();
2927 //================================================================================
2929 * \brief Find arguments that are objects like mesh, group, geometry
2930 * \param meshes - referred meshes (directly or indirrectly)
2931 * \retval bool - false if a referred geometry is not in the study
2933 //================================================================================
2935 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2937 if ( IsAlgo() ) return true;
2939 bool geomPublished = true;
2940 vector< _AString > args;
2941 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2942 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2944 CreationMethod& crMethod = type2meth->second;
2945 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2947 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2948 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2949 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2950 args.push_back( (*cmd)->GetArg( nb ));
2953 for ( size_t i = 0; i < args.size(); ++i )
2955 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2956 if ( idList.empty() && !args[ i ].IsEmpty() )
2957 idList.push_back( args[ i ]);
2958 list< _pyID >::iterator id = idList.begin();
2959 for ( ; id != idList.end(); ++id )
2961 Handle(_pyObject) obj = theGen->FindObject( *id );
2962 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2965 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2966 geomPublished = false;
2970 myReferredObjs.push_back( obj );
2971 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2972 if ( !mesh.IsNull() )
2973 meshes.push_back( mesh );
2974 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2975 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2976 obj->SetRemovedFromStudy( false );
2980 return geomPublished;
2983 //================================================================================
2985 * \brief Remember theCommand setting a parameter
2987 //================================================================================
2989 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2991 // parameters are discriminated by method name
2992 _AString method = theCommand->GetMethod();
2993 if ( myAccumulativeMethods.count( method ))
2994 return; // this method adds values and not override the previus value
2996 // discriminate commands setting different parameters via one method
2997 // by passing parameter names like e.g. SetOption("size", "0.2")
2998 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2999 theCommand->GetNbArgs() > 1 )
3001 // mangle method by appending a 1st textual arg
3002 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3004 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3005 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3006 if ( !isalpha( arg.Value(2))) continue;
3011 // parameters are discriminated by method name
3012 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3013 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3015 cmds.back()->Clear(); // previous parameter value has not been used
3016 cmds.back() = theCommand;
3020 cmds.push_back( theCommand );
3024 //================================================================================
3026 * \brief Return true if a setting parameter command ha been used to compute mesh
3028 //================================================================================
3030 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3031 _pyCommand::TAddr avoidComputeAddr ) const
3033 bool isUsed = false;
3034 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3035 myComputeAddr2Cmds.begin();
3036 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3038 if ( addr2cmds->first == avoidComputeAddr ) continue;
3039 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3040 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3045 //================================================================================
3047 * \brief Save commands setting parameters as they are used for a mesh computation
3049 //================================================================================
3051 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3053 myComputeCmds.push_back( theComputeCmd );
3054 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3056 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3057 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3058 savedCmds.push_back( m2c->second.back() );
3061 //================================================================================
3063 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3065 //================================================================================
3067 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3069 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3071 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3072 for ( ; cmd != savedCmds.end(); ++cmd )
3074 // check if a cmd has been used to compute another mesh
3075 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3077 // check if a cmd is a sole command setting its parameter;
3078 // don't use method name for search as it can change
3079 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3080 m2cmds = myMeth2Commands.begin();
3081 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3083 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3084 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3085 if ( cmdIt != cmds.end() )
3087 if ( cmds.back() != *cmd )
3089 cmds.erase( cmdIt );
3096 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3099 //================================================================================
3101 * \brief Sets an argNb-th argument of current creation command
3102 * \param argNb - argument index countered from 1
3104 //================================================================================
3106 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3108 if ( myCurCrMethod )
3110 while ( myCurCrMethod->myArgs.size() < argNb )
3111 myCurCrMethod->myArgs.push_back( "None" );
3112 if ( arg.IsEmpty() )
3113 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3115 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3120 //================================================================================
3122 * \brief Remember hypothesis parameter values
3123 * \param theCommand - The called hypothesis method
3125 //================================================================================
3127 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3129 if ( GetAlgoType() == "Cartesian_3D" )
3131 // CartesianParameters3D hyp
3133 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3134 theCommand->GetMethod() == "SetToAddEdges" )
3136 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3137 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3138 myArgCommands.push_back( theCommand );
3141 if ( theCommand->GetMethod() == "SetGrid" ||
3142 theCommand->GetMethod() == "SetGridSpacing" )
3144 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3145 int iArg = axis.Value(1) - '0';
3146 if ( theCommand->GetMethod() == "SetGrid" )
3148 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3152 myCurCrMethod->myArgs[ iArg ] = "[ ";
3153 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3154 myCurCrMethod->myArgs[ iArg ] += ", ";
3155 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3156 myCurCrMethod->myArgs[ iArg ] += "]";
3158 myArgCommands.push_back( theCommand );
3159 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3160 // accumulative, else, if the creation
3161 // is not converted, commands for axes 1 and 2 are lost
3166 if( theCommand->GetMethod() == "SetLength" )
3168 // NOW it is OBSOLETE
3169 // ex: hyp.SetLength(start, 1)
3170 // hyp.SetLength(end, 0)
3171 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3172 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3173 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3174 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3176 CreationMethod& crMethod = type2meth->second;
3177 while ( crMethod.myArgs.size() < i+1 )
3178 crMethod.myArgs.push_back( "[]" );
3179 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3181 myArgCommands.push_back( theCommand );
3185 _pyHypothesis::Process( theCommand );
3188 //================================================================================
3190 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3192 //================================================================================
3194 void _pyComplexParamHypo::Flush()
3196 list < Handle(_pyCommand) >::iterator cmd;
3199 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3200 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3204 // if ( GetAlgoType() == "Cartesian_3D" )
3206 // _pyID algo = myCreationCmd->GetObject();
3207 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3209 // if ( IsWrapped() )
3211 // StructToList( *cmd, /*checkMethod=*/false );
3212 // const _AString & method = (*cmd)->GetMethod();
3213 // if ( method == "SetFixedPoint" )
3214 // (*cmd)->SetObject( algo );
3220 //================================================================================
3222 * \brief Convert methods of 1D hypotheses to my own methods
3223 * \param theCommand - The called hypothesis method
3225 //================================================================================
3227 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3229 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3232 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3233 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3234 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3236 // TCollection_AsciiString cmd =
3237 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3238 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3239 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3242 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3244 // // 1D hypo is already set, so distribution changes and the old
3245 // // 1D hypo is thrown away
3246 // my1dHyp->ClearAllCommands();
3249 // //my1dHyp->SetRemovedFromStudy( false );
3251 // if ( !myArgCommands.empty() )
3252 // myArgCommands.back()->Clear();
3253 myCurCrMethod->myArgs.push_back( hyp1dID );
3254 myArgCommands.push_back( theCommand );
3257 //================================================================================
3260 * \param theAdditionCmd - command to be converted
3261 * \param theMesh - mesh instance
3262 * \retval bool - status
3264 //================================================================================
3266 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3267 const _pyID& theMesh)
3269 myIsWrapped = false;
3271 if ( my1dHyp.IsNull() )
3274 // set "SetLayerDistribution()" after addition cmd
3275 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3277 _pyID geom = theAdditionCmd->GetArg( 1 );
3279 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3280 if ( !algo.IsNull() )
3282 my1dHyp->SetMesh( theMesh );
3283 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3284 algo->GetAlgoType().ToCString());
3285 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3288 // clear "SetLayerDistribution()" cmd
3289 myArgCommands.back()->Clear();
3291 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3293 // find RadialPrism algo created on <geom> for theMesh
3294 GetCreationCmd()->SetObject( algo->GetID() );
3295 GetCreationCmd()->SetMethod( myAlgoMethod );
3296 GetCreationCmd()->RemoveArgs();
3297 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3303 //================================================================================
3307 //================================================================================
3309 void _pyLayerDistributionHypo::Flush()
3311 // as creation of 1D hyp was written later then it's edition,
3312 // we need to find all it's edition calls and process them
3313 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3315 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3317 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3318 if ( hyp1dID.IsEmpty() ) continue;
3320 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3322 // make a new name for 1D hyp = "HypType" + "_Distribution"
3324 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3326 if ( prevNewName.IsEmpty() ) continue;
3327 newName = prevNewName;
3331 if ( hyp1d->IsWrapped() ) {
3332 newName = hyp1d->GetCreationCmd()->GetMethod();
3335 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3336 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3338 newName += "_Distribution";
3339 prevNewName = newName;
3341 hyp1d->GetCreationCmd()->SetResultValue( newName );
3343 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3344 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3345 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3346 const _pyID& objID = (*cmdIt)->GetObject();
3347 if ( objID == hyp1dID ) {
3348 if ( !hyp1d.IsNull() )
3350 hyp1d->Process( *cmdIt );
3351 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3353 ( *cmdIt )->SetObject( newName );
3356 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3357 (*cmd)->SetArg( 1, newName );
3361 //================================================================================
3363 * \brief additionally to Addition2Creation, clears SetDistrType() command
3364 * \param theCmd - AddHypothesis() command
3365 * \param theMesh - mesh to which a hypothesis is added
3366 * \retval bool - convertion result
3368 //================================================================================
3370 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3371 const _pyID& theMesh)
3373 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3374 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3375 bool scaleDistrType = false;
3376 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3377 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3378 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3379 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3380 scaleDistrType = true;
3383 else if ( !scaleDistrType ) {
3384 // distribution type changed: remove scale factor from args
3385 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3386 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3388 CreationMethod& crMethod = type2meth->second;
3389 if ( crMethod.myArgs.size() == 2 )
3390 crMethod.myArgs.pop_back();
3397 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3400 //================================================================================
3402 * \brief remove repeated commands defining distribution
3404 //================================================================================
3406 void _pyNumberOfSegmentsHyp::Flush()
3408 // find number of the last SetDistrType() command
3409 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3410 int distrTypeNb = 0;
3411 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3412 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3413 if ( cmd != myUnusedCommands.rbegin() )
3414 distrTypeNb = (*cmd)->GetOrderNb();
3416 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3419 // clear commands before the last SetDistrType()
3420 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3421 set< int > treatedCmdNbs; // avoid treating same cmd twice
3422 for ( int i = 0; i < 2; ++i ) {
3423 set<TCollection_AsciiString> uniqueMethods;
3424 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3425 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3427 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3428 continue;// avoid treating same cmd twice
3429 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3430 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3431 if ( !clear || method == "SetNumberOfSegments" ) {
3432 bool isNewInSet = uniqueMethods.insert( method ).second;
3433 clear = !isNewInSet;
3442 //================================================================================
3444 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3445 * into regular1D.LengthNearVertex( length, vertex )
3446 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3447 * \param theMesh - The mesh needing this hypo
3448 * \retval bool - false if the command cant be converted
3450 //================================================================================
3452 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3453 const _pyID& theMeshID)
3455 if ( IsWrappable( theMeshID )) {
3457 _pyID vertex = theCmd->GetArg( 1 );
3459 // the problem here is that segment algo will not be found
3460 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3461 // geometry where segment algorithm is assigned
3462 Handle(_pyHypothesis) algo;
3463 _pyID geom = vertex;
3464 while ( algo.IsNull() && !geom.IsEmpty()) {
3465 // try to find geom as a father of <vertex>
3466 geom = FatherID( geom );
3467 algo = theGen->FindAlgo( geom, theMeshID, this );
3469 if ( algo.IsNull() )
3470 return false; // also possible to find geom as brother of veretex...
3471 // set geom instead of vertex
3472 theCmd->SetArg( 1, geom );
3474 // set vertex as a second arg
3475 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3476 setCreationArg( 2, vertex );
3478 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3479 // theMeshID.LengthNearVertex( length, vertex )
3480 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3485 //================================================================================
3487 * \brief _pyAlgorithm constructor
3488 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3490 //================================================================================
3492 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3493 : _pyHypothesis( theCreationCmd )
3498 //================================================================================
3500 * \brief Convert the command adding an algorithm to mesh
3501 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3502 * \param theMesh - The mesh needing this algo
3503 * \retval bool - false if the command cant be converted
3505 //================================================================================
3507 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3508 const _pyID& theMeshID)
3510 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3511 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3512 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3518 //================================================================================
3520 * \brief Return starting position of a part of python command
3521 * \param thePartIndex - The index of command part
3522 * \retval int - Part position
3524 //================================================================================
3526 int _pyCommand::GetBegPos( int thePartIndex ) const
3530 if ( myBegPos.Length() < thePartIndex )
3532 ASSERT( thePartIndex > 0 );
3533 return myBegPos( thePartIndex );
3536 //================================================================================
3538 * \brief Store starting position of a part of python command
3539 * \param thePartIndex - The index of command part
3540 * \param thePosition - Part position
3542 //================================================================================
3544 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3546 while ( myBegPos.Length() < thePartIndex )
3547 myBegPos.Append( UNKNOWN );
3548 ASSERT( thePartIndex > 0 );
3549 myBegPos( thePartIndex ) = thePosition;
3552 //================================================================================
3554 * \brief Returns whitespace symbols at the line beginning
3555 * \retval TCollection_AsciiString - result
3557 //================================================================================
3559 TCollection_AsciiString _pyCommand::GetIndentation()
3562 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3563 GetWord( myString, end, true );
3565 end = GetBegPos( RESULT_IND );
3566 return myString.SubString( 1, Max( end - 1, 1 ));
3569 //================================================================================
3571 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3572 * \retval const TCollection_AsciiString & - ResultValue substring
3574 //================================================================================
3576 const TCollection_AsciiString & _pyCommand::GetResultValue()
3578 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3580 SetBegPos( RESULT_IND, EMPTY );
3581 int begPos, endPos = myString.Location( "=", 1, Length() );
3585 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3586 if ( begPos < endPos )
3588 SetBegPos( RESULT_IND, begPos );
3590 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3591 myRes = myString.SubString( begPos, endPos );
3598 //================================================================================
3600 * \brief Return number of python command result value ResultValue = Obj.Meth()
3602 //================================================================================
3604 int _pyCommand::GetNbResultValues()
3607 return myResults.Length();
3611 //================================================================================
3613 * \brief Return substring of python command looking like
3614 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3615 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3617 //================================================================================
3618 const _AString& _pyCommand::GetResultValue(int res)
3620 if ( GetResultValue().IsEmpty() )
3621 return theEmptyString;
3623 if ( myResults.IsEmpty() )
3626 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3627 ++begPos; // skip [, else the whole list is returned
3628 while ( begPos < myRes.Length() ) {
3629 _AString result = GetWord( myRes, begPos, true );
3630 begPos += result.Length();
3632 // result.RemoveAll('[');
3633 // result.RemoveAll(']');
3638 myResults.Append( result );
3641 if ( res > 0 && res <= myResults.Length() )
3642 return myResults( res );
3643 return theEmptyString;
3646 //================================================================================
3648 * \brief Return substring of python command looking like ResVal = Object.Meth()
3649 * \retval const TCollection_AsciiString & - Object substring
3651 //================================================================================
3653 const TCollection_AsciiString & _pyCommand::GetObject()
3655 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3658 int begPos = GetBegPos( RESULT_IND );
3660 begPos = myString.Location( "=", 1, Length() ) + 1;
3661 // is '=' in the string argument (for example, name) or not
3662 int nb1 = 0; // number of ' character at the left of =
3663 int nb2 = 0; // number of " character at the left of =
3664 for ( int i = 1; i < begPos-1; i++ ) {
3665 if ( myString.Value( i )=='\'' )
3667 else if ( myString.Value( i )=='"' )
3670 // if number of ' or " is not divisible by 2,
3671 // then get an object at the start of the command
3672 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3676 begPos += myRes.Length();
3678 myObj = GetWord( myString, begPos, true );
3679 if ( begPos != EMPTY )
3681 // check if object is complex,
3682 // so far consider case like "smesh.Method()"
3683 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3684 //if ( bracketPos==0 ) bracketPos = Length();
3685 int dotPos = begPos+myObj.Length();
3686 while ( dotPos+1 < bracketPos ) {
3687 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3692 if ( dotPos > begPos+myObj.Length() )
3693 myObj = myString.SubString( begPos, dotPos-1 );
3696 // 1st word after '=' is an object
3697 // else // no method -> no object
3703 SetBegPos( OBJECT_IND, begPos );
3709 //================================================================================
3711 * \brief Return substring of python command looking like ResVal = Obj.Method()
3712 * \retval const TCollection_AsciiString & - Method substring
3714 //================================================================================
3716 const TCollection_AsciiString & _pyCommand::GetMethod()
3718 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3721 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3722 bool forward = true;
3724 begPos = myString.Location( "(", 1, Length() ) - 1;
3728 myMeth = GetWord( myString, begPos, forward );
3729 SetBegPos( METHOD_IND, begPos );
3735 //================================================================================
3737 * \brief Returns true if there are brackets after the method
3739 //================================================================================
3741 bool _pyCommand::IsMethodCall()
3743 if ( GetMethod().IsEmpty() )
3745 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3746 return ( s[0] == '(' || s[1] == '(' );
3749 //================================================================================
3751 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3752 * \retval const TCollection_AsciiString & - Arg<index> substring
3754 //================================================================================
3756 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3758 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3762 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3764 pos = myString.Location( "(", 1, Length() );
3768 // we are at or before '(', skip it if present
3770 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3771 if ( pos > Length() )
3775 SetBegPos( ARG1_IND, 0 ); // even no '('
3776 return theEmptyString;
3780 list< TCollection_AsciiString > separatorStack( 1, ",)");
3781 bool ignoreNesting = false;
3783 while ( pos <= Length() )
3785 const char chr = myString.Value( pos );
3787 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3789 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3791 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3793 TCollection_AsciiString arg;
3794 if ( pos-1 >= prevPos ) {
3795 arg = myString.SubString( prevPos, pos-1 );
3796 arg.RightAdjust(); // remove spaces
3799 if ( !arg.IsEmpty() || chr == ',' )
3801 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3802 myArgs.Append( arg );
3808 else // end of nesting args found
3810 separatorStack.pop_back();
3811 ignoreNesting = false;
3814 else if ( !ignoreNesting )
3817 case '(' : separatorStack.push_back(")"); break;
3818 case '[' : separatorStack.push_back("]"); break;
3819 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3820 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3827 if ( myArgs.Length() < index )
3828 return theEmptyString;
3829 return myArgs( index );
3832 //================================================================================
3834 * \brief Return position where arguments begin
3836 //================================================================================
3838 int _pyCommand::GetArgBeginning() const
3840 int pos = GetBegPos( ARG1_IND );
3841 if ( pos == UNKNOWN )
3843 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3845 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3850 //================================================================================
3852 * \brief Check if char is a word part
3853 * \param c - The character to check
3854 * \retval bool - The check result
3856 //================================================================================
3858 static inline bool isWord(const char c, const bool dotIsWord)
3861 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3864 //================================================================================
3866 * \brief Looks for a word in the string and returns word's beginning
3867 * \param theString - The input string
3868 * \param theStartPos - The position to start the search, returning word's beginning
3869 * \param theForward - The search direction
3870 * \retval TCollection_AsciiString - The found word
3872 //================================================================================
3874 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3876 const bool theForward,
3877 const bool dotIsWord )
3879 int beg = theStartPos, end = theStartPos;
3880 theStartPos = EMPTY;
3881 if ( beg < 1 || beg > theString.Length() )
3882 return theEmptyString;
3884 if ( theForward ) { // search forward
3886 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3888 if ( beg > theString.Length() )
3889 return theEmptyString; // no word found
3892 char begChar = theString.Value( beg );
3893 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3894 char endChar = ( begChar == '[' ) ? ']' : begChar;
3895 // end is at the corresponding quoting mark or bracket
3896 while ( end < theString.Length() &&
3897 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3901 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3906 else { // search backward
3908 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3911 return theEmptyString; // no word found
3913 char endChar = theString.Value( end );
3914 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3915 char begChar = ( endChar == ']' ) ? '[' : endChar;
3916 // beg is at the corresponding quoting mark
3918 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3922 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3928 //cout << theString << " ---- " << beg << " - " << end << endl;
3929 return theString.SubString( beg, end );
3932 //================================================================================
3934 * \brief Returns true if the string looks like a study entry
3936 //================================================================================
3938 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3940 if ( str.Length() < 5 ) return false;
3942 int nbColons = 0, isColon;
3943 for ( int i = 1; i <= str.Length(); ++i )
3945 char c = str.Value(i);
3946 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3948 nbColons += isColon;
3950 return nbColons > 2 && str.Length()-nbColons > 2;
3953 //================================================================================
3955 * \brief Returns true if the string looks like an object ID but not like a list,
3956 * string, command etc.
3958 //================================================================================
3960 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3962 if ( str.Length() < 1 ) return false;
3964 const char* s = str.ToCString();
3966 for ( int i = 0; i < str.Length(); ++i )
3967 if ( !IsIDChar( s[i] ))
3973 //================================================================================
3975 * \brief Finds entries in a sting
3977 //================================================================================
3979 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3981 std::list< _pyID > resList;
3983 while ( ++pos <= str.Length() )
3985 if ( !isdigit( str.Value( pos ))) continue;
3986 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3989 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3990 _pyID entry = str.SubString( pos, end-1 );
3992 if ( IsStudyEntry( entry ))
3993 resList.push_back( entry );
3998 //================================================================================
4000 * \brief Look for position where not space char is
4001 * \param theString - The string
4002 * \param thePos - The position to search from and which returns result
4003 * \retval bool - false if there are only space after thePos in theString
4005 //================================================================================
4007 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4009 if ( thePos < 1 || thePos > theString.Length() )
4012 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4015 return thePos <= theString.Length();
4018 //================================================================================
4020 * \brief Modify a part of the command
4021 * \param thePartIndex - The index of the part
4022 * \param thePart - The new part string
4023 * \param theOldPart - The old part
4025 //================================================================================
4027 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4028 TCollection_AsciiString& theOldPart)
4030 int pos = GetBegPos( thePartIndex );
4031 if ( pos <= Length() && theOldPart != thePart)
4033 TCollection_AsciiString seperator;
4035 pos = GetBegPos( thePartIndex + 1 );
4036 if ( pos < 1 ) return;
4037 switch ( thePartIndex ) {
4038 case RESULT_IND: seperator = " = "; break;
4039 case OBJECT_IND: seperator = "."; break;
4040 case METHOD_IND: seperator = "()"; break;
4044 myString.Remove( pos, theOldPart.Length() );
4045 if ( !seperator.IsEmpty() )
4046 myString.Insert( pos , seperator );
4047 myString.Insert( pos, thePart );
4048 // update starting positions of the following parts
4049 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4050 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4051 if ( myBegPos( i ) > 0 )
4052 myBegPos( i ) += posDelta;
4054 theOldPart = thePart;
4058 //================================================================================
4060 * \brief Set agrument
4061 * \param index - The argument index, it counts from 1
4062 * \param theArg - The argument string
4064 //================================================================================
4066 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4069 int argInd = ARG1_IND + index - 1;
4070 int pos = GetBegPos( argInd );
4071 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4073 // find a closing parenthesis
4074 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4075 int lastArgInd = GetNbArgs();
4076 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4077 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4082 while ( pos > 0 && myString.Value( pos ) != ')' )
4085 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4089 while ( myArgs.Length() < index ) {
4090 if ( myArgs.Length() )
4091 myString.Insert( pos++, "," );
4092 myArgs.Append("None");
4093 myString.Insert( pos, myArgs.Last() );
4094 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4095 pos += myArgs.Last().Length();
4098 SetPart( argInd, theArg, myArgs( index ));
4101 //================================================================================
4103 * \brief Empty arg list
4105 //================================================================================
4107 void _pyCommand::RemoveArgs()
4109 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4110 myString.Trunc( pos );
4113 if ( myBegPos.Length() >= ARG1_IND )
4114 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4117 //================================================================================
4119 * \brief Comment a python command
4121 //================================================================================
4123 void _pyCommand::Comment()
4125 if ( IsEmpty() ) return;
4128 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4129 if ( i <= Length() )
4131 myString.Insert( i, "#" );
4132 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4134 int begPos = GetBegPos( iPart );
4135 if ( begPos != UNKNOWN && begPos != EMPTY )
4136 SetBegPos( iPart, begPos + 1 );
4141 //================================================================================
4143 * \brief Set dependent commands after this one
4145 //================================================================================
4147 bool _pyCommand::SetDependentCmdsAfter() const
4149 bool orderChanged = false;
4150 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4151 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4152 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4153 orderChanged = true;
4154 theGen->SetCommandAfter( *cmd, this );
4155 (*cmd)->SetDependentCmdsAfter();
4158 return orderChanged;
4160 //================================================================================
4162 * \brief Insert accessor method after theObjectID
4163 * \param theObjectID - id of the accessed object
4164 * \param theAcsMethod - name of the method giving access to the object
4165 * \retval bool - false if theObjectID is not found in the command string
4167 //================================================================================
4169 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4171 if ( !theAcsMethod )
4173 // start object search from the object, i.e. ignore result
4175 int beg = GetBegPos( OBJECT_IND );
4176 if ( beg < 1 || beg > Length() )
4179 while (( beg = myString.Location( theObjectID, beg, Length() )))
4181 // check that theObjectID is not just a part of a longer ID
4182 int afterEnd = beg + theObjectID.Length();
4183 Standard_Character c = myString.Value( afterEnd );
4184 if ( !IsIDChar( c ))
4186 // check if accessor method already present
4188 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4190 int oldLen = Length();
4191 myString.Insert( afterEnd, (char*) theAcsMethod );
4192 myString.Insert( afterEnd, "." );
4193 // update starting positions of the parts following the modified one
4194 int posDelta = Length() - oldLen;
4195 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4196 if ( myBegPos( i ) > afterEnd )
4197 myBegPos( i ) += posDelta;
4202 beg = afterEnd; // is a part -> next search
4207 //================================================================================
4209 * \brief Creates pyObject
4211 //================================================================================
4213 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4214 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4219 //================================================================================
4221 * \brief Set up myID and myIsPublished
4223 //================================================================================
4225 void _pyObject::setID(const _pyID& theID)
4228 myIsPublished = !theGen->IsNotPublished( GetID() );
4231 //================================================================================
4233 * \brief Clear myCreationCmd and myProcessedCmds
4235 //================================================================================
4237 void _pyObject::ClearCommands()
4242 if ( !myCreationCmd.IsNull() )
4243 myCreationCmd->Clear();
4245 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4246 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4250 //================================================================================
4252 * \brief Return method name giving access to an interaface object wrapped by python class
4253 * \retval const char* - method name
4255 //================================================================================
4257 const char* _pyObject::AccessorMethod() const
4261 //================================================================================
4263 * \brief Return ID of a father
4265 //================================================================================
4267 _pyID _pyObject::FatherID(const _pyID & childID)
4269 int colPos = childID.SearchFromEnd(':');
4271 return childID.SubString( 1, colPos-1 );
4275 //================================================================================
4277 * \brief SelfEraser erases creation command if none of it's commands invoked
4278 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4280 //================================================================================
4282 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4283 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4285 myIsPublished = true; // prevent clearing as a not published
4286 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4289 //================================================================================
4291 * \brief SelfEraser erases creation command if none of it's commands invoked
4292 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4294 //================================================================================
4296 bool _pySelfEraser::CanClear()
4298 bool toErase = false;
4299 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4302 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4303 for ( ; cmd != myArgCmds.end(); ++cmd )
4304 nbArgUses += IsAliveCmd( *cmd );
4306 toErase = ( nbArgUses < 1 );
4311 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4312 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4313 for ( ; cmd != cmds.end(); )
4314 // check of cmd emptiness is not enough as object can change
4315 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4318 cmd = cmds.erase( cmd ); // save the cmd from clearing
4320 toErase = ( nbCalls < 1 );
4325 //================================================================================
4327 * \brief Check if a command is or can be cleared
4329 //================================================================================
4331 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4333 if ( theCmd->IsEmpty() )
4336 if ( !theGen->IsToKeepAllCommands() )
4338 const _pyID& objID = theCmd->GetObject();
4339 Handle( _pyObject ) obj = theGen->FindObject( objID );
4340 if ( !obj.IsNull() )
4341 return !obj->CanClear();
4346 //================================================================================
4348 * \brief SelfEraser erases creation command if none of it's commands invoked
4349 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4351 //================================================================================
4353 void _pySelfEraser::Flush()
4357 myIsPublished = false;
4358 _pyObject::ClearCommands();
4362 //================================================================================
4364 * \brief _pySubMesh constructor
4366 //================================================================================
4368 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4369 _pyObject(theCreationCmd)
4371 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4372 if ( toKeepAgrCmds )
4373 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4376 //================================================================================
4378 * \brief Return true if a sub-mesh can be used as argument of the given method
4380 //================================================================================
4382 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4385 // // names of all methods where a sub-mesh can be used as argument
4386 // static TStringSet methods;
4387 // if ( methods.empty() ) {
4388 // const char * names[] = {
4389 // // methods of SMESH_Gen
4391 // // methods of SMESH_Group
4393 // // methods of SMESH_Measurements
4395 // // methods of SMESH_Mesh
4396 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4398 // // methods of SMESH_MeshEditor
4399 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4400 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4401 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4402 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4403 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4404 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4405 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4406 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4407 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4408 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4409 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4410 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4411 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4412 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4413 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4414 // "" }; // <- mark of end
4415 // methods.Insert( names );
4417 // return methods.Contains( theMethodName );
4420 //================================================================================
4422 * \brief count invoked commands
4424 //================================================================================
4426 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4428 _pyObject::Process(theCommand); // count calls of Process()
4431 //================================================================================
4433 * \brief Move creation command depending on invoked commands
4435 //================================================================================
4437 void _pySubMesh::Flush()
4439 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4440 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4441 else if ( !myCreator.IsNull() )
4442 // move to be just after creator
4443 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4445 // move sub-mesh usage after creation cmd
4446 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4447 for ( ; cmd != myArgCmds.end(); ++cmd )
4448 if ( !(*cmd)->IsEmpty() )
4449 GetCreationCmd()->AddDependantCmd( *cmd );
4452 //================================================================================
4454 * \brief Creates _pyGroup
4456 //================================================================================
4458 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4459 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4461 if ( !id.IsEmpty() )
4464 myCanClearCreationCmd = true;
4466 const _AString& method = theCreationCmd->GetMethod();
4467 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4469 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4471 // ----------------------------------------------------------------------
4472 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4474 _pyID geom = theCreationCmd->GetArg( 3 );
4475 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4476 // next if(){...} section is commented
4477 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4478 // theCreationCmd->SetMethod( "Group" );
4479 // theCreationCmd->RemoveArgs();
4480 // theCreationCmd->SetArg( 1, geom );
4483 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4484 _pyID type = theCreationCmd->GetArg( 1 );
4485 _pyID name = theCreationCmd->GetArg( 2 );
4486 theCreationCmd->SetMethod( "GroupOnGeom" );
4487 theCreationCmd->RemoveArgs();
4488 theCreationCmd->SetArg( 1, geom );
4489 theCreationCmd->SetArg( 2, name );
4490 theCreationCmd->SetArg( 3, type );
4493 else if ( method == "CreateGroupFromFilter" )
4495 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4496 theCreationCmd->SetMethod( "GroupOnFilter" );
4498 _pyID filterID = theCreationCmd->GetArg(3);
4499 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4500 if ( !filter.IsNull())
4502 if ( !filter->GetNewID().IsEmpty() )
4503 theCreationCmd->SetArg( 3, filter->GetNewID() );
4504 //filter->AddUser( this );
4508 else if ( method == "GetGroups" )
4510 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4514 // theCreationCmd does something else apart from creation of this group
4515 // and thus it can't be cleared if this group is removed
4516 myCanClearCreationCmd = false;
4520 //================================================================================
4522 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4525 //================================================================================
4527 bool _pyGroup::CanClear()
4532 if ( !myCanClearCreationCmd &&
4533 !myCreationCmd.IsNull() &&
4534 myCreationCmd->GetMethod() == "GetGroups" )
4536 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4537 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4538 list< _pyID >::iterator grID = idList.begin();
4539 if ( GetID() == *grID )
4541 myCanClearCreationCmd = true;
4542 list< Handle(_pyGroup ) > groups;
4543 for ( ; grID != idList.end(); ++grID )
4545 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4546 if ( group.IsNull() ) continue;
4547 groups.push_back( group );
4548 if ( group->IsInStudy() )
4549 myCanClearCreationCmd = false;
4551 // set myCanClearCreationCmd == true to all groups
4552 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4553 for ( ; group != groups.end(); ++group )
4554 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4558 return myCanClearCreationCmd;
4561 //================================================================================
4563 * \brief set myCanClearCreationCmd = true if the main action of the creation
4564 * command is discarded
4566 //================================================================================
4568 void _pyGroup::RemovedWithContents()
4570 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4571 // via a created group
4572 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4573 // myCanClearCreationCmd = true;
4576 //================================================================================
4578 * \brief To convert creation of a group by filter
4580 //================================================================================
4582 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4584 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4585 // group = mesh.CreateEmptyGroup( elemType, groupName )
4586 // aFilter.SetMesh(mesh)
4587 // nbAdd = group.AddFrom( aFilter )
4588 Handle(_pyFilter) filter;
4589 if ( theCommand->GetMethod() == "AddFrom" )
4591 _pyID idSource = theCommand->GetArg(1);
4592 // check if idSource is a filter
4593 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4594 if ( !filter.IsNull() )
4596 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4597 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4598 while ( *cmdIt != theCommand ) ++cmdIt;
4599 while ( (*cmdIt)->GetOrderNb() != 1 )
4601 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4602 if ((setMeshCmd->GetObject() == idSource ||
4603 setMeshCmd->GetObject() == filter->GetNewID() )
4605 setMeshCmd->GetMethod() == "SetMesh")
4607 setMeshCmd->Clear();
4611 // replace 3 commands by one
4612 theCommand->Clear();
4613 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4614 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4615 if ( !filter->GetNewID().IsEmpty() )
4616 idSource = filter->GetNewID();
4617 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4618 makeGroupCmd->SetArg( 1, name );
4619 makeGroupCmd->SetArg( 2, idSource );
4620 filter->AddArgCmd( makeGroupCmd );
4623 else if ( theCommand->GetMethod() == "SetFilter" )
4625 // set new name of a filter or clear the command if the same filter is set
4626 _pyID filterID = theCommand->GetArg(1);
4627 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4628 if ( !myFilter.IsNull() && filter == myFilter )
4629 theCommand->Clear();
4630 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4631 theCommand->SetArg( 1, filter->GetNewID() );
4634 else if ( theCommand->GetMethod() == "GetFilter" )
4636 // GetFilter() returns a filter with other ID, make myFilter process
4637 // calls of the returned filter
4638 if ( !myFilter.IsNull() )
4640 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4641 theCommand->Clear();
4645 // if ( !filter.IsNull() )
4646 // filter->AddUser( this );
4648 theGen->AddMeshAccessorMethod( theCommand );
4651 //================================================================================
4653 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4655 //================================================================================
4657 void _pyGroup::Flush()
4659 if ( !theGen->IsToKeepAllCommands() &&
4660 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4662 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4666 //================================================================================
4668 * \brief Constructor of _pyFilter
4670 //================================================================================
4672 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4673 :_pyObject(theCreationCmd), myNewID( newID )
4675 //myIsPublished = true; // prevent clearing as a not published
4676 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4679 //================================================================================
4681 * \brief To convert creation of a filter by criteria and
4682 * to replace an old name by a new one
4684 //================================================================================
4686 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4688 if ( theCommand->GetObject() == GetID() )
4689 _pyObject::Process(theCommand); // count commands
4691 if ( !myNewID.IsEmpty() )
4692 theCommand->SetObject( myNewID );
4694 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4695 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4696 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4697 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4698 theCommand->GetMethod() == "SetCriteria")
4700 // aFilter.SetCriteria(aCriteria) ->
4701 // aFilter = smesh.GetFilterFromCriteria(criteria)
4702 if ( myNewID.IsEmpty() )
4703 theCommand->SetResultValue( GetID() );
4705 theCommand->SetResultValue( myNewID );
4706 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4707 theCommand->SetMethod( "GetFilterFromCriteria" );
4709 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4710 GetCreationCmd()->Clear();
4711 GetCreationCmd()->GetString() = theCommand->GetString();
4712 theCommand->Clear();
4713 theCommand->AddDependantCmd( GetCreationCmd() );
4714 // why swap? -- it's needed
4715 //GetCreationCmd()->Clear();
4717 else if ( theCommand->GetMethod() == "SetMesh" )
4719 if ( myMesh == theCommand->GetArg( 1 ))
4720 theCommand->Clear();
4722 myMesh = theCommand->GetArg( 1 );
4723 theGen->AddMeshAccessorMethod( theCommand );
4727 //================================================================================
4729 * \brief Set new filter name to the creation command and to myArgCmds
4731 //================================================================================
4733 void _pyFilter::Flush()
4735 if ( myNewID.IsEmpty() ) return;
4737 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4738 for ( ; cmd != myArgCmds.end(); ++cmd )
4739 if ( !(*cmd)->IsEmpty() )
4741 _AString cmdStr = (*cmd)->GetString();
4742 _AString id = GetID();
4743 int pos = cmdStr.Search( id );
4746 cmdStr.Remove( pos, id.Length() );
4747 cmdStr.Insert( pos, myNewID );
4750 (*cmd)->GetString() = cmdStr;
4753 if ( !GetCreationCmd()->IsEmpty() )
4754 GetCreationCmd()->SetResultValue( myNewID );
4757 //================================================================================
4759 * \brief Return true if all my users can be cleared
4761 //================================================================================
4763 bool _pyObject::CanClear()
4765 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4766 for ( ; cmd != myArgCmds.end(); ++cmd )
4767 if ( !(*cmd)->IsEmpty() )
4769 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4770 if ( !obj.IsNull() && !obj->CanClear() )
4773 return ( !myIsPublished );
4776 //================================================================================
4778 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4780 //================================================================================
4782 _pyHypothesisReader::_pyHypothesisReader()
4785 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4786 LDOMParser xmlParser;
4787 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4789 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4793 INFOS( xmlParser.GetError(data) );
4796 // <algorithm type="Regular_1D"
4797 // label-id="Wire discretisation"
4800 // <algo>Regular_1D=Segment()</algo>
4801 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4803 LDOM_Document xmlDoc = xmlParser.getDocument();
4804 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4805 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4807 LDOM_Node algoNode = algoNodeList.item( i );
4808 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4809 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4810 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4812 _AString text, algoType, method, arg;
4813 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4815 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4816 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4817 text = textNode.getNodeValue();
4818 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4819 algoType = algoCmd->GetResultValue();
4820 method = algoCmd->GetMethod();
4821 arg = algoCmd->GetArg(1);
4822 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4824 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4825 algo->SetConvMethodAndType( method, algoType );
4826 if ( !arg.IsEmpty() )
4827 algo->setCreationArg( 1, arg );
4829 myType2Hyp[ algoType ] = algo;
4833 if ( algoType.IsEmpty() ) continue;
4835 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4837 Handle( _pyHypothesis ) hyp;
4838 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4840 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4841 LDOM_Node textNode = pyHypoNode.getFirstChild();
4842 text = textNode.getNodeValue();
4843 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4844 hypType = hypoCmd->GetResultValue();
4845 method = hypoCmd->GetMethod();
4846 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4848 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4849 if ( type2hyp == myType2Hyp.end() )
4850 hyp = new _pyHypothesis( hypoCmd );
4852 hyp = type2hyp->second;
4853 hyp->SetConvMethodAndType( method, algoType );
4854 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4856 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4857 _AString argMethod = argCmd.GetMethod();
4858 _AString argNbText = argCmd.GetArg( 1 );
4859 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4860 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4862 hyp->AddArgMethod( argMethod,
4863 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4865 myType2Hyp[ hypType ] = hyp;
4869 // <hypothesis type="BLSURF_Parameters"
4873 // <accumulative-methods>
4874 // SetEnforcedVertex,
4875 // SetEnforcedVertexNamed
4876 // </accumulative-methods>
4880 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4881 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4883 LDOM_Node hypNode = hypNodeList.item( i );
4884 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4885 _AString hypType = hypElem.getAttribute("type");
4886 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4887 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4889 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4890 if ( type2hyp == myType2Hyp.end() ) continue;
4892 LDOM_Node methNode = methNodeList.item( 0 );
4893 LDOM_Node textNode = methNode.getFirstChild();
4894 _AString text = textNode.getNodeValue();
4898 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4899 pos += method.Length();
4900 type2hyp->second->AddAccumulativeMethod( method );
4902 while ( !method.IsEmpty() );
4905 } // loop on xmlPaths
4908 //================================================================================
4910 * \brief Returns a new hypothesis initialized according to the read information
4912 //================================================================================
4914 Handle(_pyHypothesis)
4915 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4916 const Handle(_pyCommand)& creationCmd) const
4918 Handle(_pyHypothesis) resHyp, sampleHyp;
4920 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4921 if ( type2hyp != myType2Hyp.end() )
4922 sampleHyp = type2hyp->second;
4924 if ( sampleHyp.IsNull() )
4926 resHyp = new _pyHypothesis(creationCmd);
4930 if ( sampleHyp->IsAlgo() )
4931 resHyp = new _pyAlgorithm( creationCmd );
4933 resHyp = new _pyHypothesis(creationCmd);
4934 resHyp->Assign( sampleHyp, _pyID() );
4939 //================================================================================
4941 * \brief Adds an object ID to some family of IDs with a common prefix
4942 * \param [in] str - the object ID
4943 * \return bool - \c false if \a str does not have the same prefix as \a this family
4944 * (for internal usage)
4946 //================================================================================
4948 bool _pyStringFamily::Add( const char* str )
4950 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4951 return false; // expected prefix is missing
4953 str += _prefix.Length(); // skip _prefix
4955 // try to add to some of child falimies
4956 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4957 for ( ; itSub != _subFams.end(); ++itSub )
4958 if ( itSub->Add( str ))
4961 // no suitable family found - add str to _strings or create a new child family
4963 // look for a proper place within sorted _strings
4964 std::list< _AString >::iterator itStr = _strings.begin();
4965 while ( itStr != _strings.end() && itStr->IsLess( str ))
4967 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4968 return true; // same ID already kept
4970 const int minPrefixSize = 4;
4972 // count "smaller" strings with the same prefix
4973 std::list< _AString >::iterator itLess = itStr; --itLess;
4975 for ( ; itLess != _strings.end(); --itLess )
4976 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4981 // count "greater" strings with the same prefix
4982 std::list< _AString >::iterator itMore = itStr;
4984 for ( ; itMore != _strings.end(); ++itMore )
4985 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4990 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4992 // look for a maximal prefix length
4993 // int lessPrefSize = 3, morePrefSize = 3;
4994 // if ( nbLess > 0 )
4995 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
4997 // if ( nbMore > 0 )
4998 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5000 // int prefixSize = 3;
5001 // if ( nbLess == 0 )
5002 // prefixSize = morePrefSize;
5003 // else if ( nbMore == 0 )
5004 // prefixSize = lessPrefSize;
5006 // prefixSize = Min( lessPrefSize, morePrefSize );
5007 int prefixSize = minPrefixSize;
5008 _AString newPrefix ( str, prefixSize );
5010 // look for a proper place within _subFams sorted by _prefix
5011 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5012 if ( !itSub->_prefix.IsLess( newPrefix ))
5015 // add the new _pyStringFamily
5016 itSub = _subFams.insert( itSub, _pyStringFamily());
5017 _pyStringFamily& newSubFam = *itSub;
5018 newSubFam._prefix = newPrefix;
5020 // pass this->_strings to newSubFam._strings
5021 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5022 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5023 newSubFam._strings.push_back( str + prefixSize );
5024 for ( ; nbMore > 0; --nbMore, ++itStr )
5025 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5027 _strings.erase( itLess, ++itMore );
5029 else // to few string to make a family fot them
5031 _strings.insert( itStr, str );
5036 //================================================================================
5038 * \brief Finds an object ID in the command
5039 * \param [in] longStr - the command string
5040 * \param [out] subStr - the found object ID
5041 * \return bool - \c true if the object ID found
5043 //================================================================================
5045 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5047 const _AString& longStr = cmd->GetString();
5048 const char* s = longStr.ToCString();
5051 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5052 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5053 if ( argBeg < 4 || argBeg > longStr.Length() )
5055 for ( ; itSub != _subFams.end(); ++itSub )
5058 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5059 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5061 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5062 from = pos + len + itSub->_prefix.Length();
5067 from += itSub->_prefix.Length();
5070 // look among _strings
5071 std::list< _AString >::iterator itStr = _strings.begin();
5072 for ( ; itStr != _strings.end(); ++itStr )
5073 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5074 // check that object ID does not continue after len
5075 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5077 subStr.push_back( *itStr );
5083 //================================================================================
5085 * \brief Return remainder length of the object ID after my _prefix
5086 * \param [in] str - remainder of the command after my _prefix
5087 * \return int - length of the object ID or -1 if not found
5089 //================================================================================
5091 int _pyStringFamily::isIn( const char* str )
5093 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5095 for ( ; itSub != _subFams.end(); ++itSub )
5097 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5100 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5101 return itSub->_prefix.Length() + len;
5106 if ( !_strings.empty() )
5108 std::list< _AString >::iterator itStr = _strings.begin();
5109 bool firstEmpty = itStr->IsEmpty();
5112 for ( ; itStr != _strings.end(); ++itStr )
5114 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5117 len = itStr->Length();
5126 // check that object ID does not continue after len
5127 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5134 //================================================================================
5138 //================================================================================
5140 void _pyStringFamily::Print( int level )
5142 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5143 std::list< _AString >::iterator itStr = _strings.begin();
5144 for ( ; itStr != _strings.end(); ++itStr )
5145 cout << *itStr << " | ";
5147 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5148 for ( ; itSub != _subFams.end(); ++itSub )
5149 itSub->Print( level + 1 );
5151 cout << string( 70, '-' ) << endl;