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 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 OCCT_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 coresponding 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
298 // It's necessary to continue recording this history and to fill
299 // undef2newItems (see below) accordingly.
301 typedef map< int, vector< int > > TUndef2newItems;
302 static TUndef2newItems undef2newItems;
303 if ( undef2newItems.empty() )
305 undef2newItems[ 26 ].push_back( 7 );
306 undef2newItems[ 27 ].push_back( 17 );
307 { int items[] = { 10, 11, 23, 24, 25 };
308 undef2newItems[ 32 ].assign( items, items+5 ); }
309 undef2newItems[ 33 ].push_back( 26 );
310 { int items[] = { 8, 9, 25, 26, 27, 28 };
311 undef2newItems[ 39 ].assign( items, items+6 ); }
312 { int items[] = { 14, 15, 16, 17 };
313 undef2newItems[ 43 ].assign( items, items+4 ); }
314 undef2newItems[ 44 ].push_back( 37 );
315 undef2newItems[ 45 ].push_back( 36 );
316 undef2newItems[ 46 ].push_back( 39 );
317 undef2newItems[ 47 ].push_back( 22 );
318 undef2newItems[ 48 ].push_back( 22 );
320 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
323 int iType = Type.IntegerValue();
324 int iCompare = Compare.IntegerValue();
325 int iUnaryOp = UnaryOp.IntegerValue();
326 int iBinaryOp = BinaryOp.IntegerValue();
328 // find out integer value of FT_Undefined at the moment of dump
329 int oldUndefined = iBinaryOp;
330 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
333 // apply history to args
334 TUndef2newItems::const_iterator undef_items =
335 undef2newItems.upper_bound( oldUndefined );
336 if ( undef_items != undef2newItems.end() )
338 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
339 for ( ; undef_items != undef2newItems.end(); ++undef_items )
341 const vector< int > & addedItems = undef_items->second;
342 for ( size_t i = 0; i < addedItems.size(); ++i )
343 for ( int iArg = 0; iArg < 4; ++iArg )
345 int& arg = *pArg[iArg];
346 if ( arg >= addedItems[i] )
350 Type = TCollection_AsciiString( iType );
351 Compare = TCollection_AsciiString( iCompare );
352 UnaryOp = TCollection_AsciiString( iUnaryOp );
353 BinaryOp = TCollection_AsciiString( iBinaryOp );
357 //================================================================================
359 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
360 * arguments of a given command by a list "[x,y,z]" if the list is accesible
363 //================================================================================
365 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
367 static TStringSet methodsAcceptingList;
368 if ( methodsAcceptingList.empty() ) {
369 const char * methodNames[] = {
370 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
371 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
372 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
373 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
374 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
375 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
376 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
377 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
378 "Translate","TranslateMakeGroups","TranslateMakeMesh",
379 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
380 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
381 ,"" }; // <- mark of the end
382 methodsAcceptingList.Insert( methodNames );
384 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
386 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
388 const _AString & arg = theCommand->GetArg( i );
389 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
390 arg.Search( "SMESH.DirStruct" ) == 1 )
392 Handle(_pyCommand) workCmd = new _pyCommand( arg );
393 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
395 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
397 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
399 _AString newArg = "[ ";
400 newArg += ( workCmd->GetArg( 1 ) + ", " +
401 workCmd->GetArg( 2 ) + ", " +
402 workCmd->GetArg( 3 ) + " ]");
403 theCommand->SetArg( i, newArg );
409 //================================================================================
411 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
412 * a list "[id1,id2]" if the list is an accesible type of argument.
414 //================================================================================
416 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
418 static TStringSet methodsAcceptingList;
419 if ( methodsAcceptingList.empty() ) {
420 const char * methodNames[] = {
421 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
422 "ExportCGNS","ExportGMF",
423 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
424 "ScaleMakeGroups","Scale","ScaleMakeMesh",
425 "FindCoincidentNodesOnPartBut","DoubleElements",
426 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
427 ,"" }; // <- mark of the end
428 methodsAcceptingList.Insert( methodNames );
430 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
432 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
434 _pyCommand argCmd( theCommand->GetArg( i ));
435 if ( argCmd.GetMethod() == "GetIDSource" &&
436 argCmd.GetNbArgs() == 2 )
438 theCommand->SetArg( i, argCmd.GetArg( 1 ));
444 bool _FilterArg( const _AString& theArg )
446 static std::list<_AString> filteredArgs;
447 static bool initialized = false;
448 if ( !initialized ) {
450 filteredArgs.push_back( "SMESH.MED_V2_1" );
451 filteredArgs.push_back( "SMESH.MED_V2_2" );
453 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
457 //================================================================================
459 * \brief Convert a python script using commands of smeshBuilder.py
460 * \param theScriptLines - Lines of the input script
461 * \param theEntry2AccessorMethod - returns method names to access to
462 * objects wrapped with python class
463 * \param theObjectNames - names of objects
464 * \param theRemovedObjIDs - entries of objects whose created commands were removed
465 * \param theHistoricalDump - true means to keep all commands, false means
466 * to exclude commands relating to objects removed from study
467 * \retval TCollection_AsciiString - Conversion result
469 //================================================================================
472 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
473 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
474 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
475 std::set< TCollection_AsciiString >& theRemovedObjIDs,
476 const bool theToKeepAllCommands)
478 std::list< TCollection_AsciiString >::iterator lineIt;
479 // process notebook variables
481 SMESH_NoteBook aNoteBook;
483 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
484 aNoteBook.AddCommand( *lineIt );
486 theScriptLines.clear();
488 aNoteBook.ReplaceVariables();
490 aNoteBook.GetResultLines( theScriptLines );
493 // convert to smeshBuilder.py API
495 theGen = new _pyGen( theEntry2AccessorMethod,
498 theToKeepAllCommands );
500 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
501 theGen->AddCommand( *lineIt );
503 theScriptLines.clear();
507 #ifdef DUMP_CONVERSION
508 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
511 // clean commmands of removed objects depending on myIsPublished flag
512 theGen->ClearCommands();
514 // reorder commands after conversion
515 list< Handle(_pyCommand) >::iterator cmd;
518 orderChanges = false;
519 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
520 if ( (*cmd)->SetDependentCmdsAfter() )
522 } while ( orderChanges );
524 // concat commands back into a script
525 TCollection_AsciiString aPrevCmd;
526 set<_pyID> createdObjects;
527 createdObjects.insert( "smeshBuilder" );
528 createdObjects.insert( "smesh" );
529 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
531 #ifdef DUMP_CONVERSION
532 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
534 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
535 CheckObjectPresence( *cmd, createdObjects );
536 if ( !(*cmd)->IsEmpty() ) {
537 aPrevCmd = (*cmd)->GetString();
538 theScriptLines.push_back( aPrevCmd );
547 //================================================================================
549 * \brief _pyGen constructor
551 //================================================================================
553 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
554 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
555 std::set< TCollection_AsciiString >& theRemovedObjIDs,
556 const bool theToKeepAllCommands)
557 : _pyObject( new _pyCommand( "", 0 )),
559 myID2AccessorMethod( theEntry2AccessorMethod ),
560 myObjectNames( theObjectNames ),
561 myRemovedObjIDs( theRemovedObjIDs ),
563 myToKeepAllCommands( theToKeepAllCommands ),
564 myGeomIDNb(0), myGeomIDIndex(-1)
566 // make that GetID() to return TPythonDump::SMESHGenName()
567 GetCreationCmd()->Clear();
568 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
569 GetCreationCmd()->GetString() += "=";
571 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
572 if ( !theObjectNames.IsEmpty() )
576 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->FindComponent("GEOM");
577 if ( geomComp->_is_nil() ) return;
578 CORBA::String_var entry = geomComp->GetID();
581 // find a SMESH entry
583 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
584 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
585 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
588 // find 1st difference between smeshID and geomID
589 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
590 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
591 if ( geomID.Value( i ) != smeshID.Value( i ))
593 myGeomIDNb = geomID.Value( i );
599 //================================================================================
601 * \brief name of SMESH_Gen in smeshBuilder.py
603 //================================================================================
605 const char* _pyGen::AccessorMethod() const
607 return SMESH_2smeshpy::GenName();
610 //================================================================================
612 * \brief Convert a command using a specific converter
613 * \param theCommand - the command to convert
615 //================================================================================
617 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
619 // store theCommand in the sequence
620 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
622 Handle(_pyCommand) aCommand = myCommands.back();
623 #ifdef DUMP_CONVERSION
624 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
627 const _pyID& objID = aCommand->GetObject();
629 if ( objID.IsEmpty() )
632 // Prevent moving a command creating a sub-mesh to the end of the script
633 // if the sub-mesh is used in theCommand as argument
634 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
636 // PlaceSubmeshAfterItsCreation( aCommand );
639 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
640 StructToList( aCommand );
642 const TCollection_AsciiString& method = aCommand->GetMethod();
644 // not to erase _pySelfEraser's etc. used as args in some commands
646 #ifdef USE_STRING_FAMILY
647 std::list<_pyID> objIDs;
648 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
650 std::list<_pyID>::iterator objID = objIDs.begin();
651 for ( ; objID != objIDs.end(); ++objID )
653 Handle(_pyObject) obj = FindObject( *objID );
656 obj->AddArgCmd( aCommand );
657 //cout << objID << " found in " << theCommand << endl;
662 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
663 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
664 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
666 Handle(_pyObject) obj = FindObject( *id );
668 obj->AddArgCmd( aCommand );
673 // Find an object to process theCommand
676 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
678 this->Process( aCommand );
679 //addFilterUser( aCommand, theGen ); // protect filters from clearing
683 // SMESH_Mesh method?
684 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
685 if ( id_mesh != myMeshes.end() )
687 //id_mesh->second->AddProcessedCmd( aCommand );
689 // Wrap Export*() into try-except
690 if ( aCommand->MethodStartsFrom("Export"))
693 _AString indent = aCommand->GetIndentation();
694 _AString tryStr = indent + "try:";
695 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
696 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
697 _AString excStr = indent + "except:";
698 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
700 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
702 aCommand->GetString() = newCmd;
703 aCommand->SetOrderNb( ++myNbCommands );
704 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
705 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
706 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
708 // check for mesh editor object
709 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
710 _pyID editorID = aCommand->GetResultValue();
711 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
712 myMeshEditors.insert( make_pair( editorID, editor ));
715 // check for SubMesh objects
716 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
717 _pyID subMeshID = aCommand->GetResultValue();
718 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
719 AddObject( subMesh );
722 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
723 GetIDSourceToList( aCommand );
725 //addFilterUser( aCommand, theGen ); // protect filters from clearing
727 id_mesh->second->Process( aCommand );
728 id_mesh->second->AddProcessedCmd( aCommand );
732 // SMESH_MeshEditor method?
733 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
734 if ( id_editor != myMeshEditors.end() )
736 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
737 GetIDSourceToList( aCommand );
739 //addFilterUser( aCommand, theGen ); // protect filters from clearing
741 // some commands of SMESH_MeshEditor create meshes and groups
742 _pyID meshID, groups;
743 if ( method.Search("MakeMesh") != -1 )
744 meshID = aCommand->GetResultValue();
745 else if ( method == "MakeBoundaryMesh")
746 meshID = aCommand->GetResultValue(1);
747 else if ( method == "MakeBoundaryElements")
748 meshID = aCommand->GetResultValue(2);
750 if ( method.Search("MakeGroups") != -1 ||
751 method == "ExtrusionAlongPathX" ||
752 method == "ExtrusionAlongPathObjX" ||
753 method == "DoubleNodeGroupNew" ||
754 method == "DoubleNodeGroupsNew" ||
755 method == "DoubleNodeElemGroupNew" ||
756 method == "DoubleNodeElemGroupsNew"||
757 method == "DoubleNodeElemGroup2New"||
758 method == "DoubleNodeElemGroups2New"
760 groups = aCommand->GetResultValue();
761 else if ( method == "MakeBoundaryMesh" )
762 groups = aCommand->GetResultValue(2);
763 else if ( method == "MakeBoundaryElements")
764 groups = aCommand->GetResultValue(3);
765 else if ( method == "Create0DElementsOnAllNodes" &&
766 aCommand->GetArg(2).Length() > 2 ) // group name != ''
767 groups = aCommand->GetResultValue();
769 id_editor->second->Process( aCommand );
770 id_editor->second->AddProcessedCmd( aCommand );
773 if ( !meshID.IsEmpty() &&
774 !myMeshes.count( meshID ) &&
775 aCommand->IsStudyEntry( meshID ))
777 _AString processedCommand = aCommand->GetString();
778 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
779 CheckObjectIsReCreated( mesh );
780 myMeshes.insert( make_pair( meshID, mesh ));
782 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
785 if ( !groups.IsEmpty() )
787 if ( !aCommand->IsStudyEntry( meshID ))
788 meshID = id_editor->second->GetMesh();
789 Handle(_pyMesh) mesh = myMeshes[ meshID ];
791 list< _pyID > idList = aCommand->GetStudyEntries( groups );
792 list< _pyID >::iterator grID = idList.begin();
793 for ( ; grID != idList.end(); ++grID )
794 if ( !myObjects.count( *grID ))
796 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
798 if ( !mesh.IsNull() ) mesh->AddGroup( group );
802 } // SMESH_MeshEditor methods
804 // SMESH_Hypothesis method?
805 Handle(_pyHypothesis) hyp = FindHyp( objID );
806 if ( !hyp.IsNull() && !hyp->IsAlgo() )
808 hyp->Process( aCommand );
809 hyp->AddProcessedCmd( aCommand );
813 // aFilterManager.CreateFilter() ?
814 if ( aCommand->GetMethod() == "CreateFilter" )
816 // Set a more human readable name to a filter
817 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
818 _pyID newID, filterID = aCommand->GetResultValue();
819 int pos = filterID.Search( "0x" );
821 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
823 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
826 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
827 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
829 // create _pySelfEraser for functors
830 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
831 functor->IgnoreOwnCalls(); // to erase if not used as an argument
832 AddObject( functor );
835 // other object method?
836 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
837 if ( id_obj != myObjects.end() ) {
838 id_obj->second->Process( aCommand );
839 id_obj->second->AddProcessedCmd( aCommand );
843 // Add access to a wrapped mesh
844 AddMeshAccessorMethod( aCommand );
846 // Add access to a wrapped algorithm
847 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
849 // PAL12227. PythonDump was not updated at proper time; result is
850 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
851 // TypeError: __init__() takes exactly 11 arguments (10 given)
852 const char wrongCommand[] = "SMESH.Filter.Criterion(";
853 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
855 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
856 // there must be 10 arguments, 5-th arg ThresholdID is missing,
857 const int wrongNbArgs = 9, missingArg = 5;
858 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
860 for ( int i = wrongNbArgs; i > missingArg; --i )
861 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
862 tmpCmd.SetArg( missingArg, "''");
863 aCommand->GetString().Trunc( beg - 1 );
864 aCommand->GetString() += tmpCmd.GetString();
867 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
869 // instead of "SMESH.Filter.Criterion(
870 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
871 // 1 2 3 4 5 6 7 8 9 10
872 // in order to avoid the problem of type mismatch of long and FunctorType
873 const TCollection_AsciiString
874 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
875 TCollection_AsciiString
876 Type = aCommand->GetArg(1), // long
877 Compare = aCommand->GetArg(2), // long
878 Threshold = aCommand->GetArg(3), // double
879 ThresholdStr = aCommand->GetArg(4), // string
880 ThresholdID = aCommand->GetArg(5), // string
881 UnaryOp = aCommand->GetArg(6), // long
882 BinaryOp = aCommand->GetArg(7), // long
883 Tolerance = aCommand->GetArg(8), // double
884 TypeOfElement = aCommand->GetArg(9), // ElementType
885 Precision = aCommand->GetArg(10); // long
886 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
887 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
888 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
889 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
890 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
892 if ( Compare == "SMESH.FT_EqualTo" )
895 aCommand->RemoveArgs();
896 aCommand->SetObject( SMESH_2smeshpy::GenName() );
897 aCommand->SetMethod( "GetCriterion" );
899 aCommand->SetArg( 1, TypeOfElement );
900 aCommand->SetArg( 2, Type );
901 aCommand->SetArg( 3, Compare );
903 if ( Threshold.IsIntegerValue() )
905 int iGeom = Threshold.IntegerValue();
906 if ( Type == "SMESH.FT_ElemGeomType" )
908 // set SMESH.GeometryType instead of a numerical Threshold
909 const int nbTypes = SMESH::Geom_LAST;
910 const char* types[] = {
911 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
912 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
913 "Geom_POLYHEDRA", "Geom_BALL" };
914 if ( -1 < iGeom && iGeom < nbTypes )
915 Threshold = SMESH + types[ iGeom ];
917 // is types complete? (compilation failure mains that enum GeometryType changed)
918 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
921 if (Type == "SMESH.FT_EntityType")
923 // set SMESH.EntityType instead of a numerical Threshold
924 const int nbTypes = SMESH::Entity_Last;
925 const char* types[] = {
926 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
927 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
928 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
929 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
930 "Entity_Pyramid", "Entity_Quad_Pyramid",
931 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
932 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
933 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
934 if ( -1 < iGeom && iGeom < nbTypes )
935 Threshold = SMESH + types[ iGeom ];
937 // is 'types' complete? (compilation failure mains that enum EntityType changed)
938 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
942 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
943 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
944 else if ( ThresholdStr.Length() != 2 )
945 aCommand->SetArg( 4, ThresholdStr );
946 else if ( ThresholdID.Length() != 2 )
947 aCommand->SetArg( 4, ThresholdID );
949 aCommand->SetArg( 4, Threshold );
950 // find the last not default arg
952 if ( Tolerance == dfltTol ) {
954 if ( BinaryOp == dfltFunctor ) {
956 if ( UnaryOp == dfltFunctor )
960 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
961 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
962 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
963 if ( Precision != dfltPreci )
965 TCollection_AsciiString crit = aCommand->GetResultValue();
966 aCommand->GetString() += "; ";
967 aCommand->GetString() += crit + ".Precision = " + Precision;
973 //================================================================================
975 * \brief Convert the command or remember it for later conversion
976 * \param theCommand - The python command calling a method of SMESH_Gen
978 //================================================================================
980 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
982 // there are methods to convert:
983 // CreateMesh( shape )
984 // Concatenate( [mesh1, ...], ... )
985 // CreateHypothesis( theHypType, theLibName )
986 // Compute( mesh, geom )
987 // Evaluate( mesh, geom )
989 TCollection_AsciiString method = theCommand->GetMethod();
991 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
993 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
997 if ( method == "CreateMeshesFromUNV" ||
998 method == "CreateMeshesFromSTL" ||
999 method == "CopyMesh" ) // command result is a mesh
1001 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1005 if( method == "CreateMeshesFromMED" ||
1006 method == "CreateMeshesFromSAUV"||
1007 method == "CreateMeshesFromCGNS" ||
1008 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1010 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1011 std::list< _pyID >::iterator meshID = meshIDs.begin();
1012 for ( ; meshID != meshIDs.end(); ++meshID )
1014 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1017 if ( method == "CreateMeshesFromGMF" )
1019 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1020 // CreateMeshesFromGMF( theFileName )
1021 _AString file = theCommand->GetArg(1);
1022 theCommand->RemoveArgs();
1023 theCommand->SetArg( 1, file );
1027 // CreateHypothesis()
1028 if ( method == "CreateHypothesis" )
1030 // issue 199929, remove standard library name (default parameter)
1031 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1032 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1033 // keep the first argument
1034 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1035 theCommand->RemoveArgs();
1036 theCommand->SetArg( 1, arg );
1039 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1040 CheckObjectIsReCreated( hyp );
1041 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1046 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1047 if ( method == "Compute" )
1049 const _pyID& meshID = theCommand->GetArg( 1 );
1050 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1051 if ( id_mesh != myMeshes.end() ) {
1052 theCommand->SetObject( meshID );
1053 theCommand->RemoveArgs();
1054 id_mesh->second->Process( theCommand );
1055 id_mesh->second->AddProcessedCmd( theCommand );
1060 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1061 if ( method == "Evaluate" )
1063 const _pyID& meshID = theCommand->GetArg( 1 );
1064 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1065 if ( id_mesh != myMeshes.end() ) {
1066 theCommand->SetObject( meshID );
1067 _pyID geom = theCommand->GetArg( 2 );
1068 theCommand->RemoveArgs();
1069 theCommand->SetArg( 1, geom );
1070 id_mesh->second->AddProcessedCmd( theCommand );
1075 // objects erasing creation command if no more its commands invoked:
1076 // SMESH_Pattern, FilterManager
1077 if ( method == "GetPattern" ||
1078 method == "CreateFilterManager" ||
1079 method == "CreateMeasurements" )
1081 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1082 if ( !AddObject( obj ) )
1083 theCommand->Clear(); // already created
1085 // Concatenate( [mesh1, ...], ... )
1086 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1088 if ( method == "ConcatenateWithGroups" ) {
1089 theCommand->SetMethod( "Concatenate" );
1090 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1092 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1094 AddMeshAccessorMethod( theCommand );
1096 else if ( method == "SetName" ) // SetName(obj,name)
1098 // store theCommand as one of object commands to erase it along with the object
1099 const _pyID& objID = theCommand->GetArg( 1 );
1100 Handle(_pyObject) obj = FindObject( objID );
1101 if ( !obj.IsNull() )
1102 obj->AddProcessedCmd( theCommand );
1105 // Replace name of SMESH_Gen
1107 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1108 static TStringSet smeshpyMethods;
1109 if ( smeshpyMethods.empty() ) {
1110 const char * names[] =
1111 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1112 "GetPattern","GetSubShapesId",
1113 "" }; // <- mark of array end
1114 smeshpyMethods.Insert( names );
1116 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1117 // smeshgen.Method() --> smesh.Method()
1118 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1120 // smeshgen.Method() --> smesh.Method()
1121 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1124 //================================================================================
1126 * \brief Convert the remembered commands
1128 //================================================================================
1130 void _pyGen::Flush()
1132 // create an empty command
1133 myLastCommand = new _pyCommand();
1135 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1136 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1137 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1139 if ( IsToKeepAllCommands() ) // historical dump
1141 // set myIsPublished = true to all objects
1142 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1143 id_mesh->second->SetRemovedFromStudy( false );
1144 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1145 id_hyp->second->SetRemovedFromStudy( false );
1146 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1147 id_obj->second->SetRemovedFromStudy( false );
1151 // let hypotheses find referred objects in order to prevent clearing
1152 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1153 list< Handle(_pyMesh) > fatherMeshes;
1154 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1155 if ( !id_hyp->second.IsNull() )
1156 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1158 // set myIsPublished = false to all objects depending on
1159 // meshes built on a removed geometry
1160 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1161 if ( id_mesh->second->IsNotGeomPublished() )
1162 id_mesh->second->SetRemovedFromStudy( true );
1165 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1166 if ( ! id_mesh->second.IsNull() )
1167 id_mesh->second->Flush();
1170 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1171 if ( !id_hyp->second.IsNull() ) {
1172 id_hyp->second->Flush();
1173 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1174 if ( !id_hyp->second->IsWrapped() )
1175 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1178 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1179 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1180 for ( ; robj != myOrderedObjects.rend(); ++robj )
1181 if ( ! robj->IsNull() )
1183 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1184 for ( ; obj != myOrderedObjects.end(); ++obj )
1185 if ( ! obj->IsNull() )
1188 myLastCommand->SetOrderNb( ++myNbCommands );
1189 myCommands.push_back( myLastCommand );
1192 //================================================================================
1194 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1195 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1197 //================================================================================
1199 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1201 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1202 // for ( ; id_obj != myObjects.end(); ++id_obj )
1204 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1205 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1207 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1208 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1210 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1211 // list< _pyID >::iterator id = idList.begin();
1212 // for ( ; id != idList.end(); ++id )
1213 // if ( id_obj->first == *id )
1214 // // _pySubMesh::Process() does what we need
1215 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1220 //================================================================================
1222 * \brief Clean commmands of removed objects depending on myIsPublished flag
1224 //================================================================================
1226 void _pyGen::ClearCommands()
1228 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1229 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1230 id_mesh->second->ClearCommands();
1232 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1233 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1234 if ( !id_hyp->second.IsNull() )
1235 id_hyp->second->ClearCommands();
1237 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1238 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1239 for ( ; robj != myOrderedObjects.rend(); ++robj )
1240 if ( ! robj->IsNull() )
1241 (*robj)->ClearCommands();
1242 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1243 for ( ; obj != myOrderedObjects.end(); ++obj )
1244 if ( ! obj->IsNull() )
1245 (*obj)->ClearCommands();
1248 //================================================================================
1250 * \brief Release mutual handles of objects
1252 //================================================================================
1256 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1257 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1258 id_mesh->second->Free();
1261 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1262 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1263 id_ed->second->Free();
1264 myMeshEditors.clear();
1266 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1267 for ( ; id_obj != myObjects.end(); ++id_obj )
1268 id_obj->second->Free();
1271 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1272 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1273 if ( !id_hyp->second.IsNull() )
1274 id_hyp->second->Free();
1277 myFile2ExportedMesh.clear();
1279 //myKeepAgrCmdsIDs.Print();
1282 //================================================================================
1284 * \brief Add access method to mesh that is an argument
1285 * \param theCmd - command to add access method
1286 * \retval bool - true if added
1288 //================================================================================
1290 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1293 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1294 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1295 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1301 //================================================================================
1303 * \brief Add access method to algo that is an object or an argument
1304 * \param theCmd - command to add access method
1305 * \retval bool - true if added
1307 //================================================================================
1309 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1312 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1313 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1314 if ( !id_hyp->second.IsNull() &&
1315 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1316 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1317 id_hyp->second->AccessorMethod() ))
1323 //================================================================================
1325 * \brief Find hypothesis by ID (entry)
1326 * \param theHypID - The hypothesis ID
1327 * \retval Handle(_pyHypothesis) - The found hypothesis
1329 //================================================================================
1331 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1333 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1334 if ( id_hyp != myHypos.end() &&
1335 !id_hyp->second.IsNull() &&
1336 theHypID == id_hyp->second->GetID() )
1337 return id_hyp->second;
1338 return Handle(_pyHypothesis)();
1341 //================================================================================
1343 * \brief Find algorithm able to create a hypothesis
1344 * \param theGeom - The shape ID the algorithm was created on
1345 * \param theMesh - The mesh ID that created the algorithm
1346 * \param theHypothesis - The hypothesis the algorithm should be able to create
1347 * \retval Handle(_pyHypothesis) - The found algo
1349 //================================================================================
1351 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1352 const Handle(_pyHypothesis)& theHypothesis )
1354 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1355 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1356 if ( !id_hyp->second.IsNull() &&
1357 id_hyp->second->IsAlgo() &&
1358 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1359 id_hyp->second->GetGeom() == theGeom &&
1360 id_hyp->second->GetMesh() == theMesh )
1361 return id_hyp->second;
1362 return Handle(_pyHypothesis)();
1365 //================================================================================
1367 * \brief Find subMesh by ID (entry)
1368 * \param theSubMeshID - The subMesh ID
1369 * \retval Handle(_pySubMesh) - The found subMesh
1371 //================================================================================
1373 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1375 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1376 if ( id_subMesh != myObjects.end() )
1377 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1378 return Handle(_pySubMesh)();
1382 //================================================================================
1384 * \brief Change order of commands in the script
1385 * \param theCmd1 - One command
1386 * \param theCmd2 - Another command
1388 //================================================================================
1390 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1392 list< Handle(_pyCommand) >::iterator pos1, pos2;
1393 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1394 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1395 myCommands.insert( pos1, theCmd2 );
1396 myCommands.insert( pos2, theCmd1 );
1397 myCommands.erase( pos1 );
1398 myCommands.erase( pos2 );
1400 int nb1 = theCmd1->GetOrderNb();
1401 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1402 theCmd2->SetOrderNb( nb1 );
1403 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1404 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1407 //================================================================================
1409 * \brief Set one command after the other
1410 * \param theCmd - Command to move
1411 * \param theAfterCmd - Command ater which to insert the first one
1413 //================================================================================
1415 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1417 setNeighbourCommand( theCmd, theAfterCmd, true );
1420 //================================================================================
1422 * \brief Set one command before the other
1423 * \param theCmd - Command to move
1424 * \param theBeforeCmd - Command before which to insert the first one
1426 //================================================================================
1428 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1430 setNeighbourCommand( theCmd, theBeforeCmd, false );
1433 //================================================================================
1435 * \brief Set one command before or after the other
1436 * \param theCmd - Command to move
1437 * \param theOtherCmd - Command ater or before which to insert the first one
1439 //================================================================================
1441 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1442 Handle(_pyCommand)& theOtherCmd,
1443 const bool theIsAfter )
1445 list< Handle(_pyCommand) >::iterator pos;
1446 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1447 myCommands.erase( pos );
1448 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1449 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1452 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1453 (*pos)->SetOrderNb( i++ );
1456 //================================================================================
1458 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1460 //================================================================================
1462 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1464 // No more needed after adding _pyObject::myArgCommands
1466 // const char filterPrefix[] = "aFilter0x";
1467 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1470 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1472 // const _AString & arg = theCommand->GetArg( i );
1473 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1474 // if ( arg.Search( filterPrefix ) != 1 )
1477 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1478 // if ( !filter.IsNull() )
1480 // filter->AddUser( user );
1481 // if ( !filter->GetNewID().IsEmpty() )
1482 // theCommand->SetArg( i, filter->GetNewID() );
1487 //================================================================================
1489 * \brief Set command be last in list of commands
1490 * \param theCmd - Command to be last
1492 //================================================================================
1494 Handle(_pyCommand)& _pyGen::GetLastCommand()
1496 return myLastCommand;
1499 //================================================================================
1501 * \brief Set method to access to object wrapped with python class
1502 * \param theID - The wrapped object entry
1503 * \param theMethod - The accessor method
1505 //================================================================================
1507 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1509 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1512 //================================================================================
1514 * \brief Generated new ID for object and assign with existing name
1515 * \param theID - ID of existing object
1517 //================================================================================
1519 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1524 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1526 while ( myObjectNames.IsBound( aNewID ) );
1528 if ( myObjectNames.IsBound( theID ) )
1529 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1531 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1535 //================================================================================
1537 * \brief Stores theObj in myObjects
1539 //================================================================================
1541 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1543 if ( theObj.IsNull() ) return false;
1545 CheckObjectIsReCreated( theObj );
1549 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1550 add = myMeshes.insert( make_pair( theObj->GetID(),
1551 Handle(_pyMesh)::DownCast( theObj ))).second;
1553 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1554 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1555 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1558 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1559 if ( add ) myOrderedObjects.push_back( theObj );
1564 //================================================================================
1566 * \brief Erases an existing object with the same ID. This method should be called
1567 * before storing theObj in _pyGen
1569 //================================================================================
1571 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1573 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1576 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1577 Handle(_pyObject) existing;
1579 existing = FindHyp( theObj->GetID() );
1581 existing = FindObject( theObj->GetID() );
1582 if ( !existing.IsNull() && existing != theObj )
1584 existing->SetRemovedFromStudy( true );
1585 existing->ClearCommands();
1588 if ( myHypos.count( theObj->GetID() ))
1589 myHypos.erase( theObj->GetID() );
1591 else if ( myMeshes.count( theObj->GetID() ))
1593 myMeshes.erase( theObj->GetID() );
1595 else if ( myObjects.count( theObj->GetID() ))
1597 myObjects.erase( theObj->GetID() );
1602 //================================================================================
1604 * \brief Re-register an object with other ID to make it Process() commands of
1605 * other object having this ID
1607 //================================================================================
1609 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1611 if ( theObj.IsNull() ) return;
1613 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1614 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1616 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1617 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1620 myObjects.insert( make_pair( theID, theObj ));
1623 //================================================================================
1625 * \brief Finds a _pyObject by ID
1627 //================================================================================
1629 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1632 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1633 if ( id_obj != myObjects.end() )
1634 return id_obj->second;
1637 _pyGen* me = const_cast< _pyGen* >( this );
1638 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1639 if ( id_obj != myMeshes.end() )
1640 return id_obj->second;
1643 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1644 // if ( id_obj != myMeshEditors.end() )
1645 // return id_obj->second;
1647 return Handle(_pyObject)();
1650 //================================================================================
1652 * \brief Check if a study entry is under GEOM component
1654 //================================================================================
1656 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1660 return ( myGeomIDIndex <= theObjID.Length() &&
1661 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1662 _pyCommand::IsStudyEntry( theObjID ));
1667 //================================================================================
1669 * \brief Returns true if an object is not present in a study
1671 //================================================================================
1673 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1675 if ( theObjID.IsEmpty() ) return false;
1677 if ( myObjectNames.IsBound( theObjID ))
1678 return false; // SMESH object is in study
1680 // either the SMESH object is not in study or it is a GEOM object
1681 if ( IsGeomObject( theObjID ))
1683 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1684 if ( so->_is_nil() ) return true;
1685 CORBA::Object_var obj = so->GetObject();
1686 return CORBA::is_nil( obj );
1688 return true; // SMESH object not in study
1691 //================================================================================
1693 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1694 * this object is not dumped
1695 * \param [in] theObjID - entry of the object whose creation command was eliminated
1697 //================================================================================
1699 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1701 myRemovedObjIDs.insert( theObjID );
1704 //================================================================================
1706 * \brief Return reader of hypotheses of plugins
1708 //================================================================================
1710 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1712 if (myHypReader.IsNull() )
1713 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1719 //================================================================================
1721 * \brief Mesh created by SMESH_Gen
1723 //================================================================================
1725 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1726 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1728 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1729 myGeomNotInStudy = true;
1731 // convert my creation command --> smeshpy.Mesh(...)
1732 Handle(_pyCommand) creationCmd = GetCreationCmd();
1733 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1734 creationCmd->SetMethod( "Mesh" );
1735 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1738 //================================================================================
1740 * \brief Mesh created by SMESH_MeshEditor
1742 //================================================================================
1744 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1745 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1747 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1749 // this mesh depends on the exported mesh
1750 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1751 if ( !file.IsEmpty() )
1753 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1754 addFatherMesh( exportData.myMesh );
1755 if ( !exportData.myLastComputeCmd.IsNull() )
1757 // restore cleared Compute() by which the exported mesh was generated
1758 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1759 // protect that Compute() cmd from clearing
1760 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1761 exportData.myMesh->myLastComputeCmd.Nullify();
1765 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1767 // this mesh depends on concatenated meshes
1768 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1769 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1770 list< _pyID >::iterator meshID = idList.begin();
1771 for ( ; meshID != idList.end(); ++meshID )
1772 addFatherMesh( *meshID );
1774 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1776 // this mesh depends on a copied IdSource
1777 const _pyID& objID = theCreationCmd->GetArg( 1 );
1778 addFatherMesh( objID );
1780 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1781 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1782 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1784 // this mesh depends on a source mesh
1785 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1786 const _pyID& meshID = theCreationCmd->GetObject();
1787 addFatherMesh( meshID );
1790 // convert my creation command
1791 Handle(_pyCommand) creationCmd = GetCreationCmd();
1792 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1793 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1796 //================================================================================
1798 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1799 * \param theCommand - Engine method called for this mesh
1801 //================================================================================
1803 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1805 // some methods of SMESH_Mesh interface needs special conversion
1806 // to methods of Mesh python class
1808 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1809 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1810 // 2. AddHypothesis(geom, hyp)
1811 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1812 // 3. CreateGroupFromGEOM(type, name, grp)
1813 // --> in Mesh.Group(grp, name="")
1814 // 4. ExportToMED(f, auto_groups, version)
1815 // --> in Mesh.ExportMED( f, auto_groups, version )
1818 const TCollection_AsciiString& method = theCommand->GetMethod();
1819 // ----------------------------------------------------------------------
1820 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1822 if ( !theGen->IsToKeepAllCommands() ) // !historical
1824 list< Handle(_pyHypothesis) >::iterator hyp;
1825 if ( !myLastComputeCmd.IsNull() )
1827 // check if the previously computed mesh has been edited,
1828 // if so then we do not clear the previous Compute()
1829 bool toClear = true;
1830 if ( myLastComputeCmd->GetMethod() == "Compute" )
1832 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1833 for ( ; e != myEditors.end() && toClear; ++e )
1835 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1836 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1837 if ( cmd != cmds.rend() &&
1838 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1844 // clear hyp commands called before myLastComputeCmd
1845 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1846 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1848 myLastComputeCmd->Clear();
1851 myLastComputeCmd = theCommand;
1853 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1854 (*hyp)->MeshComputed( myLastComputeCmd );
1858 // ----------------------------------------------------------------------
1859 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1861 if ( !theGen->IsToKeepAllCommands() ) // !historical
1864 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1865 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1866 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1868 if ( !myLastComputeCmd.IsNull() )
1870 list< Handle(_pyHypothesis) >::iterator hyp;
1871 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1872 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1874 myLastComputeCmd->Clear();
1877 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1878 for ( ; e != myEditors.end(); ++e )
1880 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1881 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1882 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1883 if ( !(*cmd)->IsEmpty() )
1885 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1889 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1892 // ----------------------------------------------------------------------
1893 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1894 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1895 if ( !subMesh.IsNull() ) {
1896 subMesh->SetCreator( this );
1897 mySubmeshes.push_back( subMesh );
1900 // ----------------------------------------------------------------------
1901 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1902 theCommand->Clear();
1904 // ----------------------------------------------------------------------
1905 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1906 myAddHypCmds.push_back( theCommand );
1908 const _pyID& hypID = theCommand->GetArg( 2 );
1909 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1910 if ( !hyp.IsNull() ) {
1911 myHypos.push_back( hyp );
1912 if ( hyp->GetMesh().IsEmpty() )
1913 hyp->SetMesh( this->GetID() );
1916 // ----------------------------------------------------------------------
1917 else if ( method == "CreateGroup" ||
1918 method == "CreateGroupFromGEOM" ||
1919 method == "CreateGroupFromFilter" ||
1920 method == "CreateDimGroup" )
1922 Handle(_pyGroup) group = new _pyGroup( theCommand );
1923 myGroups.push_back( group );
1924 theGen->AddObject( group );
1926 // ----------------------------------------------------------------------
1927 // update list of groups
1928 else if ( method == "GetGroups" )
1930 bool allGroupsRemoved = true;
1931 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1932 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1933 list< _pyID >::iterator grID = idList.begin();
1934 const size_t nbGroupsBefore = myGroups.size();
1935 Handle(_pyObject) obj;
1936 for ( ; grID != idList.end(); ++grID )
1938 obj = theGen->FindObject( *grID );
1941 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1942 theGen->AddObject( group );
1943 myGroups.push_back( group );
1946 if ( !obj->CanClear() )
1947 allGroupsRemoved = false;
1949 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1950 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1952 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1954 // check if the preceding command is Compute();
1955 // if GetGroups() is just after Compute(), this can mean that the groups
1956 // were created by some algorithm and hence Compute() should not be discarded
1957 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1958 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1959 while ( (*cmd)->GetMethod() == "GetGroups" )
1961 if ( myLastComputeCmd == (*cmd))
1962 // protect last Compute() from clearing by the next Compute()
1963 myLastComputeCmd.Nullify();
1966 // ----------------------------------------------------------------------
1967 // notify a group about full removal
1968 else if ( method == "RemoveGroupWithContents" ||
1969 method == "RemoveGroup")
1971 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1972 const _pyID groupID = theCommand->GetArg( 1 );
1973 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1974 if ( !grp.IsNull() )
1976 if ( method == "RemoveGroupWithContents" )
1977 grp->RemovedWithContents();
1978 // to clear RemoveGroup() if the group creation is cleared
1979 grp->AddProcessedCmd( theCommand );
1983 // ----------------------------------------------------------------------
1984 else if ( theCommand->MethodStartsFrom( "Export" ))
1986 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1987 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
1988 method == "ExportMED" )
1990 theCommand->SetMethod( "ExportMED" );
1991 // filter out deprecated version parameter
1992 vector< _AString > args;
1993 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
1994 if ( !_FilterArg( theCommand->GetArg( i ) ) )
1995 args.push_back( theCommand->GetArg( i ) );
1997 theCommand->RemoveArgs();
1998 for ( uint i = 0; i < args.size(); i++ )
1999 theCommand->SetArg( i+1, args[i] );
2000 if ( theCommand->GetNbArgs() == 4 )
2002 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2003 _AString autoDimension = theCommand->GetArg( 4 );
2004 theCommand->SetArg( 4, "None" );
2005 theCommand->SetArg( 5, autoDimension );
2008 else if ( method == "ExportCGNS" )
2009 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2010 _pyID partID = theCommand->GetArg( 1 );
2011 int nbArgs = theCommand->GetNbArgs();
2012 for ( int i = 2; i <= nbArgs; ++i )
2013 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2014 theCommand->SetArg( nbArgs, partID );
2016 else if ( method == "ExportGMF" )
2017 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2018 _pyID partID = theCommand->GetArg( 1 );
2019 _AString file = theCommand->GetArg( 2 );
2020 theCommand->RemoveArgs();
2021 theCommand->SetArg( 1, file );
2022 theCommand->SetArg( 2, partID );
2024 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2025 { // ExportPartTo*(part, ...) -> Export*(..., part)
2027 // remove "PartTo" from the method
2028 TCollection_AsciiString newMethod = method;
2029 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2030 theCommand->SetMethod( newMethod );
2031 // filter out deprecated version parameter
2032 vector< _AString > args;
2033 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2034 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2035 args.push_back( theCommand->GetArg( i ) );
2037 theCommand->RemoveArgs();
2038 for ( uint i = 0; i < args.size(); i++ )
2039 theCommand->SetArg( i+1, args[i] );
2040 // make the 1st arg be the last one (or last but three for ExportMED())
2041 _pyID partID = theCommand->GetArg( 1 );
2042 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2043 for ( int i = 2; i <= nbArgs; ++i )
2044 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2045 theCommand->SetArg( nbArgs, partID );
2047 // remember file name
2048 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2049 ExportedMeshData( this, myLastComputeCmd ));
2051 // ----------------------------------------------------------------------
2052 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2054 _pyID hypID = theCommand->GetArg( 2 );
2055 _pyID geomID = theCommand->GetArg( 1 );
2056 bool isLocal = ( geomID != GetGeom() );
2058 // check if this mesh still has corresponding addition command
2059 Handle(_pyCommand) addCmd;
2060 list< Handle(_pyCommand) >::iterator cmd;
2061 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2062 for ( int i = 0; i < 2; ++i )
2064 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2065 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2067 bool sameHyp = true;
2068 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2069 sameHyp = false; // other hyp
2070 if ( (*cmd)->GetNbArgs() == 2 &&
2071 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2072 sameHyp = false; // other geom
2073 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2074 sameHyp = false; // other geom
2078 cmd = addHypCmds.erase( cmd );
2079 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2081 theCommand->Clear();
2085 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2086 addCmd->RemoveArgs();
2087 addCmd->SetArg( 1, hypID );
2089 addCmd->SetArg( 2, geomID );
2098 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2099 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2100 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2101 _pyID geom = theCommand->GetArg( 1 );
2102 theCommand->RemoveArgs();
2103 theCommand->SetArg( 1, hypID );
2104 if ( geom != GetGeom() )
2105 theCommand->SetArg( 2, geom );
2107 // remove hyp from myHypos
2108 myHypos.remove( hyp );
2110 // check for SubMesh order commands
2111 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2113 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2114 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2115 // commands are moved at the end of the script
2116 TCollection_AsciiString subIDs =
2117 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2118 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2119 list< _pyID >::iterator subID = idList.begin();
2120 for ( ; subID != idList.end(); ++subID )
2122 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2123 if ( !subMesh.IsNull() )
2124 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2127 // add accessor method if necessary
2130 if ( NeedMeshAccess( theCommand ))
2131 // apply theCommand to the mesh wrapped by smeshpy mesh
2132 AddMeshAccess( theCommand );
2136 //================================================================================
2138 * \brief Return True if addition of accesor method is needed
2140 //================================================================================
2142 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2144 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2145 // so no conversion is needed for them at all:
2146 static TStringSet sameMethods;
2147 if ( sameMethods.empty() ) {
2148 const char * names[] =
2149 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2150 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2151 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2152 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2153 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2154 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2155 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2156 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2157 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2158 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2159 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2160 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2161 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2162 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2163 ,"" }; // <- mark of end
2164 sameMethods.Insert( names );
2167 return !sameMethods.Contains( theCommand->GetMethod() );
2170 //================================================================================
2172 * \brief Convert creation and addition of all algos and hypos
2174 //================================================================================
2176 void _pyMesh::Flush()
2179 // get the meshes this mesh depends on via hypotheses
2180 list< Handle(_pyMesh) > fatherMeshes;
2181 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2182 for ( ; hyp != myHypos.end(); ++hyp )
2183 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2184 myGeomNotInStudy = true;
2186 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2187 for ( ; m != fatherMeshes.end(); ++m )
2188 addFatherMesh( *m );
2189 // if ( removedGeom )
2190 // SetRemovedFromStudy(); // as referred geometry not in study
2192 if ( myGeomNotInStudy )
2195 list < Handle(_pyCommand) >::iterator cmd;
2197 // try to convert algo addition like this:
2198 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2199 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2201 Handle(_pyCommand) addCmd = *cmd;
2203 _pyID algoID = addCmd->GetArg( 2 );
2204 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2205 if ( algo.IsNull() || !algo->IsAlgo() )
2208 // check and create new algorithm instance if it is already wrapped
2209 if ( algo->IsWrapped() ) {
2210 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2211 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2212 TCollection_AsciiString( " = " ) + theGen->GetID() +
2213 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2214 TCollection_AsciiString( "\" )" );
2216 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2217 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2218 if ( !newAlgo.IsNull() ) {
2219 newAlgo->Assign( algo, this->GetID() );
2220 newAlgo->SetCreationCmd( newCmd );
2222 // set algorithm creation
2223 theGen->SetCommandBefore( newCmd, addCmd );
2224 myHypos.push_back( newAlgo );
2225 if ( !myLastComputeCmd.IsNull() &&
2226 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2227 newAlgo->MeshComputed( myLastComputeCmd );
2232 _pyID geom = addCmd->GetArg( 1 );
2233 bool isLocalAlgo = ( geom != GetGeom() );
2236 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2238 // wrapped algo is created after mesh creation
2239 GetCreationCmd()->AddDependantCmd( addCmd );
2241 if ( isLocalAlgo ) {
2242 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2243 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2244 TCollection_AsciiString( "geom=" ) + geom );
2245 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2246 list < Handle(_pySubMesh) >::iterator smIt;
2247 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2248 Handle(_pySubMesh) subMesh = *smIt;
2249 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2250 if ( geom == subCmd->GetArg( 1 )) {
2251 subCmd->SetObject( algo->GetID() );
2252 subCmd->RemoveArgs();
2253 subMesh->SetCreator( algo );
2258 else // KO - ALGO was already created
2260 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2261 addCmd->RemoveArgs();
2262 addCmd->SetArg( 1, algoID );
2264 addCmd->SetArg( 2, geom );
2265 myNotConvertedAddHypCmds.push_back( addCmd );
2269 // try to convert hypo addition like this:
2270 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2271 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2273 Handle(_pyCommand) addCmd = *cmd;
2274 _pyID hypID = addCmd->GetArg( 2 );
2275 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2276 if ( hyp.IsNull() || hyp->IsAlgo() )
2278 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2280 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2281 _pyID geom = addCmd->GetArg( 1 );
2282 addCmd->RemoveArgs();
2283 addCmd->SetArg( 1, hypID );
2284 if ( geom != GetGeom() )
2285 addCmd->SetArg( 2, geom );
2286 myNotConvertedAddHypCmds.push_back( addCmd );
2290 myAddHypCmds.clear();
2291 mySubmeshes.clear();
2294 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2295 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2299 //================================================================================
2301 * \brief Sets myIsPublished of me and of all objects depending on me.
2303 //================================================================================
2305 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2307 _pyObject::SetRemovedFromStudy(isRemoved);
2309 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2310 for ( ; sm != mySubmeshes.end(); ++sm )
2311 (*sm)->SetRemovedFromStudy(isRemoved);
2313 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2314 for ( ; gr != myGroups.end(); ++gr )
2315 (*gr)->SetRemovedFromStudy(isRemoved);
2317 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2318 for ( ; m != myChildMeshes.end(); ++m )
2319 (*m)->SetRemovedFromStudy(isRemoved);
2321 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2322 for ( ; e != myEditors.end(); ++e )
2323 (*e)->SetRemovedFromStudy(isRemoved);
2326 //================================================================================
2328 * \brief Return true if none of myChildMeshes is in study
2330 //================================================================================
2332 bool _pyMesh::CanClear()
2337 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2338 for ( ; m != myChildMeshes.end(); ++m )
2339 if ( !(*m)->CanClear() )
2345 //================================================================================
2347 * \brief Clear my commands and commands of mesh editor
2349 //================================================================================
2351 void _pyMesh::ClearCommands()
2357 // mark all sub-objects as not removed, except child meshes
2358 list< Handle(_pyMesh) > children;
2359 children.swap( myChildMeshes );
2360 SetRemovedFromStudy( false );
2361 children.swap( myChildMeshes );
2365 _pyObject::ClearCommands();
2367 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2368 for ( ; sm != mySubmeshes.end(); ++sm )
2369 (*sm)->ClearCommands();
2371 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2372 for ( ; gr != myGroups.end(); ++gr )
2373 (*gr)->ClearCommands();
2375 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2376 for ( ; e != myEditors.end(); ++e )
2377 (*e)->ClearCommands();
2380 //================================================================================
2382 * \brief Add a father mesh by ID
2384 //================================================================================
2386 void _pyMesh::addFatherMesh( const _pyID& meshID )
2388 if ( !meshID.IsEmpty() && meshID != GetID() )
2389 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2392 //================================================================================
2394 * \brief Add a father mesh
2396 //================================================================================
2398 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2400 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2402 //myFatherMeshes.push_back( mesh );
2403 mesh->myChildMeshes.push_back( this );
2405 // protect last Compute() from clearing by the next Compute()
2406 mesh->myLastComputeCmd.Nullify();
2410 //================================================================================
2412 * \brief MeshEditor convert its commands to ones of mesh
2414 //================================================================================
2416 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2417 _pyObject( theCreationCmd )
2419 myMesh = theCreationCmd->GetObject();
2420 myCreationCmdStr = theCreationCmd->GetString();
2421 theCreationCmd->Clear();
2423 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2424 if ( !mesh.IsNull() )
2425 mesh->AddEditor( this );
2428 //================================================================================
2430 * \brief convert its commands to ones of mesh
2432 //================================================================================
2434 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2436 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2437 // commands calling these methods are converted to calls of Mesh methods without
2438 // additional modifs, only object is changed from MeshEditor to Mesh.
2439 static TStringSet sameMethods;
2440 if ( sameMethods.empty() ) {
2441 const char * names[] = {
2442 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2443 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2444 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2445 "MoveNode", "MoveClosestNodeToPoint",
2446 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2447 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2448 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2449 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2450 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2451 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2452 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2453 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2454 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2455 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2456 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2457 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2458 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2459 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2460 "GetLastCreatedElems",
2461 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2462 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2463 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2464 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2465 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2466 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2467 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2468 ,"" }; // <- mark of the end
2469 sameMethods.Insert( names );
2472 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2473 TStringMap diffMethods;
2474 if ( diffMethods.empty() ) {
2475 const char * orig2newName[] = {
2476 // original name --------------> new name
2477 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2478 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2479 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2480 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2481 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2482 ""};// <- mark of the end
2483 diffMethods.Insert( orig2newName );
2486 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2487 // only by last two arguments
2488 static TStringSet diffLastTwoArgsMethods;
2489 if (diffLastTwoArgsMethods.empty() ) {
2490 const char * names[] = {
2491 "MirrorMakeGroups","MirrorObjectMakeGroups",
2492 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2493 "RotateMakeGroups","RotateObjectMakeGroups",
2494 ""};// <- mark of the end
2495 diffLastTwoArgsMethods.Insert( names );
2498 // only a method name is to change?
2499 const TCollection_AsciiString & method = theCommand->GetMethod();
2500 bool isPyMeshMethod = sameMethods.Contains( method );
2501 if ( !isPyMeshMethod )
2503 TCollection_AsciiString newMethod = diffMethods.Value( method );
2504 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2505 theCommand->SetMethod( newMethod );
2507 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2508 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2510 isPyMeshMethod = true;
2511 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2512 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2515 if ( !isPyMeshMethod )
2517 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2518 // functions with the flag "theMakeGroups = True" like:
2519 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2520 int pos = method.Search("MakeGroups");
2523 isPyMeshMethod = true;
2524 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2525 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2527 // 1. Remove "MakeGroups" from the Command
2528 TCollection_AsciiString aMethod = theCommand->GetMethod();
2529 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2532 pos = pos-2; //Remove "0D" from the Command too
2533 aMethod.Trunc(pos-1);
2534 theCommand->SetMethod(aMethod);
2536 // 2. And add last "True" argument(s)
2537 while(nbArgsToAdd--)
2538 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2539 if( is0DmethId || is0DmethObj )
2540 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2544 // ExtrusionSweep0D() -> ExtrusionSweep()
2545 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2546 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2547 method == "ExtrusionSweepObject0D" ))
2549 isPyMeshMethod = true;
2550 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2551 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2552 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2555 // DoubleNode...New(...) -> DoubleNode...(...,True)
2556 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2557 method == "DoubleNodeElemGroupsNew" ||
2558 method == "DoubleNodeGroupNew" ||
2559 method == "DoubleNodeGroupsNew" ||
2560 method == "DoubleNodeElemGroup2New" ||
2561 method == "DoubleNodeElemGroups2New"))
2563 isPyMeshMethod = true;
2564 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2565 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2566 if ( excessLen == 3 )
2568 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2570 else if ( theCommand->GetArg(4) == "0" ||
2571 theCommand->GetArg(5) == "0" )
2573 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2574 // Group = DoubleNodeGroup2New(,,,False, True)
2575 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2576 theCommand->SetResultValue( groupID );
2579 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2580 // FindElementsByPoint(x, y, z, elementType, meshPart)
2581 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2583 isPyMeshMethod = true;
2584 theCommand->SetMethod( "FindElementsByPoint" );
2585 // make the 1st arg be the last one
2586 _pyID partID = theCommand->GetArg( 1 );
2587 int nbArgs = theCommand->GetNbArgs();
2588 for ( int i = 2; i <= nbArgs; ++i )
2589 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2590 theCommand->SetArg( nbArgs, partID );
2592 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2593 if ( !isPyMeshMethod && method == "Reorient2D" )
2595 isPyMeshMethod = true;
2596 _AString mesh = theCommand->GetArg( 1 );
2597 _AString dir = theCommand->GetArg( 2 );
2598 _AString face = theCommand->GetArg( 3 );
2599 _AString point = theCommand->GetArg( 4 );
2600 theCommand->RemoveArgs();
2601 theCommand->SetArg( 1, mesh );
2602 theCommand->SetArg( 2, dir );
2603 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2604 theCommand->SetArg( 3, point );
2606 theCommand->SetArg( 3, face );
2609 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2611 isPyMeshMethod = true;
2612 int crit_arg = theCommand->GetNbArgs();
2613 const _AString& crit = theCommand->GetArg(crit_arg);
2614 if (crit.Search("MaxElementLength2D") != -1)
2615 theCommand->SetArg(crit_arg, "");
2618 if ( isPyMeshMethod )
2620 theCommand->SetObject( myMesh );
2624 // editor creation command is needed only if any editor function is called
2625 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2626 if ( !myCreationCmdStr.IsEmpty() ) {
2627 GetCreationCmd()->GetString() = myCreationCmdStr;
2628 myCreationCmdStr.Clear();
2633 //================================================================================
2635 * \brief Return true if my mesh can be removed
2637 //================================================================================
2639 bool _pyMeshEditor::CanClear()
2641 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2642 return mesh.IsNull() ? true : mesh->CanClear();
2645 //================================================================================
2647 * \brief _pyHypothesis constructor
2648 * \param theCreationCmd -
2650 //================================================================================
2652 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2653 _pyObject( theCreationCmd ), myCurCrMethod(0)
2655 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2658 //================================================================================
2660 * \brief Creates algorithm or hypothesis
2661 * \param theCreationCmd - The engine command creating a hypothesis
2662 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2664 //================================================================================
2666 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2668 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2669 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2671 Handle(_pyHypothesis) hyp, algo;
2674 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2675 if ( hypTypeQuoted.IsEmpty() )
2678 TCollection_AsciiString hypType =
2679 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2681 algo = new _pyAlgorithm( theCreationCmd );
2682 hyp = new _pyHypothesis( theCreationCmd );
2684 if ( hypType == "NumberOfSegments" ) {
2685 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2686 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2687 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2688 hyp->AddArgMethod( "SetNumberOfSegments" );
2689 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2690 hyp->AddArgMethod( "SetScaleFactor" );
2691 hyp->AddArgMethod( "SetReversedEdges" );
2692 // same for ""CompositeSegment_1D:
2693 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2694 hyp->AddArgMethod( "SetNumberOfSegments" );
2695 hyp->AddArgMethod( "SetScaleFactor" );
2696 hyp->AddArgMethod( "SetReversedEdges" );
2698 else if ( hypType == "SegmentLengthAroundVertex" ) {
2699 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2700 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2701 hyp->AddArgMethod( "SetLength" );
2702 // same for ""CompositeSegment_1D:
2703 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2704 hyp->AddArgMethod( "SetLength" );
2706 else if ( hypType == "LayerDistribution2D" ) {
2707 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2708 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2710 else if ( hypType == "LayerDistribution" ) {
2711 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2712 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2714 else if ( hypType == "CartesianParameters3D" ) {
2715 hyp = new _pyComplexParamHypo( theCreationCmd );
2716 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2717 for ( int iArg = 0; iArg < 4; ++iArg )
2718 hyp->setCreationArg( iArg+1, "[]");
2719 hyp->AddAccumulativeMethod( "SetGrid" );
2720 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2724 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2727 return algo->IsValid() ? algo : hyp;
2730 //================================================================================
2732 * \brief Returns true if addition of this hypothesis to a given mesh can be
2733 * wrapped into hypothesis creation
2735 //================================================================================
2737 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2739 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2741 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2742 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2748 //================================================================================
2750 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2751 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2752 * \param theAlgo - The algo that can create this hypo
2753 * \retval bool - false if the command can't be converted
2755 //================================================================================
2757 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2758 const _pyID& theMesh)
2760 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2762 if ( !IsWrappable( theMesh ))
2765 myGeom = theCmd->GetArg( 1 );
2767 Handle(_pyHypothesis) algo;
2769 // find algo created on myGeom in theMesh
2770 algo = theGen->FindAlgo( myGeom, theMesh, this );
2771 if ( algo.IsNull() )
2773 // attach hypothesis creation command to be after algo creation command
2774 // because it can be new created instance of algorithm
2775 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2779 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2780 theCmd->SetResultValue( GetID() );
2781 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2782 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2783 // set args (geom will be set by _pyMesh calling this method)
2784 theCmd->RemoveArgs();
2785 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2786 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2787 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2789 theCmd->SetArg( i+1, "[]");
2791 // set a new creation command
2792 GetCreationCmd()->Clear();
2793 // replace creation command by wrapped instance
2794 // please note, that hypothesis attaches to algo creation command (see upper)
2795 SetCreationCmd( theCmd );
2798 // clear commands setting arg values
2799 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2800 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2803 // set unknown arg commands after hypo creation
2804 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2805 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2806 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2807 afterCmd->AddDependantCmd( *cmd );
2813 //================================================================================
2815 * \brief Remember hypothesis parameter values
2816 * \param theCommand - The called hypothesis method
2818 //================================================================================
2820 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2822 ASSERT( !myIsAlgo );
2823 if ( !theGen->IsToKeepAllCommands() )
2824 rememberCmdOfParameter( theCommand );
2826 bool usedCommand = false;
2827 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2828 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2830 CreationMethod& crMethod = type2meth->second;
2831 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2832 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2834 myArgCommands.push_back( theCommand );
2836 while ( crMethod.myArgs.size() < i+1 )
2837 crMethod.myArgs.push_back( "None" );
2838 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2843 myUnusedCommands.push_back( theCommand );
2846 //================================================================================
2848 * \brief Finish conversion
2850 //================================================================================
2852 void _pyHypothesis::Flush()
2856 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2857 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2858 // Add access to a wrapped mesh
2859 theGen->AddMeshAccessorMethod( *cmd );
2860 // Add access to a wrapped algorithm
2861 theGen->AddAlgoAccessorMethod( *cmd );
2863 cmd = myUnusedCommands.begin();
2864 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2865 // Add access to a wrapped mesh
2866 theGen->AddMeshAccessorMethod( *cmd );
2867 // Add access to a wrapped algorithm
2868 theGen->AddAlgoAccessorMethod( *cmd );
2871 // forget previous hypothesis modifications
2872 myArgCommands.clear();
2873 myUnusedCommands.clear();
2876 //================================================================================
2878 * \brief clear creation, arg and unknown commands
2880 //================================================================================
2882 void _pyHypothesis::ClearAllCommands()
2884 GetCreationCmd()->Clear();
2885 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2886 for ( ; cmd != myArgCommands.end(); ++cmd )
2888 cmd = myUnusedCommands.begin();
2889 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2894 //================================================================================
2896 * \brief Assign fields of theOther to me except myIsWrapped
2898 //================================================================================
2900 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2901 const _pyID& theMesh )
2903 // myCreationCmd = theOther->myCreationCmd;
2904 myIsAlgo = theOther->myIsAlgo;
2905 myIsWrapped = false;
2906 myGeom = theOther->myGeom;
2908 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2909 myAccumulativeMethods = theOther->myAccumulativeMethods;
2910 //myUnusedCommands = theOther->myUnusedCommands;
2911 // init myCurCrMethod
2912 GetCreationMethod( theOther->GetAlgoType() );
2915 //================================================================================
2917 * \brief Analyze my erasability depending on myReferredObjs
2919 //================================================================================
2921 bool _pyHypothesis::CanClear()
2925 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2926 for ( ; obj != myReferredObjs.end(); ++obj )
2927 if ( (*obj)->CanClear() )
2934 //================================================================================
2936 * \brief Clear my commands depending on usage by meshes
2938 //================================================================================
2940 void _pyHypothesis::ClearCommands()
2942 // if ( !theGen->IsToKeepAllCommands() )
2944 // bool isUsed = false;
2945 // int lastComputeOrder = 0;
2946 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2947 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2948 // if ( ! (*cmd)->IsEmpty() )
2951 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2952 // lastComputeOrder = (*cmd)->GetOrderNb();
2956 // SetRemovedFromStudy( true );
2960 // // clear my commands invoked after lastComputeOrder
2961 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2962 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2964 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2965 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2966 // // cmds.back()->Clear();
2970 _pyObject::ClearCommands();
2973 //================================================================================
2975 * \brief Find arguments that are objects like mesh, group, geometry
2976 * \param meshes - referred meshes (directly or indirrectly)
2977 * \retval bool - false if a referred geometry is not in the study
2979 //================================================================================
2981 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2983 if ( IsAlgo() ) return true;
2985 bool geomPublished = true;
2986 vector< _AString > args;
2987 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2988 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2990 CreationMethod& crMethod = type2meth->second;
2991 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2993 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2994 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2995 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2996 args.push_back( (*cmd)->GetArg( nb ));
2999 for ( size_t i = 0; i < args.size(); ++i )
3001 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3002 if ( idList.empty() && !args[ i ].IsEmpty() )
3003 idList.push_back( args[ i ]);
3004 list< _pyID >::iterator id = idList.begin();
3005 for ( ; id != idList.end(); ++id )
3007 Handle(_pyObject) obj = theGen->FindObject( *id );
3008 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3011 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3012 geomPublished = false;
3016 myReferredObjs.push_back( obj );
3017 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3018 if ( !mesh.IsNull() )
3019 meshes.push_back( mesh );
3020 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3021 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3022 obj->SetRemovedFromStudy( false );
3026 return geomPublished;
3029 //================================================================================
3031 * \brief Remember theCommand setting a parameter
3033 //================================================================================
3035 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3037 // parameters are discriminated by method name
3038 _AString method = theCommand->GetMethod();
3039 if ( myAccumulativeMethods.count( method ))
3040 return; // this method adds values and not override the previus value
3042 // discriminate commands setting different parameters via one method
3043 // by passing parameter names like e.g. SetOption("size", "0.2")
3044 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3045 theCommand->GetNbArgs() > 1 )
3047 // mangle method by appending a 1st textual arg
3048 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3050 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3051 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3052 if ( !isalpha( arg.Value(2))) continue;
3057 // parameters are discriminated by method name
3058 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3059 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3061 cmds.back()->Clear(); // previous parameter value has not been used
3062 cmds.back() = theCommand;
3066 cmds.push_back( theCommand );
3070 //================================================================================
3072 * \brief Return true if a setting parameter command ha been used to compute mesh
3074 //================================================================================
3076 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3077 _pyCommand::TAddr avoidComputeAddr ) const
3079 bool isUsed = false;
3080 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3081 myComputeAddr2Cmds.begin();
3082 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3084 if ( addr2cmds->first == avoidComputeAddr ) continue;
3085 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3086 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3091 //================================================================================
3093 * \brief Save commands setting parameters as they are used for a mesh computation
3095 //================================================================================
3097 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3099 myComputeCmds.push_back( theComputeCmd );
3100 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3102 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3103 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3104 savedCmds.push_back( m2c->second.back() );
3107 //================================================================================
3109 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3111 //================================================================================
3113 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3115 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3117 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3118 for ( ; cmd != savedCmds.end(); ++cmd )
3120 // check if a cmd has been used to compute another mesh
3121 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3123 // check if a cmd is a sole command setting its parameter;
3124 // don't use method name for search as it can change
3125 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3126 m2cmds = myMeth2Commands.begin();
3127 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3129 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3130 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3131 if ( cmdIt != cmds.end() )
3133 if ( cmds.back() != *cmd )
3135 cmds.erase( cmdIt );
3142 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3145 //================================================================================
3147 * \brief Sets an argNb-th argument of current creation command
3148 * \param argNb - argument index countered from 1
3150 //================================================================================
3152 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3154 if ( myCurCrMethod )
3156 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3157 myCurCrMethod->myArgs.push_back( "None" );
3158 if ( arg.IsEmpty() )
3159 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3161 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3166 //================================================================================
3168 * \brief Remember hypothesis parameter values
3169 * \param theCommand - The called hypothesis method
3171 //================================================================================
3173 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3175 if ( GetAlgoType() == "Cartesian_3D" )
3177 // CartesianParameters3D hyp
3179 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3180 theCommand->GetMethod() == "SetToAddEdges" )
3182 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3183 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3184 myArgCommands.push_back( theCommand );
3187 if ( theCommand->GetMethod() == "SetGrid" ||
3188 theCommand->GetMethod() == "SetGridSpacing" )
3190 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3191 int iArg = axis.Value(1) - '0';
3192 if ( theCommand->GetMethod() == "SetGrid" )
3194 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3198 myCurCrMethod->myArgs[ iArg ] = "[ ";
3199 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3200 myCurCrMethod->myArgs[ iArg ] += ", ";
3201 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3202 myCurCrMethod->myArgs[ iArg ] += "]";
3204 myArgCommands.push_back( theCommand );
3205 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3206 // accumulative, else, if the creation
3207 // is not converted, commands for axes 1 and 2 are lost
3212 if( theCommand->GetMethod() == "SetLength" )
3214 // NOW it is OBSOLETE
3215 // ex: hyp.SetLength(start, 1)
3216 // hyp.SetLength(end, 0)
3217 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3218 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3219 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3220 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3222 CreationMethod& crMethod = type2meth->second;
3223 while ( (int) crMethod.myArgs.size() < i+1 )
3224 crMethod.myArgs.push_back( "[]" );
3225 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3227 myArgCommands.push_back( theCommand );
3231 _pyHypothesis::Process( theCommand );
3234 //================================================================================
3236 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3238 //================================================================================
3240 void _pyComplexParamHypo::Flush()
3242 list < Handle(_pyCommand) >::iterator cmd;
3245 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3246 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3250 // if ( GetAlgoType() == "Cartesian_3D" )
3252 // _pyID algo = myCreationCmd->GetObject();
3253 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3255 // if ( IsWrapped() )
3257 // StructToList( *cmd, /*checkMethod=*/false );
3258 // const _AString & method = (*cmd)->GetMethod();
3259 // if ( method == "SetFixedPoint" )
3260 // (*cmd)->SetObject( algo );
3266 //================================================================================
3268 * \brief Convert methods of 1D hypotheses to my own methods
3269 * \param theCommand - The called hypothesis method
3271 //================================================================================
3273 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3275 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3278 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3279 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3280 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3282 // TCollection_AsciiString cmd =
3283 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3284 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3285 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3288 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3290 // // 1D hypo is already set, so distribution changes and the old
3291 // // 1D hypo is thrown away
3292 // my1dHyp->ClearAllCommands();
3295 // //my1dHyp->SetRemovedFromStudy( false );
3297 // if ( !myArgCommands.empty() )
3298 // myArgCommands.back()->Clear();
3299 myCurCrMethod->myArgs.push_back( hyp1dID );
3300 myArgCommands.push_back( theCommand );
3303 //================================================================================
3306 * \param theAdditionCmd - command to be converted
3307 * \param theMesh - mesh instance
3308 * \retval bool - status
3310 //================================================================================
3312 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3313 const _pyID& theMesh)
3315 myIsWrapped = false;
3317 if ( my1dHyp.IsNull() )
3320 // set "SetLayerDistribution()" after addition cmd
3321 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3323 _pyID geom = theAdditionCmd->GetArg( 1 );
3325 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3326 if ( !algo.IsNull() )
3328 my1dHyp->SetMesh( theMesh );
3329 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3330 algo->GetAlgoType().ToCString());
3331 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3334 // clear "SetLayerDistribution()" cmd
3335 myArgCommands.back()->Clear();
3337 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3339 // find RadialPrism algo created on <geom> for theMesh
3340 GetCreationCmd()->SetObject( algo->GetID() );
3341 GetCreationCmd()->SetMethod( myAlgoMethod );
3342 GetCreationCmd()->RemoveArgs();
3343 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3349 //================================================================================
3353 //================================================================================
3355 void _pyLayerDistributionHypo::Flush()
3357 // as creation of 1D hyp was written later then it's edition,
3358 // we need to find all it's edition calls and process them
3359 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3361 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3363 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3364 if ( hyp1dID.IsEmpty() ) continue;
3366 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3368 // make a new name for 1D hyp = "HypType" + "_Distribution"
3370 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3372 if ( prevNewName.IsEmpty() ) continue;
3373 newName = prevNewName;
3377 if ( hyp1d->IsWrapped() ) {
3378 newName = hyp1d->GetCreationCmd()->GetMethod();
3381 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3382 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3384 newName += "_Distribution";
3385 prevNewName = newName;
3387 hyp1d->GetCreationCmd()->SetResultValue( newName );
3389 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3390 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3391 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3392 const _pyID& objID = (*cmdIt)->GetObject();
3393 if ( objID == hyp1dID ) {
3394 if ( !hyp1d.IsNull() )
3396 hyp1d->Process( *cmdIt );
3397 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3399 ( *cmdIt )->SetObject( newName );
3402 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3403 (*cmd)->SetArg( 1, newName );
3407 //================================================================================
3409 * \brief additionally to Addition2Creation, clears SetDistrType() command
3410 * \param theCmd - AddHypothesis() command
3411 * \param theMesh - mesh to which a hypothesis is added
3412 * \retval bool - conversion result
3414 //================================================================================
3416 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3417 const _pyID& theMesh)
3419 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3420 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3421 bool scaleDistrType = false;
3422 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3423 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3424 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3425 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3426 scaleDistrType = true;
3429 else if ( !scaleDistrType ) {
3430 // distribution type changed: remove scale factor from args
3431 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3432 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3434 CreationMethod& crMethod = type2meth->second;
3435 if ( crMethod.myArgs.size() == 2 )
3436 crMethod.myArgs.pop_back();
3443 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3446 //================================================================================
3448 * \brief remove repeated commands defining distribution
3450 //================================================================================
3452 void _pyNumberOfSegmentsHyp::Flush()
3454 // find number of the last SetDistrType() command
3455 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3456 int distrTypeNb = 0;
3457 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3458 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3459 if ( cmd != myUnusedCommands.rbegin() )
3460 distrTypeNb = (*cmd)->GetOrderNb();
3462 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3465 // clear commands before the last SetDistrType()
3466 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3467 set< int > treatedCmdNbs; // avoid treating same cmd twice
3468 for ( int i = 0; i < 2; ++i ) {
3469 set<TCollection_AsciiString> uniqueMethods;
3470 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3471 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3473 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3474 continue;// avoid treating same cmd twice
3475 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3476 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3477 if ( !clear || method == "SetNumberOfSegments" ) {
3478 bool isNewInSet = uniqueMethods.insert( method ).second;
3479 clear = !isNewInSet;
3488 //================================================================================
3490 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3491 * into regular1D.LengthNearVertex( length, vertex )
3492 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3493 * \param theMesh - The mesh needing this hypo
3494 * \retval bool - false if the command can't be converted
3496 //================================================================================
3498 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3499 const _pyID& theMeshID)
3501 if ( IsWrappable( theMeshID )) {
3503 _pyID vertex = theCmd->GetArg( 1 );
3505 // the problem here is that segment algo can be not found
3506 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3507 // geometry where segment algorithm is assigned
3508 _pyID geom = vertex;
3509 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3510 while ( algo.IsNull() && !geom.IsEmpty()) {
3511 // try to find geom as a father of <vertex>
3512 geom = FatherID( geom );
3513 algo = theGen->FindAlgo( geom, theMeshID, this );
3515 if ( algo.IsNull() || geom.IsEmpty() )
3516 return false; // also possible to find geom as brother of veretex...
3518 // set geom instead of vertex
3519 theCmd->SetArg( 1, geom );
3521 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3522 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3523 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3525 // set vertex as a second arg
3526 theCmd->SetArg( 2, vertex );
3534 //================================================================================
3536 * \brief _pyAlgorithm constructor
3537 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3539 //================================================================================
3541 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3542 : _pyHypothesis( theCreationCmd )
3547 //================================================================================
3549 * \brief Convert the command adding an algorithm to mesh
3550 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3551 * \param theMesh - The mesh needing this algo
3552 * \retval bool - false if the command can't be converted
3554 //================================================================================
3556 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3557 const _pyID& theMeshID)
3559 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3560 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3561 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3567 //================================================================================
3569 * \brief Return starting position of a part of python command
3570 * \param thePartIndex - The index of command part
3571 * \retval int - Part position
3573 //================================================================================
3575 int _pyCommand::GetBegPos( int thePartIndex ) const
3579 if ( myBegPos.Length() < thePartIndex )
3581 ASSERT( thePartIndex > 0 );
3582 return myBegPos( thePartIndex );
3585 //================================================================================
3587 * \brief Store starting position of a part of python command
3588 * \param thePartIndex - The index of command part
3589 * \param thePosition - Part position
3591 //================================================================================
3593 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3595 while ( myBegPos.Length() < thePartIndex )
3596 myBegPos.Append( UNKNOWN );
3597 ASSERT( thePartIndex > 0 );
3598 myBegPos( thePartIndex ) = thePosition;
3601 //================================================================================
3603 * \brief Returns whitespace symbols at the line beginning
3604 * \retval TCollection_AsciiString - result
3606 //================================================================================
3608 TCollection_AsciiString _pyCommand::GetIndentation()
3611 //while ( end <= Length() && isblank( myString.Value( end )))
3612 //ANA: isblank() function isn't provided in VC2010 compiler
3613 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3615 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3618 //================================================================================
3620 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3621 * \retval const TCollection_AsciiString & - ResultValue substring
3623 //================================================================================
3625 const TCollection_AsciiString & _pyCommand::GetResultValue()
3627 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3629 SetBegPos( RESULT_IND, EMPTY );
3630 int begPos, endPos = myString.Location( "=", 1, Length() );
3634 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3635 if ( begPos < endPos )
3637 SetBegPos( RESULT_IND, begPos );
3639 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3640 myRes = myString.SubString( begPos, endPos );
3647 //================================================================================
3649 * \brief Return number of python command result value ResultValue = Obj.Meth()
3651 //================================================================================
3653 int _pyCommand::GetNbResultValues()
3656 return myResults.Length();
3660 //================================================================================
3662 * \brief Return substring of python command looking like
3663 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3664 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3666 //================================================================================
3667 const _AString& _pyCommand::GetResultValue(int res)
3669 if ( GetResultValue().IsEmpty() )
3670 return theEmptyString;
3672 if ( myResults.IsEmpty() )
3675 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3676 ++begPos; // skip [, else the whole list is returned
3677 while ( begPos < myRes.Length() ) {
3678 _AString result = GetWord( myRes, begPos, true );
3679 begPos += result.Length();
3681 // result.RemoveAll('[');
3682 // result.RemoveAll(']');
3687 myResults.Append( result );
3690 if ( res > 0 && res <= myResults.Length() )
3691 return myResults( res );
3692 return theEmptyString;
3695 //================================================================================
3697 * \brief Return substring of python command looking like ResVal = Object.Meth()
3698 * \retval const TCollection_AsciiString & - Object substring
3700 //================================================================================
3702 const TCollection_AsciiString & _pyCommand::GetObject()
3704 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3707 int begPos = GetBegPos( RESULT_IND );
3709 begPos = myString.Location( "=", 1, Length() ) + 1;
3710 // is '=' in the string argument (for example, name) or not
3711 int nb1 = 0; // number of ' character at the left of =
3712 int nb2 = 0; // number of " character at the left of =
3713 for ( int i = 1; i < begPos-1; i++ ) {
3714 if ( myString.Value( i )=='\'' )
3716 else if ( myString.Value( i )=='"' )
3719 // if number of ' or " is not divisible by 2,
3720 // then get an object at the start of the command
3721 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3725 begPos += myRes.Length();
3727 myObj = GetWord( myString, begPos, true );
3728 if ( begPos != EMPTY )
3730 // check if object is complex,
3731 // so far consider case like "smesh.Method()"
3732 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3733 //if ( bracketPos==0 ) bracketPos = Length();
3734 int dotPos = begPos+myObj.Length();
3735 while ( dotPos+1 < bracketPos ) {
3736 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3741 if ( dotPos > begPos+myObj.Length() )
3742 myObj = myString.SubString( begPos, dotPos-1 );
3745 // 1st word after '=' is an object
3746 // else // no method -> no object
3752 SetBegPos( OBJECT_IND, begPos );
3758 //================================================================================
3760 * \brief Return substring of python command looking like ResVal = Obj.Method()
3761 * \retval const TCollection_AsciiString & - Method substring
3763 //================================================================================
3765 const TCollection_AsciiString & _pyCommand::GetMethod()
3767 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3770 int begPos = GetBegPos( OBJECT_IND );
3771 bool forward = true;
3773 begPos = myString.Location( "(", 1, Length() ) - 1;
3777 begPos += myObj.Length();
3780 myMeth = GetWord( myString, begPos, forward );
3781 SetBegPos( METHOD_IND, begPos );
3787 //================================================================================
3789 * \brief Returns true if there are brackets after the method
3791 //================================================================================
3793 bool _pyCommand::IsMethodCall()
3795 if ( GetMethod().IsEmpty() )
3797 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3798 return ( s[0] == '(' || s[1] == '(' );
3801 //================================================================================
3803 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3804 * \retval const TCollection_AsciiString & - Arg<index> substring
3806 //================================================================================
3808 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3810 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3814 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3816 pos = myString.Location( "(", 1, Length() );
3820 // we are at or before '(', skip it if present
3822 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3823 if ( pos > Length() )
3827 SetBegPos( ARG1_IND, 0 ); // even no '('
3828 return theEmptyString;
3832 list< TCollection_AsciiString > separatorStack( 1, ",)");
3833 bool ignoreNesting = false;
3835 while ( pos <= Length() )
3837 const char chr = myString.Value( pos );
3839 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3841 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3843 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3845 TCollection_AsciiString arg;
3846 if ( pos-1 >= prevPos ) {
3847 arg = myString.SubString( prevPos, pos-1 );
3848 arg.RightAdjust(); // remove spaces
3851 if ( !arg.IsEmpty() || chr == ',' )
3853 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3854 myArgs.Append( arg );
3860 else // end of nesting args found
3862 separatorStack.pop_back();
3863 ignoreNesting = false;
3866 else if ( !ignoreNesting )
3869 case '(' : separatorStack.push_back(")"); break;
3870 case '[' : separatorStack.push_back("]"); break;
3871 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3872 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3879 if ( myArgs.Length() < index )
3880 return theEmptyString;
3881 return myArgs( index );
3884 //================================================================================
3886 * \brief Return position where arguments begin
3888 //================================================================================
3890 int _pyCommand::GetArgBeginning() const
3892 int pos = GetBegPos( ARG1_IND );
3893 if ( pos == UNKNOWN )
3895 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3897 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3902 //================================================================================
3904 * \brief Check if char is a word part
3905 * \param c - The character to check
3906 * \retval bool - The check result
3908 //================================================================================
3910 static inline bool isWord(const char c, const bool dotIsWord)
3913 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3916 //================================================================================
3918 * \brief Looks for a word in the string and returns word's beginning
3919 * \param theString - The input string
3920 * \param theStartPos - The position to start the search, returning word's beginning
3921 * \param theForward - The search direction
3922 * \retval TCollection_AsciiString - The found word
3924 //================================================================================
3926 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3928 const bool theForward,
3929 const bool dotIsWord )
3931 int beg = theStartPos, end = theStartPos;
3932 theStartPos = EMPTY;
3933 if ( beg < 1 || beg > theString.Length() )
3934 return theEmptyString;
3936 if ( theForward ) { // search forward
3938 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3940 if ( beg > theString.Length() )
3941 return theEmptyString; // no word found
3944 char begChar = theString.Value( beg );
3945 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3946 char endChar = ( begChar == '[' ) ? ']' : begChar;
3947 // end is at the corresponding quoting mark or bracket
3948 while ( end < theString.Length() &&
3949 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3953 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3958 else { // search backward
3960 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3963 return theEmptyString; // no word found
3965 char endChar = theString.Value( end );
3966 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3967 char begChar = ( endChar == ']' ) ? '[' : endChar;
3968 // beg is at the corresponding quoting mark
3970 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3974 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3980 //cout << theString << " ---- " << beg << " - " << end << endl;
3981 return theString.SubString( beg, end );
3984 //================================================================================
3986 * \brief Returns true if the string looks like a study entry
3988 //================================================================================
3990 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3992 if ( str.Length() < 5 ) return false;
3994 int nbColons = 0, isColon;
3995 for ( int i = 1; i <= str.Length(); ++i )
3997 char c = str.Value(i);
3998 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4000 nbColons += isColon;
4002 return nbColons > 2 && str.Length()-nbColons > 2;
4005 //================================================================================
4007 * \brief Returns true if the string looks like an object ID but not like a list,
4008 * string, command etc.
4010 //================================================================================
4012 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4014 if ( str.Length() < 1 ) return false;
4016 const char* s = str.ToCString();
4018 for ( int i = 0; i < str.Length(); ++i )
4019 if ( !IsIDChar( s[i] ))
4025 //================================================================================
4027 * \brief Finds entries in a sting
4029 //================================================================================
4031 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4033 std::list< _pyID > resList;
4035 while ( ++pos <= str.Length() )
4037 if ( !isdigit( str.Value( pos ))) continue;
4038 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4041 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4042 _pyID entry = str.SubString( pos, end-1 );
4044 if ( IsStudyEntry( entry ))
4045 resList.push_back( entry );
4050 //================================================================================
4052 * \brief Look for position where not space char is
4053 * \param theString - The string
4054 * \param thePos - The position to search from and which returns result
4055 * \retval bool - false if there are only space after thePos in theString
4057 //================================================================================
4059 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4061 if ( thePos < 1 || thePos > theString.Length() )
4064 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4067 return thePos <= theString.Length();
4070 //================================================================================
4072 * \brief Modify a part of the command
4073 * \param thePartIndex - The index of the part
4074 * \param thePart - The new part string
4075 * \param theOldPart - The old part
4077 //================================================================================
4079 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4080 TCollection_AsciiString& theOldPart)
4082 int pos = GetBegPos( thePartIndex );
4083 if ( pos <= Length() && theOldPart != thePart)
4085 TCollection_AsciiString seperator;
4087 pos = GetBegPos( thePartIndex + 1 );
4088 if ( pos < 1 ) return;
4089 switch ( thePartIndex ) {
4090 case RESULT_IND: seperator = " = "; break;
4091 case OBJECT_IND: seperator = "."; break;
4092 case METHOD_IND: seperator = "()"; break;
4096 myString.Remove( pos, theOldPart.Length() );
4097 if ( !seperator.IsEmpty() )
4098 myString.Insert( pos , seperator );
4099 myString.Insert( pos, thePart );
4100 // update starting positions of the following parts
4101 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4102 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4103 if ( myBegPos( i ) > 0 )
4104 myBegPos( i ) += posDelta;
4106 theOldPart = thePart;
4110 //================================================================================
4112 * \brief Set agrument
4113 * \param index - The argument index, it counts from 1
4114 * \param theArg - The argument string
4116 //================================================================================
4118 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4121 int argInd = ARG1_IND + index - 1;
4122 int pos = GetBegPos( argInd );
4123 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4125 // find a closing parenthesis
4126 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4127 int lastArgInd = GetNbArgs();
4128 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4129 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4134 while ( pos > 0 && myString.Value( pos ) != ')' )
4137 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4141 while ( myArgs.Length() < index ) {
4142 if ( myArgs.Length() )
4143 myString.Insert( pos++, "," );
4144 myArgs.Append("None");
4145 myString.Insert( pos, myArgs.Last() );
4146 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4147 pos += myArgs.Last().Length();
4150 SetPart( argInd, theArg, myArgs( index ));
4153 //================================================================================
4155 * \brief Empty arg list
4157 //================================================================================
4159 void _pyCommand::RemoveArgs()
4161 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4162 myString.Trunc( pos );
4165 if ( myBegPos.Length() >= ARG1_IND )
4166 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4169 //================================================================================
4171 * \brief Comment a python command
4173 //================================================================================
4175 void _pyCommand::Comment()
4177 if ( IsEmpty() ) return;
4180 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4181 if ( i <= Length() )
4183 myString.Insert( i, "#" );
4184 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4186 int begPos = GetBegPos( iPart );
4187 if ( begPos != UNKNOWN && begPos != EMPTY )
4188 SetBegPos( iPart, begPos + 1 );
4193 //================================================================================
4195 * \brief Set dependent commands after this one
4197 //================================================================================
4199 bool _pyCommand::SetDependentCmdsAfter() const
4201 bool orderChanged = false;
4202 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4203 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4204 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4205 orderChanged = true;
4206 theGen->SetCommandAfter( *cmd, this );
4207 (*cmd)->SetDependentCmdsAfter();
4210 return orderChanged;
4212 //================================================================================
4214 * \brief Insert accessor method after theObjectID
4215 * \param theObjectID - id of the accessed object
4216 * \param theAcsMethod - name of the method giving access to the object
4217 * \retval bool - false if theObjectID is not found in the command string
4219 //================================================================================
4221 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4223 if ( !theAcsMethod )
4225 // start object search from the object, i.e. ignore result
4227 int beg = GetBegPos( OBJECT_IND );
4228 if ( beg < 1 || beg > Length() )
4231 while (( beg = myString.Location( theObjectID, beg, Length() )))
4233 // check that theObjectID is not just a part of a longer ID
4234 int afterEnd = beg + theObjectID.Length();
4235 Standard_Character c = myString.Value( afterEnd );
4236 if ( !IsIDChar( c ))
4238 // check if accessor method already present
4240 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4242 int oldLen = Length();
4243 myString.Insert( afterEnd, (char*) theAcsMethod );
4244 myString.Insert( afterEnd, "." );
4245 // update starting positions of the parts following the modified one
4246 int posDelta = Length() - oldLen;
4247 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4248 if ( myBegPos( i ) > afterEnd )
4249 myBegPos( i ) += posDelta;
4254 beg = afterEnd; // is a part -> next search
4259 //================================================================================
4261 * \brief Creates pyObject
4263 //================================================================================
4265 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4266 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4271 //================================================================================
4273 * \brief Set up myID and myIsPublished
4275 //================================================================================
4277 void _pyObject::setID(const _pyID& theID)
4280 myIsPublished = !theGen->IsNotPublished( GetID() );
4283 //================================================================================
4285 * \brief Clear myCreationCmd and myProcessedCmds
4287 //================================================================================
4289 void _pyObject::ClearCommands()
4294 if ( !myCreationCmd.IsNull() )
4295 myCreationCmd->Clear();
4297 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4298 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4302 //================================================================================
4304 * \brief Return method name giving access to an interaface object wrapped by python class
4305 * \retval const char* - method name
4307 //================================================================================
4309 const char* _pyObject::AccessorMethod() const
4313 //================================================================================
4315 * \brief Return ID of a father
4317 //================================================================================
4319 _pyID _pyObject::FatherID(const _pyID & childID)
4321 int colPos = childID.SearchFromEnd(':');
4323 return childID.SubString( 1, colPos-1 );
4327 //================================================================================
4329 * \brief SelfEraser erases creation command if none of it's commands invoked
4330 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4332 //================================================================================
4334 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4335 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4337 myIsPublished = true; // prevent clearing as a not published
4338 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4341 //================================================================================
4343 * \brief SelfEraser erases creation command if none of it's commands invoked
4344 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4346 //================================================================================
4348 bool _pySelfEraser::CanClear()
4350 bool toErase = false;
4351 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4354 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4355 for ( ; cmd != myArgCmds.end(); ++cmd )
4356 nbArgUses += IsAliveCmd( *cmd );
4358 toErase = ( nbArgUses < 1 );
4363 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4364 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4365 for ( ; cmd != cmds.end(); )
4366 // check of cmd emptiness is not enough as object can change
4367 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4370 cmd = cmds.erase( cmd ); // save the cmd from clearing
4372 toErase = ( nbCalls < 1 );
4377 //================================================================================
4379 * \brief Check if a command is or can be cleared
4381 //================================================================================
4383 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4385 if ( theCmd->IsEmpty() )
4388 if ( !theGen->IsToKeepAllCommands() )
4390 const _pyID& objID = theCmd->GetObject();
4391 Handle( _pyObject ) obj = theGen->FindObject( objID );
4392 if ( !obj.IsNull() )
4393 return !obj->CanClear();
4398 //================================================================================
4400 * \brief SelfEraser erases creation command if none of it's commands invoked
4401 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4403 //================================================================================
4405 void _pySelfEraser::Flush()
4409 myIsPublished = false;
4410 _pyObject::ClearCommands();
4414 //================================================================================
4416 * \brief _pySubMesh constructor
4418 //================================================================================
4420 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4421 _pyObject(theCreationCmd)
4423 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4424 if ( toKeepAgrCmds )
4425 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4428 //================================================================================
4430 * \brief Return true if a sub-mesh can be used as argument of the given method
4432 //================================================================================
4434 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4437 // // names of all methods where a sub-mesh can be used as argument
4438 // static TStringSet methods;
4439 // if ( methods.empty() ) {
4440 // const char * names[] = {
4441 // // methods of SMESH_Gen
4443 // // methods of SMESH_Group
4445 // // methods of SMESH_Measurements
4447 // // methods of SMESH_Mesh
4448 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4450 // // methods of SMESH_MeshEditor
4451 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4452 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4453 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4454 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4455 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4456 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4457 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4458 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4459 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4460 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4461 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4462 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4463 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4464 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4465 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4466 // "" }; // <- mark of end
4467 // methods.Insert( names );
4469 // return methods.Contains( theMethodName );
4472 //================================================================================
4474 * \brief count invoked commands
4476 //================================================================================
4478 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4480 _pyObject::Process(theCommand); // count calls of Process()
4483 //================================================================================
4485 * \brief Move creation command depending on invoked commands
4487 //================================================================================
4489 void _pySubMesh::Flush()
4491 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4492 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4493 else if ( !myCreator.IsNull() )
4494 // move to be just after creator
4495 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4497 // move sub-mesh usage after creation cmd
4498 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4499 for ( ; cmd != myArgCmds.end(); ++cmd )
4500 if ( !(*cmd)->IsEmpty() )
4501 GetCreationCmd()->AddDependantCmd( *cmd );
4504 //================================================================================
4506 * \brief Creates _pyGroup
4508 //================================================================================
4510 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4511 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4513 if ( !id.IsEmpty() )
4516 myCanClearCreationCmd = true;
4518 const _AString& method = theCreationCmd->GetMethod();
4519 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4521 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4523 // ----------------------------------------------------------------------
4524 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4526 _pyID geom = theCreationCmd->GetArg( 3 );
4527 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4528 // next if(){...} section is commented
4529 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4530 // theCreationCmd->SetMethod( "Group" );
4531 // theCreationCmd->RemoveArgs();
4532 // theCreationCmd->SetArg( 1, geom );
4535 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4536 _pyID type = theCreationCmd->GetArg( 1 );
4537 _pyID name = theCreationCmd->GetArg( 2 );
4538 theCreationCmd->SetMethod( "GroupOnGeom" );
4539 theCreationCmd->RemoveArgs();
4540 theCreationCmd->SetArg( 1, geom );
4541 theCreationCmd->SetArg( 2, name );
4542 theCreationCmd->SetArg( 3, type );
4545 else if ( method == "CreateGroupFromFilter" )
4547 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4548 theCreationCmd->SetMethod( "GroupOnFilter" );
4550 _pyID filterID = theCreationCmd->GetArg(3);
4551 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4552 if ( !filter.IsNull())
4554 if ( !filter->GetNewID().IsEmpty() )
4555 theCreationCmd->SetArg( 3, filter->GetNewID() );
4556 //filter->AddUser( this );
4560 else if ( method == "GetGroups" )
4562 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4566 // theCreationCmd does something else apart from creation of this group
4567 // and thus it can't be cleared if this group is removed
4568 myCanClearCreationCmd = false;
4572 //================================================================================
4574 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4577 //================================================================================
4579 bool _pyGroup::CanClear()
4584 if ( !myCanClearCreationCmd &&
4585 !myCreationCmd.IsNull() &&
4586 myCreationCmd->GetMethod() == "GetGroups" )
4588 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4589 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4590 list< _pyID >::iterator grID = idList.begin();
4591 if ( GetID() == *grID )
4593 myCanClearCreationCmd = true;
4594 list< Handle(_pyGroup ) > groups;
4595 for ( ; grID != idList.end(); ++grID )
4597 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4598 if ( group.IsNull() ) continue;
4599 groups.push_back( group );
4600 if ( group->IsInStudy() )
4601 myCanClearCreationCmd = false;
4603 // set myCanClearCreationCmd == true to all groups
4604 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4605 for ( ; group != groups.end(); ++group )
4606 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4610 return myCanClearCreationCmd;
4613 //================================================================================
4615 * \brief set myCanClearCreationCmd = true if the main action of the creation
4616 * command is discarded
4618 //================================================================================
4620 void _pyGroup::RemovedWithContents()
4622 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4623 // via a created group
4624 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4625 // myCanClearCreationCmd = true;
4628 //================================================================================
4630 * \brief To convert creation of a group by filter
4632 //================================================================================
4634 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4636 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4637 // group = mesh.CreateEmptyGroup( elemType, groupName )
4638 // aFilter.SetMesh(mesh)
4639 // nbAdd = group.AddFrom( aFilter )
4640 Handle(_pyFilter) filter;
4641 if ( theCommand->GetMethod() == "AddFrom" )
4643 _pyID idSource = theCommand->GetArg(1);
4644 // check if idSource is a filter
4645 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4646 if ( !filter.IsNull() )
4648 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4649 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4650 while ( *cmdIt != theCommand ) ++cmdIt;
4651 while ( (*cmdIt)->GetOrderNb() != 1 )
4653 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4654 if ((setMeshCmd->GetObject() == idSource ||
4655 setMeshCmd->GetObject() == filter->GetNewID() )
4657 setMeshCmd->GetMethod() == "SetMesh")
4659 setMeshCmd->Clear();
4663 // replace 3 commands by one
4664 theCommand->Clear();
4665 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4666 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4667 if ( !filter->GetNewID().IsEmpty() )
4668 idSource = filter->GetNewID();
4669 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4670 makeGroupCmd->SetArg( 1, name );
4671 makeGroupCmd->SetArg( 2, idSource );
4672 filter->AddArgCmd( makeGroupCmd );
4675 else if ( theCommand->GetMethod() == "SetFilter" )
4677 // set new name of a filter or clear the command if the same filter is set
4678 _pyID filterID = theCommand->GetArg(1);
4679 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4680 if ( !myFilter.IsNull() && filter == myFilter )
4681 theCommand->Clear();
4682 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4683 theCommand->SetArg( 1, filter->GetNewID() );
4686 else if ( theCommand->GetMethod() == "GetFilter" )
4688 // GetFilter() returns a filter with other ID, make myFilter process
4689 // calls of the returned filter
4690 if ( !myFilter.IsNull() )
4692 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4693 theCommand->Clear();
4697 // if ( !filter.IsNull() )
4698 // filter->AddUser( this );
4700 theGen->AddMeshAccessorMethod( theCommand );
4703 //================================================================================
4705 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4707 //================================================================================
4709 void _pyGroup::Flush()
4711 if ( !theGen->IsToKeepAllCommands() &&
4712 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4714 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4718 //================================================================================
4720 * \brief Constructor of _pyFilter
4722 //================================================================================
4724 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4725 :_pyObject(theCreationCmd), myNewID( newID )
4727 //myIsPublished = true; // prevent clearing as a not published
4728 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4731 //================================================================================
4733 * \brief To convert creation of a filter by criteria and
4734 * to replace an old name by a new one
4736 //================================================================================
4738 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4740 if ( theCommand->GetObject() == GetID() )
4741 _pyObject::Process(theCommand); // count commands
4743 if ( !myNewID.IsEmpty() )
4744 theCommand->SetObject( myNewID );
4746 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4747 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4748 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4749 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4750 theCommand->GetMethod() == "SetCriteria")
4752 // aFilter.SetCriteria(aCriteria) ->
4753 // aFilter = smesh.GetFilterFromCriteria(criteria)
4754 if ( myNewID.IsEmpty() )
4755 theCommand->SetResultValue( GetID() );
4757 theCommand->SetResultValue( myNewID );
4758 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4759 theCommand->SetMethod( "GetFilterFromCriteria" );
4761 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4762 GetCreationCmd()->Clear();
4763 GetCreationCmd()->GetString() = theCommand->GetString();
4764 theCommand->Clear();
4765 theCommand->AddDependantCmd( GetCreationCmd() );
4766 // why swap? -- it's needed
4767 //GetCreationCmd()->Clear();
4769 else if ( theCommand->GetMethod() == "SetMesh" )
4771 if ( myMesh == theCommand->GetArg( 1 ))
4772 theCommand->Clear();
4774 myMesh = theCommand->GetArg( 1 );
4775 theGen->AddMeshAccessorMethod( theCommand );
4779 //================================================================================
4781 * \brief Set new filter name to the creation command and to myArgCmds
4783 //================================================================================
4785 void _pyFilter::Flush()
4787 if ( myNewID.IsEmpty() ) return;
4789 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4790 for ( ; cmd != myArgCmds.end(); ++cmd )
4791 if ( !(*cmd)->IsEmpty() )
4793 _AString cmdStr = (*cmd)->GetString();
4794 _AString id = GetID();
4795 int pos = cmdStr.Search( id );
4798 cmdStr.Remove( pos, id.Length() );
4799 cmdStr.Insert( pos, myNewID );
4802 (*cmd)->GetString() = cmdStr;
4805 if ( !GetCreationCmd()->IsEmpty() )
4806 GetCreationCmd()->SetResultValue( myNewID );
4809 //================================================================================
4811 * \brief Return true if all my users can be cleared
4813 //================================================================================
4815 bool _pyObject::CanClear()
4817 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4818 for ( ; cmd != myArgCmds.end(); ++cmd )
4819 if ( !(*cmd)->IsEmpty() )
4821 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4822 if ( !obj.IsNull() && !obj->CanClear() )
4825 return ( !myIsPublished );
4828 //================================================================================
4830 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4832 //================================================================================
4834 _pyHypothesisReader::_pyHypothesisReader()
4837 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4838 LDOMParser xmlParser;
4839 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4841 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4845 INFOS( xmlParser.GetError(data) );
4848 // <algorithm type="Regular_1D"
4849 // label-id="Wire discretisation"
4852 // <algo>Regular_1D=Segment()</algo>
4853 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4855 LDOM_Document xmlDoc = xmlParser.getDocument();
4856 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4857 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4859 LDOM_Node algoNode = algoNodeList.item( i );
4860 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4861 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4862 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4864 _AString text, algoType, method, arg;
4865 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4867 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4868 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4869 text = textNode.getNodeValue();
4870 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4871 algoType = algoCmd->GetResultValue();
4872 method = algoCmd->GetMethod();
4873 arg = algoCmd->GetArg(1);
4874 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4876 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4877 algo->SetConvMethodAndType( method, algoType );
4878 if ( !arg.IsEmpty() )
4879 algo->setCreationArg( 1, arg );
4881 myType2Hyp[ algoType ] = algo;
4885 if ( algoType.IsEmpty() ) continue;
4887 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4889 Handle( _pyHypothesis ) hyp;
4890 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4892 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4893 LDOM_Node textNode = pyHypoNode.getFirstChild();
4894 text = textNode.getNodeValue();
4895 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4896 hypType = hypoCmd->GetResultValue();
4897 method = hypoCmd->GetMethod();
4898 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4900 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4901 if ( type2hyp == myType2Hyp.end() )
4902 hyp = new _pyHypothesis( hypoCmd );
4904 hyp = type2hyp->second;
4905 hyp->SetConvMethodAndType( method, algoType );
4906 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4908 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4909 _AString argMethod = argCmd.GetMethod();
4910 _AString argNbText = argCmd.GetArg( 1 );
4911 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4912 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4914 hyp->AddArgMethod( argMethod,
4915 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4917 myType2Hyp[ hypType ] = hyp;
4921 // <hypothesis type="BLSURF_Parameters"
4925 // <accumulative-methods>
4926 // SetEnforcedVertex,
4927 // SetEnforcedVertexNamed
4928 // </accumulative-methods>
4932 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4933 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4935 LDOM_Node hypNode = hypNodeList.item( i );
4936 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4937 _AString hypType = hypElem.getAttribute("type");
4938 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4939 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4941 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4942 if ( type2hyp == myType2Hyp.end() ) continue;
4944 LDOM_Node methNode = methNodeList.item( 0 );
4945 LDOM_Node textNode = methNode.getFirstChild();
4946 _AString text = textNode.getNodeValue();
4950 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4951 pos += method.Length();
4952 type2hyp->second->AddAccumulativeMethod( method );
4954 while ( !method.IsEmpty() );
4957 } // loop on xmlPaths
4960 //================================================================================
4962 * \brief Returns a new hypothesis initialized according to the read information
4964 //================================================================================
4966 Handle(_pyHypothesis)
4967 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4968 const Handle(_pyCommand)& creationCmd) const
4970 Handle(_pyHypothesis) resHyp, sampleHyp;
4972 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4973 if ( type2hyp != myType2Hyp.end() )
4974 sampleHyp = type2hyp->second;
4976 if ( sampleHyp.IsNull() )
4978 resHyp = new _pyHypothesis(creationCmd);
4982 if ( sampleHyp->IsAlgo() )
4983 resHyp = new _pyAlgorithm( creationCmd );
4985 resHyp = new _pyHypothesis(creationCmd);
4986 resHyp->Assign( sampleHyp, _pyID() );
4991 //================================================================================
4993 * \brief Adds an object ID to some family of IDs with a common prefix
4994 * \param [in] str - the object ID
4995 * \return bool - \c false if \a str does not have the same prefix as \a this family
4996 * (for internal usage)
4998 //================================================================================
5000 bool _pyStringFamily::Add( const char* str )
5002 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5003 return false; // expected prefix is missing
5005 str += _prefix.Length(); // skip _prefix
5007 // try to add to some of child falimies
5008 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5009 for ( ; itSub != _subFams.end(); ++itSub )
5010 if ( itSub->Add( str ))
5013 // no suitable family found - add str to _strings or create a new child family
5015 // look for a proper place within sorted _strings
5016 std::list< _AString >::iterator itStr = _strings.begin();
5017 while ( itStr != _strings.end() && itStr->IsLess( str ))
5019 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5020 return true; // same ID already kept
5022 const int minPrefixSize = 4;
5024 // count "smaller" strings with the same prefix
5025 std::list< _AString >::iterator itLess = itStr; --itLess;
5027 for ( ; itLess != _strings.end(); --itLess )
5028 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5033 // count "greater" strings with the same prefix
5034 std::list< _AString >::iterator itMore = itStr;
5036 for ( ; itMore != _strings.end(); ++itMore )
5037 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5042 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5044 // look for a maximal prefix length
5045 // int lessPrefSize = 3, morePrefSize = 3;
5046 // if ( nbLess > 0 )
5047 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5049 // if ( nbMore > 0 )
5050 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5052 // int prefixSize = 3;
5053 // if ( nbLess == 0 )
5054 // prefixSize = morePrefSize;
5055 // else if ( nbMore == 0 )
5056 // prefixSize = lessPrefSize;
5058 // prefixSize = Min( lessPrefSize, morePrefSize );
5059 int prefixSize = minPrefixSize;
5060 _AString newPrefix ( str, prefixSize );
5062 // look for a proper place within _subFams sorted by _prefix
5063 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5064 if ( !itSub->_prefix.IsLess( newPrefix ))
5067 // add the new _pyStringFamily
5068 itSub = _subFams.insert( itSub, _pyStringFamily());
5069 _pyStringFamily& newSubFam = *itSub;
5070 newSubFam._prefix = newPrefix;
5072 // pass this->_strings to newSubFam._strings
5073 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5074 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5075 newSubFam._strings.push_back( str + prefixSize );
5076 for ( ; nbMore > 0; --nbMore, ++itStr )
5077 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5079 _strings.erase( itLess, ++itMore );
5081 else // to few string to make a family fot them
5083 _strings.insert( itStr, str );
5088 //================================================================================
5090 * \brief Finds an object ID in the command
5091 * \param [in] longStr - the command string
5092 * \param [out] subStr - the found object ID
5093 * \return bool - \c true if the object ID found
5095 //================================================================================
5097 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5099 const _AString& longStr = cmd->GetString();
5100 const char* s = longStr.ToCString();
5103 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5104 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5105 if ( argBeg < 4 || argBeg > longStr.Length() )
5107 for ( ; itSub != _subFams.end(); ++itSub )
5110 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5111 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5113 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5114 from = pos + len + itSub->_prefix.Length();
5119 from += itSub->_prefix.Length();
5122 // look among _strings
5123 std::list< _AString >::iterator itStr = _strings.begin();
5124 for ( ; itStr != _strings.end(); ++itStr )
5125 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5126 // check that object ID does not continue after len
5127 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5129 subStr.push_back( *itStr );
5135 //================================================================================
5137 * \brief Return remainder length of the object ID after my _prefix
5138 * \param [in] str - remainder of the command after my _prefix
5139 * \return int - length of the object ID or -1 if not found
5141 //================================================================================
5143 int _pyStringFamily::isIn( const char* str )
5145 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5147 for ( ; itSub != _subFams.end(); ++itSub )
5149 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5152 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5153 return itSub->_prefix.Length() + len;
5158 if ( !_strings.empty() )
5160 std::list< _AString >::iterator itStr = _strings.begin();
5161 bool firstEmpty = itStr->IsEmpty();
5164 for ( ; itStr != _strings.end(); ++itStr )
5166 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5169 len = itStr->Length();
5178 // check that object ID does not continue after len
5179 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5186 //================================================================================
5190 //================================================================================
5192 void _pyStringFamily::Print( int level )
5194 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5195 std::list< _AString >::iterator itStr = _strings.begin();
5196 for ( ; itStr != _strings.end(); ++itStr )
5197 cout << *itStr << " | ";
5199 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5200 for ( ; itSub != _subFams.end(); ++itSub )
5201 itSub->Print( level + 1 );
5203 cout << string( 70, '-' ) << endl;