1 // Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
53 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
71 using SMESH::TPythonDump;
74 * \brief Container of commands into which the initial script is split.
75 * It also contains data corresponding to SMESH_Gen contents
77 static Handle(_pyGen) theGen;
79 static TCollection_AsciiString theEmptyString;
81 //#define DUMP_CONVERSION
83 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
84 #undef DUMP_CONVERSION
90 //================================================================================
92 * \brief Set of TCollection_AsciiString initialized by C array of C strings
94 //================================================================================
96 struct TStringSet: public set<TCollection_AsciiString>
99 * \brief Filling. The last string must be ""
101 void Insert(const char* names[]) {
102 for ( int i = 0; names[i][0] ; ++i )
103 insert( (char*) names[i] );
106 * \brief Check if a string is in
108 bool Contains(const TCollection_AsciiString& name ) {
109 return find( name ) != end();
113 //================================================================================
115 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
116 * Odd items of the C array are map keys, and even items are values
118 //================================================================================
120 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
123 * \brief Filling. The last string must be ""
125 void Insert(const char* names_values[]) {
126 for ( int i = 0; names_values[i][0] ; i += 2 )
127 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
130 * \brief Check if a string is in
132 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
133 map< _AString, _AString >::iterator it = find( name );
134 return it == end() ? "" : it->second;
138 //================================================================================
140 * \brief Returns a mesh by object
142 //================================================================================
144 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
148 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
149 return Handle(_pyMesh)::DownCast( obj );
150 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
151 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
152 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
153 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
155 return Handle(_pyMesh)();
158 //================================================================================
160 * \brief Check if objects used as args have been created by previous commands
162 //================================================================================
164 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
166 // either comment or erase a command including NotPublishedObjectName()
167 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
169 bool isResultPublished = false;
170 const int nbRes = cmd->GetNbResultValues();
171 for ( int i = 0; i < nbRes; i++ )
173 _pyID objID = cmd->GetResultValue( i+1 );
174 if ( cmd->IsStudyEntry( objID ))
175 isResultPublished = (! theGen->IsNotPublished( objID ));
176 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
178 if ( isResultPublished )
184 // check if an Object was created in the script
187 _pyID obj = cmd->GetObject();
188 if ( obj.Search( "print(" ) == 1 )
189 return; // print statement
191 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
192 // remove an accessor method
193 obj = _pyCommand( obj ).GetObject();
195 const bool isMethodCall = cmd->IsMethodCall();
196 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
198 comment = "not created Object";
199 theGen->ObjectCreationRemoved( obj );
201 // check if a command has not created args
202 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
204 const _pyID& arg = cmd->GetArg( iArg );
205 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
207 list< _pyID > idList = cmd->GetStudyEntries( arg );
208 list< _pyID >::iterator id = idList.begin();
209 for ( ; id != idList.end(); ++id )
210 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
212 comment += *id + " has not been yet created";
215 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
216 // comment += arg + " has not been yet created";
218 // treat result objects
219 const _pyID& result = cmd->GetResultValue();
220 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
222 list< _pyID > idList = cmd->GetStudyEntries( result );
223 list< _pyID >::iterator id = idList.begin();
224 for ( ; id != idList.end(); ++id )
226 if ( comment.IsEmpty() )
227 presentObjects.insert( *id );
229 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
231 if ( idList.empty() && cmd->IsID( result ))
232 presentObjects.insert( result );
234 // comment the command
235 if ( !comment.IsEmpty() )
238 cmd->GetString() += " ### ";
239 cmd->GetString() += comment;
243 //================================================================================
245 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
247 //================================================================================
249 void fixFunctorType( TCollection_AsciiString& Type,
250 TCollection_AsciiString& Compare,
251 TCollection_AsciiString& UnaryOp,
252 TCollection_AsciiString& BinaryOp )
254 // The problem is that dumps of old studies created using filters becomes invalid
255 // when new items are inserted in the enum SMESH::FunctorType since values
256 // of this enum are dumped as integer values.
257 // This function corrects enum values of old studies given as args (Type,Compare,...)
258 // We can find out how to correct them by value of BinaryOp which can have only two
259 // values: FT_Undefined or FT_LogicalNOT.
260 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
261 // where PythonDump appeared
262 // v 3.0.0: FT_Undefined == 25
263 // v 3.1.0: FT_Undefined == 26, new items:
265 // v 4.1.2: FT_Undefined == 27, new items:
266 // - FT_BelongToGenSurface = 17
267 // v 5.1.1: FT_Undefined == 32, new items:
268 // - FT_FreeNodes = 10
269 // - FT_FreeFaces = 11
270 // - FT_LinearOrQuadratic = 23
271 // - FT_GroupColor = 24
272 // - FT_ElemGeomType = 25
273 // v 5.1.5: FT_Undefined == 33, new items:
274 // - FT_CoplanarFaces = 26
275 // v 6.2.0: FT_Undefined == 39, new items:
276 // - FT_MaxElementLength2D = 8
277 // - FT_MaxElementLength3D = 9
278 // - FT_BareBorderVolume = 25
279 // - FT_BareBorderFace = 26
280 // - FT_OverConstrainedVolume = 27
281 // - FT_OverConstrainedFace = 28
282 // v 6.5.0: FT_Undefined == 43, new items:
283 // - FT_EqualNodes = 14
284 // - FT_EqualEdges = 15
285 // - FT_EqualFaces = 16
286 // - FT_EqualVolumes = 17
287 // v 6.6.0: FT_Undefined == 44, new items:
288 // - FT_BallDiameter = 37
289 // v 6.7.1: FT_Undefined == 45, new items:
290 // - FT_EntityType = 36
291 // v 7.3.0: FT_Undefined == 46, new items:
292 // - FT_ConnectedElements = 39
293 // v 7.6.0: FT_Undefined == 47, new items:
294 // - FT_BelongToMeshGroup = 22
295 // v 8.1.0: FT_Undefined == 48, new items:
296 // - FT_NodeConnectivityNumber= 22
297 // v 8.5.0: FT_Undefined == 49, new items:
298 // - FT_Deflection2D = 22
299 // v 9.3.0: FT_Undefined == 50, new items:
300 // - FT_Length3D = 22
302 // It's necessary to continue recording this history and to fill
303 // undef2newItems (see below) accordingly.
305 typedef map< int, vector< int > > TUndef2newItems;
306 static TUndef2newItems undef2newItems;
307 if ( undef2newItems.empty() )
309 undef2newItems[ 26 ].push_back( 7 );
310 undef2newItems[ 27 ].push_back( 17 );
311 { int items[] = { 10, 11, 23, 24, 25 };
312 undef2newItems[ 32 ].assign( items, items+5 ); }
313 undef2newItems[ 33 ].push_back( 26 );
314 { int items[] = { 8, 9, 25, 26, 27, 28 };
315 undef2newItems[ 39 ].assign( items, items+6 ); }
316 { int items[] = { 14, 15, 16, 17 };
317 undef2newItems[ 43 ].assign( items, items+4 ); }
318 undef2newItems[ 44 ].push_back( 37 );
319 undef2newItems[ 45 ].push_back( 36 );
320 undef2newItems[ 46 ].push_back( 39 );
321 undef2newItems[ 47 ].push_back( 22 );
322 undef2newItems[ 48 ].push_back( 22 );
323 undef2newItems[ 49 ].push_back( 22 );
324 undef2newItems[ 50 ].push_back( 22 );
326 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
329 int iType = Type.IntegerValue();
330 int iCompare = Compare.IntegerValue();
331 int iUnaryOp = UnaryOp.IntegerValue();
332 int iBinaryOp = BinaryOp.IntegerValue();
334 // find out integer value of FT_Undefined at the moment of dump
335 int oldUndefined = iBinaryOp;
336 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
339 // apply history to args
340 TUndef2newItems::const_iterator undef_items =
341 undef2newItems.upper_bound( oldUndefined );
342 if ( undef_items != undef2newItems.end() )
344 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
345 for ( ; undef_items != undef2newItems.end(); ++undef_items )
347 const vector< int > & addedItems = undef_items->second;
348 for ( size_t i = 0; i < addedItems.size(); ++i )
349 for ( int iArg = 0; iArg < 4; ++iArg )
351 int& arg = *pArg[iArg];
352 if ( arg >= addedItems[i] )
356 Type = TCollection_AsciiString( iType );
357 Compare = TCollection_AsciiString( iCompare );
358 UnaryOp = TCollection_AsciiString( iUnaryOp );
359 BinaryOp = TCollection_AsciiString( iBinaryOp );
363 //================================================================================
365 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
366 * arguments of a given command by a list "[x,y,z]" if the list is accessible
369 //================================================================================
371 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
373 static TStringSet methodsAcceptingList;
374 if ( methodsAcceptingList.empty() ) {
375 const char * methodNames[] = {
376 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
377 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
378 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
379 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
380 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
381 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
382 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
383 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
384 "Translate","TranslateMakeGroups","TranslateMakeMesh",
385 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
386 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
387 ,"" }; // <- mark of the end
388 methodsAcceptingList.Insert( methodNames );
390 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
392 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
394 const _AString & arg = theCommand->GetArg( i );
395 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
396 arg.Search( "SMESH.DirStruct" ) == 1 )
398 Handle(_pyCommand) workCmd = new _pyCommand( arg );
399 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
401 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
403 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
405 _AString newArg = "[ ";
406 newArg += ( workCmd->GetArg( 1 ) + ", " +
407 workCmd->GetArg( 2 ) + ", " +
408 workCmd->GetArg( 3 ) + " ]");
409 theCommand->SetArg( i, newArg );
415 //================================================================================
417 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
418 * a list "[id1,id2]" if the list is an accessible type of argument.
420 //================================================================================
422 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
424 static TStringSet methodsAcceptingList;
425 if ( methodsAcceptingList.empty() ) {
426 const char * methodNames[] = {
427 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
428 "ExportCGNS","ExportGMF",
429 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
430 "ScaleMakeGroups","Scale","ScaleMakeMesh",
431 "FindCoincidentNodesOnPartBut","DoubleElements",
432 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
433 ,"" }; // <- mark of the end
434 methodsAcceptingList.Insert( methodNames );
436 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
438 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
440 _pyCommand argCmd( theCommand->GetArg( i ));
441 if ( argCmd.GetMethod() == "GetIDSource" &&
442 argCmd.GetNbArgs() == 2 )
444 theCommand->SetArg( i, argCmd.GetArg( 1 ));
450 bool _FilterArg( const _AString& theArg )
452 static std::list<_AString> filteredArgs;
453 static bool initialized = false;
454 if ( !initialized ) {
456 filteredArgs.push_back( "SMESH.MED_V2_1" );
457 filteredArgs.push_back( "SMESH.MED_V2_2" );
459 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
463 //================================================================================
465 * \brief Convert a python script using commands of smeshBuilder.py
466 * \param theScriptLines - Lines of the input script
467 * \param theEntry2AccessorMethod - returns method names to access to
468 * objects wrapped with python class
469 * \param theObjectNames - names of objects
470 * \param theRemovedObjIDs - entries of objects whose created commands were removed
471 * \param theHistoricalDump - true means to keep all commands, false means
472 * to exclude commands relating to objects removed from study
473 * \retval TCollection_AsciiString - Conversion result
475 //================================================================================
478 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
479 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
480 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
481 std::set< TCollection_AsciiString >& theRemovedObjIDs,
482 const bool theToKeepAllCommands)
484 std::list< TCollection_AsciiString >::iterator lineIt;
485 // process notebook variables
487 SMESH_NoteBook aNoteBook;
489 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
490 aNoteBook.AddCommand( *lineIt );
492 theScriptLines.clear();
494 aNoteBook.ReplaceVariables();
496 aNoteBook.GetResultLines( theScriptLines );
499 // convert to smeshBuilder.py API
501 theGen = new _pyGen( theEntry2AccessorMethod,
504 theToKeepAllCommands );
506 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
507 theGen->AddCommand( *lineIt );
509 theScriptLines.clear();
513 #ifdef DUMP_CONVERSION
514 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
517 // clean commands of removed objects depending on myIsPublished flag
518 theGen->ClearCommands();
520 // reorder commands after conversion
521 list< Handle(_pyCommand) >::iterator cmd;
524 orderChanges = false;
525 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
526 if ( (*cmd)->SetDependentCmdsAfter() )
528 } while ( orderChanges );
530 // concat commands back into a script
531 TCollection_AsciiString aPrevCmd;
532 set<_pyID> createdObjects;
533 createdObjects.insert( "smeshBuilder" );
534 createdObjects.insert( "smesh" );
535 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
537 #ifdef DUMP_CONVERSION
538 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
540 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
541 CheckObjectPresence( *cmd, createdObjects );
542 if ( !(*cmd)->IsEmpty() ) {
543 aPrevCmd = (*cmd)->GetString();
544 theScriptLines.push_back( aPrevCmd );
553 //================================================================================
555 * \brief _pyGen constructor
557 //================================================================================
559 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
560 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
561 std::set< TCollection_AsciiString >& theRemovedObjIDs,
562 const bool theToKeepAllCommands)
563 : _pyObject( new _pyCommand( "", 0 )),
565 myID2AccessorMethod( theEntry2AccessorMethod ),
566 myObjectNames( theObjectNames ),
567 myRemovedObjIDs( theRemovedObjIDs ),
569 myToKeepAllCommands( theToKeepAllCommands ),
570 myGeomIDNb(0), myGeomIDIndex(-1),
571 myShaperIDNb(0), myShaperIDIndex(-1)
573 // make that GetID() to return TPythonDump::SMESHGenName()
574 GetCreationCmd()->Clear();
575 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
576 GetCreationCmd()->GetString() += "=";
578 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
579 if (!theObjectNames.IsEmpty())
581 // find a GEOM (aPass == 0) and SHAPERSTUDY (aPass == 1) entries
582 for(int aPass = 0; aPass < 2; aPass++) {
584 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->
585 FindComponent(aPass == 0 ? "GEOM" : "SHAPERSTUDY");
586 if (geomComp->_is_nil()) continue;
587 CORBA::String_var entry = geomComp->GetID();
590 // find a SMESH entry
592 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n(theObjectNames);
593 for (; e2n.More() && smeshID.IsEmpty(); e2n.Next())
594 if (_pyCommand::IsStudyEntry(e2n.Key()))
597 // find 1st difference between smeshID and geomID
598 if (!geomID.IsEmpty() && !smeshID.IsEmpty())
599 for (int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i)
600 if (geomID.Value(i) != smeshID.Value(i))
603 myGeomIDNb = geomID.Value(i);
606 myShaperIDNb = geomID.Value(i);
614 //================================================================================
616 * \brief name of SMESH_Gen in smeshBuilder.py
618 //================================================================================
620 const char* _pyGen::AccessorMethod() const
622 return SMESH_2smeshpy::GenName();
625 //================================================================================
627 * \brief Convert a command using a specific converter
628 * \param theCommand - the command to convert
630 //================================================================================
632 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
634 // store theCommand in the sequence
635 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
637 Handle(_pyCommand) aCommand = myCommands.back();
638 #ifdef DUMP_CONVERSION
639 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
642 const _pyID& objID = aCommand->GetObject();
644 if ( objID.IsEmpty() )
647 // Prevent moving a command creating a sub-mesh to the end of the script
648 // if the sub-mesh is used in theCommand as argument
649 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
651 // PlaceSubmeshAfterItsCreation( aCommand );
654 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
655 StructToList( aCommand );
657 const TCollection_AsciiString& method = aCommand->GetMethod();
659 // not to erase _pySelfEraser's etc. used as args in some commands
661 #ifdef USE_STRING_FAMILY
662 std::list<_pyID> objIDs;
663 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
665 std::list<_pyID>::iterator objID = objIDs.begin();
666 for ( ; objID != objIDs.end(); ++objID )
668 Handle(_pyObject) obj = FindObject( *objID );
671 obj->AddArgCmd( aCommand );
672 //cout << objID << " found in " << theCommand << endl;
677 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
678 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
679 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
681 Handle(_pyObject) obj = FindObject( *id );
683 obj->AddArgCmd( aCommand );
688 // Find an object to process theCommand
691 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
693 this->Process( aCommand );
694 //addFilterUser( aCommand, theGen ); // protect filters from clearing
698 // SMESH_Mesh method?
699 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
700 if ( id_mesh != myMeshes.end() )
702 //id_mesh->second->AddProcessedCmd( aCommand );
704 // Wrap Export*() into try-except
705 if ( aCommand->MethodStartsFrom("Export"))
708 _AString indent = aCommand->GetIndentation();
709 _AString tryStr = indent + "try:";
710 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
711 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
712 _AString excStr = indent + "except:";
713 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
715 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
717 aCommand->GetString() = newCmd;
718 aCommand->SetOrderNb( ++myNbCommands );
719 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
720 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
721 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
723 // check for mesh editor object
724 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
725 _pyID editorID = aCommand->GetResultValue();
726 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
727 myMeshEditors.insert( make_pair( editorID, editor ));
730 // check for SubMesh objects
731 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
732 _pyID subMeshID = aCommand->GetResultValue();
733 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
734 AddObject( subMesh );
737 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
738 GetIDSourceToList( aCommand );
740 //addFilterUser( aCommand, theGen ); // protect filters from clearing
742 id_mesh->second->Process( aCommand );
743 id_mesh->second->AddProcessedCmd( aCommand );
747 // SMESH_MeshEditor method?
748 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
749 if ( id_editor != myMeshEditors.end() )
751 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
752 GetIDSourceToList( aCommand );
754 //addFilterUser( aCommand, theGen ); // protect filters from clearing
756 // some commands of SMESH_MeshEditor create meshes and groups
757 _pyID meshID, groups;
758 if ( method.Search("MakeMesh") != -1 )
759 meshID = aCommand->GetResultValue();
760 else if ( method == "MakeBoundaryMesh")
761 meshID = aCommand->GetResultValue(1);
762 else if ( method == "MakeBoundaryElements")
763 meshID = aCommand->GetResultValue(2);
765 if ( method.Search("MakeGroups") != -1 ||
766 method == "ExtrusionAlongPathX" ||
767 method == "ExtrusionAlongPathObjX" ||
768 method == "DoubleNodeGroupNew" ||
769 method == "DoubleNodeGroupsNew" ||
770 method == "DoubleNodeElemGroupNew" ||
771 method == "DoubleNodeElemGroupsNew" ||
772 method == "DoubleNodeElemGroup2New" ||
773 method == "DoubleNodeElemGroups2New" ||
774 method == "AffectedElemGroupsInRegion"
776 groups = aCommand->GetResultValue();
777 else if ( method == "MakeBoundaryMesh" )
778 groups = aCommand->GetResultValue(2);
779 else if ( method == "MakeBoundaryElements")
780 groups = aCommand->GetResultValue(3);
781 else if ( method == "Create0DElementsOnAllNodes" &&
782 aCommand->GetArg(2).Length() > 2 ) // group name != ''
783 groups = aCommand->GetResultValue();
785 id_editor->second->Process( aCommand );
786 id_editor->second->AddProcessedCmd( aCommand );
789 if ( !meshID.IsEmpty() &&
790 !myMeshes.count( meshID ) &&
791 aCommand->IsStudyEntry( meshID ))
793 _AString processedCommand = aCommand->GetString();
794 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
795 CheckObjectIsReCreated( mesh );
796 myMeshes.insert( make_pair( meshID, mesh ));
798 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
801 if ( !groups.IsEmpty() )
803 if ( !aCommand->IsStudyEntry( meshID ))
804 meshID = id_editor->second->GetMesh();
805 Handle(_pyMesh) mesh = myMeshes[ meshID ];
807 list< _pyID > idList = aCommand->GetStudyEntries( groups );
808 list< _pyID >::iterator grID = idList.begin();
809 for ( ; grID != idList.end(); ++grID )
810 if ( !myObjects.count( *grID ))
812 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
814 if ( !mesh.IsNull() ) mesh->AddGroup( group );
818 } // SMESH_MeshEditor methods
820 // SMESH_Hypothesis method?
821 Handle(_pyHypothesis) hyp = FindHyp( objID );
822 if ( !hyp.IsNull() && !hyp->IsAlgo() )
824 hyp->Process( aCommand );
825 hyp->AddProcessedCmd( aCommand );
829 // aFilterManager.CreateFilter() ?
830 if ( aCommand->GetMethod() == "CreateFilter" )
832 // Set a more human readable name to a filter
833 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
834 _pyID newID, filterID = aCommand->GetResultValue();
835 int pos = filterID.Search( "0x" );
837 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
839 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
842 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
843 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
845 // create _pySelfEraser for functors
846 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
847 functor->IgnoreOwnCalls(); // to erase if not used as an argument
848 AddObject( functor );
851 // other object method?
852 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
853 if ( id_obj != myObjects.end() ) {
854 id_obj->second->Process( aCommand );
855 id_obj->second->AddProcessedCmd( aCommand );
859 // Add access to a wrapped mesh
860 AddMeshAccessorMethod( aCommand );
862 // Add access to a wrapped algorithm
863 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
865 // PAL12227. PythonDump was not updated at proper time; result is
866 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
867 // TypeError: __init__() takes exactly 11 arguments (10 given)
868 const char wrongCommand[] = "SMESH.Filter.Criterion(";
869 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
871 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
872 // there must be 10 arguments, 5-th arg ThresholdID is missing,
873 const int wrongNbArgs = 9, missingArg = 5;
874 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
876 for ( int i = wrongNbArgs; i > missingArg; --i )
877 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
878 tmpCmd.SetArg( missingArg, "''");
879 aCommand->GetString().Trunc( beg - 1 );
880 aCommand->GetString() += tmpCmd.GetString();
883 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
885 // instead of "SMESH.Filter.Criterion(
886 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
887 // 1 2 3 4 5 6 7 8 9 10
888 // in order to avoid the problem of type mismatch of long and FunctorType
889 const TCollection_AsciiString
890 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
891 TCollection_AsciiString
892 Type = aCommand->GetArg(1), // long
893 Compare = aCommand->GetArg(2), // long
894 Threshold = aCommand->GetArg(3), // double
895 ThresholdStr = aCommand->GetArg(4), // string
896 ThresholdID = aCommand->GetArg(5), // string
897 UnaryOp = aCommand->GetArg(6), // long
898 BinaryOp = aCommand->GetArg(7), // long
899 Tolerance = aCommand->GetArg(8), // double
900 TypeOfElement = aCommand->GetArg(9), // ElementType
901 Precision = aCommand->GetArg(10); // long
902 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
903 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
904 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
905 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
906 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
908 if ( Compare == "SMESH.FT_EqualTo" )
911 aCommand->RemoveArgs();
912 aCommand->SetObject( SMESH_2smeshpy::GenName() );
913 aCommand->SetMethod( "GetCriterion" );
915 aCommand->SetArg( 1, TypeOfElement );
916 aCommand->SetArg( 2, Type );
917 aCommand->SetArg( 3, Compare );
919 if ( Threshold.IsIntegerValue() )
921 int iGeom = Threshold.IntegerValue();
922 if ( Type == "SMESH.FT_ElemGeomType" )
924 // set SMESH.GeometryType instead of a numerical Threshold
925 const int nbTypes = SMESH::Geom_LAST;
926 const char* types[] = {
927 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
928 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
929 "Geom_POLYHEDRA", "Geom_BALL" };
930 if ( -1 < iGeom && iGeom < nbTypes )
931 Threshold = SMESH + types[ iGeom ];
933 // is types complete? (compilation failure mains that enum GeometryType changed)
934 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
937 if (Type == "SMESH.FT_EntityType")
939 // set SMESH.EntityType instead of a numerical Threshold
940 const int nbTypes = SMESH::Entity_Last;
941 const char* types[] = {
942 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
943 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
944 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
945 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
946 "Entity_Pyramid", "Entity_Quad_Pyramid",
947 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
948 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
949 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
950 if ( -1 < iGeom && iGeom < nbTypes )
951 Threshold = SMESH + types[ iGeom ];
953 // is 'types' complete? (compilation failure mains that enum EntityType changed)
954 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
958 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
959 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
960 else if ( ThresholdStr.Length() != 2 )
961 aCommand->SetArg( 4, ThresholdStr );
962 else if ( ThresholdID.Length() != 2 )
963 aCommand->SetArg( 4, ThresholdID );
965 aCommand->SetArg( 4, Threshold );
966 // find the last not default arg
968 if ( Tolerance == dfltTol ) {
970 if ( BinaryOp == dfltFunctor ) {
972 if ( UnaryOp == dfltFunctor )
976 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
977 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
978 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
979 if ( Precision != dfltPreci )
981 TCollection_AsciiString crit = aCommand->GetResultValue();
982 aCommand->GetString() += "; ";
983 aCommand->GetString() += crit + ".Precision = " + Precision;
989 //================================================================================
991 * \brief Convert the command or remember it for later conversion
992 * \param theCommand - The python command calling a method of SMESH_Gen
994 //================================================================================
996 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
998 // there are methods to convert:
999 // CreateMesh( shape )
1000 // Concatenate( [mesh1, ...], ... )
1001 // CreateHypothesis( theHypType, theLibName )
1002 // Compute( mesh, geom )
1003 // Evaluate( mesh, geom )
1005 TCollection_AsciiString method = theCommand->GetMethod();
1007 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
1009 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1013 if ( method == "CreateMeshesFromUNV" ||
1014 method == "CreateMeshesFromSTL" ||
1015 method == "CopyMesh" ) // command result is a mesh
1017 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1021 if ( method == "CreateMeshesFromMED" ||
1022 method == "CreateMeshesFromSAUV"||
1023 method == "CreateMeshesFromCGNS" ||
1024 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1026 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1027 std::list< _pyID >::iterator meshID = meshIDs.begin();
1028 for ( ; meshID != meshIDs.end(); ++meshID )
1030 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1033 if ( method == "CreateMeshesFromGMF" )
1035 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1036 // CreateMeshesFromGMF( theFileName )
1037 _AString file = theCommand->GetArg(1);
1038 theCommand->RemoveArgs();
1039 theCommand->SetArg( 1, file );
1042 if ( method == "CopyMeshWithGeom" )
1044 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1045 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1049 // CreateHypothesis()
1050 if ( method == "CreateHypothesis" )
1052 // issue 199929, remove standard library name (default parameter)
1053 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1054 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1055 // keep the first argument
1056 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1057 theCommand->RemoveArgs();
1058 theCommand->SetArg( 1, arg );
1061 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1062 CheckObjectIsReCreated( hyp );
1063 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1068 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1069 if ( method == "Compute" )
1071 const _pyID& meshID = theCommand->GetArg( 1 );
1072 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1073 if ( id_mesh != myMeshes.end() ) {
1074 theCommand->SetObject( meshID );
1075 theCommand->RemoveArgs();
1076 id_mesh->second->Process( theCommand );
1077 id_mesh->second->AddProcessedCmd( theCommand );
1082 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1083 if ( method == "Evaluate" )
1085 const _pyID& meshID = theCommand->GetArg( 1 );
1086 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1087 if ( id_mesh != myMeshes.end() ) {
1088 theCommand->SetObject( meshID );
1089 _pyID geom = theCommand->GetArg( 2 );
1090 theCommand->RemoveArgs();
1091 theCommand->SetArg( 1, geom );
1092 id_mesh->second->AddProcessedCmd( theCommand );
1097 // objects erasing creation command if no more its commands invoked:
1098 // SMESH_Pattern, FilterManager
1099 if ( method == "GetPattern" ||
1100 method == "CreateFilterManager" ||
1101 method == "CreateMeasurements" )
1103 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1104 if ( !AddObject( obj ) )
1105 theCommand->Clear(); // already created
1107 // Concatenate( [mesh1, ...], ... )
1108 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1110 // OLD IDL: ( meshes, uniteGroups, toMerge, tol )
1111 // IDL: ( meshes, uniteGroups, toMerge, tol, meshToAppendTo )
1112 // PY: ( meshes, uniteGroups, toMerge, tol, allGroups=False, name="", meshToAppendTo=None )
1113 _pyID appendMesh = theCommand->GetArg( 5 );
1114 if ( method == "ConcatenateWithGroups" ) {
1115 theCommand->SetMethod( "Concatenate" );
1116 theCommand->SetArg( 5, "True" );
1119 theCommand->SetArg( 5, "False" );
1121 if ( !appendMesh.IsEmpty() && appendMesh != "None" )
1123 appendMesh.Insert( 1, "meshToAppendTo=" );
1124 theCommand->SetArg( theCommand->GetNbArgs() + 1, appendMesh );
1126 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1128 AddMeshAccessorMethod( theCommand );
1130 else if ( method == "SetName" ) // SetName(obj,name)
1132 // store theCommand as one of object commands to erase it along with the object
1133 const _pyID& objID = theCommand->GetArg( 1 );
1134 Handle(_pyObject) obj = FindObject( objID );
1135 if ( !obj.IsNull() )
1136 obj->AddProcessedCmd( theCommand );
1139 // Replace name of SMESH_Gen
1141 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1142 static TStringSet smeshpyMethods;
1143 if ( smeshpyMethods.empty() ) {
1144 const char * names[] =
1145 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1146 "GetPattern","GetSubShapesId",
1147 "" }; // <- mark of array end
1148 smeshpyMethods.Insert( names );
1150 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1151 // smeshgen.Method() --> smesh.Method()
1152 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1154 // smeshgen.Method() --> smesh.Method()
1155 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1158 //================================================================================
1160 * \brief Convert the remembered commands
1162 //================================================================================
1164 void _pyGen::Flush()
1166 // create an empty command
1167 myLastCommand = new _pyCommand();
1169 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1170 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1171 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1173 if ( IsToKeepAllCommands() ) // historical dump
1175 // set myIsPublished = true to all objects
1176 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1177 id_mesh->second->SetRemovedFromStudy( false );
1178 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1179 id_hyp->second->SetRemovedFromStudy( false );
1180 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1181 id_obj->second->SetRemovedFromStudy( false );
1185 // let hypotheses find referred objects in order to prevent clearing
1186 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1187 list< Handle(_pyMesh) > fatherMeshes;
1188 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1189 if ( !id_hyp->second.IsNull() )
1190 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1192 // set myIsPublished = false to all objects depending on
1193 // meshes built on a removed geometry
1194 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1195 if ( id_mesh->second->IsNotGeomPublished() )
1196 id_mesh->second->SetRemovedFromStudy( true );
1199 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1200 if ( ! id_mesh->second.IsNull() )
1201 id_mesh->second->Flush();
1204 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1205 if ( !id_hyp->second.IsNull() ) {
1206 id_hyp->second->Flush();
1207 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1208 if ( !id_hyp->second->IsWrapped() )
1209 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1212 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1213 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1214 for ( ; robj != myOrderedObjects.rend(); ++robj )
1215 if ( ! robj->IsNull() )
1217 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1218 for ( ; obj != myOrderedObjects.end(); ++obj )
1219 if ( ! obj->IsNull() )
1222 myLastCommand->SetOrderNb( ++myNbCommands );
1223 myCommands.push_back( myLastCommand );
1226 //================================================================================
1228 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1229 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1231 //================================================================================
1233 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1235 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1236 // for ( ; id_obj != myObjects.end(); ++id_obj )
1238 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1239 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1241 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1242 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1244 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1245 // list< _pyID >::iterator id = idList.begin();
1246 // for ( ; id != idList.end(); ++id )
1247 // if ( id_obj->first == *id )
1248 // // _pySubMesh::Process() does what we need
1249 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1254 //================================================================================
1256 * \brief Clean commands of removed objects depending on myIsPublished flag
1258 //================================================================================
1260 void _pyGen::ClearCommands()
1262 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1263 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1264 id_mesh->second->ClearCommands();
1266 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1267 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1268 if ( !id_hyp->second.IsNull() )
1269 id_hyp->second->ClearCommands();
1271 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1272 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1273 for ( ; robj != myOrderedObjects.rend(); ++robj )
1274 if ( ! robj->IsNull() )
1275 (*robj)->ClearCommands();
1276 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1277 for ( ; obj != myOrderedObjects.end(); ++obj )
1278 if ( ! obj->IsNull() )
1279 (*obj)->ClearCommands();
1282 //================================================================================
1284 * \brief Release mutual handles of objects
1286 //================================================================================
1290 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1291 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1292 id_mesh->second->Free();
1295 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1296 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1297 id_ed->second->Free();
1298 myMeshEditors.clear();
1300 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1301 for ( ; id_obj != myObjects.end(); ++id_obj )
1302 id_obj->second->Free();
1305 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1306 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1307 if ( !id_hyp->second.IsNull() )
1308 id_hyp->second->Free();
1311 myFile2ExportedMesh.clear();
1313 //myKeepAgrCmdsIDs.Print();
1316 //================================================================================
1318 * \brief Add access method to mesh that is an argument
1319 * \param theCmd - command to add access method
1320 * \retval bool - true if added
1322 //================================================================================
1324 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1327 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1328 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1329 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1335 //================================================================================
1337 * \brief Add access method to algo that is an object or an argument
1338 * \param theCmd - command to add access method
1339 * \retval bool - true if added
1341 //================================================================================
1343 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1346 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1347 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1348 if ( !id_hyp->second.IsNull() &&
1349 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1350 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1351 id_hyp->second->AccessorMethod() ))
1357 //================================================================================
1359 * \brief Find hypothesis by ID (entry)
1360 * \param theHypID - The hypothesis ID
1361 * \retval Handle(_pyHypothesis) - The found hypothesis
1363 //================================================================================
1365 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1367 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1368 if ( id_hyp != myHypos.end() &&
1369 !id_hyp->second.IsNull() &&
1370 theHypID == id_hyp->second->GetID() )
1371 return id_hyp->second;
1372 return Handle(_pyHypothesis)();
1375 //================================================================================
1377 * \brief Find algorithm able to create a hypothesis
1378 * \param theGeom - The shape ID the algorithm was created on
1379 * \param theMesh - The mesh ID that created the algorithm
1380 * \param theHypothesis - The hypothesis the algorithm should be able to create
1381 * \retval Handle(_pyHypothesis) - The found algo
1383 //================================================================================
1385 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1386 const Handle(_pyHypothesis)& theHypothesis )
1388 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1389 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1390 if ( !id_hyp->second.IsNull() &&
1391 id_hyp->second->IsAlgo() &&
1392 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1393 id_hyp->second->GetGeom() == theGeom &&
1394 id_hyp->second->GetMesh() == theMesh )
1395 return id_hyp->second;
1396 return Handle(_pyHypothesis)();
1399 //================================================================================
1401 * \brief Find subMesh by ID (entry)
1402 * \param theSubMeshID - The subMesh ID
1403 * \retval Handle(_pySubMesh) - The found subMesh
1405 //================================================================================
1407 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1409 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1410 if ( id_subMesh != myObjects.end() )
1411 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1412 return Handle(_pySubMesh)();
1416 //================================================================================
1418 * \brief Change order of commands in the script
1419 * \param theCmd1 - One command
1420 * \param theCmd2 - Another command
1422 //================================================================================
1424 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1426 list< Handle(_pyCommand) >::iterator pos1, pos2;
1427 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1428 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1429 myCommands.insert( pos1, theCmd2 );
1430 myCommands.insert( pos2, theCmd1 );
1431 myCommands.erase( pos1 );
1432 myCommands.erase( pos2 );
1434 int nb1 = theCmd1->GetOrderNb();
1435 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1436 theCmd2->SetOrderNb( nb1 );
1437 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1438 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1441 //================================================================================
1443 * \brief Set one command after the other
1444 * \param theCmd - Command to move
1445 * \param theAfterCmd - Command ater which to insert the first one
1447 //================================================================================
1449 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1451 setNeighbourCommand( theCmd, theAfterCmd, true );
1454 //================================================================================
1456 * \brief Set one command before the other
1457 * \param theCmd - Command to move
1458 * \param theBeforeCmd - Command before which to insert the first one
1460 //================================================================================
1462 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1464 setNeighbourCommand( theCmd, theBeforeCmd, false );
1467 //================================================================================
1469 * \brief Set one command before or after the other
1470 * \param theCmd - Command to move
1471 * \param theOtherCmd - Command ater or before which to insert the first one
1473 //================================================================================
1475 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1476 Handle(_pyCommand)& theOtherCmd,
1477 const bool theIsAfter )
1479 list< Handle(_pyCommand) >::iterator pos;
1480 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1481 myCommands.erase( pos );
1482 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1483 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1486 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1487 (*pos)->SetOrderNb( i++ );
1490 //================================================================================
1492 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1494 //================================================================================
1496 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1498 // No more needed after adding _pyObject::myArgCommands
1500 // const char filterPrefix[] = "aFilter0x";
1501 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1504 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1506 // const _AString & arg = theCommand->GetArg( i );
1507 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1508 // if ( arg.Search( filterPrefix ) != 1 )
1511 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1512 // if ( !filter.IsNull() )
1514 // filter->AddUser( user );
1515 // if ( !filter->GetNewID().IsEmpty() )
1516 // theCommand->SetArg( i, filter->GetNewID() );
1521 //================================================================================
1523 * \brief Set command be last in list of commands
1524 * \param theCmd - Command to be last
1526 //================================================================================
1528 Handle(_pyCommand)& _pyGen::GetLastCommand()
1530 return myLastCommand;
1533 //================================================================================
1535 * \brief Set method to access to object wrapped with python class
1536 * \param theID - The wrapped object entry
1537 * \param theMethod - The accessor method
1539 //================================================================================
1541 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1543 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1546 //================================================================================
1548 * \brief Generated new ID for object and assign with existing name
1549 * \param theID - ID of existing object
1551 //================================================================================
1553 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1558 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1560 while ( myObjectNames.IsBound( aNewID ) );
1562 if ( myObjectNames.IsBound( theID ) )
1563 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1565 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1569 //================================================================================
1571 * \brief Stores theObj in myObjects
1573 //================================================================================
1575 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1577 if ( theObj.IsNull() ) return false;
1579 CheckObjectIsReCreated( theObj );
1583 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1584 add = myMeshes.insert( make_pair( theObj->GetID(),
1585 Handle(_pyMesh)::DownCast( theObj ))).second;
1587 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1588 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1589 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1592 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1593 if ( add ) myOrderedObjects.push_back( theObj );
1598 //================================================================================
1600 * \brief Erases an existing object with the same ID. This method should be called
1601 * before storing theObj in _pyGen
1603 //================================================================================
1605 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1607 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1610 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1611 Handle(_pyObject) existing;
1613 existing = FindHyp( theObj->GetID() );
1615 existing = FindObject( theObj->GetID() );
1616 if ( !existing.IsNull() && existing != theObj )
1618 existing->SetRemovedFromStudy( true );
1619 existing->ClearCommands();
1622 if ( myHypos.count( theObj->GetID() ))
1623 myHypos.erase( theObj->GetID() );
1625 else if ( myMeshes.count( theObj->GetID() ))
1627 myMeshes.erase( theObj->GetID() );
1629 else if ( myObjects.count( theObj->GetID() ))
1631 myObjects.erase( theObj->GetID() );
1636 //================================================================================
1638 * \brief Re-register an object with other ID to make it Process() commands of
1639 * other object having this ID
1641 //================================================================================
1643 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1645 if ( theObj.IsNull() ) return;
1647 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1648 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1650 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1651 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1654 myObjects.insert( make_pair( theID, theObj ));
1657 //================================================================================
1659 * \brief Finds a _pyObject by ID
1661 //================================================================================
1663 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1666 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1667 if ( id_obj != myObjects.end() )
1668 return id_obj->second;
1671 _pyGen* me = const_cast< _pyGen* >( this );
1672 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1673 if ( id_obj != myMeshes.end() )
1674 return id_obj->second;
1677 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1678 // if ( id_obj != myMeshEditors.end() )
1679 // return id_obj->second;
1681 return Handle(_pyObject)();
1684 //================================================================================
1686 * \brief Check if a study entry is under GEOM component
1688 //================================================================================
1690 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1692 bool isGeom = myGeomIDNb && myGeomIDIndex <= theObjID.Length() &&
1693 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb;
1694 bool isShaper = myShaperIDNb && myShaperIDIndex <= theObjID.Length() &&
1695 int( theObjID.Value( myShaperIDIndex )) == myShaperIDNb;
1696 return ((isGeom || isShaper) && _pyCommand::IsStudyEntry( theObjID ));
1699 //================================================================================
1701 * \brief Returns true if an object is not present in a study
1703 //================================================================================
1705 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1707 if ( theObjID.IsEmpty() ) return false;
1709 if ( myObjectNames.IsBound( theObjID ))
1710 return false; // SMESH object is in study
1712 // either the SMESH object is not in study or it is a GEOM object
1713 if ( IsGeomObject( theObjID ))
1715 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1716 if ( so->_is_nil() ) return true;
1717 CORBA::Object_var obj = so->GetObject();
1718 return CORBA::is_nil( obj );
1720 return true; // SMESH object not in study
1723 //================================================================================
1725 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1726 * this object is not dumped
1727 * \param [in] theObjID - entry of the object whose creation command was eliminated
1729 //================================================================================
1731 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1733 myRemovedObjIDs.insert( theObjID );
1736 //================================================================================
1738 * \brief Return reader of hypotheses of plugins
1740 //================================================================================
1742 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1744 if (myHypReader.IsNull() )
1745 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1751 //================================================================================
1753 * \brief Mesh created by SMESH_Gen
1755 //================================================================================
1757 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1758 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1760 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1761 myGeomNotInStudy = true;
1763 // convert my creation command --> smeshpy.Mesh(...)
1764 Handle(_pyCommand) creationCmd = GetCreationCmd();
1765 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1766 creationCmd->SetMethod( "Mesh" );
1767 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1770 //================================================================================
1772 * \brief Mesh created by SMESH_MeshEditor
1774 //================================================================================
1776 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1777 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1779 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1781 // this mesh depends on the exported mesh
1782 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1783 if ( !file.IsEmpty() )
1785 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1786 addFatherMesh( exportData.myMesh );
1787 if ( !exportData.myLastComputeCmd.IsNull() )
1789 // restore cleared Compute() by which the exported mesh was generated
1790 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1791 // protect that Compute() cmd from clearing
1792 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1793 exportData.myMesh->myLastComputeCmd.Nullify();
1797 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1799 // this mesh depends on concatenated meshes
1800 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1801 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1802 list< _pyID >::iterator meshID = idList.begin();
1803 for ( ; meshID != idList.end(); ++meshID )
1804 addFatherMesh( *meshID );
1806 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1808 // this mesh depends on a copied IdSource
1809 const _pyID& objID = theCreationCmd->GetArg( 1 );
1810 addFatherMesh( objID );
1812 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1813 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1814 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1816 // this mesh depends on a source mesh
1817 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1818 const _pyID& meshID = theCreationCmd->GetObject();
1819 addFatherMesh( meshID );
1822 // convert my creation command
1823 Handle(_pyCommand) creationCmd = GetCreationCmd();
1824 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1825 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1828 //================================================================================
1830 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1831 * \param theCommand - Engine method called for this mesh
1833 //================================================================================
1835 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1837 // some methods of SMESH_Mesh interface need special conversion
1838 // to methods of Mesh python class
1840 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1841 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1842 // 2. AddHypothesis(geom, hyp)
1843 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1844 // 3. CreateGroupFromGEOM(type, name, grp)
1845 // --> in Mesh.Group(grp, name="")
1846 // 4. ExportToMED(f, auto_groups, version)
1847 // --> in Mesh.ExportMED( f, auto_groups, version )
1850 const TCollection_AsciiString& method = theCommand->GetMethod();
1851 // ----------------------------------------------------------------------
1852 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1854 if ( !theGen->IsToKeepAllCommands() ) // !historical
1856 list< Handle(_pyHypothesis) >::iterator hyp;
1857 if ( !myLastComputeCmd.IsNull() )
1859 // check if the previously computed mesh has been edited,
1860 // if so then we do not clear the previous Compute()
1861 bool toClear = true;
1862 if ( myLastComputeCmd->GetMethod() == "Compute" )
1864 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1865 for ( ; e != myEditors.end() && toClear; ++e )
1867 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1868 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1869 if ( cmd != cmds.rend() &&
1870 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1876 // clear hyp commands called before myLastComputeCmd
1877 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1878 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1880 myLastComputeCmd->Clear();
1883 myLastComputeCmd = theCommand;
1885 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1886 (*hyp)->MeshComputed( myLastComputeCmd );
1890 // ----------------------------------------------------------------------
1891 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1893 if ( !theGen->IsToKeepAllCommands() ) // !historical
1896 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1897 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1898 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1900 if ( !myLastComputeCmd.IsNull() )
1902 list< Handle(_pyHypothesis) >::iterator hyp;
1903 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1904 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1906 myLastComputeCmd->Clear();
1909 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1910 for ( ; e != myEditors.end(); ++e )
1912 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1913 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1914 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1915 if ( !(*cmd)->IsEmpty() )
1917 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1921 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1924 // ----------------------------------------------------------------------
1925 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1926 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1927 if ( !subMesh.IsNull() ) {
1928 subMesh->SetCreator( this );
1929 mySubmeshes.push_back( subMesh );
1932 // ----------------------------------------------------------------------
1933 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1934 theCommand->Clear();
1936 // ----------------------------------------------------------------------
1937 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1938 myAddHypCmds.push_back( theCommand );
1940 const _pyID& hypID = theCommand->GetArg( 2 );
1941 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1942 if ( !hyp.IsNull() ) {
1943 myHypos.push_back( hyp );
1944 if ( hyp->GetMesh().IsEmpty() )
1945 hyp->SetMesh( this->GetID() );
1948 // ----------------------------------------------------------------------
1949 else if ( method == "CreateGroup" ||
1950 method == "CreateGroupFromGEOM" ||
1951 method == "CreateGroupFromFilter" ||
1952 method == "CreateDimGroup" )
1954 Handle(_pyGroup) group = new _pyGroup( theCommand );
1955 myGroups.push_back( group );
1956 theGen->AddObject( group );
1958 // ----------------------------------------------------------------------
1959 // update list of groups
1960 else if ( method == "GetGroups" )
1962 bool allGroupsRemoved = true;
1963 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1964 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1965 list< _pyID >::iterator grID = idList.begin();
1966 const size_t nbGroupsBefore = myGroups.size();
1967 Handle(_pyObject) obj;
1968 for ( ; grID != idList.end(); ++grID )
1970 obj = theGen->FindObject( *grID );
1973 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1974 theGen->AddObject( group );
1975 myGroups.push_back( group );
1978 if ( !obj->CanClear() )
1979 allGroupsRemoved = false;
1981 if ( nbGroupsBefore == myGroups.size() && !obj.IsNull() ) // no new _pyGroup created
1982 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1984 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1986 // check if the preceding command is Compute();
1987 // if GetGroups() is just after Compute(), this can mean that the groups
1988 // were created by some algorithm and hence Compute() should not be discarded
1989 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1990 std::list< Handle(_pyCommand) >::reverse_iterator cmd = cmdList.rbegin();
1991 while ( (*cmd)->GetMethod() == "GetGroups" )
1993 if ( myLastComputeCmd == (*cmd))
1994 // protect last Compute() from clearing by the next Compute()
1995 myLastComputeCmd.Nullify();
1998 // ----------------------------------------------------------------------
1999 // notify a group about full removal
2000 else if ( method == "RemoveGroupWithContents" ||
2001 method == "RemoveGroup")
2003 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
2004 const _pyID groupID = theCommand->GetArg( 1 );
2005 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
2006 if ( !grp.IsNull() )
2008 if ( method == "RemoveGroupWithContents" )
2009 grp->RemovedWithContents();
2010 // to clear RemoveGroup() if the group creation is cleared
2011 grp->AddProcessedCmd( theCommand );
2015 // ----------------------------------------------------------------------
2016 else if ( theCommand->MethodStartsFrom( "Export" ))
2018 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
2019 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
2020 method == "ExportMED" )
2022 theCommand->SetMethod( "ExportMED" );
2023 // filter out deprecated version parameter
2024 vector< _AString > args;
2025 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2026 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2027 args.push_back( theCommand->GetArg( i ) );
2029 theCommand->RemoveArgs();
2030 for ( unsigned int i = 0; i < args.size(); i++ )
2031 theCommand->SetArg( i+1, args[i] );
2032 if ( theCommand->GetNbArgs() == 4 )
2034 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2035 _AString autoDimension = theCommand->GetArg( 4 );
2036 theCommand->SetArg( 4, "None" );
2037 theCommand->SetArg( 5, autoDimension );
2040 else if ( method == "ExportCGNS" )
2041 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2042 _pyID partID = theCommand->GetArg( 1 );
2043 int nbArgs = theCommand->GetNbArgs();
2044 for ( int i = 2; i <= nbArgs; ++i )
2045 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2046 theCommand->SetArg( nbArgs, partID );
2048 else if ( method == "ExportGMF" )
2049 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2050 _pyID partID = theCommand->GetArg( 1 );
2051 _AString file = theCommand->GetArg( 2 );
2052 theCommand->RemoveArgs();
2053 theCommand->SetArg( 1, file );
2054 theCommand->SetArg( 2, partID );
2056 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2057 { // ExportPartTo*(part, ...) -> Export*(..., part)
2059 // remove "PartTo" from the method
2060 TCollection_AsciiString newMethod = method;
2061 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2062 theCommand->SetMethod( newMethod );
2063 // replace version parameter by minor
2064 std::list< _AString > args;
2065 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2066 if ( _FilterArg( theCommand->GetArg( i )))
2067 args.push_back( "minor=0");
2069 args.push_back( theCommand->GetArg( i ));
2071 // check the 1st arg meshPart, it must be SMESH_IDSource
2072 _AString meshPart = args.front();
2073 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2074 meshPart.Search( "Filter" ) > 0 ||
2075 meshPart.Search( "GetIDSource" ) > 0 ||
2076 meshPart.Search( "meshPart" ) > 0 )
2078 // set the 1st arg meshPart
2079 // - to 5th place for ExportMED command
2080 // - to last place for the rest commands
2081 std::list< _AString >::iterator newPos = args.end();
2082 if ( newMethod == "ExportMED" )
2083 std::advance( newPos = args.begin(), 5 );
2084 args.splice( newPos, args, args.begin() );
2086 std::list< _AString >::iterator a = args.begin();
2087 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2088 theCommand->SetArg( i, *a );
2090 // remember file name
2091 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2092 ExportedMeshData( this, myLastComputeCmd ));
2094 // ----------------------------------------------------------------------
2095 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2097 _pyID hypID = theCommand->GetArg( 2 );
2098 _pyID geomID = theCommand->GetArg( 1 );
2099 bool isLocal = ( geomID != GetGeom() );
2101 // check if this mesh still has corresponding addition command
2102 Handle(_pyCommand) addCmd;
2103 list< Handle(_pyCommand) >::iterator cmd;
2104 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2105 for ( int i = 0; i < 2; ++i )
2107 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2108 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2110 bool sameHyp = true;
2111 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2112 sameHyp = false; // other hyp
2113 if ( (*cmd)->GetNbArgs() == 2 &&
2114 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2115 sameHyp = false; // other geom
2116 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2117 sameHyp = false; // other geom
2121 cmd = addHypCmds.erase( cmd );
2122 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2124 theCommand->Clear();
2128 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2129 addCmd->RemoveArgs();
2130 addCmd->SetArg( 1, hypID );
2132 addCmd->SetArg( 2, geomID );
2141 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2142 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2143 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2144 _pyID geom = theCommand->GetArg( 1 );
2145 theCommand->RemoveArgs();
2146 theCommand->SetArg( 1, hypID );
2147 if ( geom != GetGeom() )
2148 theCommand->SetArg( 2, geom );
2150 // remove hyp from myHypos
2151 myHypos.remove( hyp );
2153 // check for SubMesh order commands
2154 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2156 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2157 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2158 // commands are moved at the end of the script
2159 TCollection_AsciiString subIDs =
2160 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2161 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2162 list< _pyID >::iterator subID = idList.begin();
2163 for ( ; subID != idList.end(); ++subID )
2165 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2166 if ( !subMesh.IsNull() )
2167 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2170 // add accessor method if necessary
2173 if ( NeedMeshAccess( theCommand ))
2174 // apply theCommand to the mesh wrapped by smeshpy mesh
2175 AddMeshAccess( theCommand );
2179 //================================================================================
2181 * \brief Return True if addition of accesor method is needed
2183 //================================================================================
2185 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2187 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2188 // so no conversion is needed for them at all:
2189 static TStringSet sameMethods;
2190 if ( sameMethods.empty() ) {
2191 const char * names[] =
2192 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2193 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2194 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2195 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2196 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2197 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2198 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2199 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2200 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2201 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2202 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2203 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2204 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2205 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2206 ,"" }; // <- mark of end
2207 sameMethods.Insert( names );
2210 return !sameMethods.Contains( theCommand->GetMethod() );
2213 //================================================================================
2215 * \brief Convert creation and addition of all algos and hypos
2217 //================================================================================
2219 void _pyMesh::Flush()
2222 // get the meshes this mesh depends on via hypotheses
2223 list< Handle(_pyMesh) > fatherMeshes;
2224 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2225 for ( ; hyp != myHypos.end(); ++hyp )
2226 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2227 myGeomNotInStudy = true;
2229 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2230 for ( ; m != fatherMeshes.end(); ++m )
2231 addFatherMesh( *m );
2232 // if ( removedGeom )
2233 // SetRemovedFromStudy(); // as referred geometry not in study
2235 if ( myGeomNotInStudy )
2238 list < Handle(_pyCommand) >::iterator cmd;
2240 // try to convert algo addition like this:
2241 // mesh.AddHypothesis( geom, ALGO ) --> ALGO = mesh.Algo()
2242 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2244 Handle(_pyCommand) addCmd = *cmd;
2246 _pyID algoID = addCmd->GetArg( 2 );
2247 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2248 if ( algo.IsNull() || !algo->IsAlgo() )
2251 // check and create new algorithm instance if it is already wrapped
2252 if ( algo->IsWrapped() ) {
2253 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2254 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2255 TCollection_AsciiString( " = " ) + theGen->GetID() +
2256 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2257 TCollection_AsciiString( "\" )" );
2259 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2260 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2261 if ( !newAlgo.IsNull() ) {
2262 newAlgo->Assign( algo, this->GetID() );
2263 newAlgo->SetCreationCmd( newCmd );
2265 // set algorithm creation
2266 theGen->SetCommandBefore( newCmd, addCmd );
2267 myHypos.push_back( newAlgo );
2268 if ( !myLastComputeCmd.IsNull() &&
2269 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2270 newAlgo->MeshComputed( myLastComputeCmd );
2275 _pyID geom = addCmd->GetArg( 1 );
2276 bool isLocalAlgo = ( geom != GetGeom() );
2279 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2281 // wrapped algo is created after mesh creation
2282 GetCreationCmd()->AddDependantCmd( addCmd );
2284 if ( isLocalAlgo ) {
2285 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2286 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2287 TCollection_AsciiString( "geom=" ) + geom );
2288 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2289 list < Handle(_pySubMesh) >::iterator smIt;
2290 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2291 Handle(_pySubMesh) subMesh = *smIt;
2292 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2293 if ( geom == subCmd->GetArg( 1 )) {
2294 subCmd->SetObject( algo->GetID() );
2295 subCmd->RemoveArgs();
2296 subMesh->SetCreator( algo );
2301 else // KO - ALGO was already created
2303 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2304 addCmd->RemoveArgs();
2305 addCmd->SetArg( 1, algoID );
2307 addCmd->SetArg( 2, geom );
2308 myNotConvertedAddHypCmds.push_back( addCmd );
2312 // try to convert hypo addition like this:
2313 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2314 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2316 Handle(_pyCommand) addCmd = *cmd;
2317 _pyID hypID = addCmd->GetArg( 2 );
2318 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2319 if ( hyp.IsNull() || hyp->IsAlgo() )
2321 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2323 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2324 _pyID geom = addCmd->GetArg( 1 );
2325 addCmd->RemoveArgs();
2326 addCmd->SetArg( 1, hypID );
2327 if ( geom != GetGeom() )
2328 addCmd->SetArg( 2, geom );
2329 myNotConvertedAddHypCmds.push_back( addCmd );
2333 myAddHypCmds.clear();
2334 mySubmeshes.clear();
2337 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2338 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2342 //================================================================================
2344 * \brief Sets myIsPublished of me and of all objects depending on me.
2346 //================================================================================
2348 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2350 _pyObject::SetRemovedFromStudy(isRemoved);
2352 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2353 for ( ; sm != mySubmeshes.end(); ++sm )
2354 (*sm)->SetRemovedFromStudy(isRemoved);
2356 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2357 for ( ; gr != myGroups.end(); ++gr )
2358 (*gr)->SetRemovedFromStudy(isRemoved);
2360 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2361 for ( ; m != myChildMeshes.end(); ++m )
2362 (*m)->SetRemovedFromStudy(isRemoved);
2364 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2365 for ( ; e != myEditors.end(); ++e )
2366 (*e)->SetRemovedFromStudy(isRemoved);
2369 //================================================================================
2371 * \brief Return true if none of myChildMeshes is in study
2373 //================================================================================
2375 bool _pyMesh::CanClear()
2380 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2381 for ( ; m != myChildMeshes.end(); ++m )
2382 if ( !(*m)->CanClear() )
2388 //================================================================================
2390 * \brief Clear my commands and commands of mesh editor
2392 //================================================================================
2394 void _pyMesh::ClearCommands()
2400 // mark all sub-objects as not removed, except child meshes
2401 list< Handle(_pyMesh) > children;
2402 children.swap( myChildMeshes );
2403 SetRemovedFromStudy( false );
2404 children.swap( myChildMeshes );
2408 _pyObject::ClearCommands();
2410 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2411 for ( ; sm != mySubmeshes.end(); ++sm )
2412 (*sm)->ClearCommands();
2414 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2415 for ( ; gr != myGroups.end(); ++gr )
2416 (*gr)->ClearCommands();
2418 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2419 for ( ; e != myEditors.end(); ++e )
2420 (*e)->ClearCommands();
2423 //================================================================================
2425 * \brief Add a father mesh by ID
2427 //================================================================================
2429 void _pyMesh::addFatherMesh( const _pyID& meshID )
2431 if ( !meshID.IsEmpty() && meshID != GetID() )
2432 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2435 //================================================================================
2437 * \brief Add a father mesh
2439 //================================================================================
2441 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2443 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2445 //myFatherMeshes.push_back( mesh );
2446 mesh->myChildMeshes.push_back( this );
2448 // protect last Compute() from clearing by the next Compute()
2449 mesh->myLastComputeCmd.Nullify();
2453 //================================================================================
2455 * \brief MeshEditor convert its commands to ones of mesh
2457 //================================================================================
2459 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2460 _pyObject( theCreationCmd )
2462 myMesh = theCreationCmd->GetObject();
2463 myCreationCmdStr = theCreationCmd->GetString();
2464 theCreationCmd->Clear();
2466 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2467 if ( !mesh.IsNull() )
2468 mesh->AddEditor( this );
2471 //================================================================================
2473 * \brief convert its commands to ones of mesh
2475 //================================================================================
2477 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2479 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2480 // commands calling these methods are converted to calls of Mesh methods without
2481 // additional modifs, only object is changed from MeshEditor to Mesh.
2482 static TStringSet sameMethods;
2483 if ( sameMethods.empty() ) {
2484 const char * names[] = {
2485 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2486 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2487 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2488 "MoveNode", "MoveClosestNodeToPoint",
2489 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2490 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2491 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2492 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2493 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2494 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2495 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2496 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2497 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2498 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject","Offset",
2499 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2500 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2501 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2502 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2503 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2504 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2505 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2506 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2507 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2508 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2509 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2510 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2511 ,"" }; // <- mark of the end
2512 sameMethods.Insert( names );
2515 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2516 TStringMap diffMethods;
2517 if ( diffMethods.empty() ) {
2518 const char * orig2newName[] = {
2519 // original name --------------> new name
2520 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2521 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2522 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2523 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2524 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2525 ""};// <- mark of the end
2526 diffMethods.Insert( orig2newName );
2529 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2530 // only by last two arguments
2531 static TStringSet diffLastTwoArgsMethods;
2532 if (diffLastTwoArgsMethods.empty() ) {
2533 const char * names[] = {
2534 "MirrorMakeGroups","MirrorObjectMakeGroups",
2535 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2536 "RotateMakeGroups","RotateObjectMakeGroups",
2537 ""};// <- mark of the end
2538 diffLastTwoArgsMethods.Insert( names );
2541 // only a method name is to change?
2542 const TCollection_AsciiString & method = theCommand->GetMethod();
2543 bool isPyMeshMethod = sameMethods.Contains( method );
2544 if ( !isPyMeshMethod )
2546 TCollection_AsciiString newMethod = diffMethods.Value( method );
2547 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2548 theCommand->SetMethod( newMethod );
2550 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2551 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2553 isPyMeshMethod = true;
2554 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2555 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2558 if ( !isPyMeshMethod )
2560 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2561 // functions with the flag "theMakeGroups = True" like:
2562 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2563 int pos = method.Search("MakeGroups");
2566 isPyMeshMethod = true;
2567 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2568 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2570 // 1. Remove "MakeGroups" from the Command
2571 TCollection_AsciiString aMethod = theCommand->GetMethod();
2572 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2575 pos = pos-2; //Remove "0D" from the Command too
2576 aMethod.Trunc(pos-1);
2577 theCommand->SetMethod(aMethod);
2579 // 2. And add last "True" argument(s)
2580 while(nbArgsToAdd--)
2581 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2582 if( is0DmethId || is0DmethObj )
2583 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2587 // ExtrusionSweep0D() -> ExtrusionSweep()
2588 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2589 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2590 method == "ExtrusionSweepObject0D" ))
2592 isPyMeshMethod = true;
2593 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2594 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2595 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2598 // DoubleNode...New(...) -> DoubleNode...(...,True)
2599 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2600 method == "DoubleNodeElemGroupsNew" ||
2601 method == "DoubleNodeGroupNew" ||
2602 method == "DoubleNodeGroupsNew" ||
2603 method == "DoubleNodeElemGroup2New" ||
2604 method == "DoubleNodeElemGroups2New"))
2606 isPyMeshMethod = true;
2607 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2608 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2609 if ( excessLen == 3 )
2611 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2613 else if ( theCommand->GetArg(4) == "0" ||
2614 theCommand->GetArg(5) == "0" )
2616 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2617 // Group = DoubleNodeGroup2New(,,,False, True)
2618 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2619 theCommand->SetResultValue( groupID );
2622 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2623 // FindElementsByPoint(x, y, z, elementType, meshPart)
2624 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2626 isPyMeshMethod = true;
2627 theCommand->SetMethod( "FindElementsByPoint" );
2628 // make the 1st arg be the last one
2629 _pyID partID = theCommand->GetArg( 1 );
2630 int nbArgs = theCommand->GetNbArgs();
2631 for ( int i = 2; i <= nbArgs; ++i )
2632 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2633 theCommand->SetArg( nbArgs, partID );
2635 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2636 if ( !isPyMeshMethod && method == "Reorient2D" )
2638 isPyMeshMethod = true;
2639 _AString mesh = theCommand->GetArg( 1 );
2640 _AString dir = theCommand->GetArg( 2 );
2641 _AString face = theCommand->GetArg( 3 );
2642 _AString point = theCommand->GetArg( 4 );
2643 theCommand->RemoveArgs();
2644 theCommand->SetArg( 1, mesh );
2645 theCommand->SetArg( 2, dir );
2646 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2647 theCommand->SetArg( 3, point );
2649 theCommand->SetArg( 3, face );
2652 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2654 isPyMeshMethod = true;
2655 int crit_arg = theCommand->GetNbArgs();
2656 const _AString& crit = theCommand->GetArg(crit_arg);
2657 if (crit.Search("MaxElementLength2D") != -1)
2658 theCommand->SetArg(crit_arg, "");
2661 if ( isPyMeshMethod )
2663 theCommand->SetObject( myMesh );
2667 // editor creation command is needed only if any editor function is called
2668 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2669 if ( !myCreationCmdStr.IsEmpty() ) {
2670 GetCreationCmd()->GetString() = myCreationCmdStr;
2671 myCreationCmdStr.Clear();
2676 //================================================================================
2678 * \brief Return true if my mesh can be removed
2680 //================================================================================
2682 bool _pyMeshEditor::CanClear()
2684 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2685 return mesh.IsNull() ? true : mesh->CanClear();
2688 //================================================================================
2690 * \brief _pyHypothesis constructor
2691 * \param theCreationCmd -
2693 //================================================================================
2695 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2696 _pyObject( theCreationCmd ), myCurCrMethod(0)
2698 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2701 //================================================================================
2703 * \brief Creates algorithm or hypothesis
2704 * \param theCreationCmd - The engine command creating a hypothesis
2705 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2707 //================================================================================
2709 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2711 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2712 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2714 Handle(_pyHypothesis) hyp, algo;
2717 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2718 if ( hypTypeQuoted.IsEmpty() )
2721 TCollection_AsciiString hypType =
2722 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2724 algo = new _pyAlgorithm( theCreationCmd );
2725 hyp = new _pyHypothesis( theCreationCmd );
2727 if ( hypType == "NumberOfSegments" ) {
2728 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2729 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2730 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2731 hyp->AddArgMethod( "SetNumberOfSegments" );
2732 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2733 hyp->AddArgMethod( "SetScaleFactor" );
2734 hyp->AddArgMethod( "SetReversedEdges" );
2735 // same for ""CompositeSegment_1D:
2736 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2737 hyp->AddArgMethod( "SetNumberOfSegments" );
2738 hyp->AddArgMethod( "SetScaleFactor" );
2739 hyp->AddArgMethod( "SetReversedEdges" );
2741 else if ( hypType == "SegmentLengthAroundVertex" ) {
2742 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2743 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2744 hyp->AddArgMethod( "SetLength" );
2745 // same for ""CompositeSegment_1D:
2746 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2747 hyp->AddArgMethod( "SetLength" );
2749 else if ( hypType == "LayerDistribution2D" ) {
2750 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2751 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2753 else if ( hypType == "LayerDistribution" ) {
2754 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2755 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2757 else if ( hypType == "CartesianParameters3D" ) {
2758 hyp = new _pyComplexParamHypo( theCreationCmd );
2759 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2760 for ( int iArg = 0; iArg < 4; ++iArg )
2761 hyp->setCreationArg( iArg+1, "[]");
2762 hyp->AddAccumulativeMethod( "SetGrid" );
2763 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2767 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2770 return algo->IsValid() ? algo : hyp;
2773 //================================================================================
2775 * \brief Returns true if addition of this hypothesis to a given mesh can be
2776 * wrapped into hypothesis creation
2778 //================================================================================
2780 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2782 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2784 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2785 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2791 //================================================================================
2793 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2794 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2795 * \param theAlgo - The algo that can create this hypo
2796 * \retval bool - false if the command can't be converted
2798 //================================================================================
2800 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2801 const _pyID& theMesh)
2803 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2805 if ( !IsWrappable( theMesh ))
2808 myGeom = theCmd->GetArg( 1 );
2810 Handle(_pyHypothesis) algo;
2812 // find algo created on myGeom in theMesh
2813 algo = theGen->FindAlgo( myGeom, theMesh, this );
2814 if ( algo.IsNull() )
2816 // attach hypothesis creation command to be after algo creation command
2817 // because it can be new created instance of algorithm
2818 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2822 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2823 theCmd->SetResultValue( GetID() );
2824 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2825 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2826 // set args (geom will be set by _pyMesh calling this method)
2827 theCmd->RemoveArgs();
2828 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2829 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2830 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2832 theCmd->SetArg( i+1, "[]");
2834 // set a new creation command
2835 GetCreationCmd()->Clear();
2836 // replace creation command by wrapped instance
2837 // please note, that hypothesis attaches to algo creation command (see upper)
2838 SetCreationCmd( theCmd );
2841 // clear commands setting arg values
2842 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2843 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2846 // set unknown arg commands after hypo creation
2847 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2848 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2849 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2850 afterCmd->AddDependantCmd( *cmd );
2856 //================================================================================
2858 * \brief Remember hypothesis parameter values
2859 * \param theCommand - The called hypothesis method
2861 //================================================================================
2863 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2865 ASSERT( !myIsAlgo );
2866 if ( !theGen->IsToKeepAllCommands() )
2867 rememberCmdOfParameter( theCommand );
2869 bool usedCommand = false;
2870 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2871 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2873 CreationMethod& crMethod = type2meth->second;
2874 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2875 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2877 myArgCommands.push_back( theCommand );
2879 while ( crMethod.myArgs.size() < i+1 )
2880 crMethod.myArgs.push_back( "None" );
2881 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2886 myUnusedCommands.push_back( theCommand );
2889 //================================================================================
2891 * \brief Finish conversion
2893 //================================================================================
2895 void _pyHypothesis::Flush()
2899 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2900 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2901 // Add access to a wrapped mesh
2902 theGen->AddMeshAccessorMethod( *cmd );
2903 // Add access to a wrapped algorithm
2904 theGen->AddAlgoAccessorMethod( *cmd );
2906 cmd = myUnusedCommands.begin();
2907 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2908 // Add access to a wrapped mesh
2909 theGen->AddMeshAccessorMethod( *cmd );
2910 // Add access to a wrapped algorithm
2911 theGen->AddAlgoAccessorMethod( *cmd );
2914 // forget previous hypothesis modifications
2915 myArgCommands.clear();
2916 myUnusedCommands.clear();
2919 //================================================================================
2921 * \brief clear creation, arg and unknown commands
2923 //================================================================================
2925 void _pyHypothesis::ClearAllCommands()
2927 GetCreationCmd()->Clear();
2928 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2929 for ( ; cmd != myArgCommands.end(); ++cmd )
2931 cmd = myUnusedCommands.begin();
2932 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2937 //================================================================================
2939 * \brief Assign fields of theOther to me except myIsWrapped
2941 //================================================================================
2943 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2944 const _pyID& theMesh )
2946 // myCreationCmd = theOther->myCreationCmd;
2947 myIsAlgo = theOther->myIsAlgo;
2948 myIsWrapped = false;
2949 myGeom = theOther->myGeom;
2951 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2952 myAccumulativeMethods = theOther->myAccumulativeMethods;
2953 //myUnusedCommands = theOther->myUnusedCommands;
2954 // init myCurCrMethod
2955 GetCreationMethod( theOther->GetAlgoType() );
2958 //================================================================================
2960 * \brief Analyze my erasability depending on myReferredObjs
2962 //================================================================================
2964 bool _pyHypothesis::CanClear()
2968 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2969 for ( ; obj != myReferredObjs.end(); ++obj )
2970 if ( (*obj)->CanClear() )
2977 //================================================================================
2979 * \brief Clear my commands depending on usage by meshes
2981 //================================================================================
2983 void _pyHypothesis::ClearCommands()
2985 // if ( !theGen->IsToKeepAllCommands() )
2987 // bool isUsed = false;
2988 // int lastComputeOrder = 0;
2989 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2990 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2991 // if ( ! (*cmd)->IsEmpty() )
2994 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2995 // lastComputeOrder = (*cmd)->GetOrderNb();
2999 // SetRemovedFromStudy( true );
3003 // // clear my commands invoked after lastComputeOrder
3004 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3005 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3007 // // list< Handle(_pyCommand)> & cmds = m2c->second;
3008 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
3009 // // cmds.back()->Clear();
3013 _pyObject::ClearCommands();
3016 //================================================================================
3018 * \brief Find arguments that are objects like mesh, group, geometry
3019 * \param meshes - referred meshes (directly or indirrectly)
3020 * \retval bool - false if a referred geometry is not in the study
3022 //================================================================================
3024 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3026 if ( IsAlgo() ) return true;
3028 bool geomPublished = true;
3029 vector< _AString > args;
3030 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3031 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3033 CreationMethod& crMethod = type2meth->second;
3034 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3036 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3037 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3038 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3039 args.push_back( (*cmd)->GetArg( nb ));
3042 for ( size_t i = 0; i < args.size(); ++i )
3044 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3045 if ( idList.empty() && !args[ i ].IsEmpty() )
3046 idList.push_back( args[ i ]);
3047 list< _pyID >::iterator id = idList.begin();
3048 for ( ; id != idList.end(); ++id )
3050 Handle(_pyObject) obj = theGen->FindObject( *id );
3051 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3054 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3055 geomPublished = false;
3059 myReferredObjs.push_back( obj );
3060 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3061 if ( !mesh.IsNull() )
3062 meshes.push_back( mesh );
3063 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3064 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3065 obj->SetRemovedFromStudy( false );
3069 return geomPublished;
3072 //================================================================================
3074 * \brief Remember theCommand setting a parameter
3076 //================================================================================
3078 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3080 // parameters are discriminated by method name
3081 _AString method = theCommand->GetMethod();
3082 if ( myAccumulativeMethods.count( method ))
3083 return; // this method adds values and not override the previous value
3085 // discriminate commands setting different parameters via one method
3086 // by passing parameter names like e.g. SetOption("size", "0.2")
3087 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3088 theCommand->GetNbArgs() > 1 )
3090 // mangle method by appending a 1st textual arg
3091 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3093 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3094 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3095 if ( !isalpha( arg.Value(2))) continue;
3100 // parameters are discriminated by method name
3101 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3102 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3104 cmds.back()->Clear(); // previous parameter value has not been used
3105 cmds.back() = theCommand;
3109 cmds.push_back( theCommand );
3113 //================================================================================
3115 * \brief Return true if a setting parameter command ha been used to compute mesh
3117 //================================================================================
3119 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3120 _pyCommand::TAddr avoidComputeAddr ) const
3122 bool isUsed = false;
3123 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3124 myComputeAddr2Cmds.begin();
3125 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3127 if ( addr2cmds->first == avoidComputeAddr ) continue;
3128 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3129 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3134 //================================================================================
3136 * \brief Save commands setting parameters as they are used for a mesh computation
3138 //================================================================================
3140 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3142 myComputeCmds.push_back( theComputeCmd );
3143 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3145 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3146 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3147 savedCmds.push_back( m2c->second.back() );
3150 //================================================================================
3152 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3154 //================================================================================
3156 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3158 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3160 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3161 for ( ; cmd != savedCmds.end(); ++cmd )
3163 // check if a cmd has been used to compute another mesh
3164 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3166 // check if a cmd is a sole command setting its parameter;
3167 // don't use method name for search as it can change
3168 map<_AString, list<Handle(_pyCommand)> >::iterator m2cmds = myMeth2Commands.begin();
3169 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3171 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3172 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3173 if ( cmdIt != cmds.end() )
3175 if ( cmds.back() != *cmd )
3177 cmds.erase( cmdIt );
3184 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3187 //================================================================================
3189 * \brief Sets an argNb-th argument of current creation command
3190 * \param argNb - argument index countered from 1
3192 //================================================================================
3194 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3196 if ( myCurCrMethod )
3198 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3199 myCurCrMethod->myArgs.push_back( "None" );
3200 if ( arg.IsEmpty() )
3201 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3203 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3208 //================================================================================
3210 * \brief Remember hypothesis parameter values
3211 * \param theCommand - The called hypothesis method
3213 //================================================================================
3215 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3217 if ( GetAlgoType() == "Cartesian_3D" )
3219 // CartesianParameters3D hyp
3221 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3222 theCommand->GetMethod() == "SetToAddEdges" )
3224 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3225 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3226 myArgCommands.push_back( theCommand );
3229 if ( theCommand->GetMethod() == "SetGrid" ||
3230 theCommand->GetMethod() == "SetGridSpacing" )
3232 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3233 int iArg = axis.Value(1) - '0';
3234 if ( theCommand->GetMethod() == "SetGrid" )
3236 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3240 myCurCrMethod->myArgs[ iArg ] = "[ ";
3241 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3242 myCurCrMethod->myArgs[ iArg ] += ", ";
3243 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3244 myCurCrMethod->myArgs[ iArg ] += "]";
3246 myArgCommands.push_back( theCommand );
3247 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3248 // accumulative, else, if the creation
3249 // is not converted, commands for axes 1 and 2 are lost
3254 if( theCommand->GetMethod() == "SetLength" )
3256 // NOW it is OBSOLETE
3257 // ex: hyp.SetLength(start, 1)
3258 // hyp.SetLength(end, 0)
3259 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3260 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3261 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3262 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3264 CreationMethod& crMethod = type2meth->second;
3265 while ( (int) crMethod.myArgs.size() < i+1 )
3266 crMethod.myArgs.push_back( "[]" );
3267 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3269 myArgCommands.push_back( theCommand );
3273 _pyHypothesis::Process( theCommand );
3276 //================================================================================
3278 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3280 //================================================================================
3282 void _pyComplexParamHypo::Flush()
3284 list < Handle(_pyCommand) >::iterator cmd;
3287 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3288 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3292 // if ( GetAlgoType() == "Cartesian_3D" )
3294 // _pyID algo = myCreationCmd->GetObject();
3295 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3297 // if ( IsWrapped() )
3299 // StructToList( *cmd, /*checkMethod=*/false );
3300 // const _AString & method = (*cmd)->GetMethod();
3301 // if ( method == "SetFixedPoint" )
3302 // (*cmd)->SetObject( algo );
3308 //================================================================================
3310 * \brief Convert methods of 1D hypotheses to my own methods
3311 * \param theCommand - The called hypothesis method
3313 //================================================================================
3315 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3317 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3320 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3321 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3322 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3324 // TCollection_AsciiString cmd =
3325 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3326 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3327 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3330 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3332 // // 1D hypo is already set, so distribution changes and the old
3333 // // 1D hypo is thrown away
3334 // my1dHyp->ClearAllCommands();
3337 // //my1dHyp->SetRemovedFromStudy( false );
3339 // if ( !myArgCommands.empty() )
3340 // myArgCommands.back()->Clear();
3341 myCurCrMethod->myArgs.push_back( hyp1dID );
3342 myArgCommands.push_back( theCommand );
3345 //================================================================================
3348 * \param theAdditionCmd - command to be converted
3349 * \param theMesh - mesh instance
3350 * \retval bool - status
3352 //================================================================================
3354 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3355 const _pyID& theMesh)
3357 myIsWrapped = false;
3359 if ( my1dHyp.IsNull() )
3362 // set "SetLayerDistribution()" after addition cmd
3363 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3365 _pyID geom = theAdditionCmd->GetArg( 1 );
3367 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3368 if ( !algo.IsNull() )
3370 my1dHyp->SetMesh( theMesh );
3371 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3372 algo->GetAlgoType().ToCString());
3373 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3376 // clear "SetLayerDistribution()" cmd
3377 myArgCommands.back()->Clear();
3379 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3381 // find RadialPrism algo created on <geom> for theMesh
3382 GetCreationCmd()->SetObject( algo->GetID() );
3383 GetCreationCmd()->SetMethod( myAlgoMethod );
3384 GetCreationCmd()->RemoveArgs();
3385 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3391 //================================================================================
3395 //================================================================================
3397 void _pyLayerDistributionHypo::Flush()
3399 // as creation of 1D hyp was written later then it's edition,
3400 // we need to find all it's edition calls and process them
3401 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3403 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3405 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3406 if ( hyp1dID.IsEmpty() ) continue;
3408 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3410 // make a new name for 1D hyp = "HypType" + "_Distribution"
3412 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3414 if ( prevNewName.IsEmpty() ) continue;
3415 newName = prevNewName;
3419 if ( hyp1d->IsWrapped() ) {
3420 newName = hyp1d->GetCreationCmd()->GetMethod();
3423 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3424 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3426 newName += "_Distribution";
3427 prevNewName = newName;
3429 hyp1d->GetCreationCmd()->SetResultValue( newName );
3431 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3432 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3433 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3434 const _pyID& objID = (*cmdIt)->GetObject();
3435 if ( objID == hyp1dID ) {
3436 if ( !hyp1d.IsNull() )
3438 hyp1d->Process( *cmdIt );
3439 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3441 ( *cmdIt )->SetObject( newName );
3444 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3445 (*cmd)->SetArg( 1, newName );
3449 //================================================================================
3451 * \brief additionally to Addition2Creation, clears SetDistrType() command
3452 * \param theCmd - AddHypothesis() command
3453 * \param theMesh - mesh to which a hypothesis is added
3454 * \retval bool - conversion result
3456 //================================================================================
3458 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3459 const _pyID& theMesh)
3461 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3462 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3463 bool scaleDistrType = false;
3464 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3465 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3466 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3467 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3468 scaleDistrType = true;
3471 else if ( !scaleDistrType ) {
3472 // distribution type changed: remove scale factor from args
3473 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3474 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3476 CreationMethod& crMethod = type2meth->second;
3477 if ( crMethod.myArgs.size() == 2 )
3478 crMethod.myArgs.pop_back();
3485 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3488 //================================================================================
3490 * \brief remove repeated commands defining distribution
3492 //================================================================================
3494 void _pyNumberOfSegmentsHyp::Flush()
3496 // find number of the last SetDistrType() command
3497 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3498 int distrTypeNb = 0;
3499 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3500 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3501 if ( cmd != myUnusedCommands.rbegin() )
3502 distrTypeNb = (*cmd)->GetOrderNb();
3504 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3507 // clear commands before the last SetDistrType()
3508 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3509 set< int > treatedCmdNbs; // avoid treating same cmd twice
3510 for ( int i = 0; i < 2; ++i ) {
3511 set<TCollection_AsciiString> uniqueMethods;
3512 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3513 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3515 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3516 continue;// avoid treating same cmd twice
3517 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3518 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3519 if ( !clear || method == "SetNumberOfSegments" ) {
3520 bool isNewInSet = uniqueMethods.insert( method ).second;
3521 clear = !isNewInSet;
3530 //================================================================================
3532 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3533 * into regular1D.LengthNearVertex( length, vertex )
3534 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3535 * \param theMesh - The mesh needing this hypo
3536 * \retval bool - false if the command can't be converted
3538 //================================================================================
3540 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3541 const _pyID& theMeshID)
3543 if ( IsWrappable( theMeshID )) {
3545 _pyID vertex = theCmd->GetArg( 1 );
3547 // the problem here is that segment algo can be not found
3548 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3549 // geometry where segment algorithm is assigned
3550 _pyID geom = vertex;
3551 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3552 while ( algo.IsNull() && !geom.IsEmpty()) {
3553 // try to find geom as a father of <vertex>
3554 geom = FatherID( geom );
3555 algo = theGen->FindAlgo( geom, theMeshID, this );
3557 if ( algo.IsNull() || geom.IsEmpty() )
3558 return false; // also possible to find geom as brother of veretex...
3560 // set geom instead of vertex
3561 theCmd->SetArg( 1, geom );
3563 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3564 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3565 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3567 // set vertex as a second arg
3568 theCmd->SetArg( 2, vertex );
3576 //================================================================================
3578 * \brief _pyAlgorithm constructor
3579 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3581 //================================================================================
3583 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3584 : _pyHypothesis( theCreationCmd )
3589 //================================================================================
3591 * \brief Convert the command adding an algorithm to mesh
3592 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3593 * \param theMesh - The mesh needing this algo
3594 * \retval bool - false if the command can't be converted
3596 //================================================================================
3598 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3599 const _pyID& theMeshID)
3601 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3602 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3603 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3609 //================================================================================
3611 * \brief Return starting position of a part of python command
3612 * \param thePartIndex - The index of command part
3613 * \retval int - Part position
3615 //================================================================================
3617 int _pyCommand::GetBegPos( int thePartIndex ) const
3621 if ( myBegPos.Length() < thePartIndex )
3623 ASSERT( thePartIndex > 0 );
3624 return myBegPos( thePartIndex );
3627 //================================================================================
3629 * \brief Store starting position of a part of python command
3630 * \param thePartIndex - The index of command part
3631 * \param thePosition - Part position
3633 //================================================================================
3635 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3637 while ( myBegPos.Length() < thePartIndex )
3638 myBegPos.Append( UNKNOWN );
3639 ASSERT( thePartIndex > 0 );
3640 myBegPos( thePartIndex ) = thePosition;
3643 //================================================================================
3645 * \brief Returns whitespace symbols at the line beginning
3646 * \retval TCollection_AsciiString - result
3648 //================================================================================
3650 TCollection_AsciiString _pyCommand::GetIndentation()
3653 //while ( end <= Length() && isblank( myString.Value( end )))
3654 //ANA: isblank() function isn't provided in VC2010 compiler
3655 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3657 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3660 //================================================================================
3662 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3663 * \retval const TCollection_AsciiString & - ResultValue substring
3665 //================================================================================
3667 const TCollection_AsciiString & _pyCommand::GetResultValue()
3669 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3671 SetBegPos( RESULT_IND, EMPTY );
3672 int begPos, endPos = myString.Location( "=", 1, Length() );
3676 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3677 if ( begPos < endPos )
3679 SetBegPos( RESULT_IND, begPos );
3681 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3682 myRes = myString.SubString( begPos, endPos );
3689 //================================================================================
3691 * \brief Return number of python command result value ResultValue = Obj.Meth()
3693 //================================================================================
3695 int _pyCommand::GetNbResultValues()
3698 return myResults.Length();
3702 //================================================================================
3704 * \brief Return substring of python command looking like
3705 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3706 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3708 //================================================================================
3709 const _AString& _pyCommand::GetResultValue(int res)
3711 if ( GetResultValue().IsEmpty() )
3712 return theEmptyString;
3714 if ( myResults.IsEmpty() )
3717 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3718 ++begPos; // skip [, else the whole list is returned
3719 while ( begPos < myRes.Length() ) {
3720 _AString result = GetWord( myRes, begPos, true );
3721 begPos += result.Length();
3723 // result.RemoveAll('[');
3724 // result.RemoveAll(']');
3729 myResults.Append( result );
3732 if ( res > 0 && res <= myResults.Length() )
3733 return myResults( res );
3734 return theEmptyString;
3737 //================================================================================
3739 * \brief Return substring of python command looking like ResVal = Object.Meth()
3740 * \retval const TCollection_AsciiString & - Object substring
3742 //================================================================================
3744 const TCollection_AsciiString & _pyCommand::GetObject()
3746 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3749 int begPos = GetBegPos( RESULT_IND );
3751 begPos = myString.Location( "=", 1, Length() ) + 1;
3752 // is '=' in the string argument (for example, name) or not
3753 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3754 for ( int i = 1; i < begPos-1; i++ )
3755 switch ( myString.Value( i )) {
3756 case '\'': nb[0]++; break;
3757 case '"' : nb[1]++; break;
3758 case '(' : nb[2]++; break;
3759 case ')' : nb[3]++; break;
3761 // if = is inside a string or a list
3762 // then get an object at the start of the command
3763 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3767 begPos += myRes.Length();
3769 myObj = GetWord( myString, begPos, true );
3770 if ( begPos != EMPTY )
3772 // check if object is complex,
3773 // so far consider case like "smesh.Method()"
3774 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3775 //if ( bracketPos==0 ) bracketPos = Length();
3776 int dotPos = begPos+myObj.Length();
3777 while ( dotPos+1 < bracketPos ) {
3778 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3783 if ( dotPos > begPos+myObj.Length() )
3784 myObj = myString.SubString( begPos, dotPos-1 );
3787 // 1st word after '=' is an object
3788 // else // no method -> no object
3794 SetBegPos( OBJECT_IND, begPos );
3800 //================================================================================
3802 * \brief Return substring of python command looking like ResVal = Obj.Method()
3803 * \retval const TCollection_AsciiString & - Method substring
3805 //================================================================================
3807 const TCollection_AsciiString & _pyCommand::GetMethod()
3809 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3812 int begPos = GetBegPos( OBJECT_IND );
3813 bool forward = true;
3815 begPos = myString.Location( "(", 1, Length() ) - 1;
3819 begPos += myObj.Length();
3822 myMeth = GetWord( myString, begPos, forward );
3823 SetBegPos( METHOD_IND, begPos );
3829 //================================================================================
3831 * \brief Returns true if there are brackets after the method
3833 //================================================================================
3835 bool _pyCommand::IsMethodCall()
3837 if ( GetMethod().IsEmpty() )
3839 if ( myString.StartsWith("#") )
3841 if ( myString.StartsWith("SHAPERSTUDY") ) // skip shaperstudy specific dump string analysis
3843 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3844 return ( s[0] == '(' || s[1] == '(' );
3847 //================================================================================
3849 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3850 * \retval const TCollection_AsciiString & - Arg<index> substring
3852 //================================================================================
3854 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3856 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3860 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3862 pos = myString.Location( "(", 1, Length() );
3866 // we are at or before '(', skip it if present
3868 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3869 if ( pos > Length() )
3873 SetBegPos( ARG1_IND, 0 ); // even no '('
3874 return theEmptyString;
3878 list< TCollection_AsciiString > separatorStack( 1, ",)");
3879 bool ignoreNesting = false;
3881 while ( pos <= Length() )
3883 const char chr = myString.Value( pos );
3885 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3887 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3889 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3891 TCollection_AsciiString arg;
3892 if ( pos-1 >= prevPos ) {
3893 arg = myString.SubString( prevPos, pos-1 );
3894 arg.RightAdjust(); // remove spaces
3897 if ( !arg.IsEmpty() || chr == ',' )
3899 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3900 myArgs.Append( arg );
3906 else // end of nesting args found
3908 separatorStack.pop_back();
3909 ignoreNesting = false;
3912 else if ( !ignoreNesting )
3915 case '(' : separatorStack.push_back(")"); break;
3916 case '[' : separatorStack.push_back("]"); break;
3917 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3918 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3925 if ( myArgs.Length() < index )
3926 return theEmptyString;
3927 return myArgs( index );
3930 //================================================================================
3932 * \brief Return position where arguments begin
3934 //================================================================================
3936 int _pyCommand::GetArgBeginning() const
3938 int pos = GetBegPos( ARG1_IND );
3939 if ( pos == UNKNOWN )
3941 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3943 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3948 //================================================================================
3950 * \brief Check if char is a word part
3951 * \param c - The character to check
3952 * \retval bool - The check result
3954 //================================================================================
3956 static inline bool isWord(const char c, const bool dotIsWord)
3959 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3962 //================================================================================
3964 * \brief Looks for a word in the string and returns word's beginning
3965 * \param theString - The input string
3966 * \param theStartPos - The position to start the search, returning word's beginning
3967 * \param theForward - The search direction
3968 * \retval TCollection_AsciiString - The found word
3970 //================================================================================
3972 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3974 const bool theForward,
3975 const bool dotIsWord )
3977 int beg = theStartPos, end = theStartPos;
3978 theStartPos = EMPTY;
3979 if ( beg < 1 || beg > theString.Length() )
3980 return theEmptyString;
3982 if ( theForward ) { // search forward
3984 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3986 if ( beg > theString.Length() )
3987 return theEmptyString; // no word found
3990 char begChar = theString.Value( beg );
3991 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3992 char endChar = ( begChar == '[' ) ? ']' : begChar;
3993 // end is at the corresponding quoting mark or bracket
3994 while ( end < theString.Length() &&
3995 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3999 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
4004 else { // search backward
4006 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
4009 return theEmptyString; // no word found
4011 char endChar = theString.Value( end );
4012 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
4013 char begChar = ( endChar == ']' ) ? '[' : endChar;
4014 // beg is at the corresponding quoting mark
4016 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
4020 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4026 //cout << theString << " ---- " << beg << " - " << end << endl;
4027 return theString.SubString( beg, end );
4030 //================================================================================
4032 * \brief Returns true if the string looks like a study entry
4034 //================================================================================
4036 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4038 if ( str.Length() < 5 ) return false;
4040 int nbColons = 0, isColon;
4041 for ( int i = 1; i <= str.Length(); ++i )
4043 char c = str.Value(i);
4044 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4046 nbColons += isColon;
4048 return nbColons > 2 && str.Length()-nbColons > 2;
4051 //================================================================================
4053 * \brief Returns true if the string looks like an object ID but not like a list,
4054 * string, command etc.
4056 //================================================================================
4058 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4060 if ( str.Length() < 1 ) return false;
4062 const char* s = str.ToCString();
4064 for ( int i = 0; i < str.Length(); ++i )
4065 if ( !IsIDChar( s[i] ))
4071 //================================================================================
4073 * \brief Finds entries in a string
4075 //================================================================================
4077 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4079 std::list< _pyID > resList;
4081 while ( ++pos <= str.Length() )
4083 if ( !isdigit( str.Value( pos ))) continue;
4084 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4087 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4088 _pyID entry = str.SubString( pos, end-1 );
4090 if ( IsStudyEntry( entry ))
4091 resList.push_back( entry );
4096 //================================================================================
4098 * \brief Look for position where not space char is
4099 * \param theString - The string
4100 * \param thePos - The position to search from and which returns result
4101 * \retval bool - false if there are only space after thePos in theString
4103 //================================================================================
4105 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4107 if ( thePos < 1 || thePos > theString.Length() )
4110 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4113 return thePos <= theString.Length();
4116 //================================================================================
4118 * \brief Modify a part of the command
4119 * \param thePartIndex - The index of the part
4120 * \param thePart - The new part string
4121 * \param theOldPart - The old part
4123 //================================================================================
4125 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4126 TCollection_AsciiString& theOldPart)
4128 int pos = GetBegPos( thePartIndex );
4129 if ( pos <= Length() && theOldPart != thePart)
4131 TCollection_AsciiString seperator;
4133 pos = GetBegPos( thePartIndex + 1 );
4134 if ( pos < 1 ) return;
4135 switch ( thePartIndex ) {
4136 case RESULT_IND: seperator = " = "; break;
4137 case OBJECT_IND: seperator = "."; break;
4138 case METHOD_IND: seperator = "()"; break;
4142 myString.Remove( pos, theOldPart.Length() );
4143 if ( !seperator.IsEmpty() )
4144 myString.Insert( pos , seperator );
4145 myString.Insert( pos, thePart );
4146 // update starting positions of the following parts
4147 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4148 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4149 if ( myBegPos( i ) > 0 )
4150 myBegPos( i ) += posDelta;
4152 theOldPart = thePart;
4156 //================================================================================
4158 * \brief Set argument
4159 * \param index - The argument index, it counts from 1
4160 * \param theArg - The argument string
4162 //================================================================================
4164 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4167 int argInd = ARG1_IND + index - 1;
4168 int pos = GetBegPos( argInd );
4169 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4171 // find a closing parenthesis
4172 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4173 int lastArgInd = GetNbArgs();
4174 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4175 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4180 while ( pos > 0 && myString.Value( pos ) != ')' )
4183 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4187 while ( myArgs.Length() < index ) {
4188 if ( myArgs.Length() )
4189 myString.Insert( pos++, "," );
4190 myArgs.Append("None");
4191 myString.Insert( pos, myArgs.Last() );
4192 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4193 pos += myArgs.Last().Length();
4196 SetPart( argInd, theArg, myArgs( index ));
4199 //================================================================================
4201 * \brief Empty arg list
4203 //================================================================================
4205 void _pyCommand::RemoveArgs()
4207 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4208 myString.Trunc( pos );
4211 if ( myBegPos.Length() >= ARG1_IND )
4212 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4215 //================================================================================
4217 * \brief Comment a python command
4219 //================================================================================
4221 void _pyCommand::Comment()
4223 if ( IsEmpty() ) return;
4226 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4227 if ( i <= Length() )
4229 myString.Insert( i, "#" );
4230 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4232 int begPos = GetBegPos( iPart );
4233 if ( begPos != UNKNOWN && begPos != EMPTY )
4234 SetBegPos( iPart, begPos + 1 );
4239 //================================================================================
4241 * \brief Set dependent commands after this one
4243 //================================================================================
4245 bool _pyCommand::SetDependentCmdsAfter() const
4247 bool orderChanged = false;
4248 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4249 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4250 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4251 orderChanged = true;
4252 theGen->SetCommandAfter( *cmd, this );
4253 (*cmd)->SetDependentCmdsAfter();
4256 return orderChanged;
4258 //================================================================================
4260 * \brief Insert accessor method after theObjectID
4261 * \param theObjectID - id of the accessed object
4262 * \param theAcsMethod - name of the method giving access to the object
4263 * \retval bool - false if theObjectID is not found in the command string
4265 //================================================================================
4267 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4269 if ( !theAcsMethod )
4271 // start object search from the object, i.e. ignore result
4273 int beg = GetBegPos( OBJECT_IND );
4274 if ( beg < 1 || beg > Length() )
4277 while (( beg = myString.Location( theObjectID, beg, Length() )))
4279 // check that theObjectID is not just a part of a longer ID
4280 int afterEnd = beg + theObjectID.Length();
4281 Standard_Character c = myString.Value( afterEnd );
4282 if ( !IsIDChar( c ))
4284 // check if accessor method already present
4286 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4288 int oldLen = Length();
4289 myString.Insert( afterEnd, (char*) theAcsMethod );
4290 myString.Insert( afterEnd, "." );
4291 // update starting positions of the parts following the modified one
4292 int posDelta = Length() - oldLen;
4293 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4294 if ( myBegPos( i ) > afterEnd )
4295 myBegPos( i ) += posDelta;
4300 beg = afterEnd; // is a part -> next search
4305 //================================================================================
4307 * \brief Creates pyObject
4309 //================================================================================
4311 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4312 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4317 //================================================================================
4319 * \brief Set up myID and myIsPublished
4321 //================================================================================
4323 void _pyObject::setID(const _pyID& theID)
4326 myIsPublished = !theGen->IsNotPublished( GetID() );
4329 //================================================================================
4331 * \brief Clear myCreationCmd and myProcessedCmds
4333 //================================================================================
4335 void _pyObject::ClearCommands()
4340 if ( !myCreationCmd.IsNull() )
4341 myCreationCmd->Clear();
4343 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4344 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4348 //================================================================================
4350 * \brief Return method name giving access to an interaface object wrapped by python class
4351 * \retval const char* - method name
4353 //================================================================================
4355 const char* _pyObject::AccessorMethod() const
4359 //================================================================================
4361 * \brief Return ID of a father
4363 //================================================================================
4365 _pyID _pyObject::FatherID(const _pyID & childID)
4367 int colPos = childID.SearchFromEnd(':');
4369 return childID.SubString( 1, colPos-1 );
4373 //================================================================================
4375 * \brief SelfEraser erases creation command if none of it's commands invoked
4376 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4378 //================================================================================
4380 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4381 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4383 myIsPublished = true; // prevent clearing as a not published
4384 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4387 //================================================================================
4389 * \brief SelfEraser erases creation command if none of it's commands invoked
4390 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4392 //================================================================================
4394 bool _pySelfEraser::CanClear()
4396 bool toErase = false;
4397 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4400 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4401 for ( ; cmd != myArgCmds.end(); ++cmd )
4402 nbArgUses += IsAliveCmd( *cmd );
4404 toErase = ( nbArgUses < 1 );
4409 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4410 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4411 for ( ; cmd != cmds.end(); )
4412 // check of cmd emptiness is not enough as object can change
4413 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4416 cmd = cmds.erase( cmd ); // save the cmd from clearing
4418 toErase = ( nbCalls < 1 );
4423 //================================================================================
4425 * \brief Check if a command is or can be cleared
4427 //================================================================================
4429 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4431 if ( theCmd->IsEmpty() )
4434 if ( !theGen->IsToKeepAllCommands() )
4436 const _pyID& objID = theCmd->GetObject();
4437 Handle( _pyObject ) obj = theGen->FindObject( objID );
4438 if ( !obj.IsNull() )
4439 return !obj->CanClear();
4444 //================================================================================
4446 * \brief SelfEraser erases creation command if none of it's commands invoked
4447 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4449 //================================================================================
4451 void _pySelfEraser::Flush()
4455 myIsPublished = false;
4456 _pyObject::ClearCommands();
4460 //================================================================================
4462 * \brief _pySubMesh constructor
4464 //================================================================================
4466 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4467 _pyObject(theCreationCmd)
4469 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4470 if ( toKeepAgrCmds )
4471 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4474 //================================================================================
4476 * \brief Return true if a sub-mesh can be used as argument of the given method
4478 //================================================================================
4480 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4483 // names of all methods where a sub-mesh can be used as argument
4484 // static TStringSet methods;
4485 // if ( methods.empty() ) {
4486 // const char * names[] = {
4487 // // methods of SMESH_Gen
4489 // // methods of SMESH_Group
4491 // // methods of SMESH_Measurements
4493 // // methods of SMESH_Mesh
4494 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4496 // // methods of SMESH_MeshEditor
4497 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4498 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4499 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4500 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4501 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4502 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4503 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4504 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4505 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4506 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4507 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4508 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4509 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4510 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4511 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4512 // "" }; // <- mark of end
4513 // methods.Insert( names );
4515 // return methods.Contains( theMethodName );
4518 //================================================================================
4520 * \brief count invoked commands
4522 //================================================================================
4524 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4526 _pyObject::Process(theCommand); // count calls of Process()
4529 //================================================================================
4531 * \brief Move creation command depending on invoked commands
4533 //================================================================================
4535 void _pySubMesh::Flush()
4537 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4538 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4539 else if ( !myCreator.IsNull() )
4540 // move to be just after creator
4541 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4543 // move sub-mesh usage after creation cmd
4544 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4545 for ( ; cmd != myArgCmds.end(); ++cmd )
4546 if ( !(*cmd)->IsEmpty() )
4547 GetCreationCmd()->AddDependantCmd( *cmd );
4550 //================================================================================
4552 * \brief Creates _pyGroup
4554 //================================================================================
4556 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4557 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4559 if ( !id.IsEmpty() )
4562 myCanClearCreationCmd = true;
4564 const _AString& method = theCreationCmd->GetMethod();
4565 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4567 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4569 // ----------------------------------------------------------------------
4570 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4572 _pyID geom = theCreationCmd->GetArg( 3 );
4573 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4574 // next if(){...} section is commented
4575 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4576 // theCreationCmd->SetMethod( "Group" );
4577 // theCreationCmd->RemoveArgs();
4578 // theCreationCmd->SetArg( 1, geom );
4581 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4582 _pyID type = theCreationCmd->GetArg( 1 );
4583 _pyID name = theCreationCmd->GetArg( 2 );
4584 theCreationCmd->SetMethod( "GroupOnGeom" );
4585 theCreationCmd->RemoveArgs();
4586 theCreationCmd->SetArg( 1, geom );
4587 theCreationCmd->SetArg( 2, name );
4588 theCreationCmd->SetArg( 3, type );
4591 else if ( method == "CreateGroupFromFilter" )
4593 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4594 theCreationCmd->SetMethod( "GroupOnFilter" );
4596 _pyID filterID = theCreationCmd->GetArg(3);
4597 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4598 if ( !filter.IsNull())
4600 if ( !filter->GetNewID().IsEmpty() )
4601 theCreationCmd->SetArg( 3, filter->GetNewID() );
4602 //filter->AddUser( this );
4606 else if ( method == "GetGroups" )
4608 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4612 // theCreationCmd does something else apart from creation of this group
4613 // and thus it can't be cleared if this group is removed
4614 myCanClearCreationCmd = false;
4618 //================================================================================
4620 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4623 //================================================================================
4625 bool _pyGroup::CanClear()
4630 if ( !myCanClearCreationCmd &&
4631 !myCreationCmd.IsNull() &&
4632 myCreationCmd->GetMethod() == "GetGroups" )
4634 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4635 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4636 list< _pyID >::iterator grID = idList.begin();
4637 if ( GetID() == *grID )
4639 myCanClearCreationCmd = true;
4640 list< Handle(_pyGroup ) > groups;
4641 for ( ; grID != idList.end(); ++grID )
4643 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4644 if ( group.IsNull() ) continue;
4645 groups.push_back( group );
4646 if ( group->IsInStudy() )
4647 myCanClearCreationCmd = false;
4649 // set myCanClearCreationCmd == true to all groups
4650 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4651 for ( ; group != groups.end(); ++group )
4652 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4656 return myCanClearCreationCmd;
4659 //================================================================================
4661 * \brief set myCanClearCreationCmd = true if the main action of the creation
4662 * command is discarded
4664 //================================================================================
4666 void _pyGroup::RemovedWithContents()
4668 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4669 // via a created group
4670 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4671 // myCanClearCreationCmd = true;
4674 //================================================================================
4676 * \brief To convert creation of a group by filter
4678 //================================================================================
4680 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4682 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4683 // group = mesh.CreateEmptyGroup( elemType, groupName )
4684 // aFilter.SetMesh(mesh)
4685 // nbAdd = group.AddFrom( aFilter )
4686 Handle(_pyFilter) filter;
4687 if ( theCommand->GetMethod() == "AddFrom" )
4689 _pyID idSource = theCommand->GetArg(1);
4690 // check if idSource is a filter
4691 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4692 if ( !filter.IsNull() )
4694 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4695 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4696 while ( *cmdIt != theCommand ) ++cmdIt;
4697 while ( (*cmdIt)->GetOrderNb() != 1 )
4699 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4700 if ((setMeshCmd->GetObject() == idSource ||
4701 setMeshCmd->GetObject() == filter->GetNewID() )
4703 setMeshCmd->GetMethod() == "SetMesh")
4705 setMeshCmd->Clear();
4709 // replace 3 commands by one
4710 theCommand->Clear();
4711 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4712 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4713 if ( !filter->GetNewID().IsEmpty() )
4714 idSource = filter->GetNewID();
4715 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4716 makeGroupCmd->SetArg( 1, name );
4717 makeGroupCmd->SetArg( 2, idSource );
4718 filter->AddArgCmd( makeGroupCmd );
4721 else if ( theCommand->GetMethod() == "SetFilter" )
4723 // set new name of a filter or clear the command if the same filter is set
4724 _pyID filterID = theCommand->GetArg(1);
4725 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4726 if ( !myFilter.IsNull() && filter == myFilter )
4727 theCommand->Clear();
4728 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4729 theCommand->SetArg( 1, filter->GetNewID() );
4732 else if ( theCommand->GetMethod() == "GetFilter" )
4734 // GetFilter() returns a filter with other ID, make myFilter process
4735 // calls of the returned filter
4736 if ( !myFilter.IsNull() )
4738 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4739 theCommand->Clear();
4743 // if ( !filter.IsNull() )
4744 // filter->AddUser( this );
4746 theGen->AddMeshAccessorMethod( theCommand );
4749 //================================================================================
4751 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4753 //================================================================================
4755 void _pyGroup::Flush()
4757 if ( !theGen->IsToKeepAllCommands() &&
4758 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4760 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4764 //================================================================================
4766 * \brief Constructor of _pyFilter
4768 //================================================================================
4770 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4771 :_pyObject(theCreationCmd), myNewID( newID )
4773 //myIsPublished = true; // prevent clearing as a not published
4774 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4777 //================================================================================
4779 * \brief To convert creation of a filter by criteria and
4780 * to replace an old name by a new one
4782 //================================================================================
4784 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4786 if ( theCommand->GetObject() == GetID() )
4787 _pyObject::Process(theCommand); // count commands
4789 if ( !myNewID.IsEmpty() )
4790 theCommand->SetObject( myNewID );
4792 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4793 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4794 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4795 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4796 theCommand->GetMethod() == "SetCriteria")
4798 // aFilter.SetCriteria(aCriteria) ->
4799 // aFilter = smesh.GetFilterFromCriteria(criteria)
4800 if ( myNewID.IsEmpty() )
4801 theCommand->SetResultValue( GetID() );
4803 theCommand->SetResultValue( myNewID );
4804 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4805 theCommand->SetMethod( "GetFilterFromCriteria" );
4807 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4808 GetCreationCmd()->Clear();
4809 GetCreationCmd()->GetString() = theCommand->GetString();
4810 theCommand->Clear();
4811 theCommand->AddDependantCmd( GetCreationCmd() );
4812 // why swap? -- it's needed
4813 //GetCreationCmd()->Clear();
4815 else if ( theCommand->GetMethod() == "SetMesh" )
4817 if ( myMesh == theCommand->GetArg( 1 ))
4818 theCommand->Clear();
4820 myMesh = theCommand->GetArg( 1 );
4821 theGen->AddMeshAccessorMethod( theCommand );
4825 //================================================================================
4827 * \brief Set new filter name to the creation command and to myArgCmds
4829 //================================================================================
4831 void _pyFilter::Flush()
4833 if ( myNewID.IsEmpty() ) return;
4835 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4836 for ( ; cmd != myArgCmds.end(); ++cmd )
4837 if ( !(*cmd)->IsEmpty() )
4839 _AString cmdStr = (*cmd)->GetString();
4840 _AString id = GetID();
4841 int pos = cmdStr.Search( id );
4844 cmdStr.Remove( pos, id.Length() );
4845 cmdStr.Insert( pos, myNewID );
4848 (*cmd)->GetString() = cmdStr;
4851 if ( !GetCreationCmd()->IsEmpty() )
4852 GetCreationCmd()->SetResultValue( myNewID );
4855 //================================================================================
4857 * \brief Return true if all my users can be cleared
4859 //================================================================================
4861 bool _pyObject::CanClear()
4863 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4864 for ( ; cmd != myArgCmds.end(); ++cmd )
4865 if ( !(*cmd)->IsEmpty() )
4867 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4868 if ( !obj.IsNull() && !obj->CanClear() )
4871 return ( !myIsPublished );
4874 //================================================================================
4876 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4878 //================================================================================
4880 _pyHypothesisReader::_pyHypothesisReader()
4883 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4884 LDOMParser xmlParser;
4885 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4887 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4891 INFOS( xmlParser.GetError(data) );
4894 // <algorithm type="Regular_1D"
4895 // label-id="Wire discretisation"
4898 // <algo>Regular_1D=Segment()</algo>
4899 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4901 LDOM_Document xmlDoc = xmlParser.getDocument();
4902 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4903 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4905 LDOM_Node algoNode = algoNodeList.item( i );
4906 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4907 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4908 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4910 _AString text, algoType, method, arg;
4911 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4913 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4914 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4915 text = textNode.getNodeValue();
4916 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4917 algoType = algoCmd->GetResultValue();
4918 method = algoCmd->GetMethod();
4919 arg = algoCmd->GetArg(1);
4920 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4922 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4923 algo->SetConvMethodAndType( method, algoType );
4924 if ( !arg.IsEmpty() )
4925 algo->setCreationArg( 1, arg );
4927 myType2Hyp[ algoType ] = algo;
4931 if ( algoType.IsEmpty() ) continue;
4933 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4935 Handle( _pyHypothesis ) hyp;
4936 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4938 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4939 LDOM_Node textNode = pyHypoNode.getFirstChild();
4940 text = textNode.getNodeValue();
4941 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4942 hypType = hypoCmd->GetResultValue();
4943 method = hypoCmd->GetMethod();
4944 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4946 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4947 if ( type2hyp == myType2Hyp.end() )
4948 hyp = new _pyHypothesis( hypoCmd );
4950 hyp = type2hyp->second;
4951 hyp->SetConvMethodAndType( method, algoType );
4952 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4954 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4955 _AString argMethod = argCmd.GetMethod();
4956 _AString argNbText = argCmd.GetArg( 1 );
4957 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4958 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4960 hyp->AddArgMethod( argMethod,
4961 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4963 myType2Hyp[ hypType ] = hyp;
4967 // <hypothesis type="BLSURF_Parameters"
4971 // <accumulative-methods>
4972 // SetEnforcedVertex,
4973 // SetEnforcedVertexNamed
4974 // </accumulative-methods>
4978 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4979 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4981 LDOM_Node hypNode = hypNodeList.item( i );
4982 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4983 _AString hypType = hypElem.getAttribute("type");
4984 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4985 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4987 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4988 if ( type2hyp == myType2Hyp.end() ) continue;
4990 LDOM_Node methNode = methNodeList.item( 0 );
4991 LDOM_Node textNode = methNode.getFirstChild();
4992 _AString text = textNode.getNodeValue();
4996 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4997 pos += method.Length();
4998 type2hyp->second->AddAccumulativeMethod( method );
5000 while ( !method.IsEmpty() );
5003 } // loop on xmlPaths
5006 //================================================================================
5008 * \brief Returns a new hypothesis initialized according to the read information
5010 //================================================================================
5012 Handle(_pyHypothesis)
5013 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
5014 const Handle(_pyCommand)& creationCmd) const
5016 Handle(_pyHypothesis) resHyp, sampleHyp;
5018 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5019 if ( type2hyp != myType2Hyp.end() )
5020 sampleHyp = type2hyp->second;
5022 if ( sampleHyp.IsNull() )
5024 resHyp = new _pyHypothesis(creationCmd);
5028 if ( sampleHyp->IsAlgo() )
5029 resHyp = new _pyAlgorithm( creationCmd );
5031 resHyp = new _pyHypothesis(creationCmd);
5032 resHyp->Assign( sampleHyp, _pyID() );
5037 //================================================================================
5039 * \brief Adds an object ID to some family of IDs with a common prefix
5040 * \param [in] str - the object ID
5041 * \return bool - \c false if \a str does not have the same prefix as \a this family
5042 * (for internal usage)
5044 //================================================================================
5046 bool _pyStringFamily::Add( const char* str )
5048 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5049 return false; // expected prefix is missing
5051 str += _prefix.Length(); // skip _prefix
5053 // try to add to some of child falimies
5054 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5055 for ( ; itSub != _subFams.end(); ++itSub )
5056 if ( itSub->Add( str ))
5059 // no suitable family found - add str to _strings or create a new child family
5061 // look for a proper place within sorted _strings
5062 std::list< _AString >::iterator itStr = _strings.begin();
5063 while ( itStr != _strings.end() && itStr->IsLess( str ))
5065 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5066 return true; // same ID already kept
5068 const int minPrefixSize = 4;
5070 // count "smaller" strings with the same prefix
5072 std::list< _AString >::iterator itLess = itStr;
5073 while ( itLess != _strings.begin() )
5076 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5084 // itLess points to the 1st string with same prefix
5086 // count "greater" strings with the same prefix
5088 std::list< _AString >::iterator itMore = itStr;
5089 for ( ; itMore != _strings.end(); ++itMore )
5090 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5094 // itMore points to the 1st string with greater prefix
5096 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5098 int prefixSize = minPrefixSize;
5099 _AString newPrefix ( str, prefixSize );
5101 // look for a proper place within _subFams sorted by _prefix
5102 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5103 if ( !itSub->_prefix.IsLess( newPrefix ))
5106 // add the new _pyStringFamily
5107 itSub = _subFams.insert( itSub, _pyStringFamily());
5108 _pyStringFamily& newSubFam = *itSub;
5109 newSubFam._prefix = newPrefix;
5111 // pass this->_strings to newSubFam._strings
5112 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5113 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5114 newSubFam._strings.push_back( str + prefixSize );
5115 for ( ; nbMore > 0; --nbMore, ++itStr )
5116 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5118 _strings.erase( itLess, itMore );
5120 else // too few string to make a family for them
5122 _strings.insert( itStr, str );
5127 //================================================================================
5129 * \brief Finds an object ID in the command
5130 * \param [in] longStr - the command string
5131 * \param [out] subStr - the found object ID
5132 * \return bool - \c true if the object ID found
5134 //================================================================================
5136 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5138 const _AString& longStr = cmd->GetString();
5139 const char* s = longStr.ToCString();
5142 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5143 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5144 if ( argBeg < 4 || argBeg > longStr.Length() )
5146 for ( ; itSub != _subFams.end(); ++itSub )
5149 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5150 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5152 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5153 from = pos + len + itSub->_prefix.Length();
5158 from += itSub->_prefix.Length();
5161 // look among _strings
5162 std::list< _AString >::iterator itStr = _strings.begin();
5163 for ( ; itStr != _strings.end(); ++itStr )
5164 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5165 // check that object ID does not continue after len
5166 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5168 subStr.push_back( *itStr );
5174 //================================================================================
5176 * \brief Return remainder length of the object ID after my _prefix
5177 * \param [in] str - remainder of the command after my _prefix
5178 * \return int - length of the object ID or -1 if not found
5180 //================================================================================
5182 int _pyStringFamily::isIn( const char* str )
5184 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5186 for ( ; itSub != _subFams.end(); ++itSub )
5188 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5191 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5192 return itSub->_prefix.Length() + len;
5197 if ( !_strings.empty() )
5199 std::list< _AString >::iterator itStr = _strings.begin();
5200 bool firstEmpty = itStr->IsEmpty();
5203 for ( ; itStr != _strings.end(); ++itStr )
5205 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5208 len = itStr->Length();
5217 // check that object ID does not continue after len
5218 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5225 //================================================================================
5229 //================================================================================
5231 void _pyStringFamily::Print( int level )
5233 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5234 std::list< _AString >::iterator itStr = _strings.begin();
5235 for ( ; itStr != _strings.end(); ++itStr )
5236 cout << *itStr << " | ";
5238 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5239 for ( ; itSub != _subFams.end(); ++itSub )
5240 itSub->Print( level + 1 );
5242 cout << string( 70, '-' ) << endl;