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 means that enum GeometryType changed)
934 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
935 "Update names of GeometryType's!!!" );
938 if (Type == "SMESH.FT_EntityType")
940 // set SMESH.EntityType instead of a numerical Threshold
941 const int nbTypes = SMESH::Entity_Last;
942 const char* types[] = {
943 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
944 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
945 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
946 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
947 "Entity_Pyramid", "Entity_Quad_Pyramid",
948 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
949 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
950 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
951 if ( -1 < iGeom && iGeom < nbTypes )
952 Threshold = SMESH + types[ iGeom ];
954 // is 'types' complete? (compilation failure means that enum EntityType changed)
955 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
956 "Update names of EntityType's!!!" );
960 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
961 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
962 else if ( ThresholdStr.Length() != 2 )
963 aCommand->SetArg( 4, ThresholdStr );
964 else if ( ThresholdID.Length() != 2 )
965 aCommand->SetArg( 4, ThresholdID );
967 aCommand->SetArg( 4, Threshold );
968 // find the last not default arg
970 if ( Tolerance == dfltTol ) {
972 if ( BinaryOp == dfltFunctor ) {
974 if ( UnaryOp == dfltFunctor )
978 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
979 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
980 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
981 if ( Precision != dfltPreci )
983 TCollection_AsciiString crit = aCommand->GetResultValue();
984 aCommand->GetString() += "; ";
985 aCommand->GetString() += crit + ".Precision = " + Precision;
991 //================================================================================
993 * \brief Convert the command or remember it for later conversion
994 * \param theCommand - The python command calling a method of SMESH_Gen
996 //================================================================================
998 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
1000 // there are methods to convert:
1001 // CreateMesh( shape )
1002 // Concatenate( [mesh1, ...], ... )
1003 // CreateHypothesis( theHypType, theLibName )
1004 // Compute( mesh, geom )
1005 // Evaluate( mesh, geom )
1007 TCollection_AsciiString method = theCommand->GetMethod();
1009 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
1011 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1015 if ( method == "CreateMeshesFromUNV" ||
1016 method == "CreateMeshesFromSTL" ||
1017 method == "CopyMesh" ) // command result is a mesh
1019 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1023 if ( method == "CreateMeshesFromMED" ||
1024 method == "CreateMeshesFromSAUV"||
1025 method == "CreateMeshesFromCGNS" ||
1026 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1028 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1029 std::list< _pyID >::iterator meshID = meshIDs.begin();
1030 for ( ; meshID != meshIDs.end(); ++meshID )
1032 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1035 if ( method == "CreateMeshesFromGMF" )
1037 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1038 // CreateMeshesFromGMF( theFileName )
1039 _AString file = theCommand->GetArg(1);
1040 theCommand->RemoveArgs();
1041 theCommand->SetArg( 1, file );
1044 if ( method == "CopyMeshWithGeom" )
1046 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1047 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1051 // CreateHypothesis()
1052 if ( method == "CreateHypothesis" )
1054 // issue 199929, remove standard library name (default parameter)
1055 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1056 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1057 // keep the first argument
1058 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1059 theCommand->RemoveArgs();
1060 theCommand->SetArg( 1, arg );
1063 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1064 CheckObjectIsReCreated( hyp );
1065 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1070 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1071 if ( method == "Compute" )
1073 const _pyID& meshID = theCommand->GetArg( 1 );
1074 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1075 if ( id_mesh != myMeshes.end() ) {
1076 theCommand->SetObject( meshID );
1077 theCommand->RemoveArgs();
1078 id_mesh->second->Process( theCommand );
1079 id_mesh->second->AddProcessedCmd( theCommand );
1084 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1085 if ( method == "Evaluate" )
1087 const _pyID& meshID = theCommand->GetArg( 1 );
1088 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1089 if ( id_mesh != myMeshes.end() ) {
1090 theCommand->SetObject( meshID );
1091 _pyID geom = theCommand->GetArg( 2 );
1092 theCommand->RemoveArgs();
1093 theCommand->SetArg( 1, geom );
1094 id_mesh->second->AddProcessedCmd( theCommand );
1099 // objects erasing creation command if no more its commands invoked:
1100 // SMESH_Pattern, FilterManager
1101 if ( method == "GetPattern" ||
1102 method == "CreateFilterManager" ||
1103 method == "CreateMeasurements" )
1105 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1106 if ( !AddObject( obj ) )
1107 theCommand->Clear(); // already created
1109 // Concatenate( [mesh1, ...], ... )
1110 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1112 // OLD IDL: ( meshes, uniteGroups, toMerge, tol )
1113 // IDL: ( meshes, uniteGroups, toMerge, tol, meshToAppendTo )
1114 // PY: ( meshes, uniteGroups, toMerge, tol, allGroups=False, name="", meshToAppendTo=None )
1115 _pyID appendMesh = theCommand->GetArg( 5 );
1116 if ( method == "ConcatenateWithGroups" ) {
1117 theCommand->SetMethod( "Concatenate" );
1118 theCommand->SetArg( 5, "True" );
1121 theCommand->SetArg( 5, "False" );
1123 if ( !appendMesh.IsEmpty() && appendMesh != "None" )
1125 appendMesh.Insert( 1, "meshToAppendTo=" );
1126 theCommand->SetArg( theCommand->GetNbArgs() + 1, appendMesh );
1128 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1130 AddMeshAccessorMethod( theCommand );
1132 else if ( method == "SetName" ) // SetName(obj,name)
1134 // store theCommand as one of object commands to erase it along with the object
1135 const _pyID& objID = theCommand->GetArg( 1 );
1136 Handle(_pyObject) obj = FindObject( objID );
1137 if ( !obj.IsNull() )
1138 obj->AddProcessedCmd( theCommand );
1141 // Replace name of SMESH_Gen
1143 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1144 static TStringSet smeshpyMethods;
1145 if ( smeshpyMethods.empty() ) {
1146 const char * names[] =
1147 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1148 "GetPattern","GetSubShapesId",
1149 "" }; // <- mark of array end
1150 smeshpyMethods.Insert( names );
1152 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1153 // smeshgen.Method() --> smesh.Method()
1154 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1156 // smeshgen.Method() --> smesh.Method()
1157 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1160 //================================================================================
1162 * \brief Convert the remembered commands
1164 //================================================================================
1166 void _pyGen::Flush()
1168 // create an empty command
1169 myLastCommand = new _pyCommand();
1171 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1172 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1173 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1175 if ( IsToKeepAllCommands() ) // historical dump
1177 // set myIsPublished = true to all objects
1178 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1179 id_mesh->second->SetRemovedFromStudy( false );
1180 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1181 id_hyp->second->SetRemovedFromStudy( false );
1182 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1183 id_obj->second->SetRemovedFromStudy( false );
1187 // let hypotheses find referred objects in order to prevent clearing
1188 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1189 list< Handle(_pyMesh) > fatherMeshes;
1190 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1191 if ( !id_hyp->second.IsNull() )
1192 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1194 // set myIsPublished = false to all objects depending on
1195 // meshes built on a removed geometry
1196 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1197 if ( id_mesh->second->IsNotGeomPublished() )
1198 id_mesh->second->SetRemovedFromStudy( true );
1201 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1202 if ( ! id_mesh->second.IsNull() )
1203 id_mesh->second->Flush();
1206 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1207 if ( !id_hyp->second.IsNull() ) {
1208 id_hyp->second->Flush();
1209 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1210 if ( !id_hyp->second->IsWrapped() )
1211 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1214 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1215 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1216 for ( ; robj != myOrderedObjects.rend(); ++robj )
1217 if ( ! robj->IsNull() )
1219 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1220 for ( ; obj != myOrderedObjects.end(); ++obj )
1221 if ( ! obj->IsNull() )
1224 myLastCommand->SetOrderNb( ++myNbCommands );
1225 myCommands.push_back( myLastCommand );
1228 //================================================================================
1230 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1231 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1233 //================================================================================
1235 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) /*theCmdUsingSubmesh*/ ) const
1237 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1238 // for ( ; id_obj != myObjects.end(); ++id_obj )
1240 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1241 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1243 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1244 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1246 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1247 // list< _pyID >::iterator id = idList.begin();
1248 // for ( ; id != idList.end(); ++id )
1249 // if ( id_obj->first == *id )
1250 // // _pySubMesh::Process() does what we need
1251 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1256 //================================================================================
1258 * \brief Clean commands of removed objects depending on myIsPublished flag
1260 //================================================================================
1262 void _pyGen::ClearCommands()
1264 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1265 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1266 id_mesh->second->ClearCommands();
1268 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1269 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1270 if ( !id_hyp->second.IsNull() )
1271 id_hyp->second->ClearCommands();
1273 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1274 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1275 for ( ; robj != myOrderedObjects.rend(); ++robj )
1276 if ( ! robj->IsNull() )
1277 (*robj)->ClearCommands();
1278 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1279 for ( ; obj != myOrderedObjects.end(); ++obj )
1280 if ( ! obj->IsNull() )
1281 (*obj)->ClearCommands();
1284 //================================================================================
1286 * \brief Release mutual handles of objects
1288 //================================================================================
1292 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1293 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1294 id_mesh->second->Free();
1297 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1298 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1299 id_ed->second->Free();
1300 myMeshEditors.clear();
1302 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1303 for ( ; id_obj != myObjects.end(); ++id_obj )
1304 id_obj->second->Free();
1307 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1308 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1309 if ( !id_hyp->second.IsNull() )
1310 id_hyp->second->Free();
1313 myFile2ExportedMesh.clear();
1315 //myKeepAgrCmdsIDs.Print();
1318 //================================================================================
1320 * \brief Add access method to mesh that is an argument
1321 * \param theCmd - command to add access method
1322 * \retval bool - true if added
1324 //================================================================================
1326 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1329 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1330 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1331 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1337 //================================================================================
1339 * \brief Add access method to algo that is an object or an argument
1340 * \param theCmd - command to add access method
1341 * \retval bool - true if added
1343 //================================================================================
1345 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1348 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1349 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1350 if ( !id_hyp->second.IsNull() &&
1351 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1352 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1353 id_hyp->second->AccessorMethod() ))
1359 //================================================================================
1361 * \brief Find hypothesis by ID (entry)
1362 * \param theHypID - The hypothesis ID
1363 * \retval Handle(_pyHypothesis) - The found hypothesis
1365 //================================================================================
1367 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1369 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1370 if ( id_hyp != myHypos.end() &&
1371 !id_hyp->second.IsNull() &&
1372 theHypID == id_hyp->second->GetID() )
1373 return id_hyp->second;
1374 return Handle(_pyHypothesis)();
1377 //================================================================================
1379 * \brief Find algorithm able to create a hypothesis
1380 * \param theGeom - The shape ID the algorithm was created on
1381 * \param theMesh - The mesh ID that created the algorithm
1382 * \param theHypothesis - The hypothesis the algorithm should be able to create
1383 * \retval Handle(_pyHypothesis) - The found algo
1385 //================================================================================
1387 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1388 const Handle(_pyHypothesis)& theHypothesis )
1390 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1391 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1392 if ( !id_hyp->second.IsNull() &&
1393 id_hyp->second->IsAlgo() &&
1394 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1395 id_hyp->second->GetGeom() == theGeom &&
1396 id_hyp->second->GetMesh() == theMesh )
1397 return id_hyp->second;
1398 return Handle(_pyHypothesis)();
1401 //================================================================================
1403 * \brief Find subMesh by ID (entry)
1404 * \param theSubMeshID - The subMesh ID
1405 * \retval Handle(_pySubMesh) - The found subMesh
1407 //================================================================================
1409 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1411 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1412 if ( id_subMesh != myObjects.end() )
1413 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1414 return Handle(_pySubMesh)();
1418 //================================================================================
1420 * \brief Change order of commands in the script
1421 * \param theCmd1 - One command
1422 * \param theCmd2 - Another command
1424 //================================================================================
1426 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1428 list< Handle(_pyCommand) >::iterator pos1, pos2;
1429 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1430 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1431 myCommands.insert( pos1, theCmd2 );
1432 myCommands.insert( pos2, theCmd1 );
1433 myCommands.erase( pos1 );
1434 myCommands.erase( pos2 );
1436 int nb1 = theCmd1->GetOrderNb();
1437 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1438 theCmd2->SetOrderNb( nb1 );
1439 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1440 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1443 //================================================================================
1445 * \brief Set one command after the other
1446 * \param theCmd - Command to move
1447 * \param theAfterCmd - Command ater which to insert the first one
1449 //================================================================================
1451 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1453 setNeighbourCommand( theCmd, theAfterCmd, true );
1456 //================================================================================
1458 * \brief Set one command before the other
1459 * \param theCmd - Command to move
1460 * \param theBeforeCmd - Command before which to insert the first one
1462 //================================================================================
1464 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1466 setNeighbourCommand( theCmd, theBeforeCmd, false );
1469 //================================================================================
1471 * \brief Set one command before or after the other
1472 * \param theCmd - Command to move
1473 * \param theOtherCmd - Command ater or before which to insert the first one
1475 //================================================================================
1477 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1478 Handle(_pyCommand)& theOtherCmd,
1479 const bool theIsAfter )
1481 list< Handle(_pyCommand) >::iterator pos;
1482 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1483 myCommands.erase( pos );
1484 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1485 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1488 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1489 (*pos)->SetOrderNb( i++ );
1492 //================================================================================
1494 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1496 //================================================================================
1498 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1500 // No more needed after adding _pyObject::myArgCommands
1502 // const char filterPrefix[] = "aFilter0x";
1503 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1506 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1508 // const _AString & arg = theCommand->GetArg( i );
1509 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1510 // if ( arg.Search( filterPrefix ) != 1 )
1513 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1514 // if ( !filter.IsNull() )
1516 // filter->AddUser( user );
1517 // if ( !filter->GetNewID().IsEmpty() )
1518 // theCommand->SetArg( i, filter->GetNewID() );
1523 //================================================================================
1525 * \brief Set command be last in list of commands
1526 * \param theCmd - Command to be last
1528 //================================================================================
1530 Handle(_pyCommand)& _pyGen::GetLastCommand()
1532 return myLastCommand;
1535 //================================================================================
1537 * \brief Set method to access to object wrapped with python class
1538 * \param theID - The wrapped object entry
1539 * \param theMethod - The accessor method
1541 //================================================================================
1543 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1545 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1548 //================================================================================
1550 * \brief Generated new ID for object and assign with existing name
1551 * \param theID - ID of existing object
1553 //================================================================================
1555 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1560 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1562 while ( myObjectNames.IsBound( aNewID ) );
1564 if ( myObjectNames.IsBound( theID ) )
1565 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1567 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1571 //================================================================================
1573 * \brief Stores theObj in myObjects
1575 //================================================================================
1577 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1579 if ( theObj.IsNull() ) return false;
1581 CheckObjectIsReCreated( theObj );
1585 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1586 add = myMeshes.insert( make_pair( theObj->GetID(),
1587 Handle(_pyMesh)::DownCast( theObj ))).second;
1589 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1590 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1591 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1594 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1595 if ( add ) myOrderedObjects.push_back( theObj );
1600 //================================================================================
1602 * \brief Erases an existing object with the same ID. This method should be called
1603 * before storing theObj in _pyGen
1605 //================================================================================
1607 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1609 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1612 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1613 Handle(_pyObject) existing;
1615 existing = FindHyp( theObj->GetID() );
1617 existing = FindObject( theObj->GetID() );
1618 if ( !existing.IsNull() && existing != theObj )
1620 existing->SetRemovedFromStudy( true );
1621 existing->ClearCommands();
1624 if ( myHypos.count( theObj->GetID() ))
1625 myHypos.erase( theObj->GetID() );
1627 else if ( myMeshes.count( theObj->GetID() ))
1629 myMeshes.erase( theObj->GetID() );
1631 else if ( myObjects.count( theObj->GetID() ))
1633 myObjects.erase( theObj->GetID() );
1638 //================================================================================
1640 * \brief Re-register an object with other ID to make it Process() commands of
1641 * other object having this ID
1643 //================================================================================
1645 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1647 if ( theObj.IsNull() ) return;
1649 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1650 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1652 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1653 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1656 myObjects.insert( make_pair( theID, theObj ));
1659 //================================================================================
1661 * \brief Finds a _pyObject by ID
1663 //================================================================================
1665 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1668 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1669 if ( id_obj != myObjects.end() )
1670 return id_obj->second;
1673 _pyGen* me = const_cast< _pyGen* >( this );
1674 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1675 if ( id_obj != myMeshes.end() )
1676 return id_obj->second;
1679 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1680 // if ( id_obj != myMeshEditors.end() )
1681 // return id_obj->second;
1683 return Handle(_pyObject)();
1686 //================================================================================
1688 * \brief Check if a study entry is under GEOM component
1690 //================================================================================
1692 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1694 bool isGeom = myGeomIDNb && myGeomIDIndex <= theObjID.Length() &&
1695 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb;
1696 bool isShaper = myShaperIDNb && myShaperIDIndex <= theObjID.Length() &&
1697 int( theObjID.Value( myShaperIDIndex )) == myShaperIDNb;
1698 return ((isGeom || isShaper) && _pyCommand::IsStudyEntry( theObjID ));
1701 //================================================================================
1703 * \brief Returns true if an object is not present in a study
1705 //================================================================================
1707 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1709 if ( theObjID.IsEmpty() ) return false;
1711 if ( myObjectNames.IsBound( theObjID ))
1712 return false; // SMESH object is in study
1714 // either the SMESH object is not in study or it is a GEOM object
1715 if ( IsGeomObject( theObjID ))
1717 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1718 if ( so->_is_nil() ) return true;
1719 CORBA::Object_var obj = so->GetObject();
1720 return CORBA::is_nil( obj );
1722 return true; // SMESH object not in study
1725 //================================================================================
1727 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1728 * this object is not dumped
1729 * \param [in] theObjID - entry of the object whose creation command was eliminated
1731 //================================================================================
1733 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1735 myRemovedObjIDs.insert( theObjID );
1738 //================================================================================
1740 * \brief Return reader of hypotheses of plugins
1742 //================================================================================
1744 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1746 if (myHypReader.IsNull() )
1747 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1753 //================================================================================
1755 * \brief Mesh created by SMESH_Gen
1757 //================================================================================
1759 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1760 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1762 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1763 myGeomNotInStudy = true;
1765 // convert my creation command --> smeshpy.Mesh(...)
1766 Handle(_pyCommand) creationCmd = GetCreationCmd();
1767 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1768 creationCmd->SetMethod( "Mesh" );
1769 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1772 //================================================================================
1774 * \brief Mesh created by SMESH_MeshEditor
1776 //================================================================================
1778 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1779 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1781 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1783 // this mesh depends on the exported mesh
1784 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1785 if ( !file.IsEmpty() )
1787 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1788 addFatherMesh( exportData.myMesh );
1789 if ( !exportData.myLastComputeCmd.IsNull() )
1791 // restore cleared Compute() by which the exported mesh was generated
1792 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1793 // protect that Compute() cmd from clearing
1794 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1795 exportData.myMesh->myLastComputeCmd.Nullify();
1799 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1801 // this mesh depends on concatenated meshes
1802 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1803 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1804 list< _pyID >::iterator meshID = idList.begin();
1805 for ( ; meshID != idList.end(); ++meshID )
1806 addFatherMesh( *meshID );
1808 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1810 // this mesh depends on a copied IdSource
1811 const _pyID& objID = theCreationCmd->GetArg( 1 );
1812 addFatherMesh( objID );
1814 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1815 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1816 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1818 // this mesh depends on a source mesh
1819 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1820 const _pyID& meshID = theCreationCmd->GetObject();
1821 addFatherMesh( meshID );
1824 // convert my creation command
1825 Handle(_pyCommand) creationCmd = GetCreationCmd();
1826 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1827 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1830 //================================================================================
1832 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1833 * \param theCommand - Engine method called for this mesh
1835 //================================================================================
1837 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1839 // some methods of SMESH_Mesh interface need special conversion
1840 // to methods of Mesh python class
1842 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1843 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1844 // 2. AddHypothesis(geom, hyp)
1845 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1846 // 3. CreateGroupFromGEOM(type, name, grp)
1847 // --> in Mesh.Group(grp, name="")
1848 // 4. ExportToMED(f, auto_groups, version)
1849 // --> in Mesh.ExportMED( f, auto_groups, version )
1852 const TCollection_AsciiString& method = theCommand->GetMethod();
1853 // ----------------------------------------------------------------------
1854 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1856 if ( !theGen->IsToKeepAllCommands() ) // !historical
1858 list< Handle(_pyHypothesis) >::iterator hyp;
1859 if ( !myLastComputeCmd.IsNull() )
1861 // check if the previously computed mesh has been edited,
1862 // if so then we do not clear the previous Compute()
1863 bool toClear = true;
1864 if ( myLastComputeCmd->GetMethod() == "Compute" )
1866 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1867 for ( ; e != myEditors.end() && toClear; ++e )
1869 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1870 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1871 if ( cmd != cmds.rend() &&
1872 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1878 // clear hyp commands called before myLastComputeCmd
1879 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1880 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1882 myLastComputeCmd->Clear();
1885 myLastComputeCmd = theCommand;
1887 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1888 (*hyp)->MeshComputed( myLastComputeCmd );
1892 // ----------------------------------------------------------------------
1893 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1895 if ( !theGen->IsToKeepAllCommands() ) // !historical
1898 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1899 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1900 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1902 if ( !myLastComputeCmd.IsNull() )
1904 list< Handle(_pyHypothesis) >::iterator hyp;
1905 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1906 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1908 myLastComputeCmd->Clear();
1911 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1912 for ( ; e != myEditors.end(); ++e )
1914 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1915 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1916 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1917 if ( !(*cmd)->IsEmpty() )
1919 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1923 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1926 // ----------------------------------------------------------------------
1927 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1928 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1929 if ( !subMesh.IsNull() ) {
1930 subMesh->SetCreator( this );
1931 mySubmeshes.push_back( subMesh );
1934 // ----------------------------------------------------------------------
1935 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1936 theCommand->Clear();
1938 // ----------------------------------------------------------------------
1939 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1940 myAddHypCmds.push_back( theCommand );
1942 const _pyID& hypID = theCommand->GetArg( 2 );
1943 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1944 if ( !hyp.IsNull() ) {
1945 myHypos.push_back( hyp );
1946 if ( hyp->GetMesh().IsEmpty() )
1947 hyp->SetMesh( this->GetID() );
1950 // ----------------------------------------------------------------------
1951 else if ( method == "CreateGroup" ||
1952 method == "CreateGroupFromGEOM" ||
1953 method == "CreateGroupFromFilter" ||
1954 method == "CreateDimGroup" )
1956 Handle(_pyGroup) group = new _pyGroup( theCommand );
1957 myGroups.push_back( group );
1958 theGen->AddObject( group );
1960 // ----------------------------------------------------------------------
1961 // update list of groups
1962 else if ( method == "GetGroups" )
1964 bool allGroupsRemoved = true;
1965 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1966 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1967 list< _pyID >::iterator grID = idList.begin();
1968 const size_t nbGroupsBefore = myGroups.size();
1969 Handle(_pyObject) obj;
1970 for ( ; grID != idList.end(); ++grID )
1972 obj = theGen->FindObject( *grID );
1975 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1976 theGen->AddObject( group );
1977 myGroups.push_back( group );
1980 if ( !obj->CanClear() )
1981 allGroupsRemoved = false;
1983 if ( nbGroupsBefore == myGroups.size() && !obj.IsNull() ) // no new _pyGroup created
1984 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1986 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1988 // check if the preceding command is Compute();
1989 // if GetGroups() is just after Compute(), this can mean that the groups
1990 // were created by some algorithm and hence Compute() should not be discarded
1991 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1992 std::list< Handle(_pyCommand) >::reverse_iterator cmd = cmdList.rbegin();
1993 while ( (*cmd)->GetMethod() == "GetGroups" )
1995 if ( myLastComputeCmd == (*cmd))
1996 // protect last Compute() from clearing by the next Compute()
1997 myLastComputeCmd.Nullify();
2000 // ----------------------------------------------------------------------
2001 // notify a group about full removal
2002 else if ( method == "RemoveGroupWithContents" ||
2003 method == "RemoveGroup")
2005 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
2006 const _pyID groupID = theCommand->GetArg( 1 );
2007 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
2008 if ( !grp.IsNull() )
2010 if ( method == "RemoveGroupWithContents" )
2011 grp->RemovedWithContents();
2012 // to clear RemoveGroup() if the group creation is cleared
2013 grp->AddProcessedCmd( theCommand );
2017 // ----------------------------------------------------------------------
2018 else if ( theCommand->MethodStartsFrom( "Export" ))
2020 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
2021 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
2022 method == "ExportMED" )
2024 theCommand->SetMethod( "ExportMED" );
2025 // filter out deprecated version parameter
2026 vector< _AString > args;
2027 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2028 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2029 args.push_back( theCommand->GetArg( i ) );
2031 theCommand->RemoveArgs();
2032 for ( unsigned int i = 0; i < args.size(); i++ )
2033 theCommand->SetArg( i+1, args[i] );
2034 if ( theCommand->GetNbArgs() == 4 )
2036 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2037 _AString autoDimension = theCommand->GetArg( 4 );
2038 theCommand->SetArg( 4, "None" );
2039 theCommand->SetArg( 5, autoDimension );
2042 else if ( method == "ExportCGNS" )
2043 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2044 _pyID partID = theCommand->GetArg( 1 );
2045 int nbArgs = theCommand->GetNbArgs();
2046 for ( int i = 2; i <= nbArgs; ++i )
2047 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2048 theCommand->SetArg( nbArgs, partID );
2050 else if ( method == "ExportGMF" )
2051 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2052 _pyID partID = theCommand->GetArg( 1 );
2053 _AString file = theCommand->GetArg( 2 );
2054 theCommand->RemoveArgs();
2055 theCommand->SetArg( 1, file );
2056 theCommand->SetArg( 2, partID );
2058 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2059 { // ExportPartTo*(part, ...) -> Export*(..., part)
2061 // remove "PartTo" from the method
2062 TCollection_AsciiString newMethod = method;
2063 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2064 theCommand->SetMethod( newMethod );
2065 // replace version parameter by minor
2066 std::list< _AString > args;
2067 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2068 if ( _FilterArg( theCommand->GetArg( i )))
2069 args.push_back( "minor=0");
2071 args.push_back( theCommand->GetArg( i ));
2073 // check the 1st arg meshPart, it must be SMESH_IDSource
2074 _AString meshPart = args.front();
2075 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2076 meshPart.Search( "Filter" ) > 0 ||
2077 meshPart.Search( "GetIDSource" ) > 0 ||
2078 meshPart.Search( "meshPart" ) > 0 )
2080 // set the 1st arg meshPart
2081 // - to 5th place for ExportMED command
2082 // - to last place for the rest commands
2083 std::list< _AString >::iterator newPos = args.end();
2084 if ( newMethod == "ExportMED" )
2085 std::advance( newPos = args.begin(), 5 );
2086 args.splice( newPos, args, args.begin() );
2088 std::list< _AString >::iterator a = args.begin();
2089 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2090 theCommand->SetArg( i, *a );
2092 // remember file name
2093 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2094 ExportedMeshData( this, myLastComputeCmd ));
2096 // ----------------------------------------------------------------------
2097 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2099 _pyID hypID = theCommand->GetArg( 2 );
2100 _pyID geomID = theCommand->GetArg( 1 );
2101 bool isLocal = ( geomID != GetGeom() );
2103 // check if this mesh still has corresponding addition command
2104 Handle(_pyCommand) addCmd;
2105 list< Handle(_pyCommand) >::iterator cmd;
2106 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2107 for ( int i = 0; i < 2; ++i )
2109 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2110 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2112 bool sameHyp = true;
2113 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2114 sameHyp = false; // other hyp
2115 if ( (*cmd)->GetNbArgs() == 2 &&
2116 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2117 sameHyp = false; // other geom
2118 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2119 sameHyp = false; // other geom
2123 cmd = addHypCmds.erase( cmd );
2124 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2126 theCommand->Clear();
2130 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2131 addCmd->RemoveArgs();
2132 addCmd->SetArg( 1, hypID );
2134 addCmd->SetArg( 2, geomID );
2143 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2144 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2145 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2146 _pyID geom = theCommand->GetArg( 1 );
2147 theCommand->RemoveArgs();
2148 theCommand->SetArg( 1, hypID );
2149 if ( geom != GetGeom() )
2150 theCommand->SetArg( 2, geom );
2152 // remove hyp from myHypos
2153 myHypos.remove( hyp );
2155 // check for SubMesh order commands
2156 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2158 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2159 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2160 // commands are moved at the end of the script
2161 TCollection_AsciiString subIDs =
2162 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2163 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2164 list< _pyID >::iterator subID = idList.begin();
2165 for ( ; subID != idList.end(); ++subID )
2167 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2168 if ( !subMesh.IsNull() )
2169 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2172 // add accessor method if necessary
2175 if ( NeedMeshAccess( theCommand ))
2176 // apply theCommand to the mesh wrapped by smeshpy mesh
2177 AddMeshAccess( theCommand );
2181 //================================================================================
2183 * \brief Return True if addition of accesor method is needed
2185 //================================================================================
2187 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2189 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2190 // so no conversion is needed for them at all:
2191 static TStringSet sameMethods;
2192 if ( sameMethods.empty() ) {
2193 const char * names[] =
2194 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2195 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2196 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2197 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2198 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2199 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2200 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2201 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2202 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2203 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2204 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2205 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2206 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2207 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2208 ,"" }; // <- mark of end
2209 sameMethods.Insert( names );
2212 return !sameMethods.Contains( theCommand->GetMethod() );
2215 //================================================================================
2217 * \brief Convert creation and addition of all algos and hypos
2219 //================================================================================
2221 void _pyMesh::Flush()
2224 // get the meshes this mesh depends on via hypotheses
2225 list< Handle(_pyMesh) > fatherMeshes;
2226 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2227 for ( ; hyp != myHypos.end(); ++hyp )
2228 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2229 myGeomNotInStudy = true;
2231 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2232 for ( ; m != fatherMeshes.end(); ++m )
2233 addFatherMesh( *m );
2234 // if ( removedGeom )
2235 // SetRemovedFromStudy(); // as referred geometry not in study
2237 if ( myGeomNotInStudy )
2240 list < Handle(_pyCommand) >::iterator cmd;
2242 // try to convert algo addition like this:
2243 // mesh.AddHypothesis( geom, ALGO ) --> ALGO = mesh.Algo()
2244 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2246 Handle(_pyCommand) addCmd = *cmd;
2248 _pyID algoID = addCmd->GetArg( 2 );
2249 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2250 if ( algo.IsNull() || !algo->IsAlgo() )
2253 // check and create new algorithm instance if it is already wrapped
2254 if ( algo->IsWrapped() ) {
2255 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2256 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2257 TCollection_AsciiString( " = " ) + theGen->GetID() +
2258 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2259 TCollection_AsciiString( "\" )" );
2261 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2262 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2263 if ( !newAlgo.IsNull() ) {
2264 newAlgo->Assign( algo, this->GetID() );
2265 newAlgo->SetCreationCmd( newCmd );
2267 // set algorithm creation
2268 theGen->SetCommandBefore( newCmd, addCmd );
2269 myHypos.push_back( newAlgo );
2270 if ( !myLastComputeCmd.IsNull() &&
2271 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2272 newAlgo->MeshComputed( myLastComputeCmd );
2277 _pyID geom = addCmd->GetArg( 1 );
2278 bool isLocalAlgo = ( geom != GetGeom() );
2281 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2283 // wrapped algo is created after mesh creation
2284 GetCreationCmd()->AddDependantCmd( addCmd );
2286 if ( isLocalAlgo ) {
2287 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2288 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2289 TCollection_AsciiString( "geom=" ) + geom );
2290 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2291 list < Handle(_pySubMesh) >::iterator smIt;
2292 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2293 Handle(_pySubMesh) subMesh = *smIt;
2294 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2295 if ( geom == subCmd->GetArg( 1 )) {
2296 subCmd->SetObject( algo->GetID() );
2297 subCmd->RemoveArgs();
2298 subMesh->SetCreator( algo );
2303 else // KO - ALGO was already created
2305 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2306 addCmd->RemoveArgs();
2307 addCmd->SetArg( 1, algoID );
2309 addCmd->SetArg( 2, geom );
2310 myNotConvertedAddHypCmds.push_back( addCmd );
2314 // try to convert hypo addition like this:
2315 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2316 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2318 Handle(_pyCommand) addCmd = *cmd;
2319 _pyID hypID = addCmd->GetArg( 2 );
2320 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2321 if ( hyp.IsNull() || hyp->IsAlgo() )
2323 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2325 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2326 _pyID geom = addCmd->GetArg( 1 );
2327 addCmd->RemoveArgs();
2328 addCmd->SetArg( 1, hypID );
2329 if ( geom != GetGeom() )
2330 addCmd->SetArg( 2, geom );
2331 myNotConvertedAddHypCmds.push_back( addCmd );
2335 myAddHypCmds.clear();
2336 mySubmeshes.clear();
2339 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2340 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2344 //================================================================================
2346 * \brief Sets myIsPublished of me and of all objects depending on me.
2348 //================================================================================
2350 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2352 _pyObject::SetRemovedFromStudy(isRemoved);
2354 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2355 for ( ; sm != mySubmeshes.end(); ++sm )
2356 (*sm)->SetRemovedFromStudy(isRemoved);
2358 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2359 for ( ; gr != myGroups.end(); ++gr )
2360 (*gr)->SetRemovedFromStudy(isRemoved);
2362 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2363 for ( ; m != myChildMeshes.end(); ++m )
2364 (*m)->SetRemovedFromStudy(isRemoved);
2366 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2367 for ( ; e != myEditors.end(); ++e )
2368 (*e)->SetRemovedFromStudy(isRemoved);
2371 //================================================================================
2373 * \brief Return true if none of myChildMeshes is in study
2375 //================================================================================
2377 bool _pyMesh::CanClear()
2382 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2383 for ( ; m != myChildMeshes.end(); ++m )
2384 if ( !(*m)->CanClear() )
2390 //================================================================================
2392 * \brief Clear my commands and commands of mesh editor
2394 //================================================================================
2396 void _pyMesh::ClearCommands()
2402 // mark all sub-objects as not removed, except child meshes
2403 list< Handle(_pyMesh) > children;
2404 children.swap( myChildMeshes );
2405 SetRemovedFromStudy( false );
2406 children.swap( myChildMeshes );
2410 _pyObject::ClearCommands();
2412 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2413 for ( ; sm != mySubmeshes.end(); ++sm )
2414 (*sm)->ClearCommands();
2416 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2417 for ( ; gr != myGroups.end(); ++gr )
2418 (*gr)->ClearCommands();
2420 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2421 for ( ; e != myEditors.end(); ++e )
2422 (*e)->ClearCommands();
2425 //================================================================================
2427 * \brief Add a father mesh by ID
2429 //================================================================================
2431 void _pyMesh::addFatherMesh( const _pyID& meshID )
2433 if ( !meshID.IsEmpty() && meshID != GetID() )
2434 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2437 //================================================================================
2439 * \brief Add a father mesh
2441 //================================================================================
2443 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2445 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2447 //myFatherMeshes.push_back( mesh );
2448 mesh->myChildMeshes.push_back( this );
2450 // protect last Compute() from clearing by the next Compute()
2451 mesh->myLastComputeCmd.Nullify();
2455 //================================================================================
2457 * \brief MeshEditor convert its commands to ones of mesh
2459 //================================================================================
2461 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2462 _pyObject( theCreationCmd )
2464 myMesh = theCreationCmd->GetObject();
2465 myCreationCmdStr = theCreationCmd->GetString();
2466 theCreationCmd->Clear();
2468 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2469 if ( !mesh.IsNull() )
2470 mesh->AddEditor( this );
2473 //================================================================================
2475 * \brief convert its commands to ones of mesh
2477 //================================================================================
2479 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2481 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2482 // commands calling these methods are converted to calls of Mesh methods without
2483 // additional modifs, only object is changed from MeshEditor to Mesh.
2484 static TStringSet sameMethods;
2485 if ( sameMethods.empty() ) {
2486 const char * names[] = {
2487 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2488 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2489 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2490 "MoveNode", "MoveClosestNodeToPoint",
2491 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2492 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2493 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2494 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2495 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2496 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2497 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2498 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2499 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2500 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject","Offset",
2501 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2502 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2503 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2504 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2505 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2506 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2507 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2508 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2509 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2510 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2511 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2512 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2513 ,"" }; // <- mark of the end
2514 sameMethods.Insert( names );
2517 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2518 TStringMap diffMethods;
2519 if ( diffMethods.empty() ) {
2520 const char * orig2newName[] = {
2521 // original name --------------> new name
2522 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2523 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2524 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2525 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2526 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2527 ""};// <- mark of the end
2528 diffMethods.Insert( orig2newName );
2531 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2532 // only by last two arguments
2533 static TStringSet diffLastTwoArgsMethods;
2534 if (diffLastTwoArgsMethods.empty() ) {
2535 const char * names[] = {
2536 "MirrorMakeGroups","MirrorObjectMakeGroups",
2537 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2538 "RotateMakeGroups","RotateObjectMakeGroups",
2539 ""};// <- mark of the end
2540 diffLastTwoArgsMethods.Insert( names );
2543 // only a method name is to change?
2544 const TCollection_AsciiString & method = theCommand->GetMethod();
2545 bool isPyMeshMethod = sameMethods.Contains( method );
2546 if ( !isPyMeshMethod )
2548 TCollection_AsciiString newMethod = diffMethods.Value( method );
2549 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2550 theCommand->SetMethod( newMethod );
2552 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2553 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2555 isPyMeshMethod = true;
2556 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2557 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2560 if ( !isPyMeshMethod )
2562 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2563 // functions with the flag "theMakeGroups = True" like:
2564 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2565 int pos = method.Search("MakeGroups");
2568 isPyMeshMethod = true;
2569 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2570 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2572 // 1. Remove "MakeGroups" from the Command
2573 TCollection_AsciiString aMethod = theCommand->GetMethod();
2574 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2577 pos = pos-2; //Remove "0D" from the Command too
2578 aMethod.Trunc(pos-1);
2579 theCommand->SetMethod(aMethod);
2581 // 2. And add last "True" argument(s)
2582 while(nbArgsToAdd--)
2583 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2584 if( is0DmethId || is0DmethObj )
2585 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2589 // ExtrusionSweep0D() -> ExtrusionSweep()
2590 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2591 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2592 method == "ExtrusionSweepObject0D" ))
2594 isPyMeshMethod = true;
2595 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2596 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2597 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2600 // DoubleNode...New(...) -> DoubleNode...(...,True)
2601 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2602 method == "DoubleNodeElemGroupsNew" ||
2603 method == "DoubleNodeGroupNew" ||
2604 method == "DoubleNodeGroupsNew" ||
2605 method == "DoubleNodeElemGroup2New" ||
2606 method == "DoubleNodeElemGroups2New"))
2608 isPyMeshMethod = true;
2609 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2610 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2611 if ( excessLen == 3 )
2613 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2615 else if ( theCommand->GetArg(4) == "0" ||
2616 theCommand->GetArg(5) == "0" )
2618 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2619 // Group = DoubleNodeGroup2New(,,,False, True)
2620 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2621 theCommand->SetResultValue( groupID );
2624 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2625 // FindElementsByPoint(x, y, z, elementType, meshPart)
2626 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2628 isPyMeshMethod = true;
2629 theCommand->SetMethod( "FindElementsByPoint" );
2630 // make the 1st arg be the last one
2631 _pyID partID = theCommand->GetArg( 1 );
2632 int nbArgs = theCommand->GetNbArgs();
2633 for ( int i = 2; i <= nbArgs; ++i )
2634 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2635 theCommand->SetArg( nbArgs, partID );
2637 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2638 if ( !isPyMeshMethod && method == "Reorient2D" )
2640 isPyMeshMethod = true;
2641 _AString mesh = theCommand->GetArg( 1 );
2642 _AString dir = theCommand->GetArg( 2 );
2643 _AString face = theCommand->GetArg( 3 );
2644 _AString point = theCommand->GetArg( 4 );
2645 theCommand->RemoveArgs();
2646 theCommand->SetArg( 1, mesh );
2647 theCommand->SetArg( 2, dir );
2648 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2649 theCommand->SetArg( 3, point );
2651 theCommand->SetArg( 3, face );
2654 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2656 isPyMeshMethod = true;
2657 int crit_arg = theCommand->GetNbArgs();
2658 const _AString& crit = theCommand->GetArg(crit_arg);
2659 if (crit.Search("MaxElementLength2D") != -1)
2660 theCommand->SetArg(crit_arg, "");
2663 if ( isPyMeshMethod )
2665 theCommand->SetObject( myMesh );
2669 // editor creation command is needed only if any editor function is called
2670 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2671 if ( !myCreationCmdStr.IsEmpty() ) {
2672 GetCreationCmd()->GetString() = myCreationCmdStr;
2673 myCreationCmdStr.Clear();
2678 //================================================================================
2680 * \brief Return true if my mesh can be removed
2682 //================================================================================
2684 bool _pyMeshEditor::CanClear()
2686 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2687 return mesh.IsNull() ? true : mesh->CanClear();
2690 //================================================================================
2692 * \brief _pyHypothesis constructor
2693 * \param theCreationCmd -
2695 //================================================================================
2697 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2698 _pyObject( theCreationCmd ), myCurCrMethod(0)
2700 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2703 //================================================================================
2705 * \brief Creates algorithm or hypothesis
2706 * \param theCreationCmd - The engine command creating a hypothesis
2707 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2709 //================================================================================
2711 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2713 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2714 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2716 Handle(_pyHypothesis) hyp, algo;
2719 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2720 if ( hypTypeQuoted.IsEmpty() )
2723 TCollection_AsciiString hypType =
2724 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2726 algo = new _pyAlgorithm( theCreationCmd );
2727 hyp = new _pyHypothesis( theCreationCmd );
2729 if ( hypType == "NumberOfSegments" ) {
2730 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2731 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2732 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2733 hyp->AddArgMethod( "SetNumberOfSegments" );
2734 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2735 hyp->AddArgMethod( "SetScaleFactor" );
2736 hyp->AddArgMethod( "SetReversedEdges" );
2737 // same for ""CompositeSegment_1D:
2738 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2739 hyp->AddArgMethod( "SetNumberOfSegments" );
2740 hyp->AddArgMethod( "SetScaleFactor" );
2741 hyp->AddArgMethod( "SetReversedEdges" );
2743 else if ( hypType == "SegmentLengthAroundVertex" ) {
2744 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2745 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2746 hyp->AddArgMethod( "SetLength" );
2747 // same for ""CompositeSegment_1D:
2748 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2749 hyp->AddArgMethod( "SetLength" );
2751 else if ( hypType == "LayerDistribution2D" ) {
2752 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2753 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2755 else if ( hypType == "LayerDistribution" ) {
2756 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2757 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2759 else if ( hypType == "CartesianParameters3D" ) {
2760 hyp = new _pyComplexParamHypo( theCreationCmd );
2761 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2762 for ( int iArg = 0; iArg < 4; ++iArg )
2763 hyp->setCreationArg( iArg+1, "[]");
2764 hyp->AddAccumulativeMethod( "SetGrid" );
2765 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2769 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2772 return algo->IsValid() ? algo : hyp;
2775 //================================================================================
2777 * \brief Returns true if addition of this hypothesis to a given mesh can be
2778 * wrapped into hypothesis creation
2780 //================================================================================
2782 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2784 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2786 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2787 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2793 //================================================================================
2795 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2796 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2797 * \param theAlgo - The algo that can create this hypo
2798 * \retval bool - false if the command can't be converted
2800 //================================================================================
2802 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2803 const _pyID& theMesh)
2805 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2807 if ( !IsWrappable( theMesh ))
2810 myGeom = theCmd->GetArg( 1 );
2812 Handle(_pyHypothesis) algo;
2814 // find algo created on myGeom in theMesh
2815 algo = theGen->FindAlgo( myGeom, theMesh, this );
2816 if ( algo.IsNull() )
2818 // attach hypothesis creation command to be after algo creation command
2819 // because it can be new created instance of algorithm
2820 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2824 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2825 theCmd->SetResultValue( GetID() );
2826 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2827 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2828 // set args (geom will be set by _pyMesh calling this method)
2829 theCmd->RemoveArgs();
2830 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2831 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2832 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2834 theCmd->SetArg( i+1, "[]");
2836 // set a new creation command
2837 GetCreationCmd()->Clear();
2838 // replace creation command by wrapped instance
2839 // please note, that hypothesis attaches to algo creation command (see upper)
2840 SetCreationCmd( theCmd );
2843 // clear commands setting arg values
2844 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2845 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2848 // set unknown arg commands after hypo creation
2849 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2850 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2851 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2852 afterCmd->AddDependantCmd( *cmd );
2858 //================================================================================
2860 * \brief Remember hypothesis parameter values
2861 * \param theCommand - The called hypothesis method
2863 //================================================================================
2865 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2867 ASSERT( !myIsAlgo );
2868 if ( !theGen->IsToKeepAllCommands() )
2869 rememberCmdOfParameter( theCommand );
2871 bool usedCommand = false;
2872 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2873 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2875 CreationMethod& crMethod = type2meth->second;
2876 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2877 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2879 myArgCommands.push_back( theCommand );
2881 while ( crMethod.myArgs.size() < i+1 )
2882 crMethod.myArgs.push_back( "None" );
2883 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2888 myUnusedCommands.push_back( theCommand );
2891 //================================================================================
2893 * \brief Finish conversion
2895 //================================================================================
2897 void _pyHypothesis::Flush()
2901 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2902 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2903 // Add access to a wrapped mesh
2904 theGen->AddMeshAccessorMethod( *cmd );
2905 // Add access to a wrapped algorithm
2906 theGen->AddAlgoAccessorMethod( *cmd );
2908 cmd = myUnusedCommands.begin();
2909 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2910 // Add access to a wrapped mesh
2911 theGen->AddMeshAccessorMethod( *cmd );
2912 // Add access to a wrapped algorithm
2913 theGen->AddAlgoAccessorMethod( *cmd );
2916 // forget previous hypothesis modifications
2917 myArgCommands.clear();
2918 myUnusedCommands.clear();
2921 //================================================================================
2923 * \brief clear creation, arg and unknown commands
2925 //================================================================================
2927 void _pyHypothesis::ClearAllCommands()
2929 GetCreationCmd()->Clear();
2930 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2931 for ( ; cmd != myArgCommands.end(); ++cmd )
2933 cmd = myUnusedCommands.begin();
2934 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2939 //================================================================================
2941 * \brief Assign fields of theOther to me except myIsWrapped
2943 //================================================================================
2945 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2946 const _pyID& theMesh )
2948 // myCreationCmd = theOther->myCreationCmd;
2949 myIsAlgo = theOther->myIsAlgo;
2950 myIsWrapped = false;
2951 myGeom = theOther->myGeom;
2953 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2954 myAccumulativeMethods = theOther->myAccumulativeMethods;
2955 //myUnusedCommands = theOther->myUnusedCommands;
2956 // init myCurCrMethod
2957 GetCreationMethod( theOther->GetAlgoType() );
2960 //================================================================================
2962 * \brief Analyze my erasability depending on myReferredObjs
2964 //================================================================================
2966 bool _pyHypothesis::CanClear()
2970 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2971 for ( ; obj != myReferredObjs.end(); ++obj )
2972 if ( (*obj)->CanClear() )
2979 //================================================================================
2981 * \brief Clear my commands depending on usage by meshes
2983 //================================================================================
2985 void _pyHypothesis::ClearCommands()
2987 // if ( !theGen->IsToKeepAllCommands() )
2989 // bool isUsed = false;
2990 // int lastComputeOrder = 0;
2991 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2992 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2993 // if ( ! (*cmd)->IsEmpty() )
2996 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2997 // lastComputeOrder = (*cmd)->GetOrderNb();
3001 // SetRemovedFromStudy( true );
3005 // // clear my commands invoked after lastComputeOrder
3006 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3007 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3009 // // list< Handle(_pyCommand)> & cmds = m2c->second;
3010 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
3011 // // cmds.back()->Clear();
3015 _pyObject::ClearCommands();
3018 //================================================================================
3020 * \brief Find arguments that are objects like mesh, group, geometry
3021 * \param meshes - referred meshes (directly or indirrectly)
3022 * \retval bool - false if a referred geometry is not in the study
3024 //================================================================================
3026 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3028 if ( IsAlgo() ) return true;
3030 bool geomPublished = true;
3031 vector< _AString > args;
3032 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3033 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3035 CreationMethod& crMethod = type2meth->second;
3036 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3038 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3039 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3040 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3041 args.push_back( (*cmd)->GetArg( nb ));
3044 for ( size_t i = 0; i < args.size(); ++i )
3046 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3047 if ( idList.empty() && !args[ i ].IsEmpty() )
3048 idList.push_back( args[ i ]);
3049 list< _pyID >::iterator id = idList.begin();
3050 for ( ; id != idList.end(); ++id )
3052 Handle(_pyObject) obj = theGen->FindObject( *id );
3053 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3056 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3057 geomPublished = false;
3061 myReferredObjs.push_back( obj );
3062 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3063 if ( !mesh.IsNull() )
3064 meshes.push_back( mesh );
3065 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3066 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3067 obj->SetRemovedFromStudy( false );
3071 return geomPublished;
3074 //================================================================================
3076 * \brief Remember theCommand setting a parameter
3078 //================================================================================
3080 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3082 // parameters are discriminated by method name
3083 _AString method = theCommand->GetMethod();
3084 if ( myAccumulativeMethods.count( method ))
3085 return; // this method adds values and not override the previous value
3087 // discriminate commands setting different parameters via one method
3088 // by passing parameter names like e.g. SetOption("size", "0.2")
3089 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3090 theCommand->GetNbArgs() > 1 )
3092 // mangle method by appending a 1st textual arg
3093 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3095 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3096 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3097 if ( !isalpha( arg.Value(2))) continue;
3102 // parameters are discriminated by method name
3103 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3104 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3106 cmds.back()->Clear(); // previous parameter value has not been used
3107 cmds.back() = theCommand;
3111 cmds.push_back( theCommand );
3115 //================================================================================
3117 * \brief Return true if a setting parameter command ha been used to compute mesh
3119 //================================================================================
3121 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3122 _pyCommand::TAddr avoidComputeAddr ) const
3124 bool isUsed = false;
3125 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3126 myComputeAddr2Cmds.begin();
3127 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3129 if ( addr2cmds->first == avoidComputeAddr ) continue;
3130 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3131 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3136 //================================================================================
3138 * \brief Save commands setting parameters as they are used for a mesh computation
3140 //================================================================================
3142 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3144 myComputeCmds.push_back( theComputeCmd );
3145 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3147 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3148 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3149 savedCmds.push_back( m2c->second.back() );
3152 //================================================================================
3154 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3156 //================================================================================
3158 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3160 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3162 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3163 for ( ; cmd != savedCmds.end(); ++cmd )
3165 // check if a cmd has been used to compute another mesh
3166 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3168 // check if a cmd is a sole command setting its parameter;
3169 // don't use method name for search as it can change
3170 map<_AString, list<Handle(_pyCommand)> >::iterator m2cmds = myMeth2Commands.begin();
3171 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3173 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3174 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3175 if ( cmdIt != cmds.end() )
3177 if ( cmds.back() != *cmd )
3179 cmds.erase( cmdIt );
3186 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3189 //================================================================================
3191 * \brief Sets an argNb-th argument of current creation command
3192 * \param argNb - argument index countered from 1
3194 //================================================================================
3196 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3198 if ( myCurCrMethod )
3200 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3201 myCurCrMethod->myArgs.push_back( "None" );
3202 if ( arg.IsEmpty() )
3203 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3205 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3210 //================================================================================
3212 * \brief Remember hypothesis parameter values
3213 * \param theCommand - The called hypothesis method
3215 //================================================================================
3217 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3219 if ( GetAlgoType() == "Cartesian_3D" )
3221 // CartesianParameters3D hyp
3223 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3224 theCommand->GetMethod() == "SetToAddEdges" )
3226 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3227 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3228 myArgCommands.push_back( theCommand );
3231 if ( theCommand->GetMethod() == "SetGrid" ||
3232 theCommand->GetMethod() == "SetGridSpacing" )
3234 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3235 int iArg = axis.Value(1) - '0';
3236 if ( theCommand->GetMethod() == "SetGrid" )
3238 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3242 myCurCrMethod->myArgs[ iArg ] = "[ ";
3243 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3244 myCurCrMethod->myArgs[ iArg ] += ", ";
3245 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3246 myCurCrMethod->myArgs[ iArg ] += "]";
3248 myArgCommands.push_back( theCommand );
3249 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3250 // accumulative, else, if the creation
3251 // is not converted, commands for axes 1 and 2 are lost
3256 if( theCommand->GetMethod() == "SetLength" )
3258 // NOW it is OBSOLETE
3259 // ex: hyp.SetLength(start, 1)
3260 // hyp.SetLength(end, 0)
3261 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3262 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3263 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3264 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3266 CreationMethod& crMethod = type2meth->second;
3267 while ( (int) crMethod.myArgs.size() < i+1 )
3268 crMethod.myArgs.push_back( "[]" );
3269 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3271 myArgCommands.push_back( theCommand );
3275 _pyHypothesis::Process( theCommand );
3278 //================================================================================
3280 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3282 //================================================================================
3284 void _pyComplexParamHypo::Flush()
3286 list < Handle(_pyCommand) >::iterator cmd;
3289 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3290 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3294 // if ( GetAlgoType() == "Cartesian_3D" )
3296 // _pyID algo = myCreationCmd->GetObject();
3297 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3299 // if ( IsWrapped() )
3301 // StructToList( *cmd, /*checkMethod=*/false );
3302 // const _AString & method = (*cmd)->GetMethod();
3303 // if ( method == "SetFixedPoint" )
3304 // (*cmd)->SetObject( algo );
3310 //================================================================================
3312 * \brief Convert methods of 1D hypotheses to my own methods
3313 * \param theCommand - The called hypothesis method
3315 //================================================================================
3317 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3319 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3322 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3323 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3324 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3326 // TCollection_AsciiString cmd =
3327 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3328 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3329 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3332 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3334 // // 1D hypo is already set, so distribution changes and the old
3335 // // 1D hypo is thrown away
3336 // my1dHyp->ClearAllCommands();
3339 // //my1dHyp->SetRemovedFromStudy( false );
3341 // if ( !myArgCommands.empty() )
3342 // myArgCommands.back()->Clear();
3343 myCurCrMethod->myArgs.push_back( hyp1dID );
3344 myArgCommands.push_back( theCommand );
3347 //================================================================================
3350 * \param theAdditionCmd - command to be converted
3351 * \param theMesh - mesh instance
3352 * \retval bool - status
3354 //================================================================================
3356 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3357 const _pyID& theMesh)
3359 myIsWrapped = false;
3361 if ( my1dHyp.IsNull() )
3364 // set "SetLayerDistribution()" after addition cmd
3365 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3367 _pyID geom = theAdditionCmd->GetArg( 1 );
3369 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3370 if ( !algo.IsNull() )
3372 my1dHyp->SetMesh( theMesh );
3373 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3374 algo->GetAlgoType().ToCString());
3375 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3378 // clear "SetLayerDistribution()" cmd
3379 myArgCommands.back()->Clear();
3381 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3383 // find RadialPrism algo created on <geom> for theMesh
3384 GetCreationCmd()->SetObject( algo->GetID() );
3385 GetCreationCmd()->SetMethod( myAlgoMethod );
3386 GetCreationCmd()->RemoveArgs();
3387 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3393 //================================================================================
3397 //================================================================================
3399 void _pyLayerDistributionHypo::Flush()
3401 // as creation of 1D hyp was written later then it's edition,
3402 // we need to find all it's edition calls and process them
3403 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3405 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3407 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3408 if ( hyp1dID.IsEmpty() ) continue;
3410 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3412 // make a new name for 1D hyp = "HypType" + "_Distribution"
3414 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3416 if ( prevNewName.IsEmpty() ) continue;
3417 newName = prevNewName;
3421 if ( hyp1d->IsWrapped() ) {
3422 newName = hyp1d->GetCreationCmd()->GetMethod();
3425 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3426 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3428 newName += "_Distribution";
3429 prevNewName = newName;
3431 hyp1d->GetCreationCmd()->SetResultValue( newName );
3433 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3434 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3435 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3436 const _pyID& objID = (*cmdIt)->GetObject();
3437 if ( objID == hyp1dID ) {
3438 if ( !hyp1d.IsNull() )
3440 hyp1d->Process( *cmdIt );
3441 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3443 ( *cmdIt )->SetObject( newName );
3446 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3447 (*cmd)->SetArg( 1, newName );
3451 //================================================================================
3453 * \brief additionally to Addition2Creation, clears SetDistrType() command
3454 * \param theCmd - AddHypothesis() command
3455 * \param theMesh - mesh to which a hypothesis is added
3456 * \retval bool - conversion result
3458 //================================================================================
3460 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3461 const _pyID& theMesh)
3463 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3464 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3465 bool scaleDistrType = false;
3466 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3467 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3468 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3469 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3470 scaleDistrType = true;
3473 else if ( !scaleDistrType ) {
3474 // distribution type changed: remove scale factor from args
3475 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3476 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3478 CreationMethod& crMethod = type2meth->second;
3479 if ( crMethod.myArgs.size() == 2 )
3480 crMethod.myArgs.pop_back();
3487 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3490 //================================================================================
3492 * \brief remove repeated commands defining distribution
3494 //================================================================================
3496 void _pyNumberOfSegmentsHyp::Flush()
3498 // find number of the last SetDistrType() command
3499 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3500 int distrTypeNb = 0;
3501 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3502 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3503 if ( cmd != myUnusedCommands.rbegin() )
3504 distrTypeNb = (*cmd)->GetOrderNb();
3506 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3509 // clear commands before the last SetDistrType()
3510 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3511 set< int > treatedCmdNbs; // avoid treating same cmd twice
3512 for ( int i = 0; i < 2; ++i ) {
3513 set<TCollection_AsciiString> uniqueMethods;
3514 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3515 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3517 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3518 continue;// avoid treating same cmd twice
3519 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3520 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3521 if ( !clear || method == "SetNumberOfSegments" ) {
3522 bool isNewInSet = uniqueMethods.insert( method ).second;
3523 clear = !isNewInSet;
3532 //================================================================================
3534 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3535 * into regular1D.LengthNearVertex( length, vertex )
3536 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3537 * \param theMesh - The mesh needing this hypo
3538 * \retval bool - false if the command can't be converted
3540 //================================================================================
3542 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3543 const _pyID& theMeshID)
3545 if ( IsWrappable( theMeshID )) {
3547 _pyID vertex = theCmd->GetArg( 1 );
3549 // the problem here is that segment algo can be not found
3550 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3551 // geometry where segment algorithm is assigned
3552 _pyID geom = vertex;
3553 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3554 while ( algo.IsNull() && !geom.IsEmpty()) {
3555 // try to find geom as a father of <vertex>
3556 geom = FatherID( geom );
3557 algo = theGen->FindAlgo( geom, theMeshID, this );
3559 if ( algo.IsNull() || geom.IsEmpty() )
3560 return false; // also possible to find geom as brother of veretex...
3562 // set geom instead of vertex
3563 theCmd->SetArg( 1, geom );
3565 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3566 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3567 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3569 // set vertex as a second arg
3570 theCmd->SetArg( 2, vertex );
3578 //================================================================================
3580 * \brief _pyAlgorithm constructor
3581 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3583 //================================================================================
3585 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3586 : _pyHypothesis( theCreationCmd )
3591 //================================================================================
3593 * \brief Convert the command adding an algorithm to mesh
3594 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3595 * \param theMesh - The mesh needing this algo
3596 * \retval bool - false if the command can't be converted
3598 //================================================================================
3600 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3601 const _pyID& theMeshID)
3603 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3604 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3605 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3611 //================================================================================
3613 * \brief Return starting position of a part of python command
3614 * \param thePartIndex - The index of command part
3615 * \retval int - Part position
3617 //================================================================================
3619 int _pyCommand::GetBegPos( int thePartIndex ) const
3623 if ( myBegPos.Length() < thePartIndex )
3625 ASSERT( thePartIndex > 0 );
3626 return myBegPos( thePartIndex );
3629 //================================================================================
3631 * \brief Store starting position of a part of python command
3632 * \param thePartIndex - The index of command part
3633 * \param thePosition - Part position
3635 //================================================================================
3637 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3639 while ( myBegPos.Length() < thePartIndex )
3640 myBegPos.Append( UNKNOWN );
3641 ASSERT( thePartIndex > 0 );
3642 myBegPos( thePartIndex ) = thePosition;
3645 //================================================================================
3647 * \brief Returns whitespace symbols at the line beginning
3648 * \retval TCollection_AsciiString - result
3650 //================================================================================
3652 TCollection_AsciiString _pyCommand::GetIndentation()
3655 //while ( end <= Length() && isblank( myString.Value( end )))
3656 //ANA: isblank() function isn't provided in VC2010 compiler
3657 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3659 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3662 //================================================================================
3664 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3665 * \retval const TCollection_AsciiString & - ResultValue substring
3667 //================================================================================
3669 const TCollection_AsciiString & _pyCommand::GetResultValue()
3671 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3673 SetBegPos( RESULT_IND, EMPTY );
3674 int begPos, endPos = myString.Location( "=", 1, Length() );
3678 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3679 if ( begPos < endPos )
3681 SetBegPos( RESULT_IND, begPos );
3683 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3684 myRes = myString.SubString( begPos, endPos );
3691 //================================================================================
3693 * \brief Return number of python command result value ResultValue = Obj.Meth()
3695 //================================================================================
3697 int _pyCommand::GetNbResultValues()
3700 return myResults.Length();
3704 //================================================================================
3706 * \brief Return substring of python command looking like
3707 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3708 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3710 //================================================================================
3711 const _AString& _pyCommand::GetResultValue(int res)
3713 if ( GetResultValue().IsEmpty() )
3714 return theEmptyString;
3716 if ( myResults.IsEmpty() )
3719 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3720 ++begPos; // skip [, else the whole list is returned
3721 while ( begPos < myRes.Length() ) {
3722 _AString result = GetWord( myRes, begPos, true );
3723 begPos += result.Length();
3725 // result.RemoveAll('[');
3726 // result.RemoveAll(']');
3731 myResults.Append( result );
3734 if ( res > 0 && res <= myResults.Length() )
3735 return myResults( res );
3736 return theEmptyString;
3739 //================================================================================
3741 * \brief Return substring of python command looking like ResVal = Object.Meth()
3742 * \retval const TCollection_AsciiString & - Object substring
3744 //================================================================================
3746 const TCollection_AsciiString & _pyCommand::GetObject()
3748 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3751 int begPos = GetBegPos( RESULT_IND );
3753 begPos = myString.Location( "=", 1, Length() ) + 1;
3754 // is '=' in the string argument (for example, name) or not
3755 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3756 for ( int i = 1; i < begPos-1; i++ )
3757 switch ( myString.Value( i )) {
3758 case '\'': nb[0]++; break;
3759 case '"' : nb[1]++; break;
3760 case '(' : nb[2]++; break;
3761 case ')' : nb[3]++; break;
3763 // if = is inside a string or a list
3764 // then get an object at the start of the command
3765 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3769 begPos += myRes.Length();
3771 myObj = GetWord( myString, begPos, true );
3772 if ( begPos != EMPTY )
3774 // check if object is complex,
3775 // so far consider case like "smesh.Method()"
3776 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3777 //if ( bracketPos==0 ) bracketPos = Length();
3778 int dotPos = begPos+myObj.Length();
3779 while ( dotPos+1 < bracketPos ) {
3780 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3785 if ( dotPos > begPos+myObj.Length() )
3786 myObj = myString.SubString( begPos, dotPos-1 );
3789 // 1st word after '=' is an object
3790 // else // no method -> no object
3796 SetBegPos( OBJECT_IND, begPos );
3802 //================================================================================
3804 * \brief Return substring of python command looking like ResVal = Obj.Method()
3805 * \retval const TCollection_AsciiString & - Method substring
3807 //================================================================================
3809 const TCollection_AsciiString & _pyCommand::GetMethod()
3811 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3814 int begPos = GetBegPos( OBJECT_IND );
3815 bool forward = true;
3817 begPos = myString.Location( "(", 1, Length() ) - 1;
3821 begPos += myObj.Length();
3824 myMeth = GetWord( myString, begPos, forward );
3825 SetBegPos( METHOD_IND, begPos );
3831 //================================================================================
3833 * \brief Returns true if there are brackets after the method
3835 //================================================================================
3837 bool _pyCommand::IsMethodCall()
3839 if ( GetMethod().IsEmpty() )
3841 if ( myString.StartsWith("#") )
3843 if ( myString.StartsWith("SHAPERSTUDY") ) // skip shaperstudy specific dump string analysis
3845 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3846 return ( s[0] == '(' || s[1] == '(' );
3849 //================================================================================
3851 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3852 * \retval const TCollection_AsciiString & - Arg<index> substring
3854 //================================================================================
3856 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3858 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3862 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3864 pos = myString.Location( "(", 1, Length() );
3868 // we are at or before '(', skip it if present
3870 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3871 if ( pos > Length() )
3875 SetBegPos( ARG1_IND, 0 ); // even no '('
3876 return theEmptyString;
3880 list< TCollection_AsciiString > separatorStack( 1, ",)");
3881 bool ignoreNesting = false;
3883 while ( pos <= Length() )
3885 const char chr = myString.Value( pos );
3887 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3889 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3891 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3893 TCollection_AsciiString arg;
3894 if ( pos-1 >= prevPos ) {
3895 arg = myString.SubString( prevPos, pos-1 );
3896 arg.RightAdjust(); // remove spaces
3899 if ( !arg.IsEmpty() || chr == ',' )
3901 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3902 myArgs.Append( arg );
3908 else // end of nesting args found
3910 separatorStack.pop_back();
3911 ignoreNesting = false;
3914 else if ( !ignoreNesting )
3917 case '(' : separatorStack.push_back(")"); break;
3918 case '[' : separatorStack.push_back("]"); break;
3919 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3920 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3927 if ( myArgs.Length() < index )
3928 return theEmptyString;
3929 return myArgs( index );
3932 //================================================================================
3934 * \brief Return position where arguments begin
3936 //================================================================================
3938 int _pyCommand::GetArgBeginning() const
3940 int pos = GetBegPos( ARG1_IND );
3941 if ( pos == UNKNOWN )
3943 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3944 if ( pos < 1 && Length() >= 4 )
3945 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3950 //================================================================================
3952 * \brief Check if char is a word part
3953 * \param c - The character to check
3954 * \retval bool - The check result
3956 //================================================================================
3958 static inline bool isWord(const char c, const bool dotIsWord)
3961 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3964 //================================================================================
3966 * \brief Looks for a word in the string and returns word's beginning
3967 * \param theString - The input string
3968 * \param theStartPos - The position to start the search, returning word's beginning
3969 * \param theForward - The search direction
3970 * \retval TCollection_AsciiString - The found word
3972 //================================================================================
3974 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3976 const bool theForward,
3977 const bool dotIsWord )
3979 int beg = theStartPos, end = theStartPos;
3980 theStartPos = EMPTY;
3981 if ( beg < 1 || beg > theString.Length() )
3982 return theEmptyString;
3984 if ( theForward ) { // search forward
3986 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3988 if ( beg > theString.Length() )
3989 return theEmptyString; // no word found
3992 char begChar = theString.Value( beg );
3993 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3994 char endChar = ( begChar == '[' ) ? ']' : begChar;
3995 // end is at the corresponding quoting mark or bracket
3996 while ( end < theString.Length() &&
3997 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
4001 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
4006 else { // search backward
4008 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
4011 return theEmptyString; // no word found
4013 char endChar = theString.Value( end );
4014 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
4015 char begChar = ( endChar == ']' ) ? '[' : endChar;
4016 // beg is at the corresponding quoting mark
4018 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
4022 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4028 //cout << theString << " ---- " << beg << " - " << end << endl;
4029 if ( end > theString.Length() )
4031 theStartPos = EMPTY;
4032 return theEmptyString;
4034 return theString.SubString( beg, end );
4037 //================================================================================
4039 * \brief Returns true if the string looks like a study entry
4041 //================================================================================
4043 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4045 if ( str.Length() < 5 ) return false;
4047 int nbColons = 0, isColon;
4048 for ( int i = 1; i <= str.Length(); ++i )
4050 char c = str.Value(i);
4051 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4053 nbColons += isColon;
4055 return nbColons > 2 && str.Length()-nbColons > 2;
4058 //================================================================================
4060 * \brief Returns true if the string looks like an object ID but not like a list,
4061 * string, command etc.
4063 //================================================================================
4065 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4067 if ( str.Length() < 1 ) return false;
4069 const char* s = str.ToCString();
4071 for ( int i = 0; i < str.Length(); ++i )
4072 if ( !IsIDChar( s[i] ))
4078 //================================================================================
4080 * \brief Finds entries in a string
4082 //================================================================================
4084 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4086 std::list< _pyID > resList;
4088 while ( ++pos <= str.Length() )
4090 if ( !isdigit( str.Value( pos ))) continue;
4091 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4094 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4095 _pyID entry = str.SubString( pos, end-1 );
4097 if ( IsStudyEntry( entry ))
4098 resList.push_back( entry );
4103 //================================================================================
4105 * \brief Look for position where not space char is
4106 * \param theString - The string
4107 * \param thePos - The position to search from and which returns result
4108 * \retval bool - false if there are only space after thePos in theString
4110 //================================================================================
4112 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4114 if ( thePos < 1 || thePos > theString.Length() )
4117 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4120 return thePos <= theString.Length();
4123 //================================================================================
4125 * \brief Modify a part of the command
4126 * \param thePartIndex - The index of the part
4127 * \param thePart - The new part string
4128 * \param theOldPart - The old part
4130 //================================================================================
4132 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4133 TCollection_AsciiString& theOldPart)
4135 int pos = GetBegPos( thePartIndex );
4136 if ( pos <= Length() && theOldPart != thePart)
4138 TCollection_AsciiString seperator;
4140 pos = GetBegPos( thePartIndex + 1 );
4141 if ( pos < 1 ) return;
4142 switch ( thePartIndex ) {
4143 case RESULT_IND: seperator = " = "; break;
4144 case OBJECT_IND: seperator = "."; break;
4145 case METHOD_IND: seperator = "()"; break;
4149 myString.Remove( pos, theOldPart.Length() );
4150 if ( !seperator.IsEmpty() )
4151 myString.Insert( pos , seperator );
4152 myString.Insert( pos, thePart );
4153 // update starting positions of the following parts
4154 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4155 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4156 if ( myBegPos( i ) > 0 )
4157 myBegPos( i ) += posDelta;
4159 theOldPart = thePart;
4163 //================================================================================
4165 * \brief Set argument
4166 * \param index - The argument index, it counts from 1
4167 * \param theArg - The argument string
4169 //================================================================================
4171 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4174 int argInd = ARG1_IND + index - 1;
4175 int pos = GetBegPos( argInd );
4176 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4178 // find a closing parenthesis
4179 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4180 int lastArgInd = GetNbArgs();
4181 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4182 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4187 while ( pos > 0 && myString.Value( pos ) != ')' )
4190 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4194 while ( myArgs.Length() < index ) {
4195 if ( myArgs.Length() )
4196 myString.Insert( pos++, "," );
4197 myArgs.Append("None");
4198 myString.Insert( pos, myArgs.Last() );
4199 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4200 pos += myArgs.Last().Length();
4203 SetPart( argInd, theArg, myArgs( index ));
4206 //================================================================================
4208 * \brief Empty arg list
4210 //================================================================================
4212 void _pyCommand::RemoveArgs()
4214 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4215 myString.Trunc( pos );
4218 if ( myBegPos.Length() >= ARG1_IND )
4219 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4222 //================================================================================
4224 * \brief Comment a python command
4226 //================================================================================
4228 void _pyCommand::Comment()
4230 if ( IsEmpty() ) return;
4233 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4234 if ( i <= Length() )
4236 myString.Insert( i, "#" );
4237 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4239 int begPos = GetBegPos( iPart );
4240 if ( begPos != UNKNOWN && begPos != EMPTY )
4241 SetBegPos( iPart, begPos + 1 );
4246 //================================================================================
4248 * \brief Set dependent commands after this one
4250 //================================================================================
4252 bool _pyCommand::SetDependentCmdsAfter() const
4254 bool orderChanged = false;
4255 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4256 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4257 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4258 orderChanged = true;
4259 theGen->SetCommandAfter( *cmd, this );
4260 (*cmd)->SetDependentCmdsAfter();
4263 return orderChanged;
4265 //================================================================================
4267 * \brief Insert accessor method after theObjectID
4268 * \param theObjectID - id of the accessed object
4269 * \param theAcsMethod - name of the method giving access to the object
4270 * \retval bool - false if theObjectID is not found in the command string
4272 //================================================================================
4274 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4276 if ( !theAcsMethod )
4278 // start object search from the object, i.e. ignore result
4280 int beg = GetBegPos( OBJECT_IND );
4281 if ( beg < 1 || beg > Length() )
4284 while (( beg = myString.Location( theObjectID, beg, Length() )))
4286 // check that theObjectID is not just a part of a longer ID
4287 int afterEnd = beg + theObjectID.Length();
4288 Standard_Character c = myString.Value( afterEnd );
4289 if ( !IsIDChar( c ))
4291 // check if accessor method already present
4293 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4295 int oldLen = Length();
4296 myString.Insert( afterEnd, (char*) theAcsMethod );
4297 myString.Insert( afterEnd, "." );
4298 // update starting positions of the parts following the modified one
4299 int posDelta = Length() - oldLen;
4300 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4301 if ( myBegPos( i ) > afterEnd )
4302 myBegPos( i ) += posDelta;
4307 beg = afterEnd; // is a part -> next search
4312 //================================================================================
4314 * \brief Creates pyObject
4316 //================================================================================
4318 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4319 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4324 //================================================================================
4326 * \brief Set up myID and myIsPublished
4328 //================================================================================
4330 void _pyObject::setID(const _pyID& theID)
4333 myIsPublished = !theGen->IsNotPublished( GetID() );
4336 //================================================================================
4338 * \brief Clear myCreationCmd and myProcessedCmds
4340 //================================================================================
4342 void _pyObject::ClearCommands()
4347 if ( !myCreationCmd.IsNull() )
4348 myCreationCmd->Clear();
4350 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4351 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4355 //================================================================================
4357 * \brief Return method name giving access to an interaface object wrapped by python class
4358 * \retval const char* - method name
4360 //================================================================================
4362 const char* _pyObject::AccessorMethod() const
4366 //================================================================================
4368 * \brief Return ID of a father
4370 //================================================================================
4372 _pyID _pyObject::FatherID(const _pyID & childID)
4374 int colPos = childID.SearchFromEnd(':');
4376 return childID.SubString( 1, colPos-1 );
4380 //================================================================================
4382 * \brief SelfEraser erases creation command if none of it's commands invoked
4383 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4385 //================================================================================
4387 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4388 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4390 myIsPublished = true; // prevent clearing as a not published
4391 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4394 //================================================================================
4396 * \brief SelfEraser erases creation command if none of it's commands invoked
4397 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4399 //================================================================================
4401 bool _pySelfEraser::CanClear()
4403 bool toErase = false;
4404 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4407 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4408 for ( ; cmd != myArgCmds.end(); ++cmd )
4409 nbArgUses += IsAliveCmd( *cmd );
4411 toErase = ( nbArgUses < 1 );
4416 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4417 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4418 for ( ; cmd != cmds.end(); )
4419 // check of cmd emptiness is not enough as object can change
4420 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4423 cmd = cmds.erase( cmd ); // save the cmd from clearing
4425 toErase = ( nbCalls < 1 );
4430 //================================================================================
4432 * \brief Check if a command is or can be cleared
4434 //================================================================================
4436 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4438 if ( theCmd->IsEmpty() )
4441 if ( !theGen->IsToKeepAllCommands() )
4443 const _pyID& objID = theCmd->GetObject();
4444 Handle( _pyObject ) obj = theGen->FindObject( objID );
4445 if ( !obj.IsNull() )
4446 return !obj->CanClear();
4451 //================================================================================
4453 * \brief SelfEraser erases creation command if none of it's commands invoked
4454 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4456 //================================================================================
4458 void _pySelfEraser::Flush()
4462 myIsPublished = false;
4463 _pyObject::ClearCommands();
4467 //================================================================================
4469 * \brief _pySubMesh constructor
4471 //================================================================================
4473 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4474 _pyObject(theCreationCmd)
4476 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4477 if ( toKeepAgrCmds )
4478 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4481 //================================================================================
4483 * \brief Return true if a sub-mesh can be used as argument of the given method
4485 //================================================================================
4487 bool _pySubMesh::CanBeArgOfMethod(const _AString& /*theMethodName*/)
4490 // names of all methods where a sub-mesh can be used as argument
4491 // static TStringSet methods;
4492 // if ( methods.empty() ) {
4493 // const char * names[] = {
4494 // // methods of SMESH_Gen
4496 // // methods of SMESH_Group
4498 // // methods of SMESH_Measurements
4500 // // methods of SMESH_Mesh
4501 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4503 // // methods of SMESH_MeshEditor
4504 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4505 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4506 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4507 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4508 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4509 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4510 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4511 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4512 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4513 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4514 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4515 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4516 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4517 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4518 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4519 // "" }; // <- mark of end
4520 // methods.Insert( names );
4522 // return methods.Contains( theMethodName );
4525 //================================================================================
4527 * \brief count invoked commands
4529 //================================================================================
4531 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4533 _pyObject::Process(theCommand); // count calls of Process()
4536 //================================================================================
4538 * \brief Move creation command depending on invoked commands
4540 //================================================================================
4542 void _pySubMesh::Flush()
4544 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4545 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4546 else if ( !myCreator.IsNull() )
4547 // move to be just after creator
4548 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4550 // move sub-mesh usage after creation cmd
4551 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4552 for ( ; cmd != myArgCmds.end(); ++cmd )
4553 if ( !(*cmd)->IsEmpty() )
4554 GetCreationCmd()->AddDependantCmd( *cmd );
4557 //================================================================================
4559 * \brief Creates _pyGroup
4561 //================================================================================
4563 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4564 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4566 if ( !id.IsEmpty() )
4569 myCanClearCreationCmd = true;
4571 const _AString& method = theCreationCmd->GetMethod();
4572 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4574 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4576 // ----------------------------------------------------------------------
4577 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4579 _pyID geom = theCreationCmd->GetArg( 3 );
4580 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4581 // next if(){...} section is commented
4582 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4583 // theCreationCmd->SetMethod( "Group" );
4584 // theCreationCmd->RemoveArgs();
4585 // theCreationCmd->SetArg( 1, geom );
4588 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4589 _pyID type = theCreationCmd->GetArg( 1 );
4590 _pyID name = theCreationCmd->GetArg( 2 );
4591 theCreationCmd->SetMethod( "GroupOnGeom" );
4592 theCreationCmd->RemoveArgs();
4593 theCreationCmd->SetArg( 1, geom );
4594 theCreationCmd->SetArg( 2, name );
4595 theCreationCmd->SetArg( 3, type );
4598 else if ( method == "CreateGroupFromFilter" )
4600 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4601 theCreationCmd->SetMethod( "GroupOnFilter" );
4603 _pyID filterID = theCreationCmd->GetArg(3);
4604 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4605 if ( !filter.IsNull())
4607 if ( !filter->GetNewID().IsEmpty() )
4608 theCreationCmd->SetArg( 3, filter->GetNewID() );
4609 //filter->AddUser( this );
4613 else if ( method == "GetGroups" )
4615 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4619 // theCreationCmd does something else apart from creation of this group
4620 // and thus it can't be cleared if this group is removed
4621 myCanClearCreationCmd = false;
4625 //================================================================================
4627 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4630 //================================================================================
4632 bool _pyGroup::CanClear()
4637 if ( !myCanClearCreationCmd &&
4638 !myCreationCmd.IsNull() &&
4639 myCreationCmd->GetMethod() == "GetGroups" )
4641 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4642 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4643 list< _pyID >::iterator grID = idList.begin();
4644 if ( GetID() == *grID )
4646 myCanClearCreationCmd = true;
4647 list< Handle(_pyGroup ) > groups;
4648 for ( ; grID != idList.end(); ++grID )
4650 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4651 if ( group.IsNull() ) continue;
4652 groups.push_back( group );
4653 if ( group->IsInStudy() )
4654 myCanClearCreationCmd = false;
4656 // set myCanClearCreationCmd == true to all groups
4657 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4658 for ( ; group != groups.end(); ++group )
4659 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4663 return myCanClearCreationCmd;
4666 //================================================================================
4668 * \brief set myCanClearCreationCmd = true if the main action of the creation
4669 * command is discarded
4671 //================================================================================
4673 void _pyGroup::RemovedWithContents()
4675 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4676 // via a created group
4677 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4678 // myCanClearCreationCmd = true;
4681 //================================================================================
4683 * \brief To convert creation of a group by filter
4685 //================================================================================
4687 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4689 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4690 // group = mesh.CreateEmptyGroup( elemType, groupName )
4691 // aFilter.SetMesh(mesh)
4692 // nbAdd = group.AddFrom( aFilter )
4693 Handle(_pyFilter) filter;
4694 if ( theCommand->GetMethod() == "AddFrom" )
4696 _pyID idSource = theCommand->GetArg(1);
4697 // check if idSource is a filter
4698 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4699 if ( !filter.IsNull() )
4701 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4702 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4703 while ( *cmdIt != theCommand ) ++cmdIt;
4704 while ( (*cmdIt)->GetOrderNb() != 1 )
4706 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4707 if ((setMeshCmd->GetObject() == idSource ||
4708 setMeshCmd->GetObject() == filter->GetNewID() )
4710 setMeshCmd->GetMethod() == "SetMesh")
4712 setMeshCmd->Clear();
4716 // replace 3 commands by one
4717 theCommand->Clear();
4718 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4719 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4720 if ( !filter->GetNewID().IsEmpty() )
4721 idSource = filter->GetNewID();
4722 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4723 makeGroupCmd->SetArg( 1, name );
4724 makeGroupCmd->SetArg( 2, idSource );
4725 filter->AddArgCmd( makeGroupCmd );
4728 else if ( theCommand->GetMethod() == "SetFilter" )
4730 // set new name of a filter or clear the command if the same filter is set
4731 _pyID filterID = theCommand->GetArg(1);
4732 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4733 if ( !myFilter.IsNull() && filter == myFilter )
4734 theCommand->Clear();
4735 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4736 theCommand->SetArg( 1, filter->GetNewID() );
4739 else if ( theCommand->GetMethod() == "GetFilter" )
4741 // GetFilter() returns a filter with other ID, make myFilter process
4742 // calls of the returned filter
4743 if ( !myFilter.IsNull() )
4745 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4746 theCommand->Clear();
4750 // if ( !filter.IsNull() )
4751 // filter->AddUser( this );
4753 theGen->AddMeshAccessorMethod( theCommand );
4756 //================================================================================
4758 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4760 //================================================================================
4762 void _pyGroup::Flush()
4764 if ( !theGen->IsToKeepAllCommands() &&
4765 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4767 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4771 //================================================================================
4773 * \brief Constructor of _pyFilter
4775 //================================================================================
4777 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4778 :_pyObject(theCreationCmd), myNewID( newID )
4780 //myIsPublished = true; // prevent clearing as a not published
4781 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4784 //================================================================================
4786 * \brief To convert creation of a filter by criteria and
4787 * to replace an old name by a new one
4789 //================================================================================
4791 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4793 if ( theCommand->GetObject() == GetID() )
4794 _pyObject::Process(theCommand); // count commands
4796 if ( !myNewID.IsEmpty() )
4797 theCommand->SetObject( myNewID );
4799 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4800 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4801 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4802 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4803 theCommand->GetMethod() == "SetCriteria")
4805 // aFilter.SetCriteria(aCriteria) ->
4806 // aFilter = smesh.GetFilterFromCriteria(criteria)
4807 if ( myNewID.IsEmpty() )
4808 theCommand->SetResultValue( GetID() );
4810 theCommand->SetResultValue( myNewID );
4811 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4812 theCommand->SetMethod( "GetFilterFromCriteria" );
4814 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4815 GetCreationCmd()->Clear();
4816 GetCreationCmd()->GetString() = theCommand->GetString();
4817 theCommand->Clear();
4818 theCommand->AddDependantCmd( GetCreationCmd() );
4819 // why swap? -- it's needed
4820 //GetCreationCmd()->Clear();
4822 else if ( theCommand->GetMethod() == "SetMesh" )
4824 if ( myMesh == theCommand->GetArg( 1 ))
4825 theCommand->Clear();
4827 myMesh = theCommand->GetArg( 1 );
4828 theGen->AddMeshAccessorMethod( theCommand );
4832 //================================================================================
4834 * \brief Set new filter name to the creation command and to myArgCmds
4836 //================================================================================
4838 void _pyFilter::Flush()
4840 if ( myNewID.IsEmpty() ) return;
4842 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4843 for ( ; cmd != myArgCmds.end(); ++cmd )
4844 if ( !(*cmd)->IsEmpty() )
4846 _AString cmdStr = (*cmd)->GetString();
4847 _AString id = GetID();
4848 int pos = cmdStr.Search( id );
4851 cmdStr.Remove( pos, id.Length() );
4852 cmdStr.Insert( pos, myNewID );
4855 (*cmd)->GetString() = cmdStr;
4858 if ( !GetCreationCmd()->IsEmpty() )
4859 GetCreationCmd()->SetResultValue( myNewID );
4862 //================================================================================
4864 * \brief Return true if all my users can be cleared
4866 //================================================================================
4868 bool _pyObject::CanClear()
4870 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4871 for ( ; cmd != myArgCmds.end(); ++cmd )
4872 if ( !(*cmd)->IsEmpty() )
4874 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4875 if ( !obj.IsNull() && !obj->CanClear() )
4878 return ( !myIsPublished );
4881 //================================================================================
4883 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4885 //================================================================================
4887 _pyHypothesisReader::_pyHypothesisReader()
4890 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4891 LDOMParser xmlParser;
4892 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4894 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4898 INFOS( xmlParser.GetError(data) );
4901 // <algorithm type="Regular_1D"
4902 // label-id="Wire discretisation"
4905 // <algo>Regular_1D=Segment()</algo>
4906 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4908 LDOM_Document xmlDoc = xmlParser.getDocument();
4909 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4910 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4912 LDOM_Node algoNode = algoNodeList.item( i );
4913 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4914 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4915 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4917 _AString text, algoType, method, arg;
4918 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4920 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4921 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4922 text = textNode.getNodeValue();
4923 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4924 algoType = algoCmd->GetResultValue();
4925 method = algoCmd->GetMethod();
4926 arg = algoCmd->GetArg(1);
4927 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4929 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4930 algo->SetConvMethodAndType( method, algoType );
4931 if ( !arg.IsEmpty() )
4932 algo->setCreationArg( 1, arg );
4934 myType2Hyp[ algoType ] = algo;
4938 if ( algoType.IsEmpty() ) continue;
4940 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4942 Handle( _pyHypothesis ) hyp;
4943 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4945 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4946 LDOM_Node textNode = pyHypoNode.getFirstChild();
4947 text = textNode.getNodeValue();
4948 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4949 hypType = hypoCmd->GetResultValue();
4950 method = hypoCmd->GetMethod();
4951 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4953 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4954 if ( type2hyp == myType2Hyp.end() )
4955 hyp = new _pyHypothesis( hypoCmd );
4957 hyp = type2hyp->second;
4958 hyp->SetConvMethodAndType( method, algoType );
4959 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4961 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4962 _AString argMethod = argCmd.GetMethod();
4963 _AString argNbText = argCmd.GetArg( 1 );
4964 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4965 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4967 hyp->AddArgMethod( argMethod,
4968 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4970 myType2Hyp[ hypType ] = hyp;
4974 // <hypothesis type="BLSURF_Parameters"
4978 // <accumulative-methods>
4979 // SetEnforcedVertex,
4980 // SetEnforcedVertexNamed
4981 // </accumulative-methods>
4985 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4986 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4988 LDOM_Node hypNode = hypNodeList.item( i );
4989 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4990 _AString hypType = hypElem.getAttribute("type");
4991 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4992 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4994 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4995 if ( type2hyp == myType2Hyp.end() ) continue;
4997 LDOM_Node methNode = methNodeList.item( 0 );
4998 LDOM_Node textNode = methNode.getFirstChild();
4999 _AString text = textNode.getNodeValue();
5003 method = _pyCommand::GetWord( text, pos, /*forward= */true );
5004 pos += method.Length();
5005 type2hyp->second->AddAccumulativeMethod( method );
5007 while ( !method.IsEmpty() );
5010 } // loop on xmlPaths
5013 //================================================================================
5015 * \brief Returns a new hypothesis initialized according to the read information
5017 //================================================================================
5019 Handle(_pyHypothesis)
5020 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
5021 const Handle(_pyCommand)& creationCmd) const
5023 Handle(_pyHypothesis) resHyp, sampleHyp;
5025 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5026 if ( type2hyp != myType2Hyp.end() )
5027 sampleHyp = type2hyp->second;
5029 if ( sampleHyp.IsNull() )
5031 resHyp = new _pyHypothesis(creationCmd);
5035 if ( sampleHyp->IsAlgo() )
5036 resHyp = new _pyAlgorithm( creationCmd );
5038 resHyp = new _pyHypothesis(creationCmd);
5039 resHyp->Assign( sampleHyp, _pyID() );
5044 //================================================================================
5046 * \brief Adds an object ID to some family of IDs with a common prefix
5047 * \param [in] str - the object ID
5048 * \return bool - \c false if \a str does not have the same prefix as \a this family
5049 * (for internal usage)
5051 //================================================================================
5053 bool _pyStringFamily::Add( const char* str )
5055 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5056 return false; // expected prefix is missing
5058 str += _prefix.Length(); // skip _prefix
5060 // try to add to some of child falimies
5061 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5062 for ( ; itSub != _subFams.end(); ++itSub )
5063 if ( itSub->Add( str ))
5066 // no suitable family found - add str to _strings or create a new child family
5068 // look for a proper place within sorted _strings
5069 std::list< _AString >::iterator itStr = _strings.begin();
5070 while ( itStr != _strings.end() && itStr->IsLess( str ))
5072 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5073 return true; // same ID already kept
5075 const int minPrefixSize = 4;
5077 // count "smaller" strings with the same prefix
5079 std::list< _AString >::iterator itLess = itStr;
5080 while ( itLess != _strings.begin() )
5083 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5091 // itLess points to the 1st string with same prefix
5093 // count "greater" strings with the same prefix
5095 std::list< _AString >::iterator itMore = itStr;
5096 for ( ; itMore != _strings.end(); ++itMore )
5097 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5101 // itMore points to the 1st string with greater prefix
5103 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5105 int prefixSize = minPrefixSize;
5106 _AString newPrefix ( str, prefixSize );
5108 // look for a proper place within _subFams sorted by _prefix
5109 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5110 if ( !itSub->_prefix.IsLess( newPrefix ))
5113 // add the new _pyStringFamily
5114 itSub = _subFams.insert( itSub, _pyStringFamily());
5115 _pyStringFamily& newSubFam = *itSub;
5116 newSubFam._prefix = newPrefix;
5118 // pass this->_strings to newSubFam._strings
5119 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5120 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5121 newSubFam._strings.push_back( str + prefixSize );
5122 for ( ; nbMore > 0; --nbMore, ++itStr )
5123 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5125 _strings.erase( itLess, itMore );
5127 else // too few string to make a family for them
5129 _strings.insert( itStr, str );
5134 //================================================================================
5136 * \brief Finds an object ID in the command
5137 * \param [in] longStr - the command string
5138 * \param [out] subStr - the found object ID
5139 * \return bool - \c true if the object ID found
5141 //================================================================================
5143 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5145 const _AString& longStr = cmd->GetString();
5146 const char* s = longStr.ToCString();
5149 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5150 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5151 if ( argBeg < 4 || argBeg > longStr.Length() )
5153 for ( ; itSub != _subFams.end(); ++itSub )
5156 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5157 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5159 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5160 from = pos + len + itSub->_prefix.Length();
5165 from += itSub->_prefix.Length();
5168 // look among _strings
5169 std::list< _AString >::iterator itStr = _strings.begin();
5170 for ( ; itStr != _strings.end(); ++itStr )
5171 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5172 // check that object ID does not continue after len
5173 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5175 subStr.push_back( *itStr );
5181 //================================================================================
5183 * \brief Return remainder length of the object ID after my _prefix
5184 * \param [in] str - remainder of the command after my _prefix
5185 * \return int - length of the object ID or -1 if not found
5187 //================================================================================
5189 int _pyStringFamily::isIn( const char* str )
5191 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5193 for ( ; itSub != _subFams.end(); ++itSub )
5195 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5198 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5199 return itSub->_prefix.Length() + len;
5204 if ( !_strings.empty() )
5206 std::list< _AString >::iterator itStr = _strings.begin();
5207 bool firstEmpty = itStr->IsEmpty();
5210 for ( ; itStr != _strings.end(); ++itStr )
5212 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5215 len = itStr->Length();
5224 // check that object ID does not continue after len
5225 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5232 //================================================================================
5236 //================================================================================
5238 void _pyStringFamily::Print( int level )
5240 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5241 std::list< _AString >::iterator itStr = _strings.begin();
5242 for ( ; itStr != _strings.end(); ++itStr )
5243 cout << *itStr << " | ";
5245 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5246 for ( ; itSub != _subFams.end(); ++itSub )
5247 itSub->Print( level + 1 );
5249 cout << string( 70, '-' ) << endl;