1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
54 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
57 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
65 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
67 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
84 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
87 using SMESH::TPythonDump;
90 * \brief Container of commands into which the initial script is split.
91 * It also contains data coresponding to SMESH_Gen contents
93 static Handle(_pyGen) theGen;
95 static TCollection_AsciiString theEmptyString;
97 //#define DUMP_CONVERSION
99 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
100 #undef DUMP_CONVERSION
106 //================================================================================
108 * \brief Set of TCollection_AsciiString initialized by C array of C strings
110 //================================================================================
112 struct TStringSet: public set<TCollection_AsciiString>
115 * \brief Filling. The last string must be ""
117 void Insert(const char* names[]) {
118 for ( int i = 0; names[i][0] ; ++i )
119 insert( (char*) names[i] );
122 * \brief Check if a string is in
124 bool Contains(const TCollection_AsciiString& name ) {
125 return find( name ) != end();
129 //================================================================================
131 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
132 * Odd items of the C array are map keys, and even items are values
134 //================================================================================
136 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
139 * \brief Filling. The last string must be ""
141 void Insert(const char* names_values[]) {
142 for ( int i = 0; names_values[i][0] ; i += 2 )
143 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
146 * \brief Check if a string is in
148 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
149 map< _AString, _AString >::iterator it = find( name );
150 return it == end() ? "" : it->second;
154 //================================================================================
156 * \brief Returns a mesh by object
158 //================================================================================
160 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
164 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
165 return Handle(_pyMesh)::DownCast( obj );
166 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
167 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
168 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
169 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
171 return Handle(_pyMesh)();
174 //================================================================================
176 * \brief Check if objects used as args have been created by previous commands
178 //================================================================================
180 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
182 // either comment or erase a command including NotPublishedObjectName()
183 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
185 bool isResultPublished = false;
186 const int nbRes = cmd->GetNbResultValues();
187 for ( int i = 0; i < nbRes; i++ )
189 _pyID objID = cmd->GetResultValue( i+1 );
190 if ( cmd->IsStudyEntry( objID ))
191 isResultPublished = (! theGen->IsNotPublished( objID ));
192 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
194 if ( isResultPublished )
200 // check if an Object was created in the script
203 _pyID obj = cmd->GetObject();
204 if ( obj.Search( "print " ) == 1 )
205 return; // print statement
207 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
208 // remove an accessor method
209 obj = _pyCommand( obj ).GetObject();
211 const bool isMethodCall = cmd->IsMethodCall();
212 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
214 comment = "not created Object";
215 theGen->ObjectCreationRemoved( obj );
217 // check if a command has not created args
218 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
220 const _pyID& arg = cmd->GetArg( iArg );
221 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
223 list< _pyID > idList = cmd->GetStudyEntries( arg );
224 list< _pyID >::iterator id = idList.begin();
225 for ( ; id != idList.end(); ++id )
226 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
228 comment += *id + " has not been yet created";
231 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
232 // comment += arg + " has not been yet created";
234 // treat result objects
235 const _pyID& result = cmd->GetResultValue();
236 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
238 list< _pyID > idList = cmd->GetStudyEntries( result );
239 list< _pyID >::iterator id = idList.begin();
240 for ( ; id != idList.end(); ++id )
242 if ( comment.IsEmpty() )
243 presentObjects.insert( *id );
245 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
247 if ( idList.empty() && cmd->IsID( result ))
248 presentObjects.insert( result );
250 // comment the command
251 if ( !comment.IsEmpty() )
254 cmd->GetString() += " ### ";
255 cmd->GetString() += comment;
259 //================================================================================
261 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
263 //================================================================================
265 void fixFunctorType( TCollection_AsciiString& Type,
266 TCollection_AsciiString& Compare,
267 TCollection_AsciiString& UnaryOp,
268 TCollection_AsciiString& BinaryOp )
270 // The problem is that dumps of old studies created using filters becomes invalid
271 // when new items are inserted in the enum SMESH::FunctorType since values
272 // of this enum are dumped as integer values.
273 // This function corrects enum values of old studies given as args (Type,Compare,...)
274 // We can find out how to correct them by value of BinaryOp which can have only two
275 // values: FT_Undefined or FT_LogicalNOT.
276 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
277 // where PythonDump appeared
278 // v 3.0.0: FT_Undefined == 25
279 // v 3.1.0: FT_Undefined == 26, new items:
281 // v 4.1.2: FT_Undefined == 27, new items:
282 // - FT_BelongToGenSurface = 17
283 // v 5.1.1: FT_Undefined == 32, new items:
284 // - FT_FreeNodes = 10
285 // - FT_FreeFaces = 11
286 // - FT_LinearOrQuadratic = 23
287 // - FT_GroupColor = 24
288 // - FT_ElemGeomType = 25
289 // v 5.1.5: FT_Undefined == 33, new items:
290 // - FT_CoplanarFaces = 26
291 // v 6.2.0: FT_Undefined == 39, new items:
292 // - FT_MaxElementLength2D = 8
293 // - FT_MaxElementLength3D = 9
294 // - FT_BareBorderVolume = 25
295 // - FT_BareBorderFace = 26
296 // - FT_OverConstrainedVolume = 27
297 // - FT_OverConstrainedFace = 28
298 // v 6.5.0: FT_Undefined == 43, new items:
299 // - FT_EqualNodes = 14
300 // - FT_EqualEdges = 15
301 // - FT_EqualFaces = 16
302 // - FT_EqualVolumes = 17
303 // v 6.6.0: FT_Undefined == 44, new items:
304 // - FT_BallDiameter = 37
305 // v 6.7.1: FT_Undefined == 45, new items:
306 // - FT_EntityType = 36
307 // v 7.3.0: FT_Undefined == 46, new items:
308 // - FT_ConnectedElements = 39
310 // It's necessary to continue recording this history and to fill
311 // undef2newItems (see below) accordingly.
313 typedef map< int, vector< int > > TUndef2newItems;
314 static TUndef2newItems undef2newItems;
315 if ( undef2newItems.empty() )
317 undef2newItems[ 26 ].push_back( 7 );
318 undef2newItems[ 27 ].push_back( 17 );
319 { int items[] = { 10, 11, 23, 24, 25 };
320 undef2newItems[ 32 ].assign( items, items+5 ); }
321 undef2newItems[ 33 ].push_back( 26 );
322 { int items[] = { 8, 9, 25, 26, 27, 28 };
323 undef2newItems[ 39 ].assign( items, items+6 ); }
324 { int items[] = { 14, 15, 16, 17 };
325 undef2newItems[ 43 ].assign( items, items+4 ); }
326 undef2newItems[ 44 ].push_back( 37 );
327 undef2newItems[ 45 ].push_back( 36 );
328 undef2newItems[ 46 ].push_back( 39 );
330 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
333 int iType = Type.IntegerValue();
334 int iCompare = Compare.IntegerValue();
335 int iUnaryOp = UnaryOp.IntegerValue();
336 int iBinaryOp = BinaryOp.IntegerValue();
338 // find out integer value of FT_Undefined at the moment of dump
339 int oldUndefined = iBinaryOp;
340 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
343 // apply history to args
344 TUndef2newItems::const_iterator undef_items =
345 undef2newItems.upper_bound( oldUndefined );
346 if ( undef_items != undef2newItems.end() )
348 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
349 for ( ; undef_items != undef2newItems.end(); ++undef_items )
351 const vector< int > & addedItems = undef_items->second;
352 for ( size_t i = 0; i < addedItems.size(); ++i )
353 for ( int iArg = 0; iArg < 4; ++iArg )
355 int& arg = *pArg[iArg];
356 if ( arg >= addedItems[i] )
360 Type = TCollection_AsciiString( iType );
361 Compare = TCollection_AsciiString( iCompare );
362 UnaryOp = TCollection_AsciiString( iUnaryOp );
363 BinaryOp = TCollection_AsciiString( iBinaryOp );
367 //================================================================================
369 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
370 * arguments of a given command by a list "[x,y,z]" if the list is accesible
373 //================================================================================
375 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
377 static TStringSet methodsAcceptingList;
378 if ( methodsAcceptingList.empty() ) {
379 const char * methodNames[] = {
380 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
381 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
382 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
383 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
384 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
385 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
386 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
387 "Translate","TranslateMakeGroups","TranslateMakeMesh",
388 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
389 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
390 ,"" }; // <- mark of the end
391 methodsAcceptingList.Insert( methodNames );
393 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
395 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
397 const _AString & arg = theCommand->GetArg( i );
398 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
399 arg.Search( "SMESH.DirStruct" ) == 1 )
401 Handle(_pyCommand) workCmd = new _pyCommand( arg );
402 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
404 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
406 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
408 _AString newArg = "[ ";
409 newArg += ( workCmd->GetArg( 1 ) + ", " +
410 workCmd->GetArg( 2 ) + ", " +
411 workCmd->GetArg( 3 ) + " ]");
412 theCommand->SetArg( i, newArg );
418 //================================================================================
420 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
421 * a list "[id1,id2]" if the list is an accesible type of argument.
423 //================================================================================
425 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
427 static TStringSet methodsAcceptingList;
428 if ( methodsAcceptingList.empty() ) {
429 const char * methodNames[] = {
430 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
431 "ExportCGNS","ExportGMF",
432 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
433 "ScaleMakeGroups","Scale","ScaleMakeMesh",
434 "FindCoincidentNodesOnPartBut","DoubleElements"
435 ,"" }; // <- mark of the end
436 methodsAcceptingList.Insert( methodNames );
438 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
440 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
442 _pyCommand argCmd( theCommand->GetArg( i ));
443 if ( argCmd.GetMethod() == "GetIDSource" &&
444 argCmd.GetNbArgs() == 2 )
446 theCommand->SetArg( i, argCmd.GetArg( 1 ));
453 //================================================================================
455 * \brief Convert a python script using commands of smeshBuilder.py
456 * \param theScriptLines - Lines of the input script
457 * \param theEntry2AccessorMethod - returns method names to access to
458 * objects wrapped with python class
459 * \param theObjectNames - names of objects
460 * \param theRemovedObjIDs - entries of objects whose created commands were removed
461 * \param theHistoricalDump - true means to keep all commands, false means
462 * to exclude commands relating to objects removed from study
463 * \retval TCollection_AsciiString - Convertion result
465 //================================================================================
468 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
469 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
470 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
471 std::set< TCollection_AsciiString >& theRemovedObjIDs,
472 SALOMEDS::Study_ptr& theStudy,
473 const bool theToKeepAllCommands)
475 std::list< TCollection_AsciiString >::iterator lineIt;
476 // process notebook variables
478 SMESH_NoteBook aNoteBook;
480 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
481 aNoteBook.AddCommand( *lineIt );
483 theScriptLines.clear();
485 aNoteBook.ReplaceVariables();
487 aNoteBook.GetResultLines( theScriptLines );
490 // convert to smeshBuilder.py API
492 theGen = new _pyGen( theEntry2AccessorMethod,
496 theToKeepAllCommands );
498 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
499 theGen->AddCommand( *lineIt );
501 theScriptLines.clear();
505 #ifdef DUMP_CONVERSION
506 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
509 // clean commmands of removed objects depending on myIsPublished flag
510 theGen->ClearCommands();
512 // reorder commands after conversion
513 list< Handle(_pyCommand) >::iterator cmd;
516 orderChanges = false;
517 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
518 if ( (*cmd)->SetDependentCmdsAfter() )
520 } while ( orderChanges );
522 // concat commands back into a script
523 TCollection_AsciiString aPrevCmd;
524 set<_pyID> createdObjects;
525 createdObjects.insert( "smeshBuilder" );
526 createdObjects.insert( "smesh" );
527 createdObjects.insert( "theStudy" );
528 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
530 #ifdef DUMP_CONVERSION
531 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
533 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
534 CheckObjectPresence( *cmd, createdObjects );
535 if ( !(*cmd)->IsEmpty() ) {
536 aPrevCmd = (*cmd)->GetString();
537 theScriptLines.push_back( aPrevCmd );
546 //================================================================================
548 * \brief _pyGen constructor
550 //================================================================================
552 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
553 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
554 std::set< TCollection_AsciiString >& theRemovedObjIDs,
555 SALOMEDS::Study_ptr& theStudy,
556 const bool theToKeepAllCommands)
557 : _pyObject( new _pyCommand( "", 0 )),
559 myID2AccessorMethod( theEntry2AccessorMethod ),
560 myObjectNames( theObjectNames ),
561 myRemovedObjIDs( theRemovedObjIDs ),
563 myToKeepAllCommands( theToKeepAllCommands ),
564 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
565 myGeomIDNb(0), myGeomIDIndex(-1)
567 // make that GetID() to return TPythonDump::SMESHGenName()
568 GetCreationCmd()->Clear();
569 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
570 GetCreationCmd()->GetString() += "=";
572 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
573 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
577 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
578 if ( geomComp->_is_nil() ) return;
579 CORBA::String_var entry = geomComp->GetID();
582 // find a SMESH entry
584 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
585 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
586 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
589 // find 1st difference between smeshID and geomID
590 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
591 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
592 if ( geomID.Value( i ) != smeshID.Value( i ))
594 myGeomIDNb = geomID.Value( i );
600 //================================================================================
602 * \brief name of SMESH_Gen in smeshBuilder.py
604 //================================================================================
606 const char* _pyGen::AccessorMethod() const
608 return SMESH_2smeshpy::GenName();
611 //================================================================================
613 * \brief Convert a command using a specific converter
614 * \param theCommand - the command to convert
616 //================================================================================
618 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
620 // store theCommand in the sequence
621 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
623 Handle(_pyCommand) aCommand = myCommands.back();
624 #ifdef DUMP_CONVERSION
625 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
628 const _pyID& objID = aCommand->GetObject();
630 if ( objID.IsEmpty() )
633 // Prevent moving a command creating a sub-mesh to the end of the script
634 // if the sub-mesh is used in theCommand as argument
635 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
637 // PlaceSubmeshAfterItsCreation( aCommand );
640 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
641 StructToList( aCommand );
643 const TCollection_AsciiString& method = aCommand->GetMethod();
645 // not to erase _pySelfEraser's etc. used as args in some commands
647 #ifdef USE_STRING_FAMILY
648 std::list<_pyID> objIDs;
649 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
651 std::list<_pyID>::iterator objID = objIDs.begin();
652 for ( ; objID != objIDs.end(); ++objID )
654 Handle(_pyObject) obj = FindObject( *objID );
657 obj->AddArgCmd( aCommand );
658 //cout << objID << " found in " << theCommand << endl;
663 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
664 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
665 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
667 Handle(_pyObject) obj = FindObject( *id );
669 obj->AddArgCmd( aCommand );
674 // Find an object to process theCommand
677 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
679 this->Process( aCommand );
680 //addFilterUser( aCommand, theGen ); // protect filters from clearing
684 // SMESH_Mesh method?
685 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
686 if ( id_mesh != myMeshes.end() )
688 //id_mesh->second->AddProcessedCmd( aCommand );
690 // check for mesh editor object
691 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
692 _pyID editorID = aCommand->GetResultValue();
693 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
694 myMeshEditors.insert( make_pair( editorID, editor ));
697 // check for SubMesh objects
698 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
699 _pyID subMeshID = aCommand->GetResultValue();
700 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
701 AddObject( subMesh );
704 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
705 GetIDSourceToList( aCommand );
707 //addFilterUser( aCommand, theGen ); // protect filters from clearing
709 id_mesh->second->Process( aCommand );
710 id_mesh->second->AddProcessedCmd( aCommand );
714 // SMESH_MeshEditor method?
715 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
716 if ( id_editor != myMeshEditors.end() )
718 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
719 GetIDSourceToList( aCommand );
721 //addFilterUser( aCommand, theGen ); // protect filters from clearing
723 // some commands of SMESH_MeshEditor create meshes and groups
724 _pyID meshID, groups;
725 if ( method.Search("MakeMesh") != -1 )
726 meshID = aCommand->GetResultValue();
727 else if ( method == "MakeBoundaryMesh")
728 meshID = aCommand->GetResultValue(1);
729 else if ( method == "MakeBoundaryElements")
730 meshID = aCommand->GetResultValue(2);
732 if ( method.Search("MakeGroups") != -1 ||
733 method == "ExtrusionAlongPathX" ||
734 method == "ExtrusionAlongPathObjX" ||
735 method == "DoubleNodeGroupNew" ||
736 method == "DoubleNodeGroupsNew" ||
737 method == "DoubleNodeElemGroupNew" ||
738 method == "DoubleNodeElemGroupsNew"||
739 method == "DoubleNodeElemGroup2New"||
740 method == "DoubleNodeElemGroups2New"
742 groups = aCommand->GetResultValue();
743 else if ( method == "MakeBoundaryMesh" )
744 groups = aCommand->GetResultValue(2);
745 else if ( method == "MakeBoundaryElements")
746 groups = aCommand->GetResultValue(3);
747 else if ( method == "Create0DElementsOnAllNodes" &&
748 aCommand->GetArg(2).Length() > 2 ) // group name != ''
749 groups = aCommand->GetResultValue();
751 id_editor->second->Process( aCommand );
752 id_editor->second->AddProcessedCmd( aCommand );
755 if ( !meshID.IsEmpty() &&
756 !myMeshes.count( meshID ) &&
757 aCommand->IsStudyEntry( meshID ))
759 _AString processedCommand = aCommand->GetString();
760 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
761 CheckObjectIsReCreated( mesh );
762 myMeshes.insert( make_pair( meshID, mesh ));
764 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
767 if ( !groups.IsEmpty() )
769 if ( !aCommand->IsStudyEntry( meshID ))
770 meshID = id_editor->second->GetMesh();
771 Handle(_pyMesh) mesh = myMeshes[ meshID ];
773 list< _pyID > idList = aCommand->GetStudyEntries( groups );
774 list< _pyID >::iterator grID = idList.begin();
775 for ( ; grID != idList.end(); ++grID )
776 if ( !myObjects.count( *grID ))
778 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
780 if ( !mesh.IsNull() ) mesh->AddGroup( group );
784 } // SMESH_MeshEditor methods
786 // SMESH_Hypothesis method?
787 Handle(_pyHypothesis) hyp = FindHyp( objID );
788 if ( !hyp.IsNull() && !hyp->IsAlgo() )
790 hyp->Process( aCommand );
791 hyp->AddProcessedCmd( aCommand );
795 // aFilterManager.CreateFilter() ?
796 if ( aCommand->GetMethod() == "CreateFilter" )
798 // Set a more human readable name to a filter
799 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
800 _pyID newID, filterID = aCommand->GetResultValue();
801 int pos = filterID.Search( "0x" );
803 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
805 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
808 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
809 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
811 // create _pySelfEraser for functors
812 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
813 functor->IgnoreOwnCalls(); // to erase if not used as an argument
814 AddObject( functor );
817 // other object method?
818 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
819 if ( id_obj != myObjects.end() ) {
820 id_obj->second->Process( aCommand );
821 id_obj->second->AddProcessedCmd( aCommand );
825 // Add access to a wrapped mesh
826 AddMeshAccessorMethod( aCommand );
828 // Add access to a wrapped algorithm
829 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
831 // PAL12227. PythonDump was not updated at proper time; result is
832 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
833 // TypeError: __init__() takes exactly 11 arguments (10 given)
834 const char wrongCommand[] = "SMESH.Filter.Criterion(";
835 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
837 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
838 // there must be 10 arguments, 5-th arg ThresholdID is missing,
839 const int wrongNbArgs = 9, missingArg = 5;
840 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
842 for ( int i = wrongNbArgs; i > missingArg; --i )
843 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
844 tmpCmd.SetArg( missingArg, "''");
845 aCommand->GetString().Trunc( beg - 1 );
846 aCommand->GetString() += tmpCmd.GetString();
849 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
851 // instead of "SMESH.Filter.Criterion(
852 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
853 // 1 2 3 4 5 6 7 8 9 10
854 // in order to avoid the problem of type mismatch of long and FunctorType
855 const TCollection_AsciiString
856 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
857 TCollection_AsciiString
858 Type = aCommand->GetArg(1), // long
859 Compare = aCommand->GetArg(2), // long
860 Threshold = aCommand->GetArg(3), // double
861 ThresholdStr = aCommand->GetArg(4), // string
862 ThresholdID = aCommand->GetArg(5), // string
863 UnaryOp = aCommand->GetArg(6), // long
864 BinaryOp = aCommand->GetArg(7), // long
865 Tolerance = aCommand->GetArg(8), // double
866 TypeOfElement = aCommand->GetArg(9), // ElementType
867 Precision = aCommand->GetArg(10); // long
868 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
869 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
870 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
871 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
872 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
874 if ( Compare == "SMESH.FT_EqualTo" )
877 aCommand->RemoveArgs();
878 aCommand->SetObject( SMESH_2smeshpy::GenName() );
879 aCommand->SetMethod( "GetCriterion" );
881 aCommand->SetArg( 1, TypeOfElement );
882 aCommand->SetArg( 2, Type );
883 aCommand->SetArg( 3, Compare );
885 if ( Threshold.IsIntegerValue() )
887 int iGeom = Threshold.IntegerValue();
888 if ( Type == "SMESH.FT_ElemGeomType" )
890 // set SMESH.GeometryType instead of a numerical Threshold
891 const int nbTypes = SMESH::Geom_LAST;
892 const char* types[nbTypes] = {
893 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
894 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
895 "Geom_POLYHEDRA", "Geom_BALL" };
896 if ( -1 < iGeom && iGeom < nbTypes )
897 Threshold = SMESH + types[ iGeom ];
899 // is types complete? (compilation failure mains that enum GeometryType changed)
900 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ];
903 if (Type == "SMESH.FT_EntityType")
905 // set SMESH.EntityType instead of a numerical Threshold
906 const int nbTypes = SMESH::Entity_Last;
907 const char* types[nbTypes] = {
908 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
909 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
910 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
911 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
912 "Entity_Pyramid", "Entity_Quad_Pyramid",
913 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
914 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
915 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
916 if ( -1 < iGeom && iGeom < nbTypes )
917 Threshold = SMESH + types[ iGeom ];
919 // is types complete? (compilation failure mains that enum EntityType changed)
920 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ];
924 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
925 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
926 else if ( ThresholdStr.Length() != 2 )
927 aCommand->SetArg( 4, ThresholdStr );
928 else if ( ThresholdID.Length() != 2 )
929 aCommand->SetArg( 4, ThresholdID );
931 aCommand->SetArg( 4, Threshold );
932 // find the last not default arg
934 if ( Tolerance == dfltTol ) {
936 if ( BinaryOp == dfltFunctor ) {
938 if ( UnaryOp == dfltFunctor )
942 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
943 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
944 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
945 if ( Precision != dfltPreci )
947 TCollection_AsciiString crit = aCommand->GetResultValue();
948 aCommand->GetString() += "; ";
949 aCommand->GetString() += crit + ".Precision = " + Precision;
955 //================================================================================
957 * \brief Convert the command or remember it for later conversion
958 * \param theCommand - The python command calling a method of SMESH_Gen
960 //================================================================================
962 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
964 // there are methods to convert:
965 // CreateMesh( shape )
966 // Concatenate( [mesh1, ...], ... )
967 // CreateHypothesis( theHypType, theLibName )
968 // Compute( mesh, geom )
969 // Evaluate( mesh, geom )
971 TCollection_AsciiString method = theCommand->GetMethod();
973 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
975 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
979 if ( method == "CreateMeshesFromUNV" ||
980 method == "CreateMeshesFromSTL" ||
981 method == "CopyMesh" ) // command result is a mesh
983 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
987 if( method == "CreateMeshesFromMED" ||
988 method == "CreateMeshesFromSAUV"||
989 method == "CreateMeshesFromCGNS" ||
990 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
992 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
993 std::list< _pyID >::iterator meshID = meshIDs.begin();
994 for ( ; meshID != meshIDs.end(); ++meshID )
996 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
999 if ( method == "CreateMeshesFromGMF" )
1001 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1002 // CreateMeshesFromGMF( theFileName )
1003 _AString file = theCommand->GetArg(1);
1004 theCommand->RemoveArgs();
1005 theCommand->SetArg( 1, file );
1009 // CreateHypothesis()
1010 if ( method == "CreateHypothesis" )
1012 // issue 199929, remove standard library name (default parameter)
1013 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1014 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1015 // keep the first argument
1016 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1017 theCommand->RemoveArgs();
1018 theCommand->SetArg( 1, arg );
1021 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1022 CheckObjectIsReCreated( hyp );
1023 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1028 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1029 if ( method == "Compute" )
1031 const _pyID& meshID = theCommand->GetArg( 1 );
1032 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1033 if ( id_mesh != myMeshes.end() ) {
1034 theCommand->SetObject( meshID );
1035 theCommand->RemoveArgs();
1036 id_mesh->second->Process( theCommand );
1037 id_mesh->second->AddProcessedCmd( theCommand );
1042 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1043 if ( method == "Evaluate" )
1045 const _pyID& meshID = theCommand->GetArg( 1 );
1046 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1047 if ( id_mesh != myMeshes.end() ) {
1048 theCommand->SetObject( meshID );
1049 _pyID geom = theCommand->GetArg( 2 );
1050 theCommand->RemoveArgs();
1051 theCommand->SetArg( 1, geom );
1052 id_mesh->second->AddProcessedCmd( theCommand );
1057 // objects erasing creation command if no more its commands invoked:
1058 // SMESH_Pattern, FilterManager
1059 if ( method == "GetPattern" ||
1060 method == "CreateFilterManager" ||
1061 method == "CreateMeasurements" )
1063 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1064 if ( !AddObject( obj ) )
1065 theCommand->Clear(); // already created
1067 // Concatenate( [mesh1, ...], ... )
1068 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1070 if ( method == "ConcatenateWithGroups" ) {
1071 theCommand->SetMethod( "Concatenate" );
1072 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1074 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1076 AddMeshAccessorMethod( theCommand );
1078 else if ( method == "SetName" ) // SetName(obj,name)
1080 // store theCommand as one of object commands to erase it along with the object
1081 const _pyID& objID = theCommand->GetArg( 1 );
1082 Handle(_pyObject) obj = FindObject( objID );
1083 if ( !obj.IsNull() )
1084 obj->AddProcessedCmd( theCommand );
1087 // Replace name of SMESH_Gen
1089 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1090 static TStringSet smeshpyMethods;
1091 if ( smeshpyMethods.empty() ) {
1092 const char * names[] =
1093 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1094 "GetPattern","GetSubShapesId",
1095 "" }; // <- mark of array end
1096 smeshpyMethods.Insert( names );
1098 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1099 // smeshgen.Method() --> smesh.Method()
1100 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1102 // smeshgen.Method() --> smesh.Method()
1103 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1106 //================================================================================
1108 * \brief Convert the remembered commands
1110 //================================================================================
1112 void _pyGen::Flush()
1114 // create an empty command
1115 myLastCommand = new _pyCommand();
1117 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1118 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1119 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1121 if ( IsToKeepAllCommands() ) // historical dump
1123 // set myIsPublished = true to all objects
1124 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1125 id_mesh->second->SetRemovedFromStudy( false );
1126 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1127 id_hyp->second->SetRemovedFromStudy( false );
1128 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1129 id_obj->second->SetRemovedFromStudy( false );
1133 // let hypotheses find referred objects in order to prevent clearing
1134 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1135 list< Handle(_pyMesh) > fatherMeshes;
1136 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1137 if ( !id_hyp->second.IsNull() )
1138 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1140 // set myIsPublished = false to all objects depending on
1141 // meshes built on a removed geometry
1142 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1143 if ( id_mesh->second->IsNotGeomPublished() )
1144 id_mesh->second->SetRemovedFromStudy( true );
1147 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1148 if ( ! id_mesh->second.IsNull() )
1149 id_mesh->second->Flush();
1152 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1153 if ( !id_hyp->second.IsNull() ) {
1154 id_hyp->second->Flush();
1155 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1156 if ( !id_hyp->second->IsWrapped() )
1157 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1160 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1161 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1162 for ( ; robj != myOrderedObjects.rend(); ++robj )
1163 if ( ! robj->IsNull() )
1165 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1166 for ( ; obj != myOrderedObjects.end(); ++obj )
1167 if ( ! obj->IsNull() )
1170 myLastCommand->SetOrderNb( ++myNbCommands );
1171 myCommands.push_back( myLastCommand );
1174 //================================================================================
1176 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1177 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1179 //================================================================================
1181 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1183 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1184 // for ( ; id_obj != myObjects.end(); ++id_obj )
1186 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1187 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1189 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1190 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1192 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1193 // list< _pyID >::iterator id = idList.begin();
1194 // for ( ; id != idList.end(); ++id )
1195 // if ( id_obj->first == *id )
1196 // // _pySubMesh::Process() does what we need
1197 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1202 //================================================================================
1204 * \brief Clean commmands of removed objects depending on myIsPublished flag
1206 //================================================================================
1208 void _pyGen::ClearCommands()
1210 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1211 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1212 id_mesh->second->ClearCommands();
1214 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1215 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1216 if ( !id_hyp->second.IsNull() )
1217 id_hyp->second->ClearCommands();
1219 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1220 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1221 for ( ; robj != myOrderedObjects.rend(); ++robj )
1222 if ( ! robj->IsNull() )
1223 (*robj)->ClearCommands();
1224 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1225 for ( ; obj != myOrderedObjects.end(); ++obj )
1226 if ( ! obj->IsNull() )
1227 (*obj)->ClearCommands();
1230 //================================================================================
1232 * \brief Release mutual handles of objects
1234 //================================================================================
1238 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1239 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1240 id_mesh->second->Free();
1243 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1244 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1245 id_ed->second->Free();
1246 myMeshEditors.clear();
1248 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1249 for ( ; id_obj != myObjects.end(); ++id_obj )
1250 id_obj->second->Free();
1253 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1254 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1255 if ( !id_hyp->second.IsNull() )
1256 id_hyp->second->Free();
1259 myFile2ExportedMesh.clear();
1261 //myKeepAgrCmdsIDs.Print();
1264 //================================================================================
1266 * \brief Add access method to mesh that is an argument
1267 * \param theCmd - command to add access method
1268 * \retval bool - true if added
1270 //================================================================================
1272 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1275 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1276 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1277 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1283 //================================================================================
1285 * \brief Add access method to algo that is an object or an argument
1286 * \param theCmd - command to add access method
1287 * \retval bool - true if added
1289 //================================================================================
1291 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1294 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1295 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1296 if ( !id_hyp->second.IsNull() &&
1297 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1298 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1299 id_hyp->second->AccessorMethod() ))
1305 //================================================================================
1307 * \brief Find hypothesis by ID (entry)
1308 * \param theHypID - The hypothesis ID
1309 * \retval Handle(_pyHypothesis) - The found hypothesis
1311 //================================================================================
1313 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1315 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1316 if ( id_hyp != myHypos.end() &&
1317 !id_hyp->second.IsNull() &&
1318 theHypID == id_hyp->second->GetID() )
1319 return id_hyp->second;
1320 return Handle(_pyHypothesis)();
1323 //================================================================================
1325 * \brief Find algorithm able to create a hypothesis
1326 * \param theGeom - The shape ID the algorithm was created on
1327 * \param theMesh - The mesh ID that created the algorithm
1328 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1329 * \retval Handle(_pyHypothesis) - The found algo
1331 //================================================================================
1333 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1334 const Handle(_pyHypothesis)& theHypothesis )
1336 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1337 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1338 if ( !id_hyp->second.IsNull() &&
1339 id_hyp->second->IsAlgo() &&
1340 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1341 id_hyp->second->GetGeom() == theGeom &&
1342 id_hyp->second->GetMesh() == theMesh )
1343 return id_hyp->second;
1344 return Handle(_pyHypothesis)();
1347 //================================================================================
1349 * \brief Find subMesh by ID (entry)
1350 * \param theSubMeshID - The subMesh ID
1351 * \retval Handle(_pySubMesh) - The found subMesh
1353 //================================================================================
1355 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1357 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1358 if ( id_subMesh != myObjects.end() )
1359 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1360 return Handle(_pySubMesh)();
1364 //================================================================================
1366 * \brief Change order of commands in the script
1367 * \param theCmd1 - One command
1368 * \param theCmd2 - Another command
1370 //================================================================================
1372 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1374 list< Handle(_pyCommand) >::iterator pos1, pos2;
1375 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1376 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1377 myCommands.insert( pos1, theCmd2 );
1378 myCommands.insert( pos2, theCmd1 );
1379 myCommands.erase( pos1 );
1380 myCommands.erase( pos2 );
1382 int nb1 = theCmd1->GetOrderNb();
1383 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1384 theCmd2->SetOrderNb( nb1 );
1385 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1386 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1389 //================================================================================
1391 * \brief Set one command after the other
1392 * \param theCmd - Command to move
1393 * \param theAfterCmd - Command ater which to insert the first one
1395 //================================================================================
1397 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1399 setNeighbourCommand( theCmd, theAfterCmd, true );
1402 //================================================================================
1404 * \brief Set one command before the other
1405 * \param theCmd - Command to move
1406 * \param theBeforeCmd - Command before which to insert the first one
1408 //================================================================================
1410 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1412 setNeighbourCommand( theCmd, theBeforeCmd, false );
1415 //================================================================================
1417 * \brief Set one command before or after the other
1418 * \param theCmd - Command to move
1419 * \param theOtherCmd - Command ater or before which to insert the first one
1421 //================================================================================
1423 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1424 Handle(_pyCommand)& theOtherCmd,
1425 const bool theIsAfter )
1427 list< Handle(_pyCommand) >::iterator pos;
1428 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1429 myCommands.erase( pos );
1430 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1431 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1434 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1435 (*pos)->SetOrderNb( i++ );
1438 //================================================================================
1440 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1442 //================================================================================
1444 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1446 // No more needed after adding _pyObject::myArgCommands
1448 // const char filterPrefix[] = "aFilter0x";
1449 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1452 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1454 // const _AString & arg = theCommand->GetArg( i );
1455 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1456 // if ( arg.Search( filterPrefix ) != 1 )
1459 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1460 // if ( !filter.IsNull() )
1462 // filter->AddUser( user );
1463 // if ( !filter->GetNewID().IsEmpty() )
1464 // theCommand->SetArg( i, filter->GetNewID() );
1469 //================================================================================
1471 * \brief Set command be last in list of commands
1472 * \param theCmd - Command to be last
1474 //================================================================================
1476 Handle(_pyCommand)& _pyGen::GetLastCommand()
1478 return myLastCommand;
1481 //================================================================================
1483 * \brief Set method to access to object wrapped with python class
1484 * \param theID - The wrapped object entry
1485 * \param theMethod - The accessor method
1487 //================================================================================
1489 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1491 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1494 //================================================================================
1496 * \brief Generated new ID for object and assign with existing name
1497 * \param theID - ID of existing object
1499 //================================================================================
1501 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1506 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1508 while ( myObjectNames.IsBound( aNewID ) );
1510 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1511 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1512 : _pyID( "A" ) + aNewID );
1516 //================================================================================
1518 * \brief Stores theObj in myObjects
1520 //================================================================================
1522 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1524 if ( theObj.IsNull() ) return false;
1526 CheckObjectIsReCreated( theObj );
1530 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1531 add = myMeshes.insert( make_pair( theObj->GetID(),
1532 Handle(_pyMesh)::DownCast( theObj ))).second;
1534 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1535 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1536 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1539 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1540 if ( add ) myOrderedObjects.push_back( theObj );
1545 //================================================================================
1547 * \brief Erases an existing object with the same ID. This method should be called
1548 * before storing theObj in _pyGen
1550 //================================================================================
1552 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1554 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1557 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1558 Handle(_pyObject) existing =
1559 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1560 if ( !existing.IsNull() && existing != theObj )
1562 existing->SetRemovedFromStudy( true );
1563 existing->ClearCommands();
1566 if ( myHypos.count( theObj->GetID() ))
1567 myHypos.erase( theObj->GetID() );
1569 else if ( myMeshes.count( theObj->GetID() ))
1571 myMeshes.erase( theObj->GetID() );
1573 else if ( myObjects.count( theObj->GetID() ))
1575 myObjects.erase( theObj->GetID() );
1580 //================================================================================
1582 * \brief Re-register an object with other ID to make it Process() commands of
1583 * other object having this ID
1585 //================================================================================
1587 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1589 if ( theObj.IsNull() ) return;
1591 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1592 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1594 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1595 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1598 myObjects.insert( make_pair( theID, theObj ));
1601 //================================================================================
1603 * \brief Finds a _pyObject by ID
1605 //================================================================================
1607 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1610 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1611 if ( id_obj != myObjects.end() )
1612 return id_obj->second;
1615 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1616 if ( id_obj != myMeshes.end() )
1617 return id_obj->second;
1620 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1621 // if ( id_obj != myMeshEditors.end() )
1622 // return id_obj->second;
1624 return Handle(_pyObject)();
1627 //================================================================================
1629 * \brief Check if a study entry is under GEOM component
1631 //================================================================================
1633 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1637 return ( myGeomIDIndex <= theObjID.Length() &&
1638 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1639 _pyCommand::IsStudyEntry( theObjID ));
1644 //================================================================================
1646 * \brief Returns true if an object is not present in a study
1648 //================================================================================
1650 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1652 if ( theObjID.IsEmpty() ) return false;
1654 if ( myObjectNames.IsBound( theObjID ))
1655 return false; // SMESH object is in study
1657 // either the SMESH object is not in study or it is a GEOM object
1658 if ( IsGeomObject( theObjID ))
1660 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1661 if ( so->_is_nil() ) return true;
1662 CORBA::Object_var obj = so->GetObject();
1663 return CORBA::is_nil( obj );
1665 return true; // SMESH object not in study
1668 //================================================================================
1670 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1671 * this object is not dumped
1672 * \param [in] theObjID - entry of the object whose creation command was eliminated
1674 //================================================================================
1676 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1678 myRemovedObjIDs.insert( theObjID );
1681 //================================================================================
1683 * \brief Return reader of hypotheses of plugins
1685 //================================================================================
1687 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1689 if (myHypReader.IsNull() )
1690 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1696 //================================================================================
1698 * \brief Mesh created by SMESH_Gen
1700 //================================================================================
1702 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1703 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1705 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1706 myGeomNotInStudy = true;
1708 // convert my creation command --> smeshpy.Mesh(...)
1709 Handle(_pyCommand) creationCmd = GetCreationCmd();
1710 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1711 creationCmd->SetMethod( "Mesh" );
1712 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1715 //================================================================================
1717 * \brief Mesh created by SMESH_MeshEditor
1719 //================================================================================
1721 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1722 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1724 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1726 // this mesh depends on the exported mesh
1727 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1728 if ( !file.IsEmpty() )
1730 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1731 addFatherMesh( exportData.myMesh );
1732 if ( !exportData.myLastComputeCmd.IsNull() )
1734 // restore cleared Compute() by which the exported mesh was generated
1735 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1736 // protect that Compute() cmd from clearing
1737 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1738 exportData.myMesh->myLastComputeCmd.Nullify();
1742 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1744 // this mesh depends on concatenated meshes
1745 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1746 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1747 list< _pyID >::iterator meshID = idList.begin();
1748 for ( ; meshID != idList.end(); ++meshID )
1749 addFatherMesh( *meshID );
1751 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1753 // this mesh depends on a copied IdSource
1754 const _pyID& objID = theCreationCmd->GetArg( 1 );
1755 addFatherMesh( objID );
1757 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1758 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1759 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1761 // this mesh depends on a source mesh
1762 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1763 const _pyID& meshID = theCreationCmd->GetObject();
1764 addFatherMesh( meshID );
1767 // convert my creation command
1768 Handle(_pyCommand) creationCmd = GetCreationCmd();
1769 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1770 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1773 //================================================================================
1775 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1776 * \param theCommand - Engine method called for this mesh
1778 //================================================================================
1780 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1782 // some methods of SMESH_Mesh interface needs special conversion
1783 // to methods of Mesh python class
1785 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1786 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1787 // 2. AddHypothesis(geom, hyp)
1788 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1789 // 3. CreateGroupFromGEOM(type, name, grp)
1790 // --> in Mesh.Group(grp, name="")
1791 // 4. ExportToMED(f, auto_groups, version)
1792 // --> in Mesh.ExportMED( f, auto_groups, version )
1795 const TCollection_AsciiString& method = theCommand->GetMethod();
1796 // ----------------------------------------------------------------------
1797 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1799 if ( !theGen->IsToKeepAllCommands() ) // !historical
1801 list< Handle(_pyHypothesis) >::iterator hyp;
1802 if ( !myLastComputeCmd.IsNull() )
1804 // check if the previously computed mesh has been edited,
1805 // if so then we do not clear the previous Compute()
1806 bool toClear = true;
1807 if ( myLastComputeCmd->GetMethod() == "Compute" )
1809 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1810 for ( ; e != myEditors.end() && toClear; ++e )
1812 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1813 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1814 if ( cmd != cmds.rend() &&
1815 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1821 // clear hyp commands called before myLastComputeCmd
1822 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1823 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1825 myLastComputeCmd->Clear();
1828 myLastComputeCmd = theCommand;
1830 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1831 (*hyp)->MeshComputed( myLastComputeCmd );
1835 // ----------------------------------------------------------------------
1836 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1838 if ( !theGen->IsToKeepAllCommands() ) // !historical
1841 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1842 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1843 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1845 if ( !myLastComputeCmd.IsNull() )
1847 list< Handle(_pyHypothesis) >::iterator hyp;
1848 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1849 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1851 myLastComputeCmd->Clear();
1854 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1855 for ( ; e != myEditors.end(); ++e )
1857 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1858 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1859 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1860 if ( !(*cmd)->IsEmpty() )
1862 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1866 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1869 // ----------------------------------------------------------------------
1870 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1871 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1872 if ( !subMesh.IsNull() ) {
1873 subMesh->SetCreator( this );
1874 mySubmeshes.push_back( subMesh );
1877 // ----------------------------------------------------------------------
1878 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1879 myAddHypCmds.push_back( theCommand );
1881 const _pyID& hypID = theCommand->GetArg( 2 );
1882 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1883 if ( !hyp.IsNull() ) {
1884 myHypos.push_back( hyp );
1885 if ( hyp->GetMesh().IsEmpty() )
1886 hyp->SetMesh( this->GetID() );
1889 // ----------------------------------------------------------------------
1890 else if ( method == "CreateGroup" ||
1891 method == "CreateGroupFromGEOM" ||
1892 method == "CreateGroupFromFilter" )
1894 Handle(_pyGroup) group = new _pyGroup( theCommand );
1895 myGroups.push_back( group );
1896 theGen->AddObject( group );
1898 // ----------------------------------------------------------------------
1899 // update list of groups
1900 else if ( method == "GetGroups" )
1902 bool allGroupsRemoved = true;
1903 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1904 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1905 list< _pyID >::iterator grID = idList.begin();
1906 const int nbGroupsBefore = myGroups.size();
1907 Handle(_pyObject) obj;
1908 for ( ; grID != idList.end(); ++grID )
1910 obj = theGen->FindObject( *grID );
1913 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1914 theGen->AddObject( group );
1915 myGroups.push_back( group );
1918 if ( !obj->CanClear() )
1919 allGroupsRemoved = false;
1921 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1922 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1924 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1926 // check if the preceding command is Compute();
1927 // if GetGroups() is just after Compute(), this can mean that the groups
1928 // were created by some algorithm and hence Compute() should not be discarded
1929 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1930 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1931 while ( (*cmd)->GetMethod() == "GetGroups" )
1933 if ( myLastComputeCmd == (*cmd))
1934 // protect last Compute() from clearing by the next Compute()
1935 myLastComputeCmd.Nullify();
1938 // ----------------------------------------------------------------------
1939 // notify a group about full removal
1940 else if ( method == "RemoveGroupWithContents" ||
1941 method == "RemoveGroup")
1943 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1944 const _pyID groupID = theCommand->GetArg( 1 );
1945 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1946 if ( !grp.IsNull() )
1948 if ( method == "RemoveGroupWithContents" )
1949 grp->RemovedWithContents();
1950 // to clear RemoveGroup() if the group creation is cleared
1951 grp->AddProcessedCmd( theCommand );
1955 // ----------------------------------------------------------------------
1956 else if ( theCommand->MethodStartsFrom( "Export" ))
1958 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1959 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1961 theCommand->SetMethod( "ExportMED" );
1962 if ( theCommand->GetNbArgs() == 5 )
1964 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1965 _AString autoDimension = theCommand->GetArg( 5 );
1966 theCommand->SetArg( 5, "None" );
1967 theCommand->SetArg( 6, autoDimension );
1970 else if ( method == "ExportCGNS" )
1971 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1972 _pyID partID = theCommand->GetArg( 1 );
1973 int nbArgs = theCommand->GetNbArgs();
1974 for ( int i = 2; i <= nbArgs; ++i )
1975 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1976 theCommand->SetArg( nbArgs, partID );
1978 else if ( method == "ExportGMF" )
1979 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1980 _pyID partID = theCommand->GetArg( 1 );
1981 _AString file = theCommand->GetArg( 2 );
1982 theCommand->RemoveArgs();
1983 theCommand->SetArg( 1, file );
1984 theCommand->SetArg( 2, partID );
1986 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1987 { // ExportPartTo*(part, ...) -> Export*(..., part)
1989 // remove "PartTo" from the method
1990 TCollection_AsciiString newMethod = method;
1991 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
1992 theCommand->SetMethod( newMethod );
1993 // make the 1st arg be the last one (or last but three for ExportMED())
1994 _pyID partID = theCommand->GetArg( 1 );
1995 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
1996 for ( int i = 2; i <= nbArgs; ++i )
1997 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1998 theCommand->SetArg( nbArgs, partID );
2000 // remember file name
2001 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2002 ExportedMeshData( this, myLastComputeCmd ));
2004 // ----------------------------------------------------------------------
2005 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2007 _pyID hypID = theCommand->GetArg( 2 );
2008 _pyID geomID = theCommand->GetArg( 1 );
2009 bool isLocal = ( geomID != GetGeom() );
2011 // check if this mesh still has corresponding addition command
2012 Handle(_pyCommand) addCmd;
2013 list< Handle(_pyCommand) >::iterator cmd;
2014 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2015 for ( int i = 0; i < 2; ++i )
2017 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2018 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2020 bool sameHyp = true;
2021 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2022 sameHyp = false; // other hyp
2023 if ( (*cmd)->GetNbArgs() == 2 &&
2024 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2025 sameHyp = false; // other geom
2026 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2027 sameHyp = false; // other geom
2031 cmd = addHypCmds.erase( cmd );
2032 if ( !theGen->IsToKeepAllCommands() && CanClear() ) {
2034 theCommand->Clear();
2038 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2039 addCmd->RemoveArgs();
2040 addCmd->SetArg( 1, hypID );
2042 addCmd->SetArg( 2, geomID );
2051 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2052 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2053 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2054 _pyID geom = theCommand->GetArg( 1 );
2055 theCommand->RemoveArgs();
2056 theCommand->SetArg( 1, hypID );
2057 if ( geom != GetGeom() )
2058 theCommand->SetArg( 2, geom );
2060 // remove hyp from myHypos
2061 myHypos.remove( hyp );
2063 // check for SubMesh order commands
2064 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2066 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2067 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2068 // commands are moved at the end of the script
2069 TCollection_AsciiString subIDs =
2070 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2071 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2072 list< _pyID >::iterator subID = idList.begin();
2073 for ( ; subID != idList.end(); ++subID )
2075 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2076 if ( !subMesh.IsNull() )
2077 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2080 // add accessor method if necessary
2083 if ( NeedMeshAccess( theCommand ))
2084 // apply theCommand to the mesh wrapped by smeshpy mesh
2085 AddMeshAccess( theCommand );
2089 //================================================================================
2091 * \brief Return True if addition of accesor method is needed
2093 //================================================================================
2095 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2097 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2098 // so no conversion is needed for them at all:
2099 static TStringSet sameMethods;
2100 if ( sameMethods.empty() ) {
2101 const char * names[] =
2102 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2103 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
2104 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2105 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2106 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2107 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2108 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2109 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2110 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2111 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2112 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2113 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2114 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2115 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2116 ,"" }; // <- mark of end
2117 sameMethods.Insert( names );
2120 return !sameMethods.Contains( theCommand->GetMethod() );
2123 //================================================================================
2125 * \brief Convert creation and addition of all algos and hypos
2127 //================================================================================
2129 void _pyMesh::Flush()
2132 // get the meshes this mesh depends on via hypotheses
2133 list< Handle(_pyMesh) > fatherMeshes;
2134 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2135 for ( ; hyp != myHypos.end(); ++hyp )
2136 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2137 myGeomNotInStudy = true;
2139 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2140 for ( ; m != fatherMeshes.end(); ++m )
2141 addFatherMesh( *m );
2142 // if ( removedGeom )
2143 // SetRemovedFromStudy(); // as reffered geometry not in study
2145 if ( myGeomNotInStudy )
2148 list < Handle(_pyCommand) >::iterator cmd;
2150 // try to convert algo addition like this:
2151 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2152 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2154 Handle(_pyCommand) addCmd = *cmd;
2156 _pyID algoID = addCmd->GetArg( 2 );
2157 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2158 if ( algo.IsNull() || !algo->IsAlgo() )
2161 // check and create new algorithm instance if it is already wrapped
2162 if ( algo->IsWrapped() ) {
2163 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2164 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2165 TCollection_AsciiString( " = " ) + theGen->GetID() +
2166 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2167 TCollection_AsciiString( "\" )" );
2169 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2170 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2171 if ( !newAlgo.IsNull() ) {
2172 newAlgo->Assign( algo, this->GetID() );
2173 newAlgo->SetCreationCmd( newCmd );
2175 // set algorithm creation
2176 theGen->SetCommandBefore( newCmd, addCmd );
2177 myHypos.push_back( newAlgo );
2178 if ( !myLastComputeCmd.IsNull() &&
2179 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2180 newAlgo->MeshComputed( myLastComputeCmd );
2185 _pyID geom = addCmd->GetArg( 1 );
2186 bool isLocalAlgo = ( geom != GetGeom() );
2189 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2191 // wrapped algo is created after mesh creation
2192 GetCreationCmd()->AddDependantCmd( addCmd );
2194 if ( isLocalAlgo ) {
2195 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2196 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2197 TCollection_AsciiString( "geom=" ) + geom );
2198 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2199 list < Handle(_pySubMesh) >::iterator smIt;
2200 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2201 Handle(_pySubMesh) subMesh = *smIt;
2202 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2203 if ( geom == subCmd->GetArg( 1 )) {
2204 subCmd->SetObject( algo->GetID() );
2205 subCmd->RemoveArgs();
2206 subMesh->SetCreator( algo );
2211 else // KO - ALGO was already created
2213 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2214 addCmd->RemoveArgs();
2215 addCmd->SetArg( 1, algoID );
2217 addCmd->SetArg( 2, geom );
2218 myNotConvertedAddHypCmds.push_back( addCmd );
2222 // try to convert hypo addition like this:
2223 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2224 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2226 Handle(_pyCommand) addCmd = *cmd;
2227 _pyID hypID = addCmd->GetArg( 2 );
2228 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2229 if ( hyp.IsNull() || hyp->IsAlgo() )
2231 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2233 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2234 _pyID geom = addCmd->GetArg( 1 );
2235 addCmd->RemoveArgs();
2236 addCmd->SetArg( 1, hypID );
2237 if ( geom != GetGeom() )
2238 addCmd->SetArg( 2, geom );
2239 myNotConvertedAddHypCmds.push_back( addCmd );
2243 myAddHypCmds.clear();
2244 mySubmeshes.clear();
2247 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2248 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2252 //================================================================================
2254 * \brief Sets myIsPublished of me and of all objects depending on me.
2256 //================================================================================
2258 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2260 _pyObject::SetRemovedFromStudy(isRemoved);
2262 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2263 for ( ; sm != mySubmeshes.end(); ++sm )
2264 (*sm)->SetRemovedFromStudy(isRemoved);
2266 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2267 for ( ; gr != myGroups.end(); ++gr )
2268 (*gr)->SetRemovedFromStudy(isRemoved);
2270 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2271 for ( ; m != myChildMeshes.end(); ++m )
2272 (*m)->SetRemovedFromStudy(isRemoved);
2274 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2275 for ( ; e != myEditors.end(); ++e )
2276 (*e)->SetRemovedFromStudy(isRemoved);
2279 //================================================================================
2281 * \brief Return true if none of myChildMeshes is in study
2283 //================================================================================
2285 bool _pyMesh::CanClear()
2290 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2291 for ( ; m != myChildMeshes.end(); ++m )
2292 if ( !(*m)->CanClear() )
2298 //================================================================================
2300 * \brief Clear my commands and commands of mesh editor
2302 //================================================================================
2304 void _pyMesh::ClearCommands()
2310 // mark all sub-objects as not removed, except child meshes
2311 list< Handle(_pyMesh) > children;
2312 children.swap( myChildMeshes );
2313 SetRemovedFromStudy( false );
2314 children.swap( myChildMeshes );
2318 _pyObject::ClearCommands();
2320 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2321 for ( ; sm != mySubmeshes.end(); ++sm )
2322 (*sm)->ClearCommands();
2324 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2325 for ( ; gr != myGroups.end(); ++gr )
2326 (*gr)->ClearCommands();
2328 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2329 for ( ; e != myEditors.end(); ++e )
2330 (*e)->ClearCommands();
2333 //================================================================================
2335 * \brief Add a father mesh by ID
2337 //================================================================================
2339 void _pyMesh::addFatherMesh( const _pyID& meshID )
2341 if ( !meshID.IsEmpty() && meshID != GetID() )
2342 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2345 //================================================================================
2347 * \brief Add a father mesh
2349 //================================================================================
2351 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2353 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2355 //myFatherMeshes.push_back( mesh );
2356 mesh->myChildMeshes.push_back( this );
2358 // protect last Compute() from clearing by the next Compute()
2359 mesh->myLastComputeCmd.Nullify();
2363 //================================================================================
2365 * \brief MeshEditor convert its commands to ones of mesh
2367 //================================================================================
2369 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2370 _pyObject( theCreationCmd )
2372 myMesh = theCreationCmd->GetObject();
2373 myCreationCmdStr = theCreationCmd->GetString();
2374 theCreationCmd->Clear();
2376 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2377 if ( !mesh.IsNull() )
2378 mesh->AddEditor( this );
2381 //================================================================================
2383 * \brief convert its commands to ones of mesh
2385 //================================================================================
2387 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2389 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2390 // commands calling these methods are converted to calls of Mesh methods without
2391 // additional modifs, only object is changed from MeshEditor to Mesh.
2392 static TStringSet sameMethods;
2393 if ( sameMethods.empty() ) {
2394 const char * names[] = {
2395 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2396 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2397 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2398 "MoveNode", "MoveClosestNodeToPoint",
2399 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2400 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2401 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2402 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2403 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2404 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2405 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2406 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2407 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2408 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2409 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2410 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2411 "GetLastCreatedElems",
2412 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2413 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2414 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2415 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2416 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2417 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2418 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2419 ,"" }; // <- mark of the end
2420 sameMethods.Insert( names );
2423 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2424 TStringMap diffMethods;
2425 if ( diffMethods.empty() ) {
2426 const char * orig2newName[] = {
2427 // original name --------------> new name
2428 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2429 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2430 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2431 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2432 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2433 ""};// <- mark of the end
2434 diffMethods.Insert( orig2newName );
2437 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2438 // only by last two arguments
2439 static TStringSet diffLastTwoArgsMethods;
2440 if (diffLastTwoArgsMethods.empty() ) {
2441 const char * names[] = {
2442 "MirrorMakeGroups","MirrorObjectMakeGroups",
2443 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2444 "RotateMakeGroups","RotateObjectMakeGroups",
2445 ""};// <- mark of the end
2446 diffLastTwoArgsMethods.Insert( names );
2449 // only a method name is to change?
2450 const TCollection_AsciiString & method = theCommand->GetMethod();
2451 bool isPyMeshMethod = sameMethods.Contains( method );
2452 if ( !isPyMeshMethod )
2454 TCollection_AsciiString newMethod = diffMethods.Value( method );
2455 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2456 theCommand->SetMethod( newMethod );
2458 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2459 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2461 isPyMeshMethod = true;
2462 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2463 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2466 if ( !isPyMeshMethod )
2468 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2469 // functions with the flag "theMakeGroups = True" like:
2470 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2471 int pos = method.Search("MakeGroups");
2474 isPyMeshMethod = true;
2475 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2476 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2478 // 1. Remove "MakeGroups" from the Command
2479 TCollection_AsciiString aMethod = theCommand->GetMethod();
2480 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2483 pos = pos-2; //Remove "0D" from the Command too
2484 aMethod.Trunc(pos-1);
2485 theCommand->SetMethod(aMethod);
2487 // 2. And add last "True" argument(s)
2488 while(nbArgsToAdd--)
2489 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2490 if( is0DmethId || is0DmethObj )
2491 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2495 // ExtrusionSweep0D() -> ExtrusionSweep()
2496 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2497 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2498 method == "ExtrusionSweepObject0D" ))
2500 isPyMeshMethod = true;
2501 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2502 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2503 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2506 // DoubleNode...New(...) -> DoubleNode...(...,True)
2507 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2508 method == "DoubleNodeElemGroupsNew" ||
2509 method == "DoubleNodeGroupNew" ||
2510 method == "DoubleNodeGroupsNew" ||
2511 method == "DoubleNodeElemGroup2New" ||
2512 method == "DoubleNodeElemGroups2New"))
2514 isPyMeshMethod = true;
2515 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2516 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2517 if ( excessLen == 3 )
2519 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2521 else if ( theCommand->GetArg(4) == "0" ||
2522 theCommand->GetArg(5) == "0" )
2524 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2525 // Group = DoubleNodeGroup2New(,,,False, True)
2526 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2527 theCommand->SetResultValue( groupID );
2530 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2531 // FindElementsByPoint(x, y, z, elementType, meshPart)
2532 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2534 isPyMeshMethod = true;
2535 theCommand->SetMethod( "FindElementsByPoint" );
2536 // make the 1st arg be the last one
2537 _pyID partID = theCommand->GetArg( 1 );
2538 int nbArgs = theCommand->GetNbArgs();
2539 for ( int i = 2; i <= nbArgs; ++i )
2540 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2541 theCommand->SetArg( nbArgs, partID );
2543 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2544 if ( !isPyMeshMethod && method == "Reorient2D" )
2546 isPyMeshMethod = true;
2547 _AString mesh = theCommand->GetArg( 1 );
2548 _AString dir = theCommand->GetArg( 2 );
2549 _AString face = theCommand->GetArg( 3 );
2550 _AString point = theCommand->GetArg( 4 );
2551 theCommand->RemoveArgs();
2552 theCommand->SetArg( 1, mesh );
2553 theCommand->SetArg( 2, dir );
2554 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2555 theCommand->SetArg( 3, point );
2557 theCommand->SetArg( 3, face );
2560 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2562 isPyMeshMethod = true;
2563 int crit_arg = theCommand->GetNbArgs();
2564 const _AString& crit = theCommand->GetArg(crit_arg);
2565 if (crit.Search("MaxElementLength2D") != -1)
2566 theCommand->SetArg(crit_arg, "");
2569 if ( isPyMeshMethod )
2571 theCommand->SetObject( myMesh );
2575 // editor creation command is needed only if any editor function is called
2576 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2577 if ( !myCreationCmdStr.IsEmpty() ) {
2578 GetCreationCmd()->GetString() = myCreationCmdStr;
2579 myCreationCmdStr.Clear();
2584 //================================================================================
2586 * \brief Return true if my mesh can be removed
2588 //================================================================================
2590 bool _pyMeshEditor::CanClear()
2592 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2593 return mesh.IsNull() ? true : mesh->CanClear();
2596 //================================================================================
2598 * \brief _pyHypothesis constructor
2599 * \param theCreationCmd -
2601 //================================================================================
2603 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2604 _pyObject( theCreationCmd ), myCurCrMethod(0)
2606 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2609 //================================================================================
2611 * \brief Creates algorithm or hypothesis
2612 * \param theCreationCmd - The engine command creating a hypothesis
2613 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2615 //================================================================================
2617 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2619 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2620 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2622 Handle(_pyHypothesis) hyp, algo;
2625 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2626 if ( hypTypeQuoted.IsEmpty() )
2629 TCollection_AsciiString hypType =
2630 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2632 algo = new _pyAlgorithm( theCreationCmd );
2633 hyp = new _pyHypothesis( theCreationCmd );
2635 if ( hypType == "NumberOfSegments" ) {
2636 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2637 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2638 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2639 hyp->AddArgMethod( "SetNumberOfSegments" );
2640 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2641 hyp->AddArgMethod( "SetScaleFactor" );
2642 hyp->AddArgMethod( "SetReversedEdges" );
2643 // same for ""CompositeSegment_1D:
2644 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2645 hyp->AddArgMethod( "SetNumberOfSegments" );
2646 hyp->AddArgMethod( "SetScaleFactor" );
2647 hyp->AddArgMethod( "SetReversedEdges" );
2649 else if ( hypType == "SegmentLengthAroundVertex" ) {
2650 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2651 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2652 hyp->AddArgMethod( "SetLength" );
2653 // same for ""CompositeSegment_1D:
2654 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2655 hyp->AddArgMethod( "SetLength" );
2657 else if ( hypType == "LayerDistribution2D" ) {
2658 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2659 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2661 else if ( hypType == "LayerDistribution" ) {
2662 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2663 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2665 else if ( hypType == "CartesianParameters3D" ) {
2666 hyp = new _pyComplexParamHypo( theCreationCmd );
2667 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2668 for ( int iArg = 0; iArg < 4; ++iArg )
2669 hyp->setCreationArg( iArg+1, "[]");
2670 hyp->AddAccumulativeMethod( "SetGrid" );
2671 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2675 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2678 return algo->IsValid() ? algo : hyp;
2681 //================================================================================
2683 * \brief Returns true if addition of this hypothesis to a given mesh can be
2684 * wrapped into hypothesis creation
2686 //================================================================================
2688 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2690 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2692 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2693 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2699 //================================================================================
2701 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2702 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2703 * \param theAlgo - The algo that can create this hypo
2704 * \retval bool - false if the command cant be converted
2706 //================================================================================
2708 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2709 const _pyID& theMesh)
2711 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2713 if ( !IsWrappable( theMesh ))
2716 myGeom = theCmd->GetArg( 1 );
2718 Handle(_pyHypothesis) algo;
2720 // find algo created on myGeom in theMesh
2721 algo = theGen->FindAlgo( myGeom, theMesh, this );
2722 if ( algo.IsNull() )
2724 // attach hypothesis creation command to be after algo creation command
2725 // because it can be new created instance of algorithm
2726 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2730 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2731 theCmd->SetResultValue( GetID() );
2732 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2733 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2734 // set args (geom will be set by _pyMesh calling this method)
2735 theCmd->RemoveArgs();
2736 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2737 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2738 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2740 theCmd->SetArg( i+1, "[]");
2742 // set a new creation command
2743 GetCreationCmd()->Clear();
2744 // replace creation command by wrapped instance
2745 // please note, that hypothesis attaches to algo creation command (see upper)
2746 SetCreationCmd( theCmd );
2749 // clear commands setting arg values
2750 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2751 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2754 // set unknown arg commands after hypo creation
2755 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2756 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2757 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2758 afterCmd->AddDependantCmd( *cmd );
2764 //================================================================================
2766 * \brief Remember hypothesis parameter values
2767 * \param theCommand - The called hypothesis method
2769 //================================================================================
2771 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2773 ASSERT( !myIsAlgo );
2774 if ( !theGen->IsToKeepAllCommands() )
2775 rememberCmdOfParameter( theCommand );
2777 bool usedCommand = false;
2778 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2779 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2781 CreationMethod& crMethod = type2meth->second;
2782 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2783 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2785 myArgCommands.push_back( theCommand );
2787 while ( crMethod.myArgs.size() < i+1 )
2788 crMethod.myArgs.push_back( "None" );
2789 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2794 myUnusedCommands.push_back( theCommand );
2797 //================================================================================
2799 * \brief Finish conversion
2801 //================================================================================
2803 void _pyHypothesis::Flush()
2807 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2808 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2809 // Add access to a wrapped mesh
2810 theGen->AddMeshAccessorMethod( *cmd );
2811 // Add access to a wrapped algorithm
2812 theGen->AddAlgoAccessorMethod( *cmd );
2814 cmd = myUnusedCommands.begin();
2815 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2816 // Add access to a wrapped mesh
2817 theGen->AddMeshAccessorMethod( *cmd );
2818 // Add access to a wrapped algorithm
2819 theGen->AddAlgoAccessorMethod( *cmd );
2822 // forget previous hypothesis modifications
2823 myArgCommands.clear();
2824 myUnusedCommands.clear();
2827 //================================================================================
2829 * \brief clear creation, arg and unkown commands
2831 //================================================================================
2833 void _pyHypothesis::ClearAllCommands()
2835 GetCreationCmd()->Clear();
2836 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2837 for ( ; cmd != myArgCommands.end(); ++cmd )
2839 cmd = myUnusedCommands.begin();
2840 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2845 //================================================================================
2847 * \brief Assign fields of theOther to me except myIsWrapped
2849 //================================================================================
2851 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2852 const _pyID& theMesh )
2854 // myCreationCmd = theOther->myCreationCmd;
2855 myIsAlgo = theOther->myIsAlgo;
2856 myIsWrapped = false;
2857 myGeom = theOther->myGeom;
2859 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2860 myAccumulativeMethods = theOther->myAccumulativeMethods;
2861 //myUnusedCommands = theOther->myUnusedCommands;
2862 // init myCurCrMethod
2863 GetCreationMethod( theOther->GetAlgoType() );
2866 //================================================================================
2868 * \brief Analyze my erasability depending on myReferredObjs
2870 //================================================================================
2872 bool _pyHypothesis::CanClear()
2876 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2877 for ( ; obj != myReferredObjs.end(); ++obj )
2878 if ( (*obj)->CanClear() )
2885 //================================================================================
2887 * \brief Clear my commands depending on usage by meshes
2889 //================================================================================
2891 void _pyHypothesis::ClearCommands()
2893 // if ( !theGen->IsToKeepAllCommands() )
2895 // bool isUsed = false;
2896 // int lastComputeOrder = 0;
2897 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2898 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2899 // if ( ! (*cmd)->IsEmpty() )
2902 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2903 // lastComputeOrder = (*cmd)->GetOrderNb();
2907 // SetRemovedFromStudy( true );
2911 // // clear my commands invoked after lastComputeOrder
2912 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2913 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2915 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2916 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2917 // // cmds.back()->Clear();
2921 _pyObject::ClearCommands();
2924 //================================================================================
2926 * \brief Find arguments that are objects like mesh, group, geometry
2927 * \param meshes - referred meshes (directly or indirrectly)
2928 * \retval bool - false if a referred geometry is not in the study
2930 //================================================================================
2932 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2934 if ( IsAlgo() ) return true;
2936 bool geomPublished = true;
2937 vector< _AString > args;
2938 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2939 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2941 CreationMethod& crMethod = type2meth->second;
2942 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2944 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2945 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2946 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2947 args.push_back( (*cmd)->GetArg( nb ));
2950 for ( size_t i = 0; i < args.size(); ++i )
2952 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2953 if ( idList.empty() && !args[ i ].IsEmpty() )
2954 idList.push_back( args[ i ]);
2955 list< _pyID >::iterator id = idList.begin();
2956 for ( ; id != idList.end(); ++id )
2958 Handle(_pyObject) obj = theGen->FindObject( *id );
2959 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2962 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2963 geomPublished = false;
2967 myReferredObjs.push_back( obj );
2968 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2969 if ( !mesh.IsNull() )
2970 meshes.push_back( mesh );
2971 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2972 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2973 obj->SetRemovedFromStudy( false );
2977 return geomPublished;
2980 //================================================================================
2982 * \brief Remember theCommand setting a parameter
2984 //================================================================================
2986 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2988 // parameters are discriminated by method name
2989 _AString method = theCommand->GetMethod();
2990 if ( myAccumulativeMethods.count( method ))
2991 return; // this method adds values and not override the previus value
2993 // discriminate commands setting different parameters via one method
2994 // by passing parameter names like e.g. SetOption("size", "0.2")
2995 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2996 theCommand->GetNbArgs() > 1 )
2998 // mangle method by appending a 1st textual arg
2999 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3001 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3002 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3003 if ( !isalpha( arg.Value(2))) continue;
3008 // parameters are discriminated by method name
3009 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3010 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3012 cmds.back()->Clear(); // previous parameter value has not been used
3013 cmds.back() = theCommand;
3017 cmds.push_back( theCommand );
3021 //================================================================================
3023 * \brief Return true if a setting parameter command ha been used to compute mesh
3025 //================================================================================
3027 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3028 _pyCommand::TAddr avoidComputeAddr ) const
3030 bool isUsed = false;
3031 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3032 myComputeAddr2Cmds.begin();
3033 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3035 if ( addr2cmds->first == avoidComputeAddr ) continue;
3036 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3037 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3042 //================================================================================
3044 * \brief Save commands setting parameters as they are used for a mesh computation
3046 //================================================================================
3048 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3050 myComputeCmds.push_back( theComputeCmd );
3051 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3053 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3054 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3055 savedCmds.push_back( m2c->second.back() );
3058 //================================================================================
3060 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3062 //================================================================================
3064 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3066 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3068 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3069 for ( ; cmd != savedCmds.end(); ++cmd )
3071 // check if a cmd has been used to compute another mesh
3072 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3074 // check if a cmd is a sole command setting its parameter;
3075 // don't use method name for search as it can change
3076 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3077 m2cmds = myMeth2Commands.begin();
3078 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3080 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3081 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3082 if ( cmdIt != cmds.end() )
3084 if ( cmds.back() != *cmd )
3086 cmds.erase( cmdIt );
3093 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3096 //================================================================================
3098 * \brief Sets an argNb-th argument of current creation command
3099 * \param argNb - argument index countered from 1
3101 //================================================================================
3103 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3105 if ( myCurCrMethod )
3107 while ( myCurCrMethod->myArgs.size() < argNb )
3108 myCurCrMethod->myArgs.push_back( "None" );
3109 if ( arg.IsEmpty() )
3110 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3112 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3117 //================================================================================
3119 * \brief Remember hypothesis parameter values
3120 * \param theCommand - The called hypothesis method
3122 //================================================================================
3124 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3126 if ( GetAlgoType() == "Cartesian_3D" )
3128 // CartesianParameters3D hyp
3130 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3131 theCommand->GetMethod() == "SetToAddEdges" )
3133 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3134 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3135 myArgCommands.push_back( theCommand );
3138 if ( theCommand->GetMethod() == "SetGrid" ||
3139 theCommand->GetMethod() == "SetGridSpacing" )
3141 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3142 int iArg = axis.Value(1) - '0';
3143 if ( theCommand->GetMethod() == "SetGrid" )
3145 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3149 myCurCrMethod->myArgs[ iArg ] = "[ ";
3150 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3151 myCurCrMethod->myArgs[ iArg ] += ", ";
3152 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3153 myCurCrMethod->myArgs[ iArg ] += "]";
3155 myArgCommands.push_back( theCommand );
3156 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3157 // accumulative, else, if the creation
3158 // is not converted, commands for axes 1 and 2 are lost
3163 if( theCommand->GetMethod() == "SetLength" )
3165 // NOW it is OBSOLETE
3166 // ex: hyp.SetLength(start, 1)
3167 // hyp.SetLength(end, 0)
3168 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3169 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3170 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3171 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3173 CreationMethod& crMethod = type2meth->second;
3174 while ( crMethod.myArgs.size() < i+1 )
3175 crMethod.myArgs.push_back( "[]" );
3176 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3178 myArgCommands.push_back( theCommand );
3182 _pyHypothesis::Process( theCommand );
3185 //================================================================================
3187 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3189 //================================================================================
3191 void _pyComplexParamHypo::Flush()
3193 list < Handle(_pyCommand) >::iterator cmd;
3196 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3197 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3201 // if ( GetAlgoType() == "Cartesian_3D" )
3203 // _pyID algo = myCreationCmd->GetObject();
3204 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3206 // if ( IsWrapped() )
3208 // StructToList( *cmd, /*checkMethod=*/false );
3209 // const _AString & method = (*cmd)->GetMethod();
3210 // if ( method == "SetFixedPoint" )
3211 // (*cmd)->SetObject( algo );
3217 //================================================================================
3219 * \brief Convert methods of 1D hypotheses to my own methods
3220 * \param theCommand - The called hypothesis method
3222 //================================================================================
3224 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3226 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3229 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3230 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3231 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3233 // TCollection_AsciiString cmd =
3234 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3235 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3236 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3239 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3241 // // 1D hypo is already set, so distribution changes and the old
3242 // // 1D hypo is thrown away
3243 // my1dHyp->ClearAllCommands();
3246 // //my1dHyp->SetRemovedFromStudy( false );
3248 // if ( !myArgCommands.empty() )
3249 // myArgCommands.back()->Clear();
3250 myCurCrMethod->myArgs.push_back( hyp1dID );
3251 myArgCommands.push_back( theCommand );
3254 //================================================================================
3257 * \param theAdditionCmd - command to be converted
3258 * \param theMesh - mesh instance
3259 * \retval bool - status
3261 //================================================================================
3263 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3264 const _pyID& theMesh)
3266 myIsWrapped = false;
3268 if ( my1dHyp.IsNull() )
3271 // set "SetLayerDistribution()" after addition cmd
3272 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3274 _pyID geom = theAdditionCmd->GetArg( 1 );
3276 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3277 if ( !algo.IsNull() )
3279 my1dHyp->SetMesh( theMesh );
3280 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3281 algo->GetAlgoType().ToCString());
3282 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3285 // clear "SetLayerDistribution()" cmd
3286 myArgCommands.back()->Clear();
3288 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3290 // find RadialPrism algo created on <geom> for theMesh
3291 GetCreationCmd()->SetObject( algo->GetID() );
3292 GetCreationCmd()->SetMethod( myAlgoMethod );
3293 GetCreationCmd()->RemoveArgs();
3294 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3300 //================================================================================
3304 //================================================================================
3306 void _pyLayerDistributionHypo::Flush()
3308 // as creation of 1D hyp was written later then it's edition,
3309 // we need to find all it's edition calls and process them
3310 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3312 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3314 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3315 if ( hyp1dID.IsEmpty() ) continue;
3317 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3319 // make a new name for 1D hyp = "HypType" + "_Distribution"
3321 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3323 if ( prevNewName.IsEmpty() ) continue;
3324 newName = prevNewName;
3328 if ( hyp1d->IsWrapped() ) {
3329 newName = hyp1d->GetCreationCmd()->GetMethod();
3332 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3333 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3335 newName += "_Distribution";
3336 prevNewName = newName;
3338 hyp1d->GetCreationCmd()->SetResultValue( newName );
3340 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3341 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3342 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3343 const _pyID& objID = (*cmdIt)->GetObject();
3344 if ( objID == hyp1dID ) {
3345 if ( !hyp1d.IsNull() )
3347 hyp1d->Process( *cmdIt );
3348 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3350 ( *cmdIt )->SetObject( newName );
3353 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3354 (*cmd)->SetArg( 1, newName );
3358 //================================================================================
3360 * \brief additionally to Addition2Creation, clears SetDistrType() command
3361 * \param theCmd - AddHypothesis() command
3362 * \param theMesh - mesh to which a hypothesis is added
3363 * \retval bool - convertion result
3365 //================================================================================
3367 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3368 const _pyID& theMesh)
3370 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3371 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3372 bool scaleDistrType = false;
3373 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3374 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3375 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3376 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3377 scaleDistrType = true;
3380 else if ( !scaleDistrType ) {
3381 // distribution type changed: remove scale factor from args
3382 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3383 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3385 CreationMethod& crMethod = type2meth->second;
3386 if ( crMethod.myArgs.size() == 2 )
3387 crMethod.myArgs.pop_back();
3394 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3397 //================================================================================
3399 * \brief remove repeated commands defining distribution
3401 //================================================================================
3403 void _pyNumberOfSegmentsHyp::Flush()
3405 // find number of the last SetDistrType() command
3406 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3407 int distrTypeNb = 0;
3408 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3409 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3410 if ( cmd != myUnusedCommands.rbegin() )
3411 distrTypeNb = (*cmd)->GetOrderNb();
3413 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3416 // clear commands before the last SetDistrType()
3417 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3418 set< int > treatedCmdNbs; // avoid treating same cmd twice
3419 for ( int i = 0; i < 2; ++i ) {
3420 set<TCollection_AsciiString> uniqueMethods;
3421 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3422 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3424 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3425 continue;// avoid treating same cmd twice
3426 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3427 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3428 if ( !clear || method == "SetNumberOfSegments" ) {
3429 bool isNewInSet = uniqueMethods.insert( method ).second;
3430 clear = !isNewInSet;
3439 //================================================================================
3441 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3442 * into regular1D.LengthNearVertex( length, vertex )
3443 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3444 * \param theMesh - The mesh needing this hypo
3445 * \retval bool - false if the command cant be converted
3447 //================================================================================
3449 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3450 const _pyID& theMeshID)
3452 if ( IsWrappable( theMeshID )) {
3454 _pyID vertex = theCmd->GetArg( 1 );
3456 // the problem here is that segment algo will not be found
3457 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3458 // geometry where segment algorithm is assigned
3459 Handle(_pyHypothesis) algo;
3460 _pyID geom = vertex;
3461 while ( algo.IsNull() && !geom.IsEmpty()) {
3462 // try to find geom as a father of <vertex>
3463 geom = FatherID( geom );
3464 algo = theGen->FindAlgo( geom, theMeshID, this );
3466 if ( algo.IsNull() )
3467 return false; // also possible to find geom as brother of veretex...
3468 // set geom instead of vertex
3469 theCmd->SetArg( 1, geom );
3471 // set vertex as a second arg
3472 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3473 setCreationArg( 2, vertex );
3475 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3476 // theMeshID.LengthNearVertex( length, vertex )
3477 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3482 //================================================================================
3484 * \brief _pyAlgorithm constructor
3485 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3487 //================================================================================
3489 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3490 : _pyHypothesis( theCreationCmd )
3495 //================================================================================
3497 * \brief Convert the command adding an algorithm to mesh
3498 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3499 * \param theMesh - The mesh needing this algo
3500 * \retval bool - false if the command cant be converted
3502 //================================================================================
3504 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3505 const _pyID& theMeshID)
3507 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3508 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3509 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3515 //================================================================================
3517 * \brief Return starting position of a part of python command
3518 * \param thePartIndex - The index of command part
3519 * \retval int - Part position
3521 //================================================================================
3523 int _pyCommand::GetBegPos( int thePartIndex ) const
3527 if ( myBegPos.Length() < thePartIndex )
3529 ASSERT( thePartIndex > 0 );
3530 return myBegPos( thePartIndex );
3533 //================================================================================
3535 * \brief Store starting position of a part of python command
3536 * \param thePartIndex - The index of command part
3537 * \param thePosition - Part position
3539 //================================================================================
3541 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3543 while ( myBegPos.Length() < thePartIndex )
3544 myBegPos.Append( UNKNOWN );
3545 ASSERT( thePartIndex > 0 );
3546 myBegPos( thePartIndex ) = thePosition;
3549 //================================================================================
3551 * \brief Returns whitespace symbols at the line beginning
3552 * \retval TCollection_AsciiString - result
3554 //================================================================================
3556 TCollection_AsciiString _pyCommand::GetIndentation()
3559 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3560 GetWord( myString, end, true );
3562 end = GetBegPos( RESULT_IND );
3563 return myString.SubString( 1, Max( end - 1, 1 ));
3566 //================================================================================
3568 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3569 * \retval const TCollection_AsciiString & - ResultValue substring
3571 //================================================================================
3573 const TCollection_AsciiString & _pyCommand::GetResultValue()
3575 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3577 SetBegPos( RESULT_IND, EMPTY );
3578 int begPos, endPos = myString.Location( "=", 1, Length() );
3582 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3583 if ( begPos < endPos )
3585 SetBegPos( RESULT_IND, begPos );
3587 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3588 myRes = myString.SubString( begPos, endPos );
3595 //================================================================================
3597 * \brief Return number of python command result value ResultValue = Obj.Meth()
3599 //================================================================================
3601 int _pyCommand::GetNbResultValues()
3604 return myResults.Length();
3608 //================================================================================
3610 * \brief Return substring of python command looking like
3611 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3612 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3614 //================================================================================
3615 const _AString& _pyCommand::GetResultValue(int res)
3617 if ( GetResultValue().IsEmpty() )
3618 return theEmptyString;
3620 if ( myResults.IsEmpty() )
3623 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3624 ++begPos; // skip [, else the whole list is returned
3625 while ( begPos < myRes.Length() ) {
3626 _AString result = GetWord( myRes, begPos, true );
3627 begPos += result.Length();
3629 // result.RemoveAll('[');
3630 // result.RemoveAll(']');
3635 myResults.Append( result );
3638 if ( res > 0 && res <= myResults.Length() )
3639 return myResults( res );
3640 return theEmptyString;
3643 //================================================================================
3645 * \brief Return substring of python command looking like ResVal = Object.Meth()
3646 * \retval const TCollection_AsciiString & - Object substring
3648 //================================================================================
3650 const TCollection_AsciiString & _pyCommand::GetObject()
3652 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3655 int begPos = GetBegPos( RESULT_IND );
3657 begPos = myString.Location( "=", 1, Length() ) + 1;
3658 // is '=' in the string argument (for example, name) or not
3659 int nb1 = 0; // number of ' character at the left of =
3660 int nb2 = 0; // number of " character at the left of =
3661 for ( int i = 1; i < begPos-1; i++ ) {
3662 if ( myString.Value( i )=='\'' )
3664 else if ( myString.Value( i )=='"' )
3667 // if number of ' or " is not divisible by 2,
3668 // then get an object at the start of the command
3669 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3673 begPos += myRes.Length();
3675 myObj = GetWord( myString, begPos, true );
3676 if ( begPos != EMPTY )
3678 // check if object is complex,
3679 // so far consider case like "smesh.Method()"
3680 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3681 //if ( bracketPos==0 ) bracketPos = Length();
3682 int dotPos = begPos+myObj.Length();
3683 while ( dotPos+1 < bracketPos ) {
3684 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3689 if ( dotPos > begPos+myObj.Length() )
3690 myObj = myString.SubString( begPos, dotPos-1 );
3693 // 1st word after '=' is an object
3694 // else // no method -> no object
3700 SetBegPos( OBJECT_IND, begPos );
3706 //================================================================================
3708 * \brief Return substring of python command looking like ResVal = Obj.Method()
3709 * \retval const TCollection_AsciiString & - Method substring
3711 //================================================================================
3713 const TCollection_AsciiString & _pyCommand::GetMethod()
3715 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3718 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3719 bool forward = true;
3721 begPos = myString.Location( "(", 1, Length() ) - 1;
3725 myMeth = GetWord( myString, begPos, forward );
3726 SetBegPos( METHOD_IND, begPos );
3732 //================================================================================
3734 * \brief Returns true if there are brackets after the method
3736 //================================================================================
3738 bool _pyCommand::IsMethodCall()
3740 if ( GetMethod().IsEmpty() )
3742 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3743 return ( s[0] == '(' || s[1] == '(' );
3746 //================================================================================
3748 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3749 * \retval const TCollection_AsciiString & - Arg<index> substring
3751 //================================================================================
3753 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3755 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3759 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3761 pos = myString.Location( "(", 1, Length() );
3765 // we are at or before '(', skip it if present
3767 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3768 if ( pos > Length() )
3772 SetBegPos( ARG1_IND, 0 ); // even no '('
3773 return theEmptyString;
3777 list< TCollection_AsciiString > separatorStack( 1, ",)");
3778 bool ignoreNesting = false;
3780 while ( pos <= Length() )
3782 const char chr = myString.Value( pos );
3784 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3786 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3788 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3790 TCollection_AsciiString arg;
3791 if ( pos-1 >= prevPos ) {
3792 arg = myString.SubString( prevPos, pos-1 );
3793 arg.RightAdjust(); // remove spaces
3796 if ( !arg.IsEmpty() || chr == ',' )
3798 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3799 myArgs.Append( arg );
3805 else // end of nesting args found
3807 separatorStack.pop_back();
3808 ignoreNesting = false;
3811 else if ( !ignoreNesting )
3814 case '(' : separatorStack.push_back(")"); break;
3815 case '[' : separatorStack.push_back("]"); break;
3816 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3817 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3824 if ( myArgs.Length() < index )
3825 return theEmptyString;
3826 return myArgs( index );
3829 //================================================================================
3831 * \brief Return position where arguments begin
3833 //================================================================================
3835 int _pyCommand::GetArgBeginning() const
3837 int pos = GetBegPos( ARG1_IND );
3838 if ( pos == UNKNOWN )
3840 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3842 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3847 //================================================================================
3849 * \brief Check if char is a word part
3850 * \param c - The character to check
3851 * \retval bool - The check result
3853 //================================================================================
3855 static inline bool isWord(const char c, const bool dotIsWord)
3858 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3861 //================================================================================
3863 * \brief Looks for a word in the string and returns word's beginning
3864 * \param theString - The input string
3865 * \param theStartPos - The position to start the search, returning word's beginning
3866 * \param theForward - The search direction
3867 * \retval TCollection_AsciiString - The found word
3869 //================================================================================
3871 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3873 const bool theForward,
3874 const bool dotIsWord )
3876 int beg = theStartPos, end = theStartPos;
3877 theStartPos = EMPTY;
3878 if ( beg < 1 || beg > theString.Length() )
3879 return theEmptyString;
3881 if ( theForward ) { // search forward
3883 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3885 if ( beg > theString.Length() )
3886 return theEmptyString; // no word found
3889 char begChar = theString.Value( beg );
3890 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3891 char endChar = ( begChar == '[' ) ? ']' : begChar;
3892 // end is at the corresponding quoting mark or bracket
3893 while ( end < theString.Length() &&
3894 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3898 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3903 else { // search backward
3905 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3908 return theEmptyString; // no word found
3910 char endChar = theString.Value( end );
3911 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3912 char begChar = ( endChar == ']' ) ? '[' : endChar;
3913 // beg is at the corresponding quoting mark
3915 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3919 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3925 //cout << theString << " ---- " << beg << " - " << end << endl;
3926 return theString.SubString( beg, end );
3929 //================================================================================
3931 * \brief Returns true if the string looks like a study entry
3933 //================================================================================
3935 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3937 if ( str.Length() < 5 ) return false;
3939 int nbColons = 0, isColon;
3940 for ( int i = 1; i <= str.Length(); ++i )
3942 char c = str.Value(i);
3943 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3945 nbColons += isColon;
3947 return nbColons > 2 && str.Length()-nbColons > 2;
3950 //================================================================================
3952 * \brief Returns true if the string looks like an object ID but not like a list,
3953 * string, command etc.
3955 //================================================================================
3957 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3959 if ( str.Length() < 1 ) return false;
3961 const char* s = str.ToCString();
3963 for ( int i = 0; i < str.Length(); ++i )
3964 if ( !IsIDChar( s[i] ))
3970 //================================================================================
3972 * \brief Finds entries in a sting
3974 //================================================================================
3976 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3978 std::list< _pyID > resList;
3980 while ( ++pos <= str.Length() )
3982 if ( !isdigit( str.Value( pos ))) continue;
3983 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3986 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3987 _pyID entry = str.SubString( pos, end-1 );
3989 if ( IsStudyEntry( entry ))
3990 resList.push_back( entry );
3995 //================================================================================
3997 * \brief Look for position where not space char is
3998 * \param theString - The string
3999 * \param thePos - The position to search from and which returns result
4000 * \retval bool - false if there are only space after thePos in theString
4002 //================================================================================
4004 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4006 if ( thePos < 1 || thePos > theString.Length() )
4009 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4012 return thePos <= theString.Length();
4015 //================================================================================
4017 * \brief Modify a part of the command
4018 * \param thePartIndex - The index of the part
4019 * \param thePart - The new part string
4020 * \param theOldPart - The old part
4022 //================================================================================
4024 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4025 TCollection_AsciiString& theOldPart)
4027 int pos = GetBegPos( thePartIndex );
4028 if ( pos <= Length() && theOldPart != thePart)
4030 TCollection_AsciiString seperator;
4032 pos = GetBegPos( thePartIndex + 1 );
4033 if ( pos < 1 ) return;
4034 switch ( thePartIndex ) {
4035 case RESULT_IND: seperator = " = "; break;
4036 case OBJECT_IND: seperator = "."; break;
4037 case METHOD_IND: seperator = "()"; break;
4041 myString.Remove( pos, theOldPart.Length() );
4042 if ( !seperator.IsEmpty() )
4043 myString.Insert( pos , seperator );
4044 myString.Insert( pos, thePart );
4045 // update starting positions of the following parts
4046 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4047 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4048 if ( myBegPos( i ) > 0 )
4049 myBegPos( i ) += posDelta;
4051 theOldPart = thePart;
4055 //================================================================================
4057 * \brief Set agrument
4058 * \param index - The argument index, it counts from 1
4059 * \param theArg - The argument string
4061 //================================================================================
4063 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4066 int argInd = ARG1_IND + index - 1;
4067 int pos = GetBegPos( argInd );
4068 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4070 // find a closing parenthesis
4071 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4072 int lastArgInd = GetNbArgs();
4073 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4074 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4079 while ( pos > 0 && myString.Value( pos ) != ')' )
4082 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4086 while ( myArgs.Length() < index ) {
4087 if ( myArgs.Length() )
4088 myString.Insert( pos++, "," );
4089 myArgs.Append("None");
4090 myString.Insert( pos, myArgs.Last() );
4091 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4092 pos += myArgs.Last().Length();
4095 SetPart( argInd, theArg, myArgs( index ));
4098 //================================================================================
4100 * \brief Empty arg list
4102 //================================================================================
4104 void _pyCommand::RemoveArgs()
4106 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4107 myString.Trunc( pos );
4110 if ( myBegPos.Length() >= ARG1_IND )
4111 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4114 //================================================================================
4116 * \brief Comment a python command
4118 //================================================================================
4120 void _pyCommand::Comment()
4122 if ( IsEmpty() ) return;
4125 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4126 if ( i <= Length() )
4128 myString.Insert( i, "#" );
4129 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4131 int begPos = GetBegPos( iPart );
4132 if ( begPos != UNKNOWN && begPos != EMPTY )
4133 SetBegPos( iPart, begPos + 1 );
4138 //================================================================================
4140 * \brief Set dependent commands after this one
4142 //================================================================================
4144 bool _pyCommand::SetDependentCmdsAfter() const
4146 bool orderChanged = false;
4147 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4148 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4149 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4150 orderChanged = true;
4151 theGen->SetCommandAfter( *cmd, this );
4152 (*cmd)->SetDependentCmdsAfter();
4155 return orderChanged;
4157 //================================================================================
4159 * \brief Insert accessor method after theObjectID
4160 * \param theObjectID - id of the accessed object
4161 * \param theAcsMethod - name of the method giving access to the object
4162 * \retval bool - false if theObjectID is not found in the command string
4164 //================================================================================
4166 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4168 if ( !theAcsMethod )
4170 // start object search from the object, i.e. ignore result
4172 int beg = GetBegPos( OBJECT_IND );
4173 if ( beg < 1 || beg > Length() )
4176 while (( beg = myString.Location( theObjectID, beg, Length() )))
4178 // check that theObjectID is not just a part of a longer ID
4179 int afterEnd = beg + theObjectID.Length();
4180 Standard_Character c = myString.Value( afterEnd );
4181 if ( !IsIDChar( c ))
4183 // check if accessor method already present
4185 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4187 int oldLen = Length();
4188 myString.Insert( afterEnd, (char*) theAcsMethod );
4189 myString.Insert( afterEnd, "." );
4190 // update starting positions of the parts following the modified one
4191 int posDelta = Length() - oldLen;
4192 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4193 if ( myBegPos( i ) > afterEnd )
4194 myBegPos( i ) += posDelta;
4199 beg = afterEnd; // is a part -> next search
4204 //================================================================================
4206 * \brief Creates pyObject
4208 //================================================================================
4210 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4211 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4216 //================================================================================
4218 * \brief Set up myID and myIsPublished
4220 //================================================================================
4222 void _pyObject::setID(const _pyID& theID)
4225 myIsPublished = !theGen->IsNotPublished( GetID() );
4228 //================================================================================
4230 * \brief Clear myCreationCmd and myProcessedCmds
4232 //================================================================================
4234 void _pyObject::ClearCommands()
4239 if ( !myCreationCmd.IsNull() )
4240 myCreationCmd->Clear();
4242 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4243 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4247 //================================================================================
4249 * \brief Return method name giving access to an interaface object wrapped by python class
4250 * \retval const char* - method name
4252 //================================================================================
4254 const char* _pyObject::AccessorMethod() const
4258 //================================================================================
4260 * \brief Return ID of a father
4262 //================================================================================
4264 _pyID _pyObject::FatherID(const _pyID & childID)
4266 int colPos = childID.SearchFromEnd(':');
4268 return childID.SubString( 1, colPos-1 );
4272 //================================================================================
4274 * \brief SelfEraser erases creation command if none of it's commands invoked
4275 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4277 //================================================================================
4279 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4280 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4282 myIsPublished = true; // prevent clearing as a not published
4283 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4286 //================================================================================
4288 * \brief SelfEraser erases creation command if none of it's commands invoked
4289 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4291 //================================================================================
4293 bool _pySelfEraser::CanClear()
4295 bool toErase = false;
4296 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4299 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4300 for ( ; cmd != myArgCmds.end(); ++cmd )
4301 nbArgUses += IsAliveCmd( *cmd );
4303 toErase = ( nbArgUses < 1 );
4308 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4309 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4310 for ( ; cmd != cmds.end(); )
4311 // check of cmd emptiness is not enough as object can change
4312 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4315 cmd = cmds.erase( cmd ); // save the cmd from clearing
4317 toErase = ( nbCalls < 1 );
4322 //================================================================================
4324 * \brief Check if a command is or can be cleared
4326 //================================================================================
4328 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4330 if ( theCmd->IsEmpty() )
4333 if ( !theGen->IsToKeepAllCommands() )
4335 const _pyID& objID = theCmd->GetObject();
4336 Handle( _pyObject ) obj = theGen->FindObject( objID );
4337 if ( !obj.IsNull() )
4338 return !obj->CanClear();
4343 //================================================================================
4345 * \brief SelfEraser erases creation command if none of it's commands invoked
4346 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4348 //================================================================================
4350 void _pySelfEraser::Flush()
4354 myIsPublished = false;
4355 _pyObject::ClearCommands();
4359 //================================================================================
4361 * \brief _pySubMesh constructor
4363 //================================================================================
4365 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4366 _pyObject(theCreationCmd)
4368 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4369 if ( toKeepAgrCmds )
4370 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4373 //================================================================================
4375 * \brief Return true if a sub-mesh can be used as argument of the given method
4377 //================================================================================
4379 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4382 // // names of all methods where a sub-mesh can be used as argument
4383 // static TStringSet methods;
4384 // if ( methods.empty() ) {
4385 // const char * names[] = {
4386 // // methods of SMESH_Gen
4388 // // methods of SMESH_Group
4390 // // methods of SMESH_Measurements
4392 // // methods of SMESH_Mesh
4393 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4395 // // methods of SMESH_MeshEditor
4396 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4397 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4398 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4399 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4400 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4401 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4402 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4403 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4404 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4405 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4406 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4407 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4408 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4409 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4410 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4411 // "" }; // <- mark of end
4412 // methods.Insert( names );
4414 // return methods.Contains( theMethodName );
4417 //================================================================================
4419 * \brief count invoked commands
4421 //================================================================================
4423 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4425 _pyObject::Process(theCommand); // count calls of Process()
4428 //================================================================================
4430 * \brief Move creation command depending on invoked commands
4432 //================================================================================
4434 void _pySubMesh::Flush()
4436 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4437 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4438 else if ( !myCreator.IsNull() )
4439 // move to be just after creator
4440 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4442 // move sub-mesh usage after creation cmd
4443 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4444 for ( ; cmd != myArgCmds.end(); ++cmd )
4445 if ( !(*cmd)->IsEmpty() )
4446 GetCreationCmd()->AddDependantCmd( *cmd );
4449 //================================================================================
4451 * \brief Creates _pyGroup
4453 //================================================================================
4455 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4456 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4458 if ( !id.IsEmpty() )
4461 myCanClearCreationCmd = true;
4463 const _AString& method = theCreationCmd->GetMethod();
4464 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4466 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4468 // ----------------------------------------------------------------------
4469 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4471 _pyID geom = theCreationCmd->GetArg( 3 );
4472 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4473 // next if(){...} section is commented
4474 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4475 // theCreationCmd->SetMethod( "Group" );
4476 // theCreationCmd->RemoveArgs();
4477 // theCreationCmd->SetArg( 1, geom );
4480 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4481 _pyID type = theCreationCmd->GetArg( 1 );
4482 _pyID name = theCreationCmd->GetArg( 2 );
4483 theCreationCmd->SetMethod( "GroupOnGeom" );
4484 theCreationCmd->RemoveArgs();
4485 theCreationCmd->SetArg( 1, geom );
4486 theCreationCmd->SetArg( 2, name );
4487 theCreationCmd->SetArg( 3, type );
4490 else if ( method == "CreateGroupFromFilter" )
4492 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4493 theCreationCmd->SetMethod( "GroupOnFilter" );
4495 _pyID filterID = theCreationCmd->GetArg(3);
4496 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4497 if ( !filter.IsNull())
4499 if ( !filter->GetNewID().IsEmpty() )
4500 theCreationCmd->SetArg( 3, filter->GetNewID() );
4501 //filter->AddUser( this );
4505 else if ( method == "GetGroups" )
4507 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4511 // theCreationCmd does something else apart from creation of this group
4512 // and thus it can't be cleared if this group is removed
4513 myCanClearCreationCmd = false;
4517 //================================================================================
4519 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4522 //================================================================================
4524 bool _pyGroup::CanClear()
4529 if ( !myCanClearCreationCmd &&
4530 !myCreationCmd.IsNull() &&
4531 myCreationCmd->GetMethod() == "GetGroups" )
4533 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4534 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4535 list< _pyID >::iterator grID = idList.begin();
4536 if ( GetID() == *grID )
4538 myCanClearCreationCmd = true;
4539 list< Handle(_pyGroup ) > groups;
4540 for ( ; grID != idList.end(); ++grID )
4542 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4543 if ( group.IsNull() ) continue;
4544 groups.push_back( group );
4545 if ( group->IsInStudy() )
4546 myCanClearCreationCmd = false;
4548 // set myCanClearCreationCmd == true to all groups
4549 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4550 for ( ; group != groups.end(); ++group )
4551 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4555 return myCanClearCreationCmd;
4558 //================================================================================
4560 * \brief set myCanClearCreationCmd = true if the main action of the creation
4561 * command is discarded
4563 //================================================================================
4565 void _pyGroup::RemovedWithContents()
4567 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4568 // via a created group
4569 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4570 // myCanClearCreationCmd = true;
4573 //================================================================================
4575 * \brief To convert creation of a group by filter
4577 //================================================================================
4579 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4581 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4582 // group = mesh.CreateEmptyGroup( elemType, groupName )
4583 // aFilter.SetMesh(mesh)
4584 // nbAdd = group.AddFrom( aFilter )
4585 Handle(_pyFilter) filter;
4586 if ( theCommand->GetMethod() == "AddFrom" )
4588 _pyID idSource = theCommand->GetArg(1);
4589 // check if idSource is a filter
4590 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4591 if ( !filter.IsNull() )
4593 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4594 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4595 while ( *cmdIt != theCommand ) ++cmdIt;
4596 while ( (*cmdIt)->GetOrderNb() != 1 )
4598 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4599 if ((setMeshCmd->GetObject() == idSource ||
4600 setMeshCmd->GetObject() == filter->GetNewID() )
4602 setMeshCmd->GetMethod() == "SetMesh")
4604 setMeshCmd->Clear();
4608 // replace 3 commands by one
4609 theCommand->Clear();
4610 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4611 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4612 if ( !filter->GetNewID().IsEmpty() )
4613 idSource = filter->GetNewID();
4614 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4615 makeGroupCmd->SetArg( 1, name );
4616 makeGroupCmd->SetArg( 2, idSource );
4617 filter->AddArgCmd( makeGroupCmd );
4620 else if ( theCommand->GetMethod() == "SetFilter" )
4622 // set new name of a filter or clear the command if the same filter is set
4623 _pyID filterID = theCommand->GetArg(1);
4624 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4625 if ( !myFilter.IsNull() && filter == myFilter )
4626 theCommand->Clear();
4627 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4628 theCommand->SetArg( 1, filter->GetNewID() );
4631 else if ( theCommand->GetMethod() == "GetFilter" )
4633 // GetFilter() returns a filter with other ID, make myFilter process
4634 // calls of the returned filter
4635 if ( !myFilter.IsNull() )
4637 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4638 theCommand->Clear();
4642 // if ( !filter.IsNull() )
4643 // filter->AddUser( this );
4645 theGen->AddMeshAccessorMethod( theCommand );
4648 //================================================================================
4650 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4652 //================================================================================
4654 void _pyGroup::Flush()
4656 if ( !theGen->IsToKeepAllCommands() &&
4657 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4659 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4663 //================================================================================
4665 * \brief Constructor of _pyFilter
4667 //================================================================================
4669 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4670 :_pyObject(theCreationCmd), myNewID( newID )
4672 //myIsPublished = true; // prevent clearing as a not published
4673 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4676 //================================================================================
4678 * \brief To convert creation of a filter by criteria and
4679 * to replace an old name by a new one
4681 //================================================================================
4683 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4685 if ( theCommand->GetObject() == GetID() )
4686 _pyObject::Process(theCommand); // count commands
4688 if ( !myNewID.IsEmpty() )
4689 theCommand->SetObject( myNewID );
4691 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4692 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4693 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4694 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4695 theCommand->GetMethod() == "SetCriteria")
4697 // aFilter.SetCriteria(aCriteria) ->
4698 // aFilter = smesh.GetFilterFromCriteria(criteria)
4699 if ( myNewID.IsEmpty() )
4700 theCommand->SetResultValue( GetID() );
4702 theCommand->SetResultValue( myNewID );
4703 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4704 theCommand->SetMethod( "GetFilterFromCriteria" );
4706 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4707 GetCreationCmd()->Clear();
4708 GetCreationCmd()->GetString() = theCommand->GetString();
4709 theCommand->Clear();
4710 theCommand->AddDependantCmd( GetCreationCmd() );
4711 // why swap? -- it's needed
4712 //GetCreationCmd()->Clear();
4714 else if ( theCommand->GetMethod() == "SetMesh" )
4716 if ( myMesh == theCommand->GetArg( 1 ))
4717 theCommand->Clear();
4719 myMesh = theCommand->GetArg( 1 );
4720 theGen->AddMeshAccessorMethod( theCommand );
4724 //================================================================================
4726 * \brief Set new filter name to the creation command and to myArgCmds
4728 //================================================================================
4730 void _pyFilter::Flush()
4732 if ( myNewID.IsEmpty() ) return;
4734 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4735 for ( ; cmd != myArgCmds.end(); ++cmd )
4736 if ( !(*cmd)->IsEmpty() )
4738 _AString cmdStr = (*cmd)->GetString();
4739 _AString id = GetID();
4740 int pos = cmdStr.Search( id );
4743 cmdStr.Remove( pos, id.Length() );
4744 cmdStr.Insert( pos, myNewID );
4747 (*cmd)->GetString() = cmdStr;
4750 if ( !GetCreationCmd()->IsEmpty() )
4751 GetCreationCmd()->SetResultValue( myNewID );
4754 //================================================================================
4756 * \brief Return true if all my users can be cleared
4758 //================================================================================
4760 bool _pyObject::CanClear()
4762 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4763 for ( ; cmd != myArgCmds.end(); ++cmd )
4764 if ( !(*cmd)->IsEmpty() )
4766 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4767 if ( !obj.IsNull() && !obj->CanClear() )
4770 return ( !myIsPublished );
4773 //================================================================================
4775 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4777 //================================================================================
4779 _pyHypothesisReader::_pyHypothesisReader()
4782 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4783 LDOMParser xmlParser;
4784 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4786 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4790 INFOS( xmlParser.GetError(data) );
4793 // <algorithm type="Regular_1D"
4794 // label-id="Wire discretisation"
4797 // <algo>Regular_1D=Segment()</algo>
4798 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4800 LDOM_Document xmlDoc = xmlParser.getDocument();
4801 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4802 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4804 LDOM_Node algoNode = algoNodeList.item( i );
4805 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4806 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4807 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4809 _AString text, algoType, method, arg;
4810 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4812 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4813 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4814 text = textNode.getNodeValue();
4815 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4816 algoType = algoCmd->GetResultValue();
4817 method = algoCmd->GetMethod();
4818 arg = algoCmd->GetArg(1);
4819 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4821 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4822 algo->SetConvMethodAndType( method, algoType );
4823 if ( !arg.IsEmpty() )
4824 algo->setCreationArg( 1, arg );
4826 myType2Hyp[ algoType ] = algo;
4830 if ( algoType.IsEmpty() ) continue;
4832 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4834 Handle( _pyHypothesis ) hyp;
4835 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4837 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4838 LDOM_Node textNode = pyHypoNode.getFirstChild();
4839 text = textNode.getNodeValue();
4840 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4841 hypType = hypoCmd->GetResultValue();
4842 method = hypoCmd->GetMethod();
4843 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4845 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4846 if ( type2hyp == myType2Hyp.end() )
4847 hyp = new _pyHypothesis( hypoCmd );
4849 hyp = type2hyp->second;
4850 hyp->SetConvMethodAndType( method, algoType );
4851 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4853 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4854 _AString argMethod = argCmd.GetMethod();
4855 _AString argNbText = argCmd.GetArg( 1 );
4856 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4857 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4859 hyp->AddArgMethod( argMethod,
4860 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4862 myType2Hyp[ hypType ] = hyp;
4866 // <hypothesis type="BLSURF_Parameters"
4870 // <accumulative-methods>
4871 // SetEnforcedVertex,
4872 // SetEnforcedVertexNamed
4873 // </accumulative-methods>
4877 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4878 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4880 LDOM_Node hypNode = hypNodeList.item( i );
4881 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4882 _AString hypType = hypElem.getAttribute("type");
4883 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4884 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4886 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4887 if ( type2hyp == myType2Hyp.end() ) continue;
4889 LDOM_Node methNode = methNodeList.item( 0 );
4890 LDOM_Node textNode = methNode.getFirstChild();
4891 _AString text = textNode.getNodeValue();
4895 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4896 pos += method.Length();
4897 type2hyp->second->AddAccumulativeMethod( method );
4899 while ( !method.IsEmpty() );
4902 } // loop on xmlPaths
4905 //================================================================================
4907 * \brief Returns a new hypothesis initialized according to the read information
4909 //================================================================================
4911 Handle(_pyHypothesis)
4912 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4913 const Handle(_pyCommand)& creationCmd) const
4915 Handle(_pyHypothesis) resHyp, sampleHyp;
4917 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4918 if ( type2hyp != myType2Hyp.end() )
4919 sampleHyp = type2hyp->second;
4921 if ( sampleHyp.IsNull() )
4923 resHyp = new _pyHypothesis(creationCmd);
4927 if ( sampleHyp->IsAlgo() )
4928 resHyp = new _pyAlgorithm( creationCmd );
4930 resHyp = new _pyHypothesis(creationCmd);
4931 resHyp->Assign( sampleHyp, _pyID() );
4936 //================================================================================
4938 * \brief Adds an object ID to some family of IDs with a common prefix
4939 * \param [in] str - the object ID
4940 * \return bool - \c false if \a str does not have the same prefix as \a this family
4941 * (for internal usage)
4943 //================================================================================
4945 bool _pyStringFamily::Add( const char* str )
4947 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4948 return false; // expected prefix is missing
4950 str += _prefix.Length(); // skip _prefix
4952 // try to add to some of child falimies
4953 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4954 for ( ; itSub != _subFams.end(); ++itSub )
4955 if ( itSub->Add( str ))
4958 // no suitable family found - add str to _strings or create a new child family
4960 // look for a proper place within sorted _strings
4961 std::list< _AString >::iterator itStr = _strings.begin();
4962 while ( itStr != _strings.end() && itStr->IsLess( str ))
4964 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4965 return true; // same ID already kept
4967 const int minPrefixSize = 4;
4969 // count "smaller" strings with the same prefix
4970 std::list< _AString >::iterator itLess = itStr; --itLess;
4972 for ( ; itLess != _strings.end(); --itLess )
4973 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4978 // count "greater" strings with the same prefix
4979 std::list< _AString >::iterator itMore = itStr;
4981 for ( ; itMore != _strings.end(); ++itMore )
4982 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4987 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4989 // look for a maximal prefix length
4990 // int lessPrefSize = 3, morePrefSize = 3;
4991 // if ( nbLess > 0 )
4992 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
4994 // if ( nbMore > 0 )
4995 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
4997 // int prefixSize = 3;
4998 // if ( nbLess == 0 )
4999 // prefixSize = morePrefSize;
5000 // else if ( nbMore == 0 )
5001 // prefixSize = lessPrefSize;
5003 // prefixSize = Min( lessPrefSize, morePrefSize );
5004 int prefixSize = minPrefixSize;
5005 _AString newPrefix ( str, prefixSize );
5007 // look for a proper place within _subFams sorted by _prefix
5008 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5009 if ( !itSub->_prefix.IsLess( newPrefix ))
5012 // add the new _pyStringFamily
5013 itSub = _subFams.insert( itSub, _pyStringFamily());
5014 _pyStringFamily& newSubFam = *itSub;
5015 newSubFam._prefix = newPrefix;
5017 // pass this->_strings to newSubFam._strings
5018 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5019 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5020 newSubFam._strings.push_back( str + prefixSize );
5021 for ( ; nbMore > 0; --nbMore, ++itStr )
5022 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5024 _strings.erase( itLess, ++itMore );
5026 else // to few string to make a family fot them
5028 _strings.insert( itStr, str );
5033 //================================================================================
5035 * \brief Finds an object ID in the command
5036 * \param [in] longStr - the command string
5037 * \param [out] subStr - the found object ID
5038 * \return bool - \c true if the object ID found
5040 //================================================================================
5042 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5044 const _AString& longStr = cmd->GetString();
5045 const char* s = longStr.ToCString();
5048 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5049 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5050 if ( argBeg < 4 || argBeg > longStr.Length() )
5052 for ( ; itSub != _subFams.end(); ++itSub )
5055 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5056 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5058 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5059 from = pos + len + itSub->_prefix.Length();
5064 from += itSub->_prefix.Length();
5067 // look among _strings
5068 std::list< _AString >::iterator itStr = _strings.begin();
5069 for ( ; itStr != _strings.end(); ++itStr )
5070 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5071 // check that object ID does not continue after len
5072 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5074 subStr.push_back( *itStr );
5080 //================================================================================
5082 * \brief Return remainder length of the object ID after my _prefix
5083 * \param [in] str - remainder of the command after my _prefix
5084 * \return int - length of the object ID or -1 if not found
5086 //================================================================================
5088 int _pyStringFamily::isIn( const char* str )
5090 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5092 for ( ; itSub != _subFams.end(); ++itSub )
5094 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5097 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5098 return itSub->_prefix.Length() + len;
5103 if ( !_strings.empty() )
5105 std::list< _AString >::iterator itStr = _strings.begin();
5106 bool firstEmpty = itStr->IsEmpty();
5109 for ( ; itStr != _strings.end(); ++itStr )
5111 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5114 len = itStr->Length();
5123 // check that object ID does not continue after len
5124 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5131 //================================================================================
5135 //================================================================================
5137 void _pyStringFamily::Print( int level )
5139 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5140 std::list< _AString >::iterator itStr = _strings.begin();
5141 for ( ; itStr != _strings.end(); ++itStr )
5142 cout << *itStr << " | ";
5144 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5145 for ( ; itSub != _subFams.end(); ++itSub )
5146 itSub->Print( level + 1 );
5148 cout << string( 70, '-' ) << endl;