1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
53 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
71 using SMESH::TPythonDump;
74 * \brief Container of commands into which the initial script is split.
75 * It also contains data corresponding to SMESH_Gen contents
77 static Handle(_pyGen) theGen;
79 static TCollection_AsciiString theEmptyString;
81 //#define DUMP_CONVERSION
83 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
84 #undef DUMP_CONVERSION
90 //================================================================================
92 * \brief Set of TCollection_AsciiString initialized by C array of C strings
94 //================================================================================
96 struct TStringSet: public set<TCollection_AsciiString>
99 * \brief Filling. The last string must be ""
101 void Insert(const char* names[]) {
102 for ( int i = 0; names[i][0] ; ++i )
103 insert( (char*) names[i] );
106 * \brief Check if a string is in
108 bool Contains(const TCollection_AsciiString& name ) {
109 return find( name ) != end();
113 //================================================================================
115 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
116 * Odd items of the C array are map keys, and even items are values
118 //================================================================================
120 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
123 * \brief Filling. The last string must be ""
125 void Insert(const char* names_values[]) {
126 for ( int i = 0; names_values[i][0] ; i += 2 )
127 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
130 * \brief Check if a string is in
132 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
133 map< _AString, _AString >::iterator it = find( name );
134 return it == end() ? "" : it->second;
138 //================================================================================
140 * \brief Returns a mesh by object
142 //================================================================================
144 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
148 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
149 return Handle(_pyMesh)::DownCast( obj );
150 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
151 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
152 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
153 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
155 return Handle(_pyMesh)();
158 //================================================================================
160 * \brief Check if objects used as args have been created by previous commands
162 //================================================================================
164 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
166 // either comment or erase a command including NotPublishedObjectName()
167 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
169 bool isResultPublished = false;
170 const int nbRes = cmd->GetNbResultValues();
171 for ( int i = 0; i < nbRes; i++ )
173 _pyID objID = cmd->GetResultValue( i+1 );
174 if ( cmd->IsStudyEntry( objID ))
175 isResultPublished = (! theGen->IsNotPublished( objID ));
176 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
178 if ( isResultPublished )
184 // check if an Object was created in the script
187 _pyID obj = cmd->GetObject();
188 if ( obj.Search( "print(" ) == 1 )
189 return; // print statement
191 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
192 // remove an accessor method
193 obj = _pyCommand( obj ).GetObject();
195 const bool isMethodCall = cmd->IsMethodCall();
196 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
198 comment = "not created Object";
199 theGen->ObjectCreationRemoved( obj );
201 // check if a command has not created args
202 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
204 const _pyID& arg = cmd->GetArg( iArg );
205 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
207 list< _pyID > idList = cmd->GetStudyEntries( arg );
208 list< _pyID >::iterator id = idList.begin();
209 for ( ; id != idList.end(); ++id )
210 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
212 comment += *id + " has not been yet created";
215 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
216 // comment += arg + " has not been yet created";
218 // treat result objects
219 const _pyID& result = cmd->GetResultValue();
220 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
222 list< _pyID > idList = cmd->GetStudyEntries( result );
223 list< _pyID >::iterator id = idList.begin();
224 for ( ; id != idList.end(); ++id )
226 if ( comment.IsEmpty() )
227 presentObjects.insert( *id );
229 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
231 if ( idList.empty() && cmd->IsID( result ))
232 presentObjects.insert( result );
234 // comment the command
235 if ( !comment.IsEmpty() )
238 cmd->GetString() += " ### ";
239 cmd->GetString() += comment;
243 //================================================================================
245 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
247 //================================================================================
249 void fixFunctorType( TCollection_AsciiString& Type,
250 TCollection_AsciiString& Compare,
251 TCollection_AsciiString& UnaryOp,
252 TCollection_AsciiString& BinaryOp )
254 // The problem is that dumps of old studies created using filters becomes invalid
255 // when new items are inserted in the enum SMESH::FunctorType since values
256 // of this enum are dumped as integer values.
257 // This function corrects enum values of old studies given as args (Type,Compare,...)
258 // We can find out how to correct them by value of BinaryOp which can have only two
259 // values: FT_Undefined or FT_LogicalNOT.
260 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
261 // where PythonDump appeared
262 // v 3.0.0: FT_Undefined == 25
263 // v 3.1.0: FT_Undefined == 26, new items:
265 // v 4.1.2: FT_Undefined == 27, new items:
266 // - FT_BelongToGenSurface = 17
267 // v 5.1.1: FT_Undefined == 32, new items:
268 // - FT_FreeNodes = 10
269 // - FT_FreeFaces = 11
270 // - FT_LinearOrQuadratic = 23
271 // - FT_GroupColor = 24
272 // - FT_ElemGeomType = 25
273 // v 5.1.5: FT_Undefined == 33, new items:
274 // - FT_CoplanarFaces = 26
275 // v 6.2.0: FT_Undefined == 39, new items:
276 // - FT_MaxElementLength2D = 8
277 // - FT_MaxElementLength3D = 9
278 // - FT_BareBorderVolume = 25
279 // - FT_BareBorderFace = 26
280 // - FT_OverConstrainedVolume = 27
281 // - FT_OverConstrainedFace = 28
282 // v 6.5.0: FT_Undefined == 43, new items:
283 // - FT_EqualNodes = 14
284 // - FT_EqualEdges = 15
285 // - FT_EqualFaces = 16
286 // - FT_EqualVolumes = 17
287 // v 6.6.0: FT_Undefined == 44, new items:
288 // - FT_BallDiameter = 37
289 // v 6.7.1: FT_Undefined == 45, new items:
290 // - FT_EntityType = 36
291 // v 7.3.0: FT_Undefined == 46, new items:
292 // - FT_ConnectedElements = 39
293 // v 7.6.0: FT_Undefined == 47, new items:
294 // - FT_BelongToMeshGroup = 22
295 // v 8.1.0: FT_Undefined == 48, new items:
296 // - FT_NodeConnectivityNumber= 22
297 // v 8.5.0: FT_Undefined == 49, new items:
298 // - FT_Deflection2D = 22
300 // It's necessary to continue recording this history and to fill
301 // undef2newItems (see below) accordingly.
303 typedef map< int, vector< int > > TUndef2newItems;
304 static TUndef2newItems undef2newItems;
305 if ( undef2newItems.empty() )
307 undef2newItems[ 26 ].push_back( 7 );
308 undef2newItems[ 27 ].push_back( 17 );
309 { int items[] = { 10, 11, 23, 24, 25 };
310 undef2newItems[ 32 ].assign( items, items+5 ); }
311 undef2newItems[ 33 ].push_back( 26 );
312 { int items[] = { 8, 9, 25, 26, 27, 28 };
313 undef2newItems[ 39 ].assign( items, items+6 ); }
314 { int items[] = { 14, 15, 16, 17 };
315 undef2newItems[ 43 ].assign( items, items+4 ); }
316 undef2newItems[ 44 ].push_back( 37 );
317 undef2newItems[ 45 ].push_back( 36 );
318 undef2newItems[ 46 ].push_back( 39 );
319 undef2newItems[ 47 ].push_back( 22 );
320 undef2newItems[ 48 ].push_back( 22 );
321 undef2newItems[ 49 ].push_back( 22 );
323 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
326 int iType = Type.IntegerValue();
327 int iCompare = Compare.IntegerValue();
328 int iUnaryOp = UnaryOp.IntegerValue();
329 int iBinaryOp = BinaryOp.IntegerValue();
331 // find out integer value of FT_Undefined at the moment of dump
332 int oldUndefined = iBinaryOp;
333 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
336 // apply history to args
337 TUndef2newItems::const_iterator undef_items =
338 undef2newItems.upper_bound( oldUndefined );
339 if ( undef_items != undef2newItems.end() )
341 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
342 for ( ; undef_items != undef2newItems.end(); ++undef_items )
344 const vector< int > & addedItems = undef_items->second;
345 for ( size_t i = 0; i < addedItems.size(); ++i )
346 for ( int iArg = 0; iArg < 4; ++iArg )
348 int& arg = *pArg[iArg];
349 if ( arg >= addedItems[i] )
353 Type = TCollection_AsciiString( iType );
354 Compare = TCollection_AsciiString( iCompare );
355 UnaryOp = TCollection_AsciiString( iUnaryOp );
356 BinaryOp = TCollection_AsciiString( iBinaryOp );
360 //================================================================================
362 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
363 * arguments of a given command by a list "[x,y,z]" if the list is accessible
366 //================================================================================
368 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
370 static TStringSet methodsAcceptingList;
371 if ( methodsAcceptingList.empty() ) {
372 const char * methodNames[] = {
373 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
374 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
375 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
376 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
377 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
378 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
379 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
380 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
381 "Translate","TranslateMakeGroups","TranslateMakeMesh",
382 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
383 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
384 ,"" }; // <- mark of the end
385 methodsAcceptingList.Insert( methodNames );
387 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
389 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
391 const _AString & arg = theCommand->GetArg( i );
392 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
393 arg.Search( "SMESH.DirStruct" ) == 1 )
395 Handle(_pyCommand) workCmd = new _pyCommand( arg );
396 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
398 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
400 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
402 _AString newArg = "[ ";
403 newArg += ( workCmd->GetArg( 1 ) + ", " +
404 workCmd->GetArg( 2 ) + ", " +
405 workCmd->GetArg( 3 ) + " ]");
406 theCommand->SetArg( i, newArg );
412 //================================================================================
414 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
415 * a list "[id1,id2]" if the list is an accessible type of argument.
417 //================================================================================
419 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
421 static TStringSet methodsAcceptingList;
422 if ( methodsAcceptingList.empty() ) {
423 const char * methodNames[] = {
424 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
425 "ExportCGNS","ExportGMF",
426 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
427 "ScaleMakeGroups","Scale","ScaleMakeMesh",
428 "FindCoincidentNodesOnPartBut","DoubleElements",
429 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
430 ,"" }; // <- mark of the end
431 methodsAcceptingList.Insert( methodNames );
433 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
435 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
437 _pyCommand argCmd( theCommand->GetArg( i ));
438 if ( argCmd.GetMethod() == "GetIDSource" &&
439 argCmd.GetNbArgs() == 2 )
441 theCommand->SetArg( i, argCmd.GetArg( 1 ));
447 bool _FilterArg( const _AString& theArg )
449 static std::list<_AString> filteredArgs;
450 static bool initialized = false;
451 if ( !initialized ) {
453 filteredArgs.push_back( "SMESH.MED_V2_1" );
454 filteredArgs.push_back( "SMESH.MED_V2_2" );
456 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
460 //================================================================================
462 * \brief Convert a python script using commands of smeshBuilder.py
463 * \param theScriptLines - Lines of the input script
464 * \param theEntry2AccessorMethod - returns method names to access to
465 * objects wrapped with python class
466 * \param theObjectNames - names of objects
467 * \param theRemovedObjIDs - entries of objects whose created commands were removed
468 * \param theHistoricalDump - true means to keep all commands, false means
469 * to exclude commands relating to objects removed from study
470 * \retval TCollection_AsciiString - Conversion result
472 //================================================================================
475 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
476 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
477 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
478 std::set< TCollection_AsciiString >& theRemovedObjIDs,
479 const bool theToKeepAllCommands)
481 std::list< TCollection_AsciiString >::iterator lineIt;
482 // process notebook variables
484 SMESH_NoteBook aNoteBook;
486 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
487 aNoteBook.AddCommand( *lineIt );
489 theScriptLines.clear();
491 aNoteBook.ReplaceVariables();
493 aNoteBook.GetResultLines( theScriptLines );
496 // convert to smeshBuilder.py API
498 theGen = new _pyGen( theEntry2AccessorMethod,
501 theToKeepAllCommands );
503 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
504 theGen->AddCommand( *lineIt );
506 theScriptLines.clear();
510 #ifdef DUMP_CONVERSION
511 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
514 // clean commands of removed objects depending on myIsPublished flag
515 theGen->ClearCommands();
517 // reorder commands after conversion
518 list< Handle(_pyCommand) >::iterator cmd;
521 orderChanges = false;
522 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
523 if ( (*cmd)->SetDependentCmdsAfter() )
525 } while ( orderChanges );
527 // concat commands back into a script
528 TCollection_AsciiString aPrevCmd;
529 set<_pyID> createdObjects;
530 createdObjects.insert( "smeshBuilder" );
531 createdObjects.insert( "smesh" );
532 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
534 #ifdef DUMP_CONVERSION
535 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
537 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
538 CheckObjectPresence( *cmd, createdObjects );
539 if ( !(*cmd)->IsEmpty() ) {
540 aPrevCmd = (*cmd)->GetString();
541 theScriptLines.push_back( aPrevCmd );
550 //================================================================================
552 * \brief _pyGen constructor
554 //================================================================================
556 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
557 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
558 std::set< TCollection_AsciiString >& theRemovedObjIDs,
559 const bool theToKeepAllCommands)
560 : _pyObject( new _pyCommand( "", 0 )),
562 myID2AccessorMethod( theEntry2AccessorMethod ),
563 myObjectNames( theObjectNames ),
564 myRemovedObjIDs( theRemovedObjIDs ),
566 myToKeepAllCommands( theToKeepAllCommands ),
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() )
579 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->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 // Wrap Export*() into try-except
693 if ( aCommand->MethodStartsFrom("Export"))
696 _AString indent = aCommand->GetIndentation();
697 _AString tryStr = indent + "try:";
698 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
699 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
700 _AString excStr = indent + "except:";
701 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
703 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
705 aCommand->GetString() = newCmd;
706 aCommand->SetOrderNb( ++myNbCommands );
707 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
708 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
709 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
711 // check for mesh editor object
712 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
713 _pyID editorID = aCommand->GetResultValue();
714 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
715 myMeshEditors.insert( make_pair( editorID, editor ));
718 // check for SubMesh objects
719 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
720 _pyID subMeshID = aCommand->GetResultValue();
721 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
722 AddObject( subMesh );
725 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
726 GetIDSourceToList( aCommand );
728 //addFilterUser( aCommand, theGen ); // protect filters from clearing
730 id_mesh->second->Process( aCommand );
731 id_mesh->second->AddProcessedCmd( aCommand );
735 // SMESH_MeshEditor method?
736 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
737 if ( id_editor != myMeshEditors.end() )
739 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
740 GetIDSourceToList( aCommand );
742 //addFilterUser( aCommand, theGen ); // protect filters from clearing
744 // some commands of SMESH_MeshEditor create meshes and groups
745 _pyID meshID, groups;
746 if ( method.Search("MakeMesh") != -1 )
747 meshID = aCommand->GetResultValue();
748 else if ( method == "MakeBoundaryMesh")
749 meshID = aCommand->GetResultValue(1);
750 else if ( method == "MakeBoundaryElements")
751 meshID = aCommand->GetResultValue(2);
753 if ( method.Search("MakeGroups") != -1 ||
754 method == "ExtrusionAlongPathX" ||
755 method == "ExtrusionAlongPathObjX" ||
756 method == "DoubleNodeGroupNew" ||
757 method == "DoubleNodeGroupsNew" ||
758 method == "DoubleNodeElemGroupNew" ||
759 method == "DoubleNodeElemGroupsNew" ||
760 method == "DoubleNodeElemGroup2New" ||
761 method == "DoubleNodeElemGroups2New" ||
762 method == "AffectedElemGroupsInRegion"
764 groups = aCommand->GetResultValue();
765 else if ( method == "MakeBoundaryMesh" )
766 groups = aCommand->GetResultValue(2);
767 else if ( method == "MakeBoundaryElements")
768 groups = aCommand->GetResultValue(3);
769 else if ( method == "Create0DElementsOnAllNodes" &&
770 aCommand->GetArg(2).Length() > 2 ) // group name != ''
771 groups = aCommand->GetResultValue();
773 id_editor->second->Process( aCommand );
774 id_editor->second->AddProcessedCmd( aCommand );
777 if ( !meshID.IsEmpty() &&
778 !myMeshes.count( meshID ) &&
779 aCommand->IsStudyEntry( meshID ))
781 _AString processedCommand = aCommand->GetString();
782 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
783 CheckObjectIsReCreated( mesh );
784 myMeshes.insert( make_pair( meshID, mesh ));
786 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
789 if ( !groups.IsEmpty() )
791 if ( !aCommand->IsStudyEntry( meshID ))
792 meshID = id_editor->second->GetMesh();
793 Handle(_pyMesh) mesh = myMeshes[ meshID ];
795 list< _pyID > idList = aCommand->GetStudyEntries( groups );
796 list< _pyID >::iterator grID = idList.begin();
797 for ( ; grID != idList.end(); ++grID )
798 if ( !myObjects.count( *grID ))
800 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
802 if ( !mesh.IsNull() ) mesh->AddGroup( group );
806 } // SMESH_MeshEditor methods
808 // SMESH_Hypothesis method?
809 Handle(_pyHypothesis) hyp = FindHyp( objID );
810 if ( !hyp.IsNull() && !hyp->IsAlgo() )
812 hyp->Process( aCommand );
813 hyp->AddProcessedCmd( aCommand );
817 // aFilterManager.CreateFilter() ?
818 if ( aCommand->GetMethod() == "CreateFilter" )
820 // Set a more human readable name to a filter
821 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
822 _pyID newID, filterID = aCommand->GetResultValue();
823 int pos = filterID.Search( "0x" );
825 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
827 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
830 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
831 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
833 // create _pySelfEraser for functors
834 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
835 functor->IgnoreOwnCalls(); // to erase if not used as an argument
836 AddObject( functor );
839 // other object method?
840 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
841 if ( id_obj != myObjects.end() ) {
842 id_obj->second->Process( aCommand );
843 id_obj->second->AddProcessedCmd( aCommand );
847 // Add access to a wrapped mesh
848 AddMeshAccessorMethod( aCommand );
850 // Add access to a wrapped algorithm
851 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
853 // PAL12227. PythonDump was not updated at proper time; result is
854 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
855 // TypeError: __init__() takes exactly 11 arguments (10 given)
856 const char wrongCommand[] = "SMESH.Filter.Criterion(";
857 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
859 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
860 // there must be 10 arguments, 5-th arg ThresholdID is missing,
861 const int wrongNbArgs = 9, missingArg = 5;
862 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
864 for ( int i = wrongNbArgs; i > missingArg; --i )
865 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
866 tmpCmd.SetArg( missingArg, "''");
867 aCommand->GetString().Trunc( beg - 1 );
868 aCommand->GetString() += tmpCmd.GetString();
871 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
873 // instead of "SMESH.Filter.Criterion(
874 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
875 // 1 2 3 4 5 6 7 8 9 10
876 // in order to avoid the problem of type mismatch of long and FunctorType
877 const TCollection_AsciiString
878 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
879 TCollection_AsciiString
880 Type = aCommand->GetArg(1), // long
881 Compare = aCommand->GetArg(2), // long
882 Threshold = aCommand->GetArg(3), // double
883 ThresholdStr = aCommand->GetArg(4), // string
884 ThresholdID = aCommand->GetArg(5), // string
885 UnaryOp = aCommand->GetArg(6), // long
886 BinaryOp = aCommand->GetArg(7), // long
887 Tolerance = aCommand->GetArg(8), // double
888 TypeOfElement = aCommand->GetArg(9), // ElementType
889 Precision = aCommand->GetArg(10); // long
890 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
891 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
892 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
893 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
894 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
896 if ( Compare == "SMESH.FT_EqualTo" )
899 aCommand->RemoveArgs();
900 aCommand->SetObject( SMESH_2smeshpy::GenName() );
901 aCommand->SetMethod( "GetCriterion" );
903 aCommand->SetArg( 1, TypeOfElement );
904 aCommand->SetArg( 2, Type );
905 aCommand->SetArg( 3, Compare );
907 if ( Threshold.IsIntegerValue() )
909 int iGeom = Threshold.IntegerValue();
910 if ( Type == "SMESH.FT_ElemGeomType" )
912 // set SMESH.GeometryType instead of a numerical Threshold
913 const int nbTypes = SMESH::Geom_LAST;
914 const char* types[] = {
915 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
916 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
917 "Geom_POLYHEDRA", "Geom_BALL" };
918 if ( -1 < iGeom && iGeom < nbTypes )
919 Threshold = SMESH + types[ iGeom ];
921 // is types complete? (compilation failure mains that enum GeometryType changed)
922 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
925 if (Type == "SMESH.FT_EntityType")
927 // set SMESH.EntityType instead of a numerical Threshold
928 const int nbTypes = SMESH::Entity_Last;
929 const char* types[] = {
930 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
931 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
932 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
933 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
934 "Entity_Pyramid", "Entity_Quad_Pyramid",
935 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
936 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
937 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
938 if ( -1 < iGeom && iGeom < nbTypes )
939 Threshold = SMESH + types[ iGeom ];
941 // is 'types' complete? (compilation failure mains that enum EntityType changed)
942 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
946 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
947 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
948 else if ( ThresholdStr.Length() != 2 )
949 aCommand->SetArg( 4, ThresholdStr );
950 else if ( ThresholdID.Length() != 2 )
951 aCommand->SetArg( 4, ThresholdID );
953 aCommand->SetArg( 4, Threshold );
954 // find the last not default arg
956 if ( Tolerance == dfltTol ) {
958 if ( BinaryOp == dfltFunctor ) {
960 if ( UnaryOp == dfltFunctor )
964 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
965 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
966 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
967 if ( Precision != dfltPreci )
969 TCollection_AsciiString crit = aCommand->GetResultValue();
970 aCommand->GetString() += "; ";
971 aCommand->GetString() += crit + ".Precision = " + Precision;
977 //================================================================================
979 * \brief Convert the command or remember it for later conversion
980 * \param theCommand - The python command calling a method of SMESH_Gen
982 //================================================================================
984 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
986 // there are methods to convert:
987 // CreateMesh( shape )
988 // Concatenate( [mesh1, ...], ... )
989 // CreateHypothesis( theHypType, theLibName )
990 // Compute( mesh, geom )
991 // Evaluate( mesh, geom )
993 TCollection_AsciiString method = theCommand->GetMethod();
995 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
997 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1001 if ( method == "CreateMeshesFromUNV" ||
1002 method == "CreateMeshesFromSTL" ||
1003 method == "CopyMesh" ) // command result is a mesh
1005 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1009 if( method == "CreateMeshesFromMED" ||
1010 method == "CreateMeshesFromSAUV"||
1011 method == "CreateMeshesFromCGNS" ||
1012 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1014 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1015 std::list< _pyID >::iterator meshID = meshIDs.begin();
1016 for ( ; meshID != meshIDs.end(); ++meshID )
1018 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1021 if ( method == "CreateMeshesFromGMF" )
1023 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1024 // CreateMeshesFromGMF( theFileName )
1025 _AString file = theCommand->GetArg(1);
1026 theCommand->RemoveArgs();
1027 theCommand->SetArg( 1, file );
1031 // CreateHypothesis()
1032 if ( method == "CreateHypothesis" )
1034 // issue 199929, remove standard library name (default parameter)
1035 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1036 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1037 // keep the first argument
1038 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1039 theCommand->RemoveArgs();
1040 theCommand->SetArg( 1, arg );
1043 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1044 CheckObjectIsReCreated( hyp );
1045 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1050 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1051 if ( method == "Compute" )
1053 const _pyID& meshID = theCommand->GetArg( 1 );
1054 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1055 if ( id_mesh != myMeshes.end() ) {
1056 theCommand->SetObject( meshID );
1057 theCommand->RemoveArgs();
1058 id_mesh->second->Process( theCommand );
1059 id_mesh->second->AddProcessedCmd( theCommand );
1064 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1065 if ( method == "Evaluate" )
1067 const _pyID& meshID = theCommand->GetArg( 1 );
1068 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1069 if ( id_mesh != myMeshes.end() ) {
1070 theCommand->SetObject( meshID );
1071 _pyID geom = theCommand->GetArg( 2 );
1072 theCommand->RemoveArgs();
1073 theCommand->SetArg( 1, geom );
1074 id_mesh->second->AddProcessedCmd( theCommand );
1079 // objects erasing creation command if no more its commands invoked:
1080 // SMESH_Pattern, FilterManager
1081 if ( method == "GetPattern" ||
1082 method == "CreateFilterManager" ||
1083 method == "CreateMeasurements" )
1085 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1086 if ( !AddObject( obj ) )
1087 theCommand->Clear(); // already created
1089 // Concatenate( [mesh1, ...], ... )
1090 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1092 if ( method == "ConcatenateWithGroups" ) {
1093 theCommand->SetMethod( "Concatenate" );
1094 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1096 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1098 AddMeshAccessorMethod( theCommand );
1100 else if ( method == "SetName" ) // SetName(obj,name)
1102 // store theCommand as one of object commands to erase it along with the object
1103 const _pyID& objID = theCommand->GetArg( 1 );
1104 Handle(_pyObject) obj = FindObject( objID );
1105 if ( !obj.IsNull() )
1106 obj->AddProcessedCmd( theCommand );
1109 // Replace name of SMESH_Gen
1111 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1112 static TStringSet smeshpyMethods;
1113 if ( smeshpyMethods.empty() ) {
1114 const char * names[] =
1115 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1116 "GetPattern","GetSubShapesId",
1117 "" }; // <- mark of array end
1118 smeshpyMethods.Insert( names );
1120 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1121 // smeshgen.Method() --> smesh.Method()
1122 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1124 // smeshgen.Method() --> smesh.Method()
1125 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1128 //================================================================================
1130 * \brief Convert the remembered commands
1132 //================================================================================
1134 void _pyGen::Flush()
1136 // create an empty command
1137 myLastCommand = new _pyCommand();
1139 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1140 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1141 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1143 if ( IsToKeepAllCommands() ) // historical dump
1145 // set myIsPublished = true to all objects
1146 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1147 id_mesh->second->SetRemovedFromStudy( false );
1148 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1149 id_hyp->second->SetRemovedFromStudy( false );
1150 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1151 id_obj->second->SetRemovedFromStudy( false );
1155 // let hypotheses find referred objects in order to prevent clearing
1156 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1157 list< Handle(_pyMesh) > fatherMeshes;
1158 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1159 if ( !id_hyp->second.IsNull() )
1160 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1162 // set myIsPublished = false to all objects depending on
1163 // meshes built on a removed geometry
1164 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1165 if ( id_mesh->second->IsNotGeomPublished() )
1166 id_mesh->second->SetRemovedFromStudy( true );
1169 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1170 if ( ! id_mesh->second.IsNull() )
1171 id_mesh->second->Flush();
1174 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1175 if ( !id_hyp->second.IsNull() ) {
1176 id_hyp->second->Flush();
1177 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1178 if ( !id_hyp->second->IsWrapped() )
1179 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1182 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1183 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1184 for ( ; robj != myOrderedObjects.rend(); ++robj )
1185 if ( ! robj->IsNull() )
1187 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1188 for ( ; obj != myOrderedObjects.end(); ++obj )
1189 if ( ! obj->IsNull() )
1192 myLastCommand->SetOrderNb( ++myNbCommands );
1193 myCommands.push_back( myLastCommand );
1196 //================================================================================
1198 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1199 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1201 //================================================================================
1203 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1205 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1206 // for ( ; id_obj != myObjects.end(); ++id_obj )
1208 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1209 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1211 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1212 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1214 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1215 // list< _pyID >::iterator id = idList.begin();
1216 // for ( ; id != idList.end(); ++id )
1217 // if ( id_obj->first == *id )
1218 // // _pySubMesh::Process() does what we need
1219 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1224 //================================================================================
1226 * \brief Clean commands of removed objects depending on myIsPublished flag
1228 //================================================================================
1230 void _pyGen::ClearCommands()
1232 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1233 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1234 id_mesh->second->ClearCommands();
1236 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1237 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1238 if ( !id_hyp->second.IsNull() )
1239 id_hyp->second->ClearCommands();
1241 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1242 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1243 for ( ; robj != myOrderedObjects.rend(); ++robj )
1244 if ( ! robj->IsNull() )
1245 (*robj)->ClearCommands();
1246 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1247 for ( ; obj != myOrderedObjects.end(); ++obj )
1248 if ( ! obj->IsNull() )
1249 (*obj)->ClearCommands();
1252 //================================================================================
1254 * \brief Release mutual handles of objects
1256 //================================================================================
1260 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1261 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1262 id_mesh->second->Free();
1265 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1266 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1267 id_ed->second->Free();
1268 myMeshEditors.clear();
1270 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1271 for ( ; id_obj != myObjects.end(); ++id_obj )
1272 id_obj->second->Free();
1275 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1276 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1277 if ( !id_hyp->second.IsNull() )
1278 id_hyp->second->Free();
1281 myFile2ExportedMesh.clear();
1283 //myKeepAgrCmdsIDs.Print();
1286 //================================================================================
1288 * \brief Add access method to mesh that is an argument
1289 * \param theCmd - command to add access method
1290 * \retval bool - true if added
1292 //================================================================================
1294 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1297 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1298 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1299 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1305 //================================================================================
1307 * \brief Add access method to algo that is an object or an argument
1308 * \param theCmd - command to add access method
1309 * \retval bool - true if added
1311 //================================================================================
1313 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1316 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1317 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1318 if ( !id_hyp->second.IsNull() &&
1319 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1320 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1321 id_hyp->second->AccessorMethod() ))
1327 //================================================================================
1329 * \brief Find hypothesis by ID (entry)
1330 * \param theHypID - The hypothesis ID
1331 * \retval Handle(_pyHypothesis) - The found hypothesis
1333 //================================================================================
1335 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1337 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1338 if ( id_hyp != myHypos.end() &&
1339 !id_hyp->second.IsNull() &&
1340 theHypID == id_hyp->second->GetID() )
1341 return id_hyp->second;
1342 return Handle(_pyHypothesis)();
1345 //================================================================================
1347 * \brief Find algorithm able to create a hypothesis
1348 * \param theGeom - The shape ID the algorithm was created on
1349 * \param theMesh - The mesh ID that created the algorithm
1350 * \param theHypothesis - The hypothesis the algorithm should be able to create
1351 * \retval Handle(_pyHypothesis) - The found algo
1353 //================================================================================
1355 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1356 const Handle(_pyHypothesis)& theHypothesis )
1358 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1359 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1360 if ( !id_hyp->second.IsNull() &&
1361 id_hyp->second->IsAlgo() &&
1362 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1363 id_hyp->second->GetGeom() == theGeom &&
1364 id_hyp->second->GetMesh() == theMesh )
1365 return id_hyp->second;
1366 return Handle(_pyHypothesis)();
1369 //================================================================================
1371 * \brief Find subMesh by ID (entry)
1372 * \param theSubMeshID - The subMesh ID
1373 * \retval Handle(_pySubMesh) - The found subMesh
1375 //================================================================================
1377 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1379 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1380 if ( id_subMesh != myObjects.end() )
1381 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1382 return Handle(_pySubMesh)();
1386 //================================================================================
1388 * \brief Change order of commands in the script
1389 * \param theCmd1 - One command
1390 * \param theCmd2 - Another command
1392 //================================================================================
1394 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1396 list< Handle(_pyCommand) >::iterator pos1, pos2;
1397 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1398 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1399 myCommands.insert( pos1, theCmd2 );
1400 myCommands.insert( pos2, theCmd1 );
1401 myCommands.erase( pos1 );
1402 myCommands.erase( pos2 );
1404 int nb1 = theCmd1->GetOrderNb();
1405 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1406 theCmd2->SetOrderNb( nb1 );
1407 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1408 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1411 //================================================================================
1413 * \brief Set one command after the other
1414 * \param theCmd - Command to move
1415 * \param theAfterCmd - Command ater which to insert the first one
1417 //================================================================================
1419 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1421 setNeighbourCommand( theCmd, theAfterCmd, true );
1424 //================================================================================
1426 * \brief Set one command before the other
1427 * \param theCmd - Command to move
1428 * \param theBeforeCmd - Command before which to insert the first one
1430 //================================================================================
1432 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1434 setNeighbourCommand( theCmd, theBeforeCmd, false );
1437 //================================================================================
1439 * \brief Set one command before or after the other
1440 * \param theCmd - Command to move
1441 * \param theOtherCmd - Command ater or before which to insert the first one
1443 //================================================================================
1445 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1446 Handle(_pyCommand)& theOtherCmd,
1447 const bool theIsAfter )
1449 list< Handle(_pyCommand) >::iterator pos;
1450 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1451 myCommands.erase( pos );
1452 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1453 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1456 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1457 (*pos)->SetOrderNb( i++ );
1460 //================================================================================
1462 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1464 //================================================================================
1466 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1468 // No more needed after adding _pyObject::myArgCommands
1470 // const char filterPrefix[] = "aFilter0x";
1471 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1474 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1476 // const _AString & arg = theCommand->GetArg( i );
1477 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1478 // if ( arg.Search( filterPrefix ) != 1 )
1481 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1482 // if ( !filter.IsNull() )
1484 // filter->AddUser( user );
1485 // if ( !filter->GetNewID().IsEmpty() )
1486 // theCommand->SetArg( i, filter->GetNewID() );
1491 //================================================================================
1493 * \brief Set command be last in list of commands
1494 * \param theCmd - Command to be last
1496 //================================================================================
1498 Handle(_pyCommand)& _pyGen::GetLastCommand()
1500 return myLastCommand;
1503 //================================================================================
1505 * \brief Set method to access to object wrapped with python class
1506 * \param theID - The wrapped object entry
1507 * \param theMethod - The accessor method
1509 //================================================================================
1511 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1513 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1516 //================================================================================
1518 * \brief Generated new ID for object and assign with existing name
1519 * \param theID - ID of existing object
1521 //================================================================================
1523 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1528 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1530 while ( myObjectNames.IsBound( aNewID ) );
1532 if ( myObjectNames.IsBound( theID ) )
1533 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1535 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1539 //================================================================================
1541 * \brief Stores theObj in myObjects
1543 //================================================================================
1545 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1547 if ( theObj.IsNull() ) return false;
1549 CheckObjectIsReCreated( theObj );
1553 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1554 add = myMeshes.insert( make_pair( theObj->GetID(),
1555 Handle(_pyMesh)::DownCast( theObj ))).second;
1557 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1558 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1559 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1562 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1563 if ( add ) myOrderedObjects.push_back( theObj );
1568 //================================================================================
1570 * \brief Erases an existing object with the same ID. This method should be called
1571 * before storing theObj in _pyGen
1573 //================================================================================
1575 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1577 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1580 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1581 Handle(_pyObject) existing;
1583 existing = FindHyp( theObj->GetID() );
1585 existing = FindObject( theObj->GetID() );
1586 if ( !existing.IsNull() && existing != theObj )
1588 existing->SetRemovedFromStudy( true );
1589 existing->ClearCommands();
1592 if ( myHypos.count( theObj->GetID() ))
1593 myHypos.erase( theObj->GetID() );
1595 else if ( myMeshes.count( theObj->GetID() ))
1597 myMeshes.erase( theObj->GetID() );
1599 else if ( myObjects.count( theObj->GetID() ))
1601 myObjects.erase( theObj->GetID() );
1606 //================================================================================
1608 * \brief Re-register an object with other ID to make it Process() commands of
1609 * other object having this ID
1611 //================================================================================
1613 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1615 if ( theObj.IsNull() ) return;
1617 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1618 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1620 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1621 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1624 myObjects.insert( make_pair( theID, theObj ));
1627 //================================================================================
1629 * \brief Finds a _pyObject by ID
1631 //================================================================================
1633 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1636 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1637 if ( id_obj != myObjects.end() )
1638 return id_obj->second;
1641 _pyGen* me = const_cast< _pyGen* >( this );
1642 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1643 if ( id_obj != myMeshes.end() )
1644 return id_obj->second;
1647 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1648 // if ( id_obj != myMeshEditors.end() )
1649 // return id_obj->second;
1651 return Handle(_pyObject)();
1654 //================================================================================
1656 * \brief Check if a study entry is under GEOM component
1658 //================================================================================
1660 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1664 return ( myGeomIDIndex <= theObjID.Length() &&
1665 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1666 _pyCommand::IsStudyEntry( theObjID ));
1671 //================================================================================
1673 * \brief Returns true if an object is not present in a study
1675 //================================================================================
1677 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1679 if ( theObjID.IsEmpty() ) return false;
1681 if ( myObjectNames.IsBound( theObjID ))
1682 return false; // SMESH object is in study
1684 // either the SMESH object is not in study or it is a GEOM object
1685 if ( IsGeomObject( theObjID ))
1687 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1688 if ( so->_is_nil() ) return true;
1689 CORBA::Object_var obj = so->GetObject();
1690 return CORBA::is_nil( obj );
1692 return true; // SMESH object not in study
1695 //================================================================================
1697 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1698 * this object is not dumped
1699 * \param [in] theObjID - entry of the object whose creation command was eliminated
1701 //================================================================================
1703 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1705 myRemovedObjIDs.insert( theObjID );
1708 //================================================================================
1710 * \brief Return reader of hypotheses of plugins
1712 //================================================================================
1714 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1716 if (myHypReader.IsNull() )
1717 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1723 //================================================================================
1725 * \brief Mesh created by SMESH_Gen
1727 //================================================================================
1729 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1730 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1732 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1733 myGeomNotInStudy = true;
1735 // convert my creation command --> smeshpy.Mesh(...)
1736 Handle(_pyCommand) creationCmd = GetCreationCmd();
1737 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1738 creationCmd->SetMethod( "Mesh" );
1739 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1742 //================================================================================
1744 * \brief Mesh created by SMESH_MeshEditor
1746 //================================================================================
1748 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1749 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1751 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1753 // this mesh depends on the exported mesh
1754 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1755 if ( !file.IsEmpty() )
1757 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1758 addFatherMesh( exportData.myMesh );
1759 if ( !exportData.myLastComputeCmd.IsNull() )
1761 // restore cleared Compute() by which the exported mesh was generated
1762 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1763 // protect that Compute() cmd from clearing
1764 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1765 exportData.myMesh->myLastComputeCmd.Nullify();
1769 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1771 // this mesh depends on concatenated meshes
1772 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1773 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1774 list< _pyID >::iterator meshID = idList.begin();
1775 for ( ; meshID != idList.end(); ++meshID )
1776 addFatherMesh( *meshID );
1778 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1780 // this mesh depends on a copied IdSource
1781 const _pyID& objID = theCreationCmd->GetArg( 1 );
1782 addFatherMesh( objID );
1784 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1785 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1786 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1788 // this mesh depends on a source mesh
1789 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1790 const _pyID& meshID = theCreationCmd->GetObject();
1791 addFatherMesh( meshID );
1794 // convert my creation command
1795 Handle(_pyCommand) creationCmd = GetCreationCmd();
1796 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1797 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1800 //================================================================================
1802 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1803 * \param theCommand - Engine method called for this mesh
1805 //================================================================================
1807 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1809 // some methods of SMESH_Mesh interface needs special conversion
1810 // to methods of Mesh python class
1812 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1813 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1814 // 2. AddHypothesis(geom, hyp)
1815 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1816 // 3. CreateGroupFromGEOM(type, name, grp)
1817 // --> in Mesh.Group(grp, name="")
1818 // 4. ExportToMED(f, auto_groups, version)
1819 // --> in Mesh.ExportMED( f, auto_groups, version )
1822 const TCollection_AsciiString& method = theCommand->GetMethod();
1823 // ----------------------------------------------------------------------
1824 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1826 if ( !theGen->IsToKeepAllCommands() ) // !historical
1828 list< Handle(_pyHypothesis) >::iterator hyp;
1829 if ( !myLastComputeCmd.IsNull() )
1831 // check if the previously computed mesh has been edited,
1832 // if so then we do not clear the previous Compute()
1833 bool toClear = true;
1834 if ( myLastComputeCmd->GetMethod() == "Compute" )
1836 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1837 for ( ; e != myEditors.end() && toClear; ++e )
1839 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1840 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1841 if ( cmd != cmds.rend() &&
1842 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1848 // clear hyp commands called before myLastComputeCmd
1849 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1850 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1852 myLastComputeCmd->Clear();
1855 myLastComputeCmd = theCommand;
1857 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1858 (*hyp)->MeshComputed( myLastComputeCmd );
1862 // ----------------------------------------------------------------------
1863 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1865 if ( !theGen->IsToKeepAllCommands() ) // !historical
1868 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1869 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1870 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1872 if ( !myLastComputeCmd.IsNull() )
1874 list< Handle(_pyHypothesis) >::iterator hyp;
1875 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1876 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1878 myLastComputeCmd->Clear();
1881 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1882 for ( ; e != myEditors.end(); ++e )
1884 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1885 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1886 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1887 if ( !(*cmd)->IsEmpty() )
1889 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1893 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1896 // ----------------------------------------------------------------------
1897 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1898 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1899 if ( !subMesh.IsNull() ) {
1900 subMesh->SetCreator( this );
1901 mySubmeshes.push_back( subMesh );
1904 // ----------------------------------------------------------------------
1905 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1906 theCommand->Clear();
1908 // ----------------------------------------------------------------------
1909 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1910 myAddHypCmds.push_back( theCommand );
1912 const _pyID& hypID = theCommand->GetArg( 2 );
1913 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1914 if ( !hyp.IsNull() ) {
1915 myHypos.push_back( hyp );
1916 if ( hyp->GetMesh().IsEmpty() )
1917 hyp->SetMesh( this->GetID() );
1920 // ----------------------------------------------------------------------
1921 else if ( method == "CreateGroup" ||
1922 method == "CreateGroupFromGEOM" ||
1923 method == "CreateGroupFromFilter" ||
1924 method == "CreateDimGroup" )
1926 Handle(_pyGroup) group = new _pyGroup( theCommand );
1927 myGroups.push_back( group );
1928 theGen->AddObject( group );
1930 // ----------------------------------------------------------------------
1931 // update list of groups
1932 else if ( method == "GetGroups" )
1934 bool allGroupsRemoved = true;
1935 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1936 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1937 list< _pyID >::iterator grID = idList.begin();
1938 const size_t nbGroupsBefore = myGroups.size();
1939 Handle(_pyObject) obj;
1940 for ( ; grID != idList.end(); ++grID )
1942 obj = theGen->FindObject( *grID );
1945 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1946 theGen->AddObject( group );
1947 myGroups.push_back( group );
1950 if ( !obj->CanClear() )
1951 allGroupsRemoved = false;
1953 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1954 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1956 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1958 // check if the preceding command is Compute();
1959 // if GetGroups() is just after Compute(), this can mean that the groups
1960 // were created by some algorithm and hence Compute() should not be discarded
1961 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1962 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1963 while ( (*cmd)->GetMethod() == "GetGroups" )
1965 if ( myLastComputeCmd == (*cmd))
1966 // protect last Compute() from clearing by the next Compute()
1967 myLastComputeCmd.Nullify();
1970 // ----------------------------------------------------------------------
1971 // notify a group about full removal
1972 else if ( method == "RemoveGroupWithContents" ||
1973 method == "RemoveGroup")
1975 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1976 const _pyID groupID = theCommand->GetArg( 1 );
1977 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1978 if ( !grp.IsNull() )
1980 if ( method == "RemoveGroupWithContents" )
1981 grp->RemovedWithContents();
1982 // to clear RemoveGroup() if the group creation is cleared
1983 grp->AddProcessedCmd( theCommand );
1987 // ----------------------------------------------------------------------
1988 else if ( theCommand->MethodStartsFrom( "Export" ))
1990 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1991 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
1992 method == "ExportMED" )
1994 theCommand->SetMethod( "ExportMED" );
1995 // filter out deprecated version parameter
1996 vector< _AString > args;
1997 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
1998 if ( !_FilterArg( theCommand->GetArg( i ) ) )
1999 args.push_back( theCommand->GetArg( i ) );
2001 theCommand->RemoveArgs();
2002 for ( unsigned int i = 0; i < args.size(); i++ )
2003 theCommand->SetArg( i+1, args[i] );
2004 if ( theCommand->GetNbArgs() == 4 )
2006 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2007 _AString autoDimension = theCommand->GetArg( 4 );
2008 theCommand->SetArg( 4, "None" );
2009 theCommand->SetArg( 5, autoDimension );
2012 else if ( method == "ExportCGNS" )
2013 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2014 _pyID partID = theCommand->GetArg( 1 );
2015 int nbArgs = theCommand->GetNbArgs();
2016 for ( int i = 2; i <= nbArgs; ++i )
2017 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2018 theCommand->SetArg( nbArgs, partID );
2020 else if ( method == "ExportGMF" )
2021 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2022 _pyID partID = theCommand->GetArg( 1 );
2023 _AString file = theCommand->GetArg( 2 );
2024 theCommand->RemoveArgs();
2025 theCommand->SetArg( 1, file );
2026 theCommand->SetArg( 2, partID );
2028 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2029 { // ExportPartTo*(part, ...) -> Export*(..., part)
2031 // remove "PartTo" from the method
2032 TCollection_AsciiString newMethod = method;
2033 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2034 theCommand->SetMethod( newMethod );
2035 // replace version parameter by minor
2036 std::list< _AString > args;
2037 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2038 if ( _FilterArg( theCommand->GetArg( i )))
2039 args.push_back( "minor=0");
2041 args.push_back( theCommand->GetArg( i ));
2043 // check the 1st arg meshPart, it must be SMESH_IDSource
2044 _AString meshPart = args.front();
2045 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2046 meshPart.Search( "Filter" ) > 0 ||
2047 meshPart.Search( "GetIDSource" ) > 0 ||
2048 meshPart.Search( "meshPart" ) > 0 )
2050 // set the 1st arg meshPart
2051 // - to 5th place for ExportMED command
2052 // - to last place for the rest commands
2053 std::list< _AString >::iterator newPos = args.end();
2054 if ( newMethod == "ExportMED" )
2055 std::advance( newPos = args.begin(), 5 );
2056 args.splice( newPos, args, args.begin() );
2058 std::list< _AString >::iterator a = args.begin();
2059 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2060 theCommand->SetArg( i, *a );
2062 // remember file name
2063 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2064 ExportedMeshData( this, myLastComputeCmd ));
2066 // ----------------------------------------------------------------------
2067 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2069 _pyID hypID = theCommand->GetArg( 2 );
2070 _pyID geomID = theCommand->GetArg( 1 );
2071 bool isLocal = ( geomID != GetGeom() );
2073 // check if this mesh still has corresponding addition command
2074 Handle(_pyCommand) addCmd;
2075 list< Handle(_pyCommand) >::iterator cmd;
2076 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2077 for ( int i = 0; i < 2; ++i )
2079 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2080 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2082 bool sameHyp = true;
2083 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2084 sameHyp = false; // other hyp
2085 if ( (*cmd)->GetNbArgs() == 2 &&
2086 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2087 sameHyp = false; // other geom
2088 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2089 sameHyp = false; // other geom
2093 cmd = addHypCmds.erase( cmd );
2094 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2096 theCommand->Clear();
2100 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2101 addCmd->RemoveArgs();
2102 addCmd->SetArg( 1, hypID );
2104 addCmd->SetArg( 2, geomID );
2113 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2114 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2115 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2116 _pyID geom = theCommand->GetArg( 1 );
2117 theCommand->RemoveArgs();
2118 theCommand->SetArg( 1, hypID );
2119 if ( geom != GetGeom() )
2120 theCommand->SetArg( 2, geom );
2122 // remove hyp from myHypos
2123 myHypos.remove( hyp );
2125 // check for SubMesh order commands
2126 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2128 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2129 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2130 // commands are moved at the end of the script
2131 TCollection_AsciiString subIDs =
2132 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2133 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2134 list< _pyID >::iterator subID = idList.begin();
2135 for ( ; subID != idList.end(); ++subID )
2137 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2138 if ( !subMesh.IsNull() )
2139 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2142 // add accessor method if necessary
2145 if ( NeedMeshAccess( theCommand ))
2146 // apply theCommand to the mesh wrapped by smeshpy mesh
2147 AddMeshAccess( theCommand );
2151 //================================================================================
2153 * \brief Return True if addition of accesor method is needed
2155 //================================================================================
2157 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2159 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2160 // so no conversion is needed for them at all:
2161 static TStringSet sameMethods;
2162 if ( sameMethods.empty() ) {
2163 const char * names[] =
2164 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2165 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2166 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2167 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2168 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2169 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2170 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2171 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2172 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2173 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2174 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2175 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2176 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2177 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2178 ,"" }; // <- mark of end
2179 sameMethods.Insert( names );
2182 return !sameMethods.Contains( theCommand->GetMethod() );
2185 //================================================================================
2187 * \brief Convert creation and addition of all algos and hypos
2189 //================================================================================
2191 void _pyMesh::Flush()
2194 // get the meshes this mesh depends on via hypotheses
2195 list< Handle(_pyMesh) > fatherMeshes;
2196 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2197 for ( ; hyp != myHypos.end(); ++hyp )
2198 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2199 myGeomNotInStudy = true;
2201 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2202 for ( ; m != fatherMeshes.end(); ++m )
2203 addFatherMesh( *m );
2204 // if ( removedGeom )
2205 // SetRemovedFromStudy(); // as referred geometry not in study
2207 if ( myGeomNotInStudy )
2210 list < Handle(_pyCommand) >::iterator cmd;
2212 // try to convert algo addition like this:
2213 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2214 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2216 Handle(_pyCommand) addCmd = *cmd;
2218 _pyID algoID = addCmd->GetArg( 2 );
2219 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2220 if ( algo.IsNull() || !algo->IsAlgo() )
2223 // check and create new algorithm instance if it is already wrapped
2224 if ( algo->IsWrapped() ) {
2225 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2226 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2227 TCollection_AsciiString( " = " ) + theGen->GetID() +
2228 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2229 TCollection_AsciiString( "\" )" );
2231 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2232 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2233 if ( !newAlgo.IsNull() ) {
2234 newAlgo->Assign( algo, this->GetID() );
2235 newAlgo->SetCreationCmd( newCmd );
2237 // set algorithm creation
2238 theGen->SetCommandBefore( newCmd, addCmd );
2239 myHypos.push_back( newAlgo );
2240 if ( !myLastComputeCmd.IsNull() &&
2241 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2242 newAlgo->MeshComputed( myLastComputeCmd );
2247 _pyID geom = addCmd->GetArg( 1 );
2248 bool isLocalAlgo = ( geom != GetGeom() );
2251 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2253 // wrapped algo is created after mesh creation
2254 GetCreationCmd()->AddDependantCmd( addCmd );
2256 if ( isLocalAlgo ) {
2257 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2258 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2259 TCollection_AsciiString( "geom=" ) + geom );
2260 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2261 list < Handle(_pySubMesh) >::iterator smIt;
2262 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2263 Handle(_pySubMesh) subMesh = *smIt;
2264 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2265 if ( geom == subCmd->GetArg( 1 )) {
2266 subCmd->SetObject( algo->GetID() );
2267 subCmd->RemoveArgs();
2268 subMesh->SetCreator( algo );
2273 else // KO - ALGO was already created
2275 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2276 addCmd->RemoveArgs();
2277 addCmd->SetArg( 1, algoID );
2279 addCmd->SetArg( 2, geom );
2280 myNotConvertedAddHypCmds.push_back( addCmd );
2284 // try to convert hypo addition like this:
2285 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2286 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2288 Handle(_pyCommand) addCmd = *cmd;
2289 _pyID hypID = addCmd->GetArg( 2 );
2290 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2291 if ( hyp.IsNull() || hyp->IsAlgo() )
2293 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2295 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2296 _pyID geom = addCmd->GetArg( 1 );
2297 addCmd->RemoveArgs();
2298 addCmd->SetArg( 1, hypID );
2299 if ( geom != GetGeom() )
2300 addCmd->SetArg( 2, geom );
2301 myNotConvertedAddHypCmds.push_back( addCmd );
2305 myAddHypCmds.clear();
2306 mySubmeshes.clear();
2309 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2310 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2314 //================================================================================
2316 * \brief Sets myIsPublished of me and of all objects depending on me.
2318 //================================================================================
2320 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2322 _pyObject::SetRemovedFromStudy(isRemoved);
2324 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2325 for ( ; sm != mySubmeshes.end(); ++sm )
2326 (*sm)->SetRemovedFromStudy(isRemoved);
2328 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2329 for ( ; gr != myGroups.end(); ++gr )
2330 (*gr)->SetRemovedFromStudy(isRemoved);
2332 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2333 for ( ; m != myChildMeshes.end(); ++m )
2334 (*m)->SetRemovedFromStudy(isRemoved);
2336 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2337 for ( ; e != myEditors.end(); ++e )
2338 (*e)->SetRemovedFromStudy(isRemoved);
2341 //================================================================================
2343 * \brief Return true if none of myChildMeshes is in study
2345 //================================================================================
2347 bool _pyMesh::CanClear()
2352 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2353 for ( ; m != myChildMeshes.end(); ++m )
2354 if ( !(*m)->CanClear() )
2360 //================================================================================
2362 * \brief Clear my commands and commands of mesh editor
2364 //================================================================================
2366 void _pyMesh::ClearCommands()
2372 // mark all sub-objects as not removed, except child meshes
2373 list< Handle(_pyMesh) > children;
2374 children.swap( myChildMeshes );
2375 SetRemovedFromStudy( false );
2376 children.swap( myChildMeshes );
2380 _pyObject::ClearCommands();
2382 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2383 for ( ; sm != mySubmeshes.end(); ++sm )
2384 (*sm)->ClearCommands();
2386 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2387 for ( ; gr != myGroups.end(); ++gr )
2388 (*gr)->ClearCommands();
2390 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2391 for ( ; e != myEditors.end(); ++e )
2392 (*e)->ClearCommands();
2395 //================================================================================
2397 * \brief Add a father mesh by ID
2399 //================================================================================
2401 void _pyMesh::addFatherMesh( const _pyID& meshID )
2403 if ( !meshID.IsEmpty() && meshID != GetID() )
2404 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2407 //================================================================================
2409 * \brief Add a father mesh
2411 //================================================================================
2413 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2415 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2417 //myFatherMeshes.push_back( mesh );
2418 mesh->myChildMeshes.push_back( this );
2420 // protect last Compute() from clearing by the next Compute()
2421 mesh->myLastComputeCmd.Nullify();
2425 //================================================================================
2427 * \brief MeshEditor convert its commands to ones of mesh
2429 //================================================================================
2431 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2432 _pyObject( theCreationCmd )
2434 myMesh = theCreationCmd->GetObject();
2435 myCreationCmdStr = theCreationCmd->GetString();
2436 theCreationCmd->Clear();
2438 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2439 if ( !mesh.IsNull() )
2440 mesh->AddEditor( this );
2443 //================================================================================
2445 * \brief convert its commands to ones of mesh
2447 //================================================================================
2449 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2451 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2452 // commands calling these methods are converted to calls of Mesh methods without
2453 // additional modifs, only object is changed from MeshEditor to Mesh.
2454 static TStringSet sameMethods;
2455 if ( sameMethods.empty() ) {
2456 const char * names[] = {
2457 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2458 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2459 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2460 "MoveNode", "MoveClosestNodeToPoint",
2461 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2462 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2463 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2464 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2465 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2466 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2467 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2468 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2469 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2470 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2471 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2472 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2473 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2474 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2475 "GetLastCreatedElems",
2476 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2477 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2478 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2479 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2480 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2481 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2482 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2483 ,"" }; // <- mark of the end
2484 sameMethods.Insert( names );
2487 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2488 TStringMap diffMethods;
2489 if ( diffMethods.empty() ) {
2490 const char * orig2newName[] = {
2491 // original name --------------> new name
2492 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2493 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2494 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2495 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2496 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2497 ""};// <- mark of the end
2498 diffMethods.Insert( orig2newName );
2501 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2502 // only by last two arguments
2503 static TStringSet diffLastTwoArgsMethods;
2504 if (diffLastTwoArgsMethods.empty() ) {
2505 const char * names[] = {
2506 "MirrorMakeGroups","MirrorObjectMakeGroups",
2507 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2508 "RotateMakeGroups","RotateObjectMakeGroups",
2509 ""};// <- mark of the end
2510 diffLastTwoArgsMethods.Insert( names );
2513 // only a method name is to change?
2514 const TCollection_AsciiString & method = theCommand->GetMethod();
2515 bool isPyMeshMethod = sameMethods.Contains( method );
2516 if ( !isPyMeshMethod )
2518 TCollection_AsciiString newMethod = diffMethods.Value( method );
2519 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2520 theCommand->SetMethod( newMethod );
2522 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2523 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2525 isPyMeshMethod = true;
2526 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2527 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2530 if ( !isPyMeshMethod )
2532 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2533 // functions with the flag "theMakeGroups = True" like:
2534 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2535 int pos = method.Search("MakeGroups");
2538 isPyMeshMethod = true;
2539 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2540 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2542 // 1. Remove "MakeGroups" from the Command
2543 TCollection_AsciiString aMethod = theCommand->GetMethod();
2544 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2547 pos = pos-2; //Remove "0D" from the Command too
2548 aMethod.Trunc(pos-1);
2549 theCommand->SetMethod(aMethod);
2551 // 2. And add last "True" argument(s)
2552 while(nbArgsToAdd--)
2553 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2554 if( is0DmethId || is0DmethObj )
2555 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2559 // ExtrusionSweep0D() -> ExtrusionSweep()
2560 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2561 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2562 method == "ExtrusionSweepObject0D" ))
2564 isPyMeshMethod = true;
2565 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2566 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2567 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2570 // DoubleNode...New(...) -> DoubleNode...(...,True)
2571 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2572 method == "DoubleNodeElemGroupsNew" ||
2573 method == "DoubleNodeGroupNew" ||
2574 method == "DoubleNodeGroupsNew" ||
2575 method == "DoubleNodeElemGroup2New" ||
2576 method == "DoubleNodeElemGroups2New"))
2578 isPyMeshMethod = true;
2579 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2580 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2581 if ( excessLen == 3 )
2583 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2585 else if ( theCommand->GetArg(4) == "0" ||
2586 theCommand->GetArg(5) == "0" )
2588 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2589 // Group = DoubleNodeGroup2New(,,,False, True)
2590 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2591 theCommand->SetResultValue( groupID );
2594 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2595 // FindElementsByPoint(x, y, z, elementType, meshPart)
2596 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2598 isPyMeshMethod = true;
2599 theCommand->SetMethod( "FindElementsByPoint" );
2600 // make the 1st arg be the last one
2601 _pyID partID = theCommand->GetArg( 1 );
2602 int nbArgs = theCommand->GetNbArgs();
2603 for ( int i = 2; i <= nbArgs; ++i )
2604 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2605 theCommand->SetArg( nbArgs, partID );
2607 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2608 if ( !isPyMeshMethod && method == "Reorient2D" )
2610 isPyMeshMethod = true;
2611 _AString mesh = theCommand->GetArg( 1 );
2612 _AString dir = theCommand->GetArg( 2 );
2613 _AString face = theCommand->GetArg( 3 );
2614 _AString point = theCommand->GetArg( 4 );
2615 theCommand->RemoveArgs();
2616 theCommand->SetArg( 1, mesh );
2617 theCommand->SetArg( 2, dir );
2618 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2619 theCommand->SetArg( 3, point );
2621 theCommand->SetArg( 3, face );
2624 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2626 isPyMeshMethod = true;
2627 int crit_arg = theCommand->GetNbArgs();
2628 const _AString& crit = theCommand->GetArg(crit_arg);
2629 if (crit.Search("MaxElementLength2D") != -1)
2630 theCommand->SetArg(crit_arg, "");
2633 if ( isPyMeshMethod )
2635 theCommand->SetObject( myMesh );
2639 // editor creation command is needed only if any editor function is called
2640 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2641 if ( !myCreationCmdStr.IsEmpty() ) {
2642 GetCreationCmd()->GetString() = myCreationCmdStr;
2643 myCreationCmdStr.Clear();
2648 //================================================================================
2650 * \brief Return true if my mesh can be removed
2652 //================================================================================
2654 bool _pyMeshEditor::CanClear()
2656 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2657 return mesh.IsNull() ? true : mesh->CanClear();
2660 //================================================================================
2662 * \brief _pyHypothesis constructor
2663 * \param theCreationCmd -
2665 //================================================================================
2667 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2668 _pyObject( theCreationCmd ), myCurCrMethod(0)
2670 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2673 //================================================================================
2675 * \brief Creates algorithm or hypothesis
2676 * \param theCreationCmd - The engine command creating a hypothesis
2677 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2679 //================================================================================
2681 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2683 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2684 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2686 Handle(_pyHypothesis) hyp, algo;
2689 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2690 if ( hypTypeQuoted.IsEmpty() )
2693 TCollection_AsciiString hypType =
2694 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2696 algo = new _pyAlgorithm( theCreationCmd );
2697 hyp = new _pyHypothesis( theCreationCmd );
2699 if ( hypType == "NumberOfSegments" ) {
2700 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2701 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2702 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2703 hyp->AddArgMethod( "SetNumberOfSegments" );
2704 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2705 hyp->AddArgMethod( "SetScaleFactor" );
2706 hyp->AddArgMethod( "SetReversedEdges" );
2707 // same for ""CompositeSegment_1D:
2708 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2709 hyp->AddArgMethod( "SetNumberOfSegments" );
2710 hyp->AddArgMethod( "SetScaleFactor" );
2711 hyp->AddArgMethod( "SetReversedEdges" );
2713 else if ( hypType == "SegmentLengthAroundVertex" ) {
2714 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2715 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2716 hyp->AddArgMethod( "SetLength" );
2717 // same for ""CompositeSegment_1D:
2718 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2719 hyp->AddArgMethod( "SetLength" );
2721 else if ( hypType == "LayerDistribution2D" ) {
2722 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2723 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2725 else if ( hypType == "LayerDistribution" ) {
2726 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2727 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2729 else if ( hypType == "CartesianParameters3D" ) {
2730 hyp = new _pyComplexParamHypo( theCreationCmd );
2731 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2732 for ( int iArg = 0; iArg < 4; ++iArg )
2733 hyp->setCreationArg( iArg+1, "[]");
2734 hyp->AddAccumulativeMethod( "SetGrid" );
2735 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2739 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2742 return algo->IsValid() ? algo : hyp;
2745 //================================================================================
2747 * \brief Returns true if addition of this hypothesis to a given mesh can be
2748 * wrapped into hypothesis creation
2750 //================================================================================
2752 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2754 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2756 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2757 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2763 //================================================================================
2765 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2766 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2767 * \param theAlgo - The algo that can create this hypo
2768 * \retval bool - false if the command can't be converted
2770 //================================================================================
2772 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2773 const _pyID& theMesh)
2775 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2777 if ( !IsWrappable( theMesh ))
2780 myGeom = theCmd->GetArg( 1 );
2782 Handle(_pyHypothesis) algo;
2784 // find algo created on myGeom in theMesh
2785 algo = theGen->FindAlgo( myGeom, theMesh, this );
2786 if ( algo.IsNull() )
2788 // attach hypothesis creation command to be after algo creation command
2789 // because it can be new created instance of algorithm
2790 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2794 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2795 theCmd->SetResultValue( GetID() );
2796 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2797 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2798 // set args (geom will be set by _pyMesh calling this method)
2799 theCmd->RemoveArgs();
2800 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2801 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2802 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2804 theCmd->SetArg( i+1, "[]");
2806 // set a new creation command
2807 GetCreationCmd()->Clear();
2808 // replace creation command by wrapped instance
2809 // please note, that hypothesis attaches to algo creation command (see upper)
2810 SetCreationCmd( theCmd );
2813 // clear commands setting arg values
2814 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2815 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2818 // set unknown arg commands after hypo creation
2819 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2820 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2821 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2822 afterCmd->AddDependantCmd( *cmd );
2828 //================================================================================
2830 * \brief Remember hypothesis parameter values
2831 * \param theCommand - The called hypothesis method
2833 //================================================================================
2835 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2837 ASSERT( !myIsAlgo );
2838 if ( !theGen->IsToKeepAllCommands() )
2839 rememberCmdOfParameter( theCommand );
2841 bool usedCommand = false;
2842 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2843 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2845 CreationMethod& crMethod = type2meth->second;
2846 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2847 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2849 myArgCommands.push_back( theCommand );
2851 while ( crMethod.myArgs.size() < i+1 )
2852 crMethod.myArgs.push_back( "None" );
2853 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2858 myUnusedCommands.push_back( theCommand );
2861 //================================================================================
2863 * \brief Finish conversion
2865 //================================================================================
2867 void _pyHypothesis::Flush()
2871 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2872 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2873 // Add access to a wrapped mesh
2874 theGen->AddMeshAccessorMethod( *cmd );
2875 // Add access to a wrapped algorithm
2876 theGen->AddAlgoAccessorMethod( *cmd );
2878 cmd = myUnusedCommands.begin();
2879 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2880 // Add access to a wrapped mesh
2881 theGen->AddMeshAccessorMethod( *cmd );
2882 // Add access to a wrapped algorithm
2883 theGen->AddAlgoAccessorMethod( *cmd );
2886 // forget previous hypothesis modifications
2887 myArgCommands.clear();
2888 myUnusedCommands.clear();
2891 //================================================================================
2893 * \brief clear creation, arg and unknown commands
2895 //================================================================================
2897 void _pyHypothesis::ClearAllCommands()
2899 GetCreationCmd()->Clear();
2900 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2901 for ( ; cmd != myArgCommands.end(); ++cmd )
2903 cmd = myUnusedCommands.begin();
2904 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2909 //================================================================================
2911 * \brief Assign fields of theOther to me except myIsWrapped
2913 //================================================================================
2915 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2916 const _pyID& theMesh )
2918 // myCreationCmd = theOther->myCreationCmd;
2919 myIsAlgo = theOther->myIsAlgo;
2920 myIsWrapped = false;
2921 myGeom = theOther->myGeom;
2923 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2924 myAccumulativeMethods = theOther->myAccumulativeMethods;
2925 //myUnusedCommands = theOther->myUnusedCommands;
2926 // init myCurCrMethod
2927 GetCreationMethod( theOther->GetAlgoType() );
2930 //================================================================================
2932 * \brief Analyze my erasability depending on myReferredObjs
2934 //================================================================================
2936 bool _pyHypothesis::CanClear()
2940 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2941 for ( ; obj != myReferredObjs.end(); ++obj )
2942 if ( (*obj)->CanClear() )
2949 //================================================================================
2951 * \brief Clear my commands depending on usage by meshes
2953 //================================================================================
2955 void _pyHypothesis::ClearCommands()
2957 // if ( !theGen->IsToKeepAllCommands() )
2959 // bool isUsed = false;
2960 // int lastComputeOrder = 0;
2961 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2962 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2963 // if ( ! (*cmd)->IsEmpty() )
2966 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2967 // lastComputeOrder = (*cmd)->GetOrderNb();
2971 // SetRemovedFromStudy( true );
2975 // // clear my commands invoked after lastComputeOrder
2976 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2977 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2979 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2980 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2981 // // cmds.back()->Clear();
2985 _pyObject::ClearCommands();
2988 //================================================================================
2990 * \brief Find arguments that are objects like mesh, group, geometry
2991 * \param meshes - referred meshes (directly or indirrectly)
2992 * \retval bool - false if a referred geometry is not in the study
2994 //================================================================================
2996 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2998 if ( IsAlgo() ) return true;
3000 bool geomPublished = true;
3001 vector< _AString > args;
3002 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3003 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3005 CreationMethod& crMethod = type2meth->second;
3006 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3008 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3009 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3010 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3011 args.push_back( (*cmd)->GetArg( nb ));
3014 for ( size_t i = 0; i < args.size(); ++i )
3016 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3017 if ( idList.empty() && !args[ i ].IsEmpty() )
3018 idList.push_back( args[ i ]);
3019 list< _pyID >::iterator id = idList.begin();
3020 for ( ; id != idList.end(); ++id )
3022 Handle(_pyObject) obj = theGen->FindObject( *id );
3023 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3026 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3027 geomPublished = false;
3031 myReferredObjs.push_back( obj );
3032 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3033 if ( !mesh.IsNull() )
3034 meshes.push_back( mesh );
3035 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3036 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3037 obj->SetRemovedFromStudy( false );
3041 return geomPublished;
3044 //================================================================================
3046 * \brief Remember theCommand setting a parameter
3048 //================================================================================
3050 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3052 // parameters are discriminated by method name
3053 _AString method = theCommand->GetMethod();
3054 if ( myAccumulativeMethods.count( method ))
3055 return; // this method adds values and not override the previous value
3057 // discriminate commands setting different parameters via one method
3058 // by passing parameter names like e.g. SetOption("size", "0.2")
3059 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3060 theCommand->GetNbArgs() > 1 )
3062 // mangle method by appending a 1st textual arg
3063 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3065 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3066 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3067 if ( !isalpha( arg.Value(2))) continue;
3072 // parameters are discriminated by method name
3073 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3074 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3076 cmds.back()->Clear(); // previous parameter value has not been used
3077 cmds.back() = theCommand;
3081 cmds.push_back( theCommand );
3085 //================================================================================
3087 * \brief Return true if a setting parameter command ha been used to compute mesh
3089 //================================================================================
3091 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3092 _pyCommand::TAddr avoidComputeAddr ) const
3094 bool isUsed = false;
3095 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3096 myComputeAddr2Cmds.begin();
3097 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3099 if ( addr2cmds->first == avoidComputeAddr ) continue;
3100 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3101 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3106 //================================================================================
3108 * \brief Save commands setting parameters as they are used for a mesh computation
3110 //================================================================================
3112 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3114 myComputeCmds.push_back( theComputeCmd );
3115 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3117 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3118 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3119 savedCmds.push_back( m2c->second.back() );
3122 //================================================================================
3124 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3126 //================================================================================
3128 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3130 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3132 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3133 for ( ; cmd != savedCmds.end(); ++cmd )
3135 // check if a cmd has been used to compute another mesh
3136 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3138 // check if a cmd is a sole command setting its parameter;
3139 // don't use method name for search as it can change
3140 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3141 m2cmds = myMeth2Commands.begin();
3142 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3144 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3145 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3146 if ( cmdIt != cmds.end() )
3148 if ( cmds.back() != *cmd )
3150 cmds.erase( cmdIt );
3157 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3160 //================================================================================
3162 * \brief Sets an argNb-th argument of current creation command
3163 * \param argNb - argument index countered from 1
3165 //================================================================================
3167 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3169 if ( myCurCrMethod )
3171 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3172 myCurCrMethod->myArgs.push_back( "None" );
3173 if ( arg.IsEmpty() )
3174 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3176 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3181 //================================================================================
3183 * \brief Remember hypothesis parameter values
3184 * \param theCommand - The called hypothesis method
3186 //================================================================================
3188 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3190 if ( GetAlgoType() == "Cartesian_3D" )
3192 // CartesianParameters3D hyp
3194 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3195 theCommand->GetMethod() == "SetToAddEdges" )
3197 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3198 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3199 myArgCommands.push_back( theCommand );
3202 if ( theCommand->GetMethod() == "SetGrid" ||
3203 theCommand->GetMethod() == "SetGridSpacing" )
3205 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3206 int iArg = axis.Value(1) - '0';
3207 if ( theCommand->GetMethod() == "SetGrid" )
3209 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3213 myCurCrMethod->myArgs[ iArg ] = "[ ";
3214 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3215 myCurCrMethod->myArgs[ iArg ] += ", ";
3216 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3217 myCurCrMethod->myArgs[ iArg ] += "]";
3219 myArgCommands.push_back( theCommand );
3220 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3221 // accumulative, else, if the creation
3222 // is not converted, commands for axes 1 and 2 are lost
3227 if( theCommand->GetMethod() == "SetLength" )
3229 // NOW it is OBSOLETE
3230 // ex: hyp.SetLength(start, 1)
3231 // hyp.SetLength(end, 0)
3232 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3233 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3234 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3235 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3237 CreationMethod& crMethod = type2meth->second;
3238 while ( (int) crMethod.myArgs.size() < i+1 )
3239 crMethod.myArgs.push_back( "[]" );
3240 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3242 myArgCommands.push_back( theCommand );
3246 _pyHypothesis::Process( theCommand );
3249 //================================================================================
3251 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3253 //================================================================================
3255 void _pyComplexParamHypo::Flush()
3257 list < Handle(_pyCommand) >::iterator cmd;
3260 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3261 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3265 // if ( GetAlgoType() == "Cartesian_3D" )
3267 // _pyID algo = myCreationCmd->GetObject();
3268 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3270 // if ( IsWrapped() )
3272 // StructToList( *cmd, /*checkMethod=*/false );
3273 // const _AString & method = (*cmd)->GetMethod();
3274 // if ( method == "SetFixedPoint" )
3275 // (*cmd)->SetObject( algo );
3281 //================================================================================
3283 * \brief Convert methods of 1D hypotheses to my own methods
3284 * \param theCommand - The called hypothesis method
3286 //================================================================================
3288 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3290 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3293 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3294 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3295 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3297 // TCollection_AsciiString cmd =
3298 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3299 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3300 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3303 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3305 // // 1D hypo is already set, so distribution changes and the old
3306 // // 1D hypo is thrown away
3307 // my1dHyp->ClearAllCommands();
3310 // //my1dHyp->SetRemovedFromStudy( false );
3312 // if ( !myArgCommands.empty() )
3313 // myArgCommands.back()->Clear();
3314 myCurCrMethod->myArgs.push_back( hyp1dID );
3315 myArgCommands.push_back( theCommand );
3318 //================================================================================
3321 * \param theAdditionCmd - command to be converted
3322 * \param theMesh - mesh instance
3323 * \retval bool - status
3325 //================================================================================
3327 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3328 const _pyID& theMesh)
3330 myIsWrapped = false;
3332 if ( my1dHyp.IsNull() )
3335 // set "SetLayerDistribution()" after addition cmd
3336 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3338 _pyID geom = theAdditionCmd->GetArg( 1 );
3340 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3341 if ( !algo.IsNull() )
3343 my1dHyp->SetMesh( theMesh );
3344 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3345 algo->GetAlgoType().ToCString());
3346 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3349 // clear "SetLayerDistribution()" cmd
3350 myArgCommands.back()->Clear();
3352 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3354 // find RadialPrism algo created on <geom> for theMesh
3355 GetCreationCmd()->SetObject( algo->GetID() );
3356 GetCreationCmd()->SetMethod( myAlgoMethod );
3357 GetCreationCmd()->RemoveArgs();
3358 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3364 //================================================================================
3368 //================================================================================
3370 void _pyLayerDistributionHypo::Flush()
3372 // as creation of 1D hyp was written later then it's edition,
3373 // we need to find all it's edition calls and process them
3374 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3376 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3378 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3379 if ( hyp1dID.IsEmpty() ) continue;
3381 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3383 // make a new name for 1D hyp = "HypType" + "_Distribution"
3385 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3387 if ( prevNewName.IsEmpty() ) continue;
3388 newName = prevNewName;
3392 if ( hyp1d->IsWrapped() ) {
3393 newName = hyp1d->GetCreationCmd()->GetMethod();
3396 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3397 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3399 newName += "_Distribution";
3400 prevNewName = newName;
3402 hyp1d->GetCreationCmd()->SetResultValue( newName );
3404 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3405 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3406 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3407 const _pyID& objID = (*cmdIt)->GetObject();
3408 if ( objID == hyp1dID ) {
3409 if ( !hyp1d.IsNull() )
3411 hyp1d->Process( *cmdIt );
3412 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3414 ( *cmdIt )->SetObject( newName );
3417 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3418 (*cmd)->SetArg( 1, newName );
3422 //================================================================================
3424 * \brief additionally to Addition2Creation, clears SetDistrType() command
3425 * \param theCmd - AddHypothesis() command
3426 * \param theMesh - mesh to which a hypothesis is added
3427 * \retval bool - conversion result
3429 //================================================================================
3431 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3432 const _pyID& theMesh)
3434 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3435 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3436 bool scaleDistrType = false;
3437 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3438 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3439 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3440 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3441 scaleDistrType = true;
3444 else if ( !scaleDistrType ) {
3445 // distribution type changed: remove scale factor from args
3446 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3447 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3449 CreationMethod& crMethod = type2meth->second;
3450 if ( crMethod.myArgs.size() == 2 )
3451 crMethod.myArgs.pop_back();
3458 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3461 //================================================================================
3463 * \brief remove repeated commands defining distribution
3465 //================================================================================
3467 void _pyNumberOfSegmentsHyp::Flush()
3469 // find number of the last SetDistrType() command
3470 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3471 int distrTypeNb = 0;
3472 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3473 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3474 if ( cmd != myUnusedCommands.rbegin() )
3475 distrTypeNb = (*cmd)->GetOrderNb();
3477 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3480 // clear commands before the last SetDistrType()
3481 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3482 set< int > treatedCmdNbs; // avoid treating same cmd twice
3483 for ( int i = 0; i < 2; ++i ) {
3484 set<TCollection_AsciiString> uniqueMethods;
3485 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3486 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3488 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3489 continue;// avoid treating same cmd twice
3490 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3491 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3492 if ( !clear || method == "SetNumberOfSegments" ) {
3493 bool isNewInSet = uniqueMethods.insert( method ).second;
3494 clear = !isNewInSet;
3503 //================================================================================
3505 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3506 * into regular1D.LengthNearVertex( length, vertex )
3507 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3508 * \param theMesh - The mesh needing this hypo
3509 * \retval bool - false if the command can't be converted
3511 //================================================================================
3513 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3514 const _pyID& theMeshID)
3516 if ( IsWrappable( theMeshID )) {
3518 _pyID vertex = theCmd->GetArg( 1 );
3520 // the problem here is that segment algo can be not found
3521 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3522 // geometry where segment algorithm is assigned
3523 _pyID geom = vertex;
3524 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3525 while ( algo.IsNull() && !geom.IsEmpty()) {
3526 // try to find geom as a father of <vertex>
3527 geom = FatherID( geom );
3528 algo = theGen->FindAlgo( geom, theMeshID, this );
3530 if ( algo.IsNull() || geom.IsEmpty() )
3531 return false; // also possible to find geom as brother of veretex...
3533 // set geom instead of vertex
3534 theCmd->SetArg( 1, geom );
3536 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3537 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3538 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3540 // set vertex as a second arg
3541 theCmd->SetArg( 2, vertex );
3549 //================================================================================
3551 * \brief _pyAlgorithm constructor
3552 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3554 //================================================================================
3556 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3557 : _pyHypothesis( theCreationCmd )
3562 //================================================================================
3564 * \brief Convert the command adding an algorithm to mesh
3565 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3566 * \param theMesh - The mesh needing this algo
3567 * \retval bool - false if the command can't be converted
3569 //================================================================================
3571 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3572 const _pyID& theMeshID)
3574 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3575 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3576 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3582 //================================================================================
3584 * \brief Return starting position of a part of python command
3585 * \param thePartIndex - The index of command part
3586 * \retval int - Part position
3588 //================================================================================
3590 int _pyCommand::GetBegPos( int thePartIndex ) const
3594 if ( myBegPos.Length() < thePartIndex )
3596 ASSERT( thePartIndex > 0 );
3597 return myBegPos( thePartIndex );
3600 //================================================================================
3602 * \brief Store starting position of a part of python command
3603 * \param thePartIndex - The index of command part
3604 * \param thePosition - Part position
3606 //================================================================================
3608 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3610 while ( myBegPos.Length() < thePartIndex )
3611 myBegPos.Append( UNKNOWN );
3612 ASSERT( thePartIndex > 0 );
3613 myBegPos( thePartIndex ) = thePosition;
3616 //================================================================================
3618 * \brief Returns whitespace symbols at the line beginning
3619 * \retval TCollection_AsciiString - result
3621 //================================================================================
3623 TCollection_AsciiString _pyCommand::GetIndentation()
3626 //while ( end <= Length() && isblank( myString.Value( end )))
3627 //ANA: isblank() function isn't provided in VC2010 compiler
3628 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3630 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3633 //================================================================================
3635 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3636 * \retval const TCollection_AsciiString & - ResultValue substring
3638 //================================================================================
3640 const TCollection_AsciiString & _pyCommand::GetResultValue()
3642 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3644 SetBegPos( RESULT_IND, EMPTY );
3645 int begPos, endPos = myString.Location( "=", 1, Length() );
3649 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3650 if ( begPos < endPos )
3652 SetBegPos( RESULT_IND, begPos );
3654 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3655 myRes = myString.SubString( begPos, endPos );
3662 //================================================================================
3664 * \brief Return number of python command result value ResultValue = Obj.Meth()
3666 //================================================================================
3668 int _pyCommand::GetNbResultValues()
3671 return myResults.Length();
3675 //================================================================================
3677 * \brief Return substring of python command looking like
3678 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3679 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3681 //================================================================================
3682 const _AString& _pyCommand::GetResultValue(int res)
3684 if ( GetResultValue().IsEmpty() )
3685 return theEmptyString;
3687 if ( myResults.IsEmpty() )
3690 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3691 ++begPos; // skip [, else the whole list is returned
3692 while ( begPos < myRes.Length() ) {
3693 _AString result = GetWord( myRes, begPos, true );
3694 begPos += result.Length();
3696 // result.RemoveAll('[');
3697 // result.RemoveAll(']');
3702 myResults.Append( result );
3705 if ( res > 0 && res <= myResults.Length() )
3706 return myResults( res );
3707 return theEmptyString;
3710 //================================================================================
3712 * \brief Return substring of python command looking like ResVal = Object.Meth()
3713 * \retval const TCollection_AsciiString & - Object substring
3715 //================================================================================
3717 const TCollection_AsciiString & _pyCommand::GetObject()
3719 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3722 int begPos = GetBegPos( RESULT_IND );
3724 begPos = myString.Location( "=", 1, Length() ) + 1;
3725 // is '=' in the string argument (for example, name) or not
3726 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3727 for ( int i = 1; i < begPos-1; i++ )
3728 switch ( myString.Value( i )) {
3729 case '\'': nb[0]++; break;
3730 case '"' : nb[1]++; break;
3731 case '(' : nb[2]++; break;
3732 case ')' : nb[3]++; break;
3734 // if = is inside a string or a list
3735 // then get an object at the start of the command
3736 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3740 begPos += myRes.Length();
3742 myObj = GetWord( myString, begPos, true );
3743 if ( begPos != EMPTY )
3745 // check if object is complex,
3746 // so far consider case like "smesh.Method()"
3747 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3748 //if ( bracketPos==0 ) bracketPos = Length();
3749 int dotPos = begPos+myObj.Length();
3750 while ( dotPos+1 < bracketPos ) {
3751 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3756 if ( dotPos > begPos+myObj.Length() )
3757 myObj = myString.SubString( begPos, dotPos-1 );
3760 // 1st word after '=' is an object
3761 // else // no method -> no object
3767 SetBegPos( OBJECT_IND, begPos );
3773 //================================================================================
3775 * \brief Return substring of python command looking like ResVal = Obj.Method()
3776 * \retval const TCollection_AsciiString & - Method substring
3778 //================================================================================
3780 const TCollection_AsciiString & _pyCommand::GetMethod()
3782 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3785 int begPos = GetBegPos( OBJECT_IND );
3786 bool forward = true;
3788 begPos = myString.Location( "(", 1, Length() ) - 1;
3792 begPos += myObj.Length();
3795 myMeth = GetWord( myString, begPos, forward );
3796 SetBegPos( METHOD_IND, begPos );
3802 //================================================================================
3804 * \brief Returns true if there are brackets after the method
3806 //================================================================================
3808 bool _pyCommand::IsMethodCall()
3810 if ( GetMethod().IsEmpty() )
3812 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3813 return ( s[0] == '(' || s[1] == '(' );
3816 //================================================================================
3818 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3819 * \retval const TCollection_AsciiString & - Arg<index> substring
3821 //================================================================================
3823 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3825 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3829 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3831 pos = myString.Location( "(", 1, Length() );
3835 // we are at or before '(', skip it if present
3837 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3838 if ( pos > Length() )
3842 SetBegPos( ARG1_IND, 0 ); // even no '('
3843 return theEmptyString;
3847 list< TCollection_AsciiString > separatorStack( 1, ",)");
3848 bool ignoreNesting = false;
3850 while ( pos <= Length() )
3852 const char chr = myString.Value( pos );
3854 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3856 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3858 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3860 TCollection_AsciiString arg;
3861 if ( pos-1 >= prevPos ) {
3862 arg = myString.SubString( prevPos, pos-1 );
3863 arg.RightAdjust(); // remove spaces
3866 if ( !arg.IsEmpty() || chr == ',' )
3868 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3869 myArgs.Append( arg );
3875 else // end of nesting args found
3877 separatorStack.pop_back();
3878 ignoreNesting = false;
3881 else if ( !ignoreNesting )
3884 case '(' : separatorStack.push_back(")"); break;
3885 case '[' : separatorStack.push_back("]"); break;
3886 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3887 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3894 if ( myArgs.Length() < index )
3895 return theEmptyString;
3896 return myArgs( index );
3899 //================================================================================
3901 * \brief Return position where arguments begin
3903 //================================================================================
3905 int _pyCommand::GetArgBeginning() const
3907 int pos = GetBegPos( ARG1_IND );
3908 if ( pos == UNKNOWN )
3910 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3912 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3917 //================================================================================
3919 * \brief Check if char is a word part
3920 * \param c - The character to check
3921 * \retval bool - The check result
3923 //================================================================================
3925 static inline bool isWord(const char c, const bool dotIsWord)
3928 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3931 //================================================================================
3933 * \brief Looks for a word in the string and returns word's beginning
3934 * \param theString - The input string
3935 * \param theStartPos - The position to start the search, returning word's beginning
3936 * \param theForward - The search direction
3937 * \retval TCollection_AsciiString - The found word
3939 //================================================================================
3941 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3943 const bool theForward,
3944 const bool dotIsWord )
3946 int beg = theStartPos, end = theStartPos;
3947 theStartPos = EMPTY;
3948 if ( beg < 1 || beg > theString.Length() )
3949 return theEmptyString;
3951 if ( theForward ) { // search forward
3953 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3955 if ( beg > theString.Length() )
3956 return theEmptyString; // no word found
3959 char begChar = theString.Value( beg );
3960 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3961 char endChar = ( begChar == '[' ) ? ']' : begChar;
3962 // end is at the corresponding quoting mark or bracket
3963 while ( end < theString.Length() &&
3964 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3968 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3973 else { // search backward
3975 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3978 return theEmptyString; // no word found
3980 char endChar = theString.Value( end );
3981 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3982 char begChar = ( endChar == ']' ) ? '[' : endChar;
3983 // beg is at the corresponding quoting mark
3985 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3989 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3995 //cout << theString << " ---- " << beg << " - " << end << endl;
3996 return theString.SubString( beg, end );
3999 //================================================================================
4001 * \brief Returns true if the string looks like a study entry
4003 //================================================================================
4005 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4007 if ( str.Length() < 5 ) return false;
4009 int nbColons = 0, isColon;
4010 for ( int i = 1; i <= str.Length(); ++i )
4012 char c = str.Value(i);
4013 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4015 nbColons += isColon;
4017 return nbColons > 2 && str.Length()-nbColons > 2;
4020 //================================================================================
4022 * \brief Returns true if the string looks like an object ID but not like a list,
4023 * string, command etc.
4025 //================================================================================
4027 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4029 if ( str.Length() < 1 ) return false;
4031 const char* s = str.ToCString();
4033 for ( int i = 0; i < str.Length(); ++i )
4034 if ( !IsIDChar( s[i] ))
4040 //================================================================================
4042 * \brief Finds entries in a string
4044 //================================================================================
4046 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4048 std::list< _pyID > resList;
4050 while ( ++pos <= str.Length() )
4052 if ( !isdigit( str.Value( pos ))) continue;
4053 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4056 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4057 _pyID entry = str.SubString( pos, end-1 );
4059 if ( IsStudyEntry( entry ))
4060 resList.push_back( entry );
4065 //================================================================================
4067 * \brief Look for position where not space char is
4068 * \param theString - The string
4069 * \param thePos - The position to search from and which returns result
4070 * \retval bool - false if there are only space after thePos in theString
4072 //================================================================================
4074 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4076 if ( thePos < 1 || thePos > theString.Length() )
4079 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4082 return thePos <= theString.Length();
4085 //================================================================================
4087 * \brief Modify a part of the command
4088 * \param thePartIndex - The index of the part
4089 * \param thePart - The new part string
4090 * \param theOldPart - The old part
4092 //================================================================================
4094 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4095 TCollection_AsciiString& theOldPart)
4097 int pos = GetBegPos( thePartIndex );
4098 if ( pos <= Length() && theOldPart != thePart)
4100 TCollection_AsciiString seperator;
4102 pos = GetBegPos( thePartIndex + 1 );
4103 if ( pos < 1 ) return;
4104 switch ( thePartIndex ) {
4105 case RESULT_IND: seperator = " = "; break;
4106 case OBJECT_IND: seperator = "."; break;
4107 case METHOD_IND: seperator = "()"; break;
4111 myString.Remove( pos, theOldPart.Length() );
4112 if ( !seperator.IsEmpty() )
4113 myString.Insert( pos , seperator );
4114 myString.Insert( pos, thePart );
4115 // update starting positions of the following parts
4116 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4117 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4118 if ( myBegPos( i ) > 0 )
4119 myBegPos( i ) += posDelta;
4121 theOldPart = thePart;
4125 //================================================================================
4127 * \brief Set argument
4128 * \param index - The argument index, it counts from 1
4129 * \param theArg - The argument string
4131 //================================================================================
4133 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4136 int argInd = ARG1_IND + index - 1;
4137 int pos = GetBegPos( argInd );
4138 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4140 // find a closing parenthesis
4141 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4142 int lastArgInd = GetNbArgs();
4143 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4144 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4149 while ( pos > 0 && myString.Value( pos ) != ')' )
4152 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4156 while ( myArgs.Length() < index ) {
4157 if ( myArgs.Length() )
4158 myString.Insert( pos++, "," );
4159 myArgs.Append("None");
4160 myString.Insert( pos, myArgs.Last() );
4161 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4162 pos += myArgs.Last().Length();
4165 SetPart( argInd, theArg, myArgs( index ));
4168 //================================================================================
4170 * \brief Empty arg list
4172 //================================================================================
4174 void _pyCommand::RemoveArgs()
4176 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4177 myString.Trunc( pos );
4180 if ( myBegPos.Length() >= ARG1_IND )
4181 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4184 //================================================================================
4186 * \brief Comment a python command
4188 //================================================================================
4190 void _pyCommand::Comment()
4192 if ( IsEmpty() ) return;
4195 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4196 if ( i <= Length() )
4198 myString.Insert( i, "#" );
4199 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4201 int begPos = GetBegPos( iPart );
4202 if ( begPos != UNKNOWN && begPos != EMPTY )
4203 SetBegPos( iPart, begPos + 1 );
4208 //================================================================================
4210 * \brief Set dependent commands after this one
4212 //================================================================================
4214 bool _pyCommand::SetDependentCmdsAfter() const
4216 bool orderChanged = false;
4217 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4218 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4219 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4220 orderChanged = true;
4221 theGen->SetCommandAfter( *cmd, this );
4222 (*cmd)->SetDependentCmdsAfter();
4225 return orderChanged;
4227 //================================================================================
4229 * \brief Insert accessor method after theObjectID
4230 * \param theObjectID - id of the accessed object
4231 * \param theAcsMethod - name of the method giving access to the object
4232 * \retval bool - false if theObjectID is not found in the command string
4234 //================================================================================
4236 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4238 if ( !theAcsMethod )
4240 // start object search from the object, i.e. ignore result
4242 int beg = GetBegPos( OBJECT_IND );
4243 if ( beg < 1 || beg > Length() )
4246 while (( beg = myString.Location( theObjectID, beg, Length() )))
4248 // check that theObjectID is not just a part of a longer ID
4249 int afterEnd = beg + theObjectID.Length();
4250 Standard_Character c = myString.Value( afterEnd );
4251 if ( !IsIDChar( c ))
4253 // check if accessor method already present
4255 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4257 int oldLen = Length();
4258 myString.Insert( afterEnd, (char*) theAcsMethod );
4259 myString.Insert( afterEnd, "." );
4260 // update starting positions of the parts following the modified one
4261 int posDelta = Length() - oldLen;
4262 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4263 if ( myBegPos( i ) > afterEnd )
4264 myBegPos( i ) += posDelta;
4269 beg = afterEnd; // is a part -> next search
4274 //================================================================================
4276 * \brief Creates pyObject
4278 //================================================================================
4280 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4281 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4286 //================================================================================
4288 * \brief Set up myID and myIsPublished
4290 //================================================================================
4292 void _pyObject::setID(const _pyID& theID)
4295 myIsPublished = !theGen->IsNotPublished( GetID() );
4298 //================================================================================
4300 * \brief Clear myCreationCmd and myProcessedCmds
4302 //================================================================================
4304 void _pyObject::ClearCommands()
4309 if ( !myCreationCmd.IsNull() )
4310 myCreationCmd->Clear();
4312 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4313 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4317 //================================================================================
4319 * \brief Return method name giving access to an interaface object wrapped by python class
4320 * \retval const char* - method name
4322 //================================================================================
4324 const char* _pyObject::AccessorMethod() const
4328 //================================================================================
4330 * \brief Return ID of a father
4332 //================================================================================
4334 _pyID _pyObject::FatherID(const _pyID & childID)
4336 int colPos = childID.SearchFromEnd(':');
4338 return childID.SubString( 1, colPos-1 );
4342 //================================================================================
4344 * \brief SelfEraser erases creation command if none of it's commands invoked
4345 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4347 //================================================================================
4349 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4350 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4352 myIsPublished = true; // prevent clearing as a not published
4353 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4356 //================================================================================
4358 * \brief SelfEraser erases creation command if none of it's commands invoked
4359 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4361 //================================================================================
4363 bool _pySelfEraser::CanClear()
4365 bool toErase = false;
4366 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4369 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4370 for ( ; cmd != myArgCmds.end(); ++cmd )
4371 nbArgUses += IsAliveCmd( *cmd );
4373 toErase = ( nbArgUses < 1 );
4378 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4379 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4380 for ( ; cmd != cmds.end(); )
4381 // check of cmd emptiness is not enough as object can change
4382 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4385 cmd = cmds.erase( cmd ); // save the cmd from clearing
4387 toErase = ( nbCalls < 1 );
4392 //================================================================================
4394 * \brief Check if a command is or can be cleared
4396 //================================================================================
4398 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4400 if ( theCmd->IsEmpty() )
4403 if ( !theGen->IsToKeepAllCommands() )
4405 const _pyID& objID = theCmd->GetObject();
4406 Handle( _pyObject ) obj = theGen->FindObject( objID );
4407 if ( !obj.IsNull() )
4408 return !obj->CanClear();
4413 //================================================================================
4415 * \brief SelfEraser erases creation command if none of it's commands invoked
4416 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4418 //================================================================================
4420 void _pySelfEraser::Flush()
4424 myIsPublished = false;
4425 _pyObject::ClearCommands();
4429 //================================================================================
4431 * \brief _pySubMesh constructor
4433 //================================================================================
4435 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4436 _pyObject(theCreationCmd)
4438 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4439 if ( toKeepAgrCmds )
4440 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4443 //================================================================================
4445 * \brief Return true if a sub-mesh can be used as argument of the given method
4447 //================================================================================
4449 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4452 // names of all methods where a sub-mesh can be used as argument
4453 // static TStringSet methods;
4454 // if ( methods.empty() ) {
4455 // const char * names[] = {
4456 // // methods of SMESH_Gen
4458 // // methods of SMESH_Group
4460 // // methods of SMESH_Measurements
4462 // // methods of SMESH_Mesh
4463 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4465 // // methods of SMESH_MeshEditor
4466 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4467 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4468 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4469 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4470 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4471 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4472 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4473 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4474 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4475 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4476 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4477 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4478 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4479 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4480 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4481 // "" }; // <- mark of end
4482 // methods.Insert( names );
4484 // return methods.Contains( theMethodName );
4487 //================================================================================
4489 * \brief count invoked commands
4491 //================================================================================
4493 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4495 _pyObject::Process(theCommand); // count calls of Process()
4498 //================================================================================
4500 * \brief Move creation command depending on invoked commands
4502 //================================================================================
4504 void _pySubMesh::Flush()
4506 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4507 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4508 else if ( !myCreator.IsNull() )
4509 // move to be just after creator
4510 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4512 // move sub-mesh usage after creation cmd
4513 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4514 for ( ; cmd != myArgCmds.end(); ++cmd )
4515 if ( !(*cmd)->IsEmpty() )
4516 GetCreationCmd()->AddDependantCmd( *cmd );
4519 //================================================================================
4521 * \brief Creates _pyGroup
4523 //================================================================================
4525 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4526 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4528 if ( !id.IsEmpty() )
4531 myCanClearCreationCmd = true;
4533 const _AString& method = theCreationCmd->GetMethod();
4534 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4536 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4538 // ----------------------------------------------------------------------
4539 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4541 _pyID geom = theCreationCmd->GetArg( 3 );
4542 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4543 // next if(){...} section is commented
4544 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4545 // theCreationCmd->SetMethod( "Group" );
4546 // theCreationCmd->RemoveArgs();
4547 // theCreationCmd->SetArg( 1, geom );
4550 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4551 _pyID type = theCreationCmd->GetArg( 1 );
4552 _pyID name = theCreationCmd->GetArg( 2 );
4553 theCreationCmd->SetMethod( "GroupOnGeom" );
4554 theCreationCmd->RemoveArgs();
4555 theCreationCmd->SetArg( 1, geom );
4556 theCreationCmd->SetArg( 2, name );
4557 theCreationCmd->SetArg( 3, type );
4560 else if ( method == "CreateGroupFromFilter" )
4562 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4563 theCreationCmd->SetMethod( "GroupOnFilter" );
4565 _pyID filterID = theCreationCmd->GetArg(3);
4566 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4567 if ( !filter.IsNull())
4569 if ( !filter->GetNewID().IsEmpty() )
4570 theCreationCmd->SetArg( 3, filter->GetNewID() );
4571 //filter->AddUser( this );
4575 else if ( method == "GetGroups" )
4577 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4581 // theCreationCmd does something else apart from creation of this group
4582 // and thus it can't be cleared if this group is removed
4583 myCanClearCreationCmd = false;
4587 //================================================================================
4589 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4592 //================================================================================
4594 bool _pyGroup::CanClear()
4599 if ( !myCanClearCreationCmd &&
4600 !myCreationCmd.IsNull() &&
4601 myCreationCmd->GetMethod() == "GetGroups" )
4603 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4604 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4605 list< _pyID >::iterator grID = idList.begin();
4606 if ( GetID() == *grID )
4608 myCanClearCreationCmd = true;
4609 list< Handle(_pyGroup ) > groups;
4610 for ( ; grID != idList.end(); ++grID )
4612 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4613 if ( group.IsNull() ) continue;
4614 groups.push_back( group );
4615 if ( group->IsInStudy() )
4616 myCanClearCreationCmd = false;
4618 // set myCanClearCreationCmd == true to all groups
4619 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4620 for ( ; group != groups.end(); ++group )
4621 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4625 return myCanClearCreationCmd;
4628 //================================================================================
4630 * \brief set myCanClearCreationCmd = true if the main action of the creation
4631 * command is discarded
4633 //================================================================================
4635 void _pyGroup::RemovedWithContents()
4637 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4638 // via a created group
4639 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4640 // myCanClearCreationCmd = true;
4643 //================================================================================
4645 * \brief To convert creation of a group by filter
4647 //================================================================================
4649 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4651 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4652 // group = mesh.CreateEmptyGroup( elemType, groupName )
4653 // aFilter.SetMesh(mesh)
4654 // nbAdd = group.AddFrom( aFilter )
4655 Handle(_pyFilter) filter;
4656 if ( theCommand->GetMethod() == "AddFrom" )
4658 _pyID idSource = theCommand->GetArg(1);
4659 // check if idSource is a filter
4660 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4661 if ( !filter.IsNull() )
4663 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4664 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4665 while ( *cmdIt != theCommand ) ++cmdIt;
4666 while ( (*cmdIt)->GetOrderNb() != 1 )
4668 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4669 if ((setMeshCmd->GetObject() == idSource ||
4670 setMeshCmd->GetObject() == filter->GetNewID() )
4672 setMeshCmd->GetMethod() == "SetMesh")
4674 setMeshCmd->Clear();
4678 // replace 3 commands by one
4679 theCommand->Clear();
4680 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4681 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4682 if ( !filter->GetNewID().IsEmpty() )
4683 idSource = filter->GetNewID();
4684 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4685 makeGroupCmd->SetArg( 1, name );
4686 makeGroupCmd->SetArg( 2, idSource );
4687 filter->AddArgCmd( makeGroupCmd );
4690 else if ( theCommand->GetMethod() == "SetFilter" )
4692 // set new name of a filter or clear the command if the same filter is set
4693 _pyID filterID = theCommand->GetArg(1);
4694 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4695 if ( !myFilter.IsNull() && filter == myFilter )
4696 theCommand->Clear();
4697 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4698 theCommand->SetArg( 1, filter->GetNewID() );
4701 else if ( theCommand->GetMethod() == "GetFilter" )
4703 // GetFilter() returns a filter with other ID, make myFilter process
4704 // calls of the returned filter
4705 if ( !myFilter.IsNull() )
4707 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4708 theCommand->Clear();
4712 // if ( !filter.IsNull() )
4713 // filter->AddUser( this );
4715 theGen->AddMeshAccessorMethod( theCommand );
4718 //================================================================================
4720 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4722 //================================================================================
4724 void _pyGroup::Flush()
4726 if ( !theGen->IsToKeepAllCommands() &&
4727 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4729 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4733 //================================================================================
4735 * \brief Constructor of _pyFilter
4737 //================================================================================
4739 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4740 :_pyObject(theCreationCmd), myNewID( newID )
4742 //myIsPublished = true; // prevent clearing as a not published
4743 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4746 //================================================================================
4748 * \brief To convert creation of a filter by criteria and
4749 * to replace an old name by a new one
4751 //================================================================================
4753 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4755 if ( theCommand->GetObject() == GetID() )
4756 _pyObject::Process(theCommand); // count commands
4758 if ( !myNewID.IsEmpty() )
4759 theCommand->SetObject( myNewID );
4761 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4762 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4763 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4764 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4765 theCommand->GetMethod() == "SetCriteria")
4767 // aFilter.SetCriteria(aCriteria) ->
4768 // aFilter = smesh.GetFilterFromCriteria(criteria)
4769 if ( myNewID.IsEmpty() )
4770 theCommand->SetResultValue( GetID() );
4772 theCommand->SetResultValue( myNewID );
4773 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4774 theCommand->SetMethod( "GetFilterFromCriteria" );
4776 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4777 GetCreationCmd()->Clear();
4778 GetCreationCmd()->GetString() = theCommand->GetString();
4779 theCommand->Clear();
4780 theCommand->AddDependantCmd( GetCreationCmd() );
4781 // why swap? -- it's needed
4782 //GetCreationCmd()->Clear();
4784 else if ( theCommand->GetMethod() == "SetMesh" )
4786 if ( myMesh == theCommand->GetArg( 1 ))
4787 theCommand->Clear();
4789 myMesh = theCommand->GetArg( 1 );
4790 theGen->AddMeshAccessorMethod( theCommand );
4794 //================================================================================
4796 * \brief Set new filter name to the creation command and to myArgCmds
4798 //================================================================================
4800 void _pyFilter::Flush()
4802 if ( myNewID.IsEmpty() ) return;
4804 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4805 for ( ; cmd != myArgCmds.end(); ++cmd )
4806 if ( !(*cmd)->IsEmpty() )
4808 _AString cmdStr = (*cmd)->GetString();
4809 _AString id = GetID();
4810 int pos = cmdStr.Search( id );
4813 cmdStr.Remove( pos, id.Length() );
4814 cmdStr.Insert( pos, myNewID );
4817 (*cmd)->GetString() = cmdStr;
4820 if ( !GetCreationCmd()->IsEmpty() )
4821 GetCreationCmd()->SetResultValue( myNewID );
4824 //================================================================================
4826 * \brief Return true if all my users can be cleared
4828 //================================================================================
4830 bool _pyObject::CanClear()
4832 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4833 for ( ; cmd != myArgCmds.end(); ++cmd )
4834 if ( !(*cmd)->IsEmpty() )
4836 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4837 if ( !obj.IsNull() && !obj->CanClear() )
4840 return ( !myIsPublished );
4843 //================================================================================
4845 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4847 //================================================================================
4849 _pyHypothesisReader::_pyHypothesisReader()
4852 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4853 LDOMParser xmlParser;
4854 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4856 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4860 INFOS( xmlParser.GetError(data) );
4863 // <algorithm type="Regular_1D"
4864 // label-id="Wire discretisation"
4867 // <algo>Regular_1D=Segment()</algo>
4868 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4870 LDOM_Document xmlDoc = xmlParser.getDocument();
4871 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4872 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4874 LDOM_Node algoNode = algoNodeList.item( i );
4875 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4876 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4877 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4879 _AString text, algoType, method, arg;
4880 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4882 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4883 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4884 text = textNode.getNodeValue();
4885 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4886 algoType = algoCmd->GetResultValue();
4887 method = algoCmd->GetMethod();
4888 arg = algoCmd->GetArg(1);
4889 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4891 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4892 algo->SetConvMethodAndType( method, algoType );
4893 if ( !arg.IsEmpty() )
4894 algo->setCreationArg( 1, arg );
4896 myType2Hyp[ algoType ] = algo;
4900 if ( algoType.IsEmpty() ) continue;
4902 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4904 Handle( _pyHypothesis ) hyp;
4905 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4907 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4908 LDOM_Node textNode = pyHypoNode.getFirstChild();
4909 text = textNode.getNodeValue();
4910 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4911 hypType = hypoCmd->GetResultValue();
4912 method = hypoCmd->GetMethod();
4913 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4915 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4916 if ( type2hyp == myType2Hyp.end() )
4917 hyp = new _pyHypothesis( hypoCmd );
4919 hyp = type2hyp->second;
4920 hyp->SetConvMethodAndType( method, algoType );
4921 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4923 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4924 _AString argMethod = argCmd.GetMethod();
4925 _AString argNbText = argCmd.GetArg( 1 );
4926 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4927 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4929 hyp->AddArgMethod( argMethod,
4930 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4932 myType2Hyp[ hypType ] = hyp;
4936 // <hypothesis type="BLSURF_Parameters"
4940 // <accumulative-methods>
4941 // SetEnforcedVertex,
4942 // SetEnforcedVertexNamed
4943 // </accumulative-methods>
4947 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4948 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4950 LDOM_Node hypNode = hypNodeList.item( i );
4951 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4952 _AString hypType = hypElem.getAttribute("type");
4953 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4954 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4956 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4957 if ( type2hyp == myType2Hyp.end() ) continue;
4959 LDOM_Node methNode = methNodeList.item( 0 );
4960 LDOM_Node textNode = methNode.getFirstChild();
4961 _AString text = textNode.getNodeValue();
4965 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4966 pos += method.Length();
4967 type2hyp->second->AddAccumulativeMethod( method );
4969 while ( !method.IsEmpty() );
4972 } // loop on xmlPaths
4975 //================================================================================
4977 * \brief Returns a new hypothesis initialized according to the read information
4979 //================================================================================
4981 Handle(_pyHypothesis)
4982 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4983 const Handle(_pyCommand)& creationCmd) const
4985 Handle(_pyHypothesis) resHyp, sampleHyp;
4987 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4988 if ( type2hyp != myType2Hyp.end() )
4989 sampleHyp = type2hyp->second;
4991 if ( sampleHyp.IsNull() )
4993 resHyp = new _pyHypothesis(creationCmd);
4997 if ( sampleHyp->IsAlgo() )
4998 resHyp = new _pyAlgorithm( creationCmd );
5000 resHyp = new _pyHypothesis(creationCmd);
5001 resHyp->Assign( sampleHyp, _pyID() );
5006 //================================================================================
5008 * \brief Adds an object ID to some family of IDs with a common prefix
5009 * \param [in] str - the object ID
5010 * \return bool - \c false if \a str does not have the same prefix as \a this family
5011 * (for internal usage)
5013 //================================================================================
5015 bool _pyStringFamily::Add( const char* str )
5017 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5018 return false; // expected prefix is missing
5020 str += _prefix.Length(); // skip _prefix
5022 // try to add to some of child falimies
5023 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5024 for ( ; itSub != _subFams.end(); ++itSub )
5025 if ( itSub->Add( str ))
5028 // no suitable family found - add str to _strings or create a new child family
5030 // look for a proper place within sorted _strings
5031 std::list< _AString >::iterator itStr = _strings.begin();
5032 while ( itStr != _strings.end() && itStr->IsLess( str ))
5034 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5035 return true; // same ID already kept
5037 const int minPrefixSize = 4;
5039 // count "smaller" strings with the same prefix
5040 std::list< _AString >::iterator itLess = itStr; --itLess;
5042 for ( ; itLess != _strings.end(); --itLess )
5043 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5048 // count "greater" strings with the same prefix
5049 std::list< _AString >::iterator itMore = itStr;
5051 for ( ; itMore != _strings.end(); ++itMore )
5052 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5057 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5059 // look for a maximal prefix length
5060 // int lessPrefSize = 3, morePrefSize = 3;
5061 // if ( nbLess > 0 )
5062 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5064 // if ( nbMore > 0 )
5065 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5067 // int prefixSize = 3;
5068 // if ( nbLess == 0 )
5069 // prefixSize = morePrefSize;
5070 // else if ( nbMore == 0 )
5071 // prefixSize = lessPrefSize;
5073 // prefixSize = Min( lessPrefSize, morePrefSize );
5074 int prefixSize = minPrefixSize;
5075 _AString newPrefix ( str, prefixSize );
5077 // look for a proper place within _subFams sorted by _prefix
5078 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5079 if ( !itSub->_prefix.IsLess( newPrefix ))
5082 // add the new _pyStringFamily
5083 itSub = _subFams.insert( itSub, _pyStringFamily());
5084 _pyStringFamily& newSubFam = *itSub;
5085 newSubFam._prefix = newPrefix;
5087 // pass this->_strings to newSubFam._strings
5088 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5089 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5090 newSubFam._strings.push_back( str + prefixSize );
5091 for ( ; nbMore > 0; --nbMore, ++itStr )
5092 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5094 _strings.erase( itLess, ++itMore );
5096 else // too few string to make a family for them
5098 _strings.insert( itStr, str );
5103 //================================================================================
5105 * \brief Finds an object ID in the command
5106 * \param [in] longStr - the command string
5107 * \param [out] subStr - the found object ID
5108 * \return bool - \c true if the object ID found
5110 //================================================================================
5112 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5114 const _AString& longStr = cmd->GetString();
5115 const char* s = longStr.ToCString();
5118 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5119 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5120 if ( argBeg < 4 || argBeg > longStr.Length() )
5122 for ( ; itSub != _subFams.end(); ++itSub )
5125 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5126 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5128 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5129 from = pos + len + itSub->_prefix.Length();
5134 from += itSub->_prefix.Length();
5137 // look among _strings
5138 std::list< _AString >::iterator itStr = _strings.begin();
5139 for ( ; itStr != _strings.end(); ++itStr )
5140 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5141 // check that object ID does not continue after len
5142 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5144 subStr.push_back( *itStr );
5150 //================================================================================
5152 * \brief Return remainder length of the object ID after my _prefix
5153 * \param [in] str - remainder of the command after my _prefix
5154 * \return int - length of the object ID or -1 if not found
5156 //================================================================================
5158 int _pyStringFamily::isIn( const char* str )
5160 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5162 for ( ; itSub != _subFams.end(); ++itSub )
5164 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5167 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5168 return itSub->_prefix.Length() + len;
5173 if ( !_strings.empty() )
5175 std::list< _AString >::iterator itStr = _strings.begin();
5176 bool firstEmpty = itStr->IsEmpty();
5179 for ( ; itStr != _strings.end(); ++itStr )
5181 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5184 len = itStr->Length();
5193 // check that object ID does not continue after len
5194 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5201 //================================================================================
5205 //================================================================================
5207 void _pyStringFamily::Print( int level )
5209 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5210 std::list< _AString >::iterator itStr = _strings.begin();
5211 for ( ; itStr != _strings.end(); ++itStr )
5212 cout << *itStr << " | ";
5214 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5215 for ( ; itSub != _subFams.end(); ++itSub )
5216 itSub->Print( level + 1 );
5218 cout << string( 70, '-' ) << endl;