1 // Copyright (C) 2007-2011 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.
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 // SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
24 // File : SMESH_2smeshpy.cxx
25 // Created : Fri Nov 18 13:20:10 2005
26 // Author : Edward AGAPOV (eap)
28 #include "SMESH_2smeshpy.hxx"
30 #include "utilities.h"
31 #include "SMESH_PythonDump.hxx"
32 #include "SMESH_NoteBook.hxx"
33 #include "SMESH_Filter_i.hxx"
35 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
36 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
38 #include "SMESH_Gen_i.hxx"
39 /* SALOME headers that include CORBA headers that include windows.h
40 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
41 * that declare methods named GetObject - to apply the same rules of GetObject renaming
42 * and thus to avoid mess with GetObject symbol on Windows */
44 #include <LDOMParser.hxx>
53 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
54 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
57 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
65 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
86 using SMESH::TPythonDump;
89 * \brief Container of commands into which the initial script is split.
90 * It also contains data coresponding to SMESH_Gen contents
92 static Handle(_pyGen) theGen;
94 static TCollection_AsciiString theEmptyString;
96 //#define DUMP_CONVERSION
98 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
99 #undef DUMP_CONVERSION
105 //================================================================================
107 * \brief Set of TCollection_AsciiString initialized by C array of C strings
109 //================================================================================
111 struct TStringSet: public set<TCollection_AsciiString>
114 * \brief Filling. The last string must be ""
116 void Insert(const char* names[]) {
117 for ( int i = 0; names[i][0] ; ++i )
118 insert( (char*) names[i] );
121 * \brief Check if a string is in
123 bool Contains(const TCollection_AsciiString& name ) {
124 return find( name ) != end();
128 //================================================================================
130 * \brief Returns a mesh by object
132 //================================================================================
134 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
138 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
139 return Handle(_pyMesh)::DownCast( obj );
140 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
141 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
142 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
143 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
145 return Handle(_pyMesh)();
148 //================================================================================
150 * \brief Check if objects used as args have been created by previous commands
152 //================================================================================
154 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
156 for ( int iArg = cmd->GetNbArgs(); iArg; --iArg )
158 const _pyID& arg = cmd->GetArg( iArg );
159 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
161 list< _pyID > idList = cmd->GetStudyEntries( arg );
162 list< _pyID >::iterator id = idList.begin();
163 for ( ; id != idList.end(); ++id )
164 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
167 cmd->GetString() += " ### " ;
168 cmd->GetString() += *id + " has not been yet created";
172 const _pyID& obj = cmd->GetObject();
173 if ( !obj.IsEmpty() && cmd->IsStudyEntry( obj ) && !presentObjects.count( obj ))
176 cmd->GetString() += " ### not created object" ;
178 const _pyID& result = cmd->GetResultValue();
179 if ( result.IsEmpty() || result.Value( 1 ) == '"' || result.Value( 1 ) == '\'' )
181 list< _pyID > idList = cmd->GetStudyEntries( result );
182 list< _pyID >::iterator id = idList.begin();
183 for ( ; id != idList.end(); ++id )
184 presentObjects.insert( *id );
187 //================================================================================
189 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
191 //================================================================================
193 void fixFunctorType( TCollection_AsciiString& Type,
194 TCollection_AsciiString& Compare,
195 TCollection_AsciiString& UnaryOp,
196 TCollection_AsciiString& BinaryOp )
198 // The problem is that dumps of old studies created using filters becomes invalid
199 // when new items are inserted in the enum SMESH::FunctorType since values
200 // of this enum are dumped as integer values.
201 // This function corrects enum values of old studies given as args (Type,Compare,...)
202 // We can find out how to correct them by value of BinaryOp which can have only two
203 // values: FT_Undefined or FT_LogicalNOT.
204 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
205 // where PythonDump appeared
206 // v 3.0.0: FT_Undefined == 25
207 // v 3.1.0: FT_Undefined == 26, new items:
209 // v 4.1.2: FT_Undefined == 27, new items:
210 // - FT_BelongToGenSurface = 17
211 // v 5.1.1: FT_Undefined == 33, new items:
212 // - FT_FreeNodes = 10
213 // - FT_FreeFaces = 11
214 // - FT_LinearOrQuadratic = 23
215 // - FT_GroupColor = 24
216 // - FT_ElemGeomType = 25
217 // v 5.1.5: FT_Undefined == 34, new items:
218 // - FT_CoplanarFaces = 26
219 // v 6.2.0: FT_Undefined == 39, new items:
220 // - FT_MaxElementLength2D = 8
221 // - FT_MaxElementLength3D = 9
222 // - FT_BareBorderVolume = 25
223 // - FT_BareBorderFace = 26
224 // - FT_OverConstrainedVolume = 27
225 // - FT_OverConstrainedFace = 28
226 // v 6.5.0: FT_Undefined == 43, new items:
227 // - FT_EqualNodes = 14
228 // - FT_EqualEdges = 15
229 // - FT_EqualFaces = 16
230 // - FT_EqualVolumes = 17
232 typedef map< int, vector< int > > TUndef2newItems;
233 static TUndef2newItems undef2newItems;
234 if ( undef2newItems.empty() )
236 undef2newItems[ 26 ].push_back( 7 );
237 undef2newItems[ 27 ].push_back( 17 );
238 { int items[] = { 10, 11, 23, 24, 25 };
239 undef2newItems[ 33 ].assign( items, items+5 ); }
240 undef2newItems[ 34 ].push_back( 26 );
241 { int items[] = { 8, 9, 25, 26, 27, 28 };
242 undef2newItems[ 39 ].assign( items, items+6 ); }
243 { int items[] = { 14, 15, 16, 17 };
244 undef2newItems[ 43 ].assign( items, items+4 ); }
247 int iType = Type.IntegerValue();
248 int iCompare = Compare.IntegerValue();
249 int iUnaryOp = UnaryOp.IntegerValue();
250 int iBinaryOp = BinaryOp.IntegerValue();
252 // find out integer value of FT_Undefined at the moment of dump
253 int oldUndefined = iBinaryOp;
254 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
257 // apply history to args
258 TUndef2newItems::const_iterator undef_items =
259 undef2newItems.upper_bound( oldUndefined );
260 if ( undef_items != undef2newItems.end() )
262 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
263 for ( ; undef_items != undef2newItems.end(); ++undef_items )
265 const vector< int > & addedItems = undef_items->second;
266 for ( size_t i = 0; i < addedItems.size(); ++i )
267 for ( int iArg = 0; iArg < 4; ++iArg )
269 int& arg = *pArg[iArg];
270 if ( arg >= addedItems[i] )
274 Type = TCollection_AsciiString( iType );
275 Compare = TCollection_AsciiString( iCompare );
276 UnaryOp = TCollection_AsciiString( iUnaryOp );
277 BinaryOp = TCollection_AsciiString( iBinaryOp );
282 //================================================================================
284 * \brief Convert python script using commands of smesh.py
285 * \param theScript - Input script
286 * \retval TCollection_AsciiString - Convertion result
287 * \param theToKeepAllCommands - to keep all commands or
288 * to exclude commands relating to objects removed from study
290 * Class SMESH_2smeshpy declared in SMESH_PythonDump.hxx
292 //================================================================================
294 TCollection_AsciiString
295 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
296 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
297 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
298 SALOMEDS::Study_ptr& theStudy,
299 const bool theToKeepAllCommands)
301 theGen = new _pyGen( theEntry2AccessorMethod, theObjectNames, theStudy, theToKeepAllCommands );
303 // split theScript into separate commands
305 SMESH_NoteBook * aNoteBook = new SMESH_NoteBook();
307 int from = 1, end = theScript.Length(), to;
308 while ( from < end && ( to = theScript.Location( "\n", from, end )))
311 // cut out and store a command
312 aNoteBook->AddCommand( theScript.SubString( from, to - 1 ));
316 aNoteBook->ReplaceVariables();
318 TCollection_AsciiString aNoteScript = aNoteBook->GetResultScript();
322 // split theScript into separate commands
323 from = 1, end = aNoteScript.Length();
324 while ( from < end && ( to = aNoteScript.Location( "\n", from, end )))
327 // cut out and store a command
328 theGen->AddCommand( aNoteScript.SubString( from, to - 1 ));
334 #ifdef DUMP_CONVERSION
335 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
338 // clean commmands of removed objects depending on myIsPublished flag
339 theGen->ClearCommands();
341 // reorder commands after conversion
342 list< Handle(_pyCommand) >::iterator cmd;
345 orderChanges = false;
346 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
347 if ( (*cmd)->SetDependentCmdsAfter() )
349 } while ( orderChanges );
351 // concat commands back into a script
352 TCollection_AsciiString aScript, aPrevCmd;
353 set<_pyID> createdObjects;
354 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
356 #ifdef DUMP_CONVERSION
357 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
359 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
360 CheckObjectPresence( *cmd, createdObjects );
361 aPrevCmd = (*cmd)->GetString();
374 //================================================================================
376 * \brief _pyGen constructor
378 //================================================================================
380 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
381 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
382 SALOMEDS::Study_ptr& theStudy,
383 const bool theToKeepAllCommands)
384 : _pyObject( new _pyCommand( "", 0 )),
386 myID2AccessorMethod( theEntry2AccessorMethod ),
387 myObjectNames( theObjectNames ),
389 myToKeepAllCommands( theToKeepAllCommands ),
390 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
391 myGeomIDNb(0), myGeomIDIndex(-1)
393 // make that GetID() to return TPythonDump::SMESHGenName()
394 GetCreationCmd()->Clear();
395 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
396 GetCreationCmd()->GetString() += "=";
398 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
399 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
403 SALOMEDS::SComponent_var geomComp = theStudy->FindComponent("GEOM");
404 if ( geomComp->_is_nil() ) return;
405 CORBA::String_var entry = geomComp->GetID();
408 // find a SMESH entry
410 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
411 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
412 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
415 // find 1st difference between smeshID and geomID
416 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
417 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
418 if ( geomID.Value( i ) != smeshID.Value( i ))
420 myGeomIDNb = geomID.Value( i );
426 //================================================================================
428 * \brief name of SMESH_Gen in smesh.py
430 //================================================================================
432 const char* _pyGen::AccessorMethod() const
434 return SMESH_2smeshpy::GenName();
437 //================================================================================
439 * \brief Convert a command using a specific converter
440 * \param theCommand - the command to convert
442 //================================================================================
444 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
446 // store theCommand in the sequence
447 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
449 Handle(_pyCommand) aCommand = myCommands.back();
450 #ifdef DUMP_CONVERSION
451 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
454 const _pyID& objID = aCommand->GetObject();
456 if ( objID.IsEmpty() )
459 // Find an object to process theCommand
462 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
464 this->Process( aCommand );
468 // SMESH_Mesh method?
469 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
470 if ( id_mesh != myMeshes.end() )
472 //id_mesh->second->AddProcessedCmd( aCommand );
474 // check for mesh editor object
475 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
476 _pyID editorID = aCommand->GetResultValue();
477 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
478 myMeshEditors.insert( make_pair( editorID, editor ));
481 // check for SubMesh objects
482 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
483 _pyID subMeshID = aCommand->GetResultValue();
484 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
485 myObjects.insert( make_pair( subMeshID, subMesh ));
488 id_mesh->second->Process( aCommand );
489 id_mesh->second->AddProcessedCmd( aCommand );
493 // SMESH_MeshEditor method?
494 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
495 if ( id_editor != myMeshEditors.end() )
497 const TCollection_AsciiString& method = aCommand->GetMethod();
499 // some commands of SMESH_MeshEditor create meshes and groups
500 _pyID meshID, groups;
501 if ( method.Search("MakeMesh") != -1 )
502 meshID = aCommand->GetResultValue();
503 else if ( method == "MakeBoundaryMesh")
504 meshID = aCommand->GetResultValue(1);
505 else if ( method == "MakeBoundaryElements")
506 meshID = aCommand->GetResultValue(2);
508 if ( method.Search("MakeGroups") != -1 ||
509 method == "ExtrusionAlongPathX" ||
510 method == "ExtrusionAlongPathObjX" ||
511 method == "DoubleNodeGroupNew" ||
512 method == "DoubleNodeGroupsNew" ||
513 method == "DoubleNodeElemGroupNew" ||
514 method == "DoubleNodeElemGroupsNew" )
515 groups = aCommand->GetResultValue();
516 else if ( method == "MakeBoundaryMesh" )
517 groups = aCommand->GetResultValue(2);
518 else if ( method == "MakeBoundaryElements")
519 groups = aCommand->GetResultValue(3);
521 id_editor->second->Process( aCommand );
522 id_editor->second->AddProcessedCmd( aCommand );
524 if ( !meshID.IsEmpty() &&
525 !myMeshes.count( meshID ) &&
526 aCommand->IsStudyEntry( meshID ))
528 TCollection_AsciiString processedCommand = aCommand->GetString();
529 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
530 myMeshes.insert( make_pair( meshID, mesh ));
532 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
534 if ( !groups.IsEmpty() )
536 if ( !aCommand->IsStudyEntry( meshID ))
537 meshID = id_editor->second->GetMesh();
538 Handle(_pyMesh) mesh = myMeshes[ meshID ];
540 list< _pyID > idList = aCommand->GetStudyEntries( groups );
541 list< _pyID >::iterator grID = idList.begin();
542 for ( ; grID != idList.end(); ++grID )
543 if ( !myObjects.count( *grID ))
545 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
547 if ( !mesh.IsNull() ) mesh->AddGroup( group );
551 } // SMESH_MeshEditor methods
553 // SMESH_Hypothesis method?
554 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
555 for ( ; hyp != myHypos.end(); ++hyp )
556 if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
557 (*hyp)->Process( aCommand );
558 (*hyp)->AddProcessedCmd( aCommand );
562 // aFilterManager.CreateFilter() ?
563 if ( aCommand->GetMethod() == "CreateFilter" )
565 // Set a more human readable name to a filter
566 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
567 _pyID newID, filterID = aCommand->GetResultValue();
568 int pos = filterID.Search( "0x" );
570 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
572 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
576 // other object method?
577 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
578 if ( id_obj != myObjects.end() ) {
579 id_obj->second->Process( aCommand );
580 id_obj->second->AddProcessedCmd( aCommand );
584 // Add access to a wrapped mesh
585 AddMeshAccessorMethod( aCommand );
587 // Add access to a wrapped algorithm
588 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
590 // PAL12227. PythonDump was not updated at proper time; result is
591 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
592 // TypeError: __init__() takes exactly 11 arguments (10 given)
593 const char wrongCommand[] = "SMESH.Filter.Criterion(";
594 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
596 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
597 // there must be 10 arguments, 5-th arg ThresholdID is missing,
598 const int wrongNbArgs = 9, missingArg = 5;
599 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
601 for ( int i = wrongNbArgs; i > missingArg; --i )
602 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
603 tmpCmd.SetArg( missingArg, "''");
604 aCommand->GetString().Trunc( beg - 1 );
605 aCommand->GetString() += tmpCmd.GetString();
608 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
610 // instead of "SMESH.Filter.Criterion(
611 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
612 // 1 2 3 4 5 6 7 8 9 10
613 // in order to avoid the problem of type mismatch of long and FunctorType
614 const TCollection_AsciiString
615 SMESH("SMESH."), dfltFunctor = "SMESH.FT_Undefined", dftlTol = "1e-07", dftlPreci = "-1";
616 TCollection_AsciiString
617 Type = aCommand->GetArg(1), // long
618 Compare = aCommand->GetArg(2), // long
619 Threshold = aCommand->GetArg(3), // double
620 ThresholdStr = aCommand->GetArg(4), // string
621 ThresholdID = aCommand->GetArg(5), // string
622 UnaryOp = aCommand->GetArg(6), // long
623 BinaryOp = aCommand->GetArg(7), // long
624 Tolerance = aCommand->GetArg(8), // double
625 TypeOfElement = aCommand->GetArg(9), // ElementType
626 Precision = aCommand->GetArg(10); // long
627 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
628 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
629 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
630 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
631 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
633 aCommand->RemoveArgs();
634 aCommand->SetObject( SMESH_2smeshpy::GenName() );
635 aCommand->SetMethod( "GetCriterion" );
637 aCommand->SetArg( 1, TypeOfElement );
638 aCommand->SetArg( 2, Type );
639 aCommand->SetArg( 3, Compare );
641 if ( Type == "SMESH.FT_ElemGeomType" && Threshold.IsIntegerValue() )
643 // set SMESH.GeometryType instead of a numerical Threshold
644 const char* types[SMESH::Geom_POLYHEDRA+1] = {
645 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
646 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
649 int iGeom = Threshold.IntegerValue();
650 if ( -1 < iGeom && iGeom < SMESH::Geom_POLYHEDRA+1 )
651 Threshold = SMESH + types[ iGeom ];
653 if ( ThresholdID.Length() != 2 && ThresholdStr.Length() != 2) // not '' or ""
654 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
655 else if ( ThresholdStr.Length() != 2 )
656 aCommand->SetArg( 4, ThresholdStr );
657 else if ( ThresholdID.Length() != 2 )
658 aCommand->SetArg( 4, ThresholdID );
660 aCommand->SetArg( 4, Threshold );
661 // find the last not default arg
663 if ( Tolerance == dftlTol ) {
665 if ( BinaryOp == dfltFunctor ) {
667 if ( UnaryOp == dfltFunctor )
671 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
672 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
673 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
674 if ( Precision != dftlPreci )
676 TCollection_AsciiString crit = aCommand->GetResultValue();
677 aCommand->GetString() += "; ";
678 aCommand->GetString() += crit + ".Precision = " + Precision;
684 //================================================================================
686 * \brief Convert the command or remember it for later conversion
687 * \param theCommand - The python command calling a method of SMESH_Gen
689 //================================================================================
691 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
693 // there are methods to convert:
694 // CreateMesh( shape )
695 // Concatenate( [mesh1, ...], ... )
696 // CreateHypothesis( theHypType, theLibName )
697 // Compute( mesh, geom )
698 // Evaluate( mesh, geom )
700 TCollection_AsciiString method = theCommand->GetMethod();
702 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
704 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
705 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
708 if ( method == "CreateMeshesFromUNV" ||
709 method == "CreateMeshesFromSTL" ||
710 method == "CreateMeshesFromCGNS" ||
711 method == "CopyMesh" )
713 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
714 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
717 if( method == "CreateMeshesFromMED" || method == "CreateMeshesFromSAUV")
719 for(int ind = 0;ind<theCommand->GetNbResultValues();ind++)
721 const _pyID& meshID = theCommand->GetResultValue(ind+1);
722 if ( !theCommand->IsStudyEntry( meshID ) ) continue;
723 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind+1));
724 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
728 // CreateHypothesis()
729 if ( method == "CreateHypothesis" )
731 // issue 199929, remove standard library name (default parameter)
732 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
733 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
734 // keep first argument
735 TCollection_AsciiString arg = theCommand->GetArg( 1 );
736 theCommand->RemoveArgs();
737 theCommand->SetArg( 1, arg );
740 myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
744 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
745 if ( method == "Compute" )
747 const _pyID& meshID = theCommand->GetArg( 1 );
748 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
749 if ( id_mesh != myMeshes.end() ) {
750 theCommand->SetObject( meshID );
751 theCommand->RemoveArgs();
752 id_mesh->second->Process( theCommand );
753 id_mesh->second->AddProcessedCmd( theCommand );
758 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
759 if ( method == "Evaluate" )
761 const _pyID& meshID = theCommand->GetArg( 1 );
762 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
763 if ( id_mesh != myMeshes.end() ) {
764 theCommand->SetObject( meshID );
765 _pyID geom = theCommand->GetArg( 2 );
766 theCommand->RemoveArgs();
767 theCommand->SetArg( 1, geom );
768 id_mesh->second->AddProcessedCmd( theCommand );
773 // objects erasing creation command if no more it's commands invoked:
774 // SMESH_Pattern, FilterManager
775 if ( method == "GetPattern" ||
776 method == "CreateFilterManager" ||
777 method == "CreateMeasurements" ) {
778 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
779 if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
780 theCommand->Clear(); // already created
782 // Concatenate( [mesh1, ...], ... )
783 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
785 if ( method == "ConcatenateWithGroups" ) {
786 theCommand->SetMethod( "Concatenate" );
787 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
789 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
790 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
791 AddMeshAccessorMethod( theCommand );
793 else if ( method == "SetName" ) // SetName(obj,name)
795 // store theCommand as one of object commands to erase it along with the object
796 const _pyID& objID = theCommand->GetArg( 1 );
797 Handle(_pyObject) obj = FindObject( objID );
799 obj->AddProcessedCmd( theCommand );
802 // Replace name of SMESH_Gen
804 // names of SMESH_Gen methods fully equal to methods defined in smesh.py
805 static TStringSet smeshpyMethods;
806 if ( smeshpyMethods.empty() ) {
807 const char * names[] =
808 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
809 "GetPattern","GetSubShapesId",
810 "" }; // <- mark of array end
811 smeshpyMethods.Insert( names );
813 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
814 // smeshgen.Method() --> smesh.Method()
815 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
817 // smeshgen.Method() --> smesh.smesh.Method()
818 theCommand->SetObject( SMESH_2smeshpy::GenName() );
821 //================================================================================
823 * \brief Convert the remembered commands
825 //================================================================================
829 // create an empty command
830 myLastCommand = new _pyCommand();
832 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
833 map< _pyID, Handle(_pyObject) >::iterator id_obj;
834 list< Handle(_pyHypothesis) >::iterator hyp;
836 if ( IsToKeepAllCommands() ) // historical dump
838 // set myIsPublished = true to all objects
839 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
840 id_mesh->second->SetRemovedFromStudy( false );
841 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
842 (*hyp)->SetRemovedFromStudy( false );
843 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
844 id_obj->second->SetRemovedFromStudy( false );
848 // let hypotheses find referred objects in order to prevent clearing
849 // not published referred hyps (it's needed for hyps like "LayerDistribution")
850 list< Handle(_pyMesh) > fatherMeshes;
851 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
852 if ( !hyp->IsNull() )
853 (*hyp)->GetReferredMeshesAndGeom( fatherMeshes );
855 // set myIsPublished = false to all objects depending on
856 // meshes built on a removed geometry
857 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
858 if ( id_mesh->second->IsNotGeomPublished() )
859 id_mesh->second->SetRemovedFromStudy( true );
862 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
863 if ( ! id_mesh->second.IsNull() )
864 id_mesh->second->Flush();
867 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
868 if ( !hyp->IsNull() ) {
870 // smeshgen.CreateHypothesis() --> smesh.smesh.CreateHypothesis()
871 if ( !(*hyp)->IsWrapped() )
872 (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
875 // Flush other objects
876 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
877 if ( ! id_obj->second.IsNull() )
878 id_obj->second->Flush();
880 myLastCommand->SetOrderNb( ++myNbCommands );
881 myCommands.push_back( myLastCommand );
884 //================================================================================
886 * \brief Clean commmands of removed objects depending on myIsPublished flag
888 //================================================================================
890 void _pyGen::ClearCommands()
892 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
893 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
894 id_mesh->second->ClearCommands();
896 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
897 for ( ; hyp != myHypos.end(); ++hyp )
898 if ( !hyp->IsNull() )
899 (*hyp)->ClearCommands();
901 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
902 for ( ; id_obj != myObjects.end(); ++id_obj )
903 id_obj->second->ClearCommands();
906 //================================================================================
908 * \brief Release mutual handles of objects
910 //================================================================================
914 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
915 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
916 id_mesh->second->Free();
919 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
920 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
921 id_ed->second->Free();
922 myMeshEditors.clear();
924 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
925 for ( ; id_obj != myObjects.end(); ++id_obj )
926 id_obj->second->Free();
929 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
930 for ( ; hyp != myHypos.end(); ++hyp )
931 if ( !hyp->IsNull() )
935 myFile2ExportedMesh.clear();
938 //================================================================================
940 * \brief Add access method to mesh that is an argument
941 * \param theCmd - command to add access method
942 * \retval bool - true if added
944 //================================================================================
946 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
949 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
950 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
951 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
957 //================================================================================
959 * \brief Add access method to algo that is an object or an argument
960 * \param theCmd - command to add access method
961 * \retval bool - true if added
963 //================================================================================
965 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
968 list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
969 for ( ; hyp != myHypos.end(); ++hyp ) {
970 if ( (*hyp)->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
971 theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
977 //================================================================================
979 * \brief Find hypothesis by ID (entry)
980 * \param theHypID - The hypothesis ID
981 * \retval Handle(_pyHypothesis) - The found hypothesis
983 //================================================================================
985 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
987 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
988 for ( ; hyp != myHypos.end(); ++hyp )
989 if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
991 return Handle(_pyHypothesis)();
994 //================================================================================
996 * \brief Find algorithm the created algorithm
997 * \param theGeom - The shape ID the algorithm was created on
998 * \param theMesh - The mesh ID that created the algorithm
999 * \param dim - The algo dimension
1000 * \retval Handle(_pyHypothesis) - The found algo
1002 //================================================================================
1004 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1005 const Handle(_pyHypothesis)& theHypothesis )
1007 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1008 for ( ; hyp != myHypos.end(); ++hyp )
1009 if ( !hyp->IsNull() &&
1011 theHypothesis->CanBeCreatedBy( (*hyp)->GetAlgoType() ) &&
1012 (*hyp)->GetGeom() == theGeom &&
1013 (*hyp)->GetMesh() == theMesh )
1018 //================================================================================
1020 * \brief Find subMesh by ID (entry)
1021 * \param theSubMeshID - The subMesh ID
1022 * \retval Handle(_pySubMesh) - The found subMesh
1024 //================================================================================
1026 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1028 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1029 if ( id_subMesh != myObjects.end() )
1030 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1031 return Handle(_pySubMesh)();
1035 //================================================================================
1037 * \brief Change order of commands in the script
1038 * \param theCmd1 - One command
1039 * \param theCmd2 - Another command
1041 //================================================================================
1043 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1045 list< Handle(_pyCommand) >::iterator pos1, pos2;
1046 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1047 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1048 myCommands.insert( pos1, theCmd2 );
1049 myCommands.insert( pos2, theCmd1 );
1050 myCommands.erase( pos1 );
1051 myCommands.erase( pos2 );
1053 int nb1 = theCmd1->GetOrderNb();
1054 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1055 theCmd2->SetOrderNb( nb1 );
1056 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1057 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1060 //================================================================================
1062 * \brief Set one command after the other
1063 * \param theCmd - Command to move
1064 * \param theAfterCmd - Command ater which to insert the first one
1066 //================================================================================
1068 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1070 setNeighbourCommand( theCmd, theAfterCmd, true );
1073 //================================================================================
1075 * \brief Set one command before the other
1076 * \param theCmd - Command to move
1077 * \param theBeforeCmd - Command before which to insert the first one
1079 //================================================================================
1081 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1083 setNeighbourCommand( theCmd, theBeforeCmd, false );
1086 //================================================================================
1088 * \brief Set one command before or after the other
1089 * \param theCmd - Command to move
1090 * \param theOtherCmd - Command ater or before which to insert the first one
1092 //================================================================================
1094 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1095 Handle(_pyCommand)& theOtherCmd,
1096 const bool theIsAfter )
1098 list< Handle(_pyCommand) >::iterator pos;
1099 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1100 myCommands.erase( pos );
1101 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1102 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1105 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1106 (*pos)->SetOrderNb( i++ );
1109 //================================================================================
1111 * \brief Set command be last in list of commands
1112 * \param theCmd - Command to be last
1114 //================================================================================
1116 Handle(_pyCommand)& _pyGen::GetLastCommand()
1118 return myLastCommand;
1121 //================================================================================
1123 * \brief Set method to access to object wrapped with python class
1124 * \param theID - The wrapped object entry
1125 * \param theMethod - The accessor method
1127 //================================================================================
1129 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1131 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1134 //================================================================================
1136 * \brief Generated new ID for object and assign with existing name
1137 * \param theID - ID of existing object
1139 //================================================================================
1141 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1146 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1148 while ( myObjectNames.IsBound( aNewID ) );
1150 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1151 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1152 : _pyID( "A" ) + aNewID );
1156 //================================================================================
1158 * \brief Stores theObj in myObjects
1160 //================================================================================
1162 void _pyGen::AddObject( Handle(_pyObject)& theObj )
1164 if ( theObj.IsNull() ) return;
1166 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1167 myMeshes.insert( make_pair( theObj->GetID(), Handle(_pyMesh)::DownCast( theObj )));
1169 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1170 myMeshEditors.insert( make_pair( theObj->GetID(), Handle(_pyMeshEditor)::DownCast( theObj )));
1173 myObjects.insert( make_pair( theObj->GetID(), theObj ));
1176 //================================================================================
1178 * \brief Finds a _pyObject by ID
1180 //================================================================================
1182 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1185 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1186 if ( id_obj != myObjects.end() )
1187 return id_obj->second;
1190 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1191 if ( id_obj != myMeshes.end() )
1192 return id_obj->second;
1195 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1196 // if ( id_obj != myMeshEditors.end() )
1197 // return id_obj->second;
1199 return Handle(_pyObject)();
1202 //================================================================================
1204 * \brief Check if a study entry is under GEOM component
1206 //================================================================================
1208 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1212 return ( myGeomIDIndex <= theObjID.Length() &&
1213 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb);
1218 //================================================================================
1220 * \brief Returns true if an object is not present in a study
1222 //================================================================================
1224 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1226 if ( theObjID.IsEmpty() ) return false;
1228 if ( myObjectNames.IsBound( theObjID ))
1229 return false; // SMESH object is in study
1231 // either the SMESH object is not in study or it is a GEOM object
1232 if ( IsGeomObject( theObjID ))
1234 SALOMEDS::SObject_var so = myStudy->FindObjectID( theObjID.ToCString() );
1235 if ( so->_is_nil() ) return true;
1236 CORBA::Object_var obj = so->GetObject();
1237 return CORBA::is_nil( obj );
1239 return true; // SMESH object not in study
1242 //================================================================================
1244 * \brief Return reader of hypotheses of plugins
1246 //================================================================================
1248 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1250 if (myHypReader.IsNull() )
1251 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1257 //================================================================================
1259 * \brief Mesh created by SMESH_Gen
1261 //================================================================================
1263 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1264 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1266 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1267 myGeomNotInStudy = true;
1269 // convert my creation command --> smeshpy.Mesh(...)
1270 Handle(_pyCommand) creationCmd = GetCreationCmd();
1271 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1272 creationCmd->SetMethod( "Mesh" );
1273 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1276 //================================================================================
1278 * \brief Mesh created by SMESH_MeshEditor
1280 //================================================================================
1282 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1283 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1285 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1287 // this mesh depends on the exported mesh
1288 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1289 if ( !file.IsEmpty() )
1291 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1292 addFatherMesh( exportData.myMesh );
1293 if ( !exportData.myLastComputeCmd.IsNull() )
1295 // restore cleared Compute() by which the exported mesh was generated
1296 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1297 // protect that Compute() cmd from clearing
1298 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1299 exportData.myMesh->myLastComputeCmd.Nullify();
1303 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1305 // this mesh depends on concatenated meshes
1306 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1307 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1308 list< _pyID >::iterator meshID = idList.begin();
1309 for ( ; meshID != idList.end(); ++meshID )
1310 addFatherMesh( *meshID );
1312 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1314 // this mesh depends on a copied IdSource
1315 const _pyID& objID = theCreationCmd->GetArg( 1 );
1316 addFatherMesh( objID );
1318 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1319 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1320 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1322 // this mesh depends on a source mesh
1323 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1324 const _pyID& meshID = theCreationCmd->GetObject();
1325 addFatherMesh( meshID );
1328 // convert my creation command
1329 Handle(_pyCommand) creationCmd = GetCreationCmd();
1330 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1331 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1334 //================================================================================
1336 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1337 * \param theCommand - Engine method called for this mesh
1339 //================================================================================
1341 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1343 // some methods of SMESH_Mesh interface needs special conversion
1344 // to methods of Mesh python class
1346 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1347 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1348 // 2. AddHypothesis(geom, hyp)
1349 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1350 // 3. CreateGroupFromGEOM(type, name, grp)
1351 // --> in Mesh.Group(grp, name="")
1352 // 4. ExportToMED(f, auto_groups, version)
1353 // --> in Mesh.ExportMED( f, auto_groups, version )
1356 const TCollection_AsciiString& method = theCommand->GetMethod();
1357 // ----------------------------------------------------------------------
1358 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1360 if ( !theGen->IsToKeepAllCommands() ) // !historical
1362 list< Handle(_pyHypothesis) >::iterator hyp;
1363 if ( !myLastComputeCmd.IsNull() )
1365 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1366 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1368 myLastComputeCmd->Clear();
1370 myLastComputeCmd = theCommand;
1372 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1373 (*hyp)->MeshComputed( myLastComputeCmd );
1377 // ----------------------------------------------------------------------
1378 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1380 if ( !theGen->IsToKeepAllCommands() ) // !historical
1383 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1384 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1385 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1387 if ( !myLastComputeCmd.IsNull() )
1389 list< Handle(_pyHypothesis) >::iterator hyp;
1390 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1391 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1393 myLastComputeCmd->Clear();
1396 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1397 for ( ; e != myEditors.end(); ++e )
1399 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1400 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1401 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1402 if ( !(*cmd)->IsEmpty() )
1404 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1408 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1411 // ----------------------------------------------------------------------
1412 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1413 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1414 if ( !subMesh.IsNull() ) {
1415 subMesh->SetCreator( this );
1416 mySubmeshes.push_back( subMesh );
1419 else if ( method == "RemoveSubMesh" ) { // move submesh creation before its removal
1420 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetArg(1) );
1421 if ( !subMesh.IsNull() )
1422 subMesh->Process( theCommand );
1423 AddMeshAccess( theCommand );
1425 // ----------------------------------------------------------------------
1426 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1427 myAddHypCmds.push_back( theCommand );
1429 const _pyID& hypID = theCommand->GetArg( 2 );
1430 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1431 if ( !hyp.IsNull() ) {
1432 myHypos.push_back( hyp );
1433 if ( hyp->GetMesh().IsEmpty() )
1434 hyp->SetMesh( this->GetID() );
1437 // ----------------------------------------------------------------------
1438 else if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
1440 theCommand->SetMethod( "CreateEmptyGroup" );
1441 Handle(_pyGroup) group = new _pyGroup( theCommand );
1442 myGroups.push_back( group );
1443 theGen->AddObject( group );
1445 // ----------------------------------------------------------------------
1446 else if ( method == "CreateGroupFromGEOM" ) {// (type, name, grp)
1447 _pyID grp = theCommand->GetArg( 3 );
1448 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
1449 // next if(){...} section is commented
1450 //if ( sameGroupType( grp, theCommand->GetArg( 1 )) ) { // --> Group(grp)
1451 // theCommand->SetMethod( "Group" );
1452 // theCommand->RemoveArgs();
1453 // theCommand->SetArg( 1, grp );
1456 // ------------------------->>>>> GroupOnGeom( grp, name, typ )
1457 _pyID type = theCommand->GetArg( 1 );
1458 _pyID name = theCommand->GetArg( 2 );
1459 theCommand->SetMethod( "GroupOnGeom" );
1460 theCommand->RemoveArgs();
1461 theCommand->SetArg( 1, grp );
1462 theCommand->SetArg( 2, name );
1463 theCommand->SetArg( 3, type );
1465 Handle(_pyGroup) group = new _pyGroup( theCommand );
1466 myGroups.push_back( group );
1467 theGen->AddObject( group );
1469 // ----------------------------------------------------------------------
1470 else if ( method == "CreateGroupFromFilter" ) // --> GroupOnFilter()
1472 theCommand->SetMethod( "GroupOnFilter" );
1473 Handle(_pyGroup) group = new _pyGroup( theCommand );
1474 myGroups.push_back( group );
1475 theGen->AddObject( group );
1477 // GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
1478 _pyID filterID = theCommand->GetArg(3);
1479 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
1480 if ( !filter.IsNull())
1482 filter->Process( theCommand );
1483 filter->AddUser( group );
1486 // ----------------------------------------------------------------------
1487 else if ( theCommand->MethodStartsFrom( "Export" ))
1489 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1490 method == "ExportToMEDX" ) { // ExportToMEDX() --> ExportMED()
1491 theCommand->SetMethod( "ExportMED" );
1493 else if ( method == "ExportCGNS" )
1494 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1495 _pyID partID = theCommand->GetArg( 1 );
1496 int nbArgs = theCommand->GetNbArgs();
1497 for ( int i = 2; i <= nbArgs; ++i )
1498 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1499 theCommand->SetArg( nbArgs, partID );
1501 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1502 { // ExportPartTo*(part, ...) -> Export*(..., part)
1504 // remove "PartTo" from the method
1505 TCollection_AsciiString newMethod = method;
1506 newMethod.Remove( 7, 6 );
1507 theCommand->SetMethod( newMethod );
1508 // make the 1st arg be the last one
1509 _pyID partID = theCommand->GetArg( 1 );
1510 int nbArgs = theCommand->GetNbArgs();
1511 for ( int i = 2; i <= nbArgs; ++i )
1512 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1513 theCommand->SetArg( nbArgs, partID );
1515 // remember file name
1516 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1517 ExportedMeshData( this, myLastComputeCmd ));
1519 // ----------------------------------------------------------------------
1520 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1522 _pyID hypID = theCommand->GetArg( 2 );
1524 // check if this mesh still has corresponding addition command
1525 bool hasAddCmd = false;
1526 list< Handle(_pyCommand) >::iterator cmd = myAddHypCmds.begin();
1527 while ( cmd != myAddHypCmds.end() )
1529 // AddHypothesis(geom, hyp)
1530 if ( hypID == (*cmd)->GetArg( 2 )) { // erase both (add and remove) commands
1531 theCommand->Clear();
1533 cmd = myAddHypCmds.erase( cmd );
1540 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1541 if ( ! hasAddCmd && hypID.Length() != 0 ) { // hypo addition already wrapped
1542 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1543 _pyID geom = theCommand->GetArg( 1 );
1544 theCommand->RemoveArgs();
1545 theCommand->SetArg( 1, hypID );
1546 if ( geom != GetGeom() )
1547 theCommand->SetArg( 2, geom );
1549 // remove hyp from myHypos
1550 myHypos.remove( hyp );
1552 // check for SubMesh order commands
1553 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
1555 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1556 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1557 // commands are moved at the end of the script
1558 TCollection_AsciiString subIDs =
1559 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
1560 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
1561 list< _pyID >::iterator subID = idList.begin();
1562 for ( ; subID != idList.end(); ++subID )
1564 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
1565 if ( !subMesh.IsNull() )
1566 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
1569 // update list of groups
1570 else if ( method == "GetGroups" )
1572 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1573 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1574 list< _pyID >::iterator grID = idList.begin();
1575 for ( ; grID != idList.end(); ++grID )
1577 Handle(_pyObject) obj = theGen->FindObject( *grID );
1580 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1581 theGen->AddObject( group );
1582 myGroups.push_back( group );
1586 // add accessor method if necessary
1589 if ( NeedMeshAccess( theCommand ))
1590 // apply theCommand to the mesh wrapped by smeshpy mesh
1591 AddMeshAccess( theCommand );
1595 //================================================================================
1597 * \brief Return True if addition of accesor method is needed
1599 //================================================================================
1601 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
1603 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
1604 // so no conversion is needed for them at all:
1605 static TStringSet sameMethods;
1606 if ( sameMethods.empty() ) {
1607 const char * names[] =
1608 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
1609 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
1610 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
1611 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
1612 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
1613 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
1614 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
1615 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
1616 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
1617 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
1618 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
1619 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
1620 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
1621 ,"" }; // <- mark of end
1622 sameMethods.Insert( names );
1625 return !sameMethods.Contains( theCommand->GetMethod() );
1628 //================================================================================
1630 * \brief Convert creation and addition of all algos and hypos
1632 //================================================================================
1634 void _pyMesh::Flush()
1637 // get the meshes this mesh depends on via hypotheses
1638 list< Handle(_pyMesh) > fatherMeshes;
1639 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1640 for ( ; hyp != myHypos.end(); ++hyp )
1641 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
1642 myGeomNotInStudy = true;
1644 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
1645 for ( ; m != fatherMeshes.end(); ++m )
1646 addFatherMesh( *m );
1647 // if ( removedGeom )
1648 // SetRemovedFromStudy(); // as reffered geometry not in study
1650 if ( myGeomNotInStudy )
1653 list < Handle(_pyCommand) >::iterator cmd;
1655 // try to convert algo addition like this:
1656 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
1657 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1659 Handle(_pyCommand) addCmd = *cmd;
1661 _pyID algoID = addCmd->GetArg( 2 );
1662 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
1663 if ( algo.IsNull() || !algo->IsAlgo() )
1666 // check and create new algorithm instance if it is already wrapped
1667 if ( algo->IsWrapped() ) {
1668 _pyID localAlgoID = theGen->GenerateNewID( algoID );
1669 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
1670 TCollection_AsciiString( " = " ) + theGen->GetID() +
1671 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
1672 TCollection_AsciiString( "\" )" );
1674 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
1675 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
1676 if ( !newAlgo.IsNull() ) {
1677 newAlgo->Assign( algo, this->GetID() );
1678 newAlgo->SetCreationCmd( newCmd );
1680 // set algorithm creation
1681 theGen->SetCommandBefore( newCmd, addCmd );
1682 myHypos.push_back( newAlgo );
1683 if ( !myLastComputeCmd.IsNull() &&
1684 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
1685 newAlgo->MeshComputed( myLastComputeCmd );
1690 _pyID geom = addCmd->GetArg( 1 );
1691 bool isLocalAlgo = ( geom != GetGeom() );
1694 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
1696 // wrapped algo is created after mesh creation
1697 GetCreationCmd()->AddDependantCmd( addCmd );
1699 if ( isLocalAlgo ) {
1700 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
1701 addCmd->SetArg( addCmd->GetNbArgs() + 1,
1702 TCollection_AsciiString( "geom=" ) + geom );
1703 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
1704 list < Handle(_pySubMesh) >::iterator smIt;
1705 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
1706 Handle(_pySubMesh) subMesh = *smIt;
1707 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
1708 if ( geom == subCmd->GetArg( 1 )) {
1709 subCmd->SetObject( algo->GetID() );
1710 subCmd->RemoveArgs();
1711 subMesh->SetCreator( algo );
1716 else // KO - ALGO was already created
1718 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
1719 addCmd->RemoveArgs();
1720 addCmd->SetArg( 1, algoID );
1722 addCmd->SetArg( 2, geom );
1726 // try to convert hypo addition like this:
1727 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
1728 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1730 Handle(_pyCommand) addCmd = *cmd;
1731 _pyID hypID = addCmd->GetArg( 2 );
1732 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1733 if ( hyp.IsNull() || hyp->IsAlgo() )
1735 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
1737 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
1738 _pyID geom = addCmd->GetArg( 1 );
1739 addCmd->RemoveArgs();
1740 addCmd->SetArg( 1, hypID );
1741 if ( geom != GetGeom() )
1742 addCmd->SetArg( 2, geom );
1746 myAddHypCmds.clear();
1747 mySubmeshes.clear();
1750 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1751 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1755 //================================================================================
1757 * \brief Sets myIsPublished of me and of all objects depending on me.
1759 //================================================================================
1761 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
1763 _pyObject::SetRemovedFromStudy(isRemoved);
1765 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
1766 for ( ; sm != mySubmeshes.end(); ++sm )
1767 (*sm)->SetRemovedFromStudy(isRemoved);
1769 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
1770 for ( ; gr != myGroups.end(); ++gr )
1771 (*gr)->SetRemovedFromStudy(isRemoved);
1773 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
1774 for ( ; m != myChildMeshes.end(); ++m )
1775 (*m)->SetRemovedFromStudy(isRemoved);
1777 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1778 for ( ; e != myEditors.end(); ++e )
1779 (*e)->SetRemovedFromStudy(isRemoved);
1782 //================================================================================
1784 * \brief Return true if none of myChildMeshes is in study
1786 //================================================================================
1788 bool _pyMesh::CanClear()
1793 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
1794 for ( ; m != myChildMeshes.end(); ++m )
1795 if ( !(*m)->CanClear() )
1801 //================================================================================
1803 * \brief Clear my commands and commands of mesh editor
1805 //================================================================================
1807 void _pyMesh::ClearCommands()
1813 // mark all sub-objects as not removed, except child meshes
1814 list< Handle(_pyMesh) > children;
1815 children.swap( myChildMeshes );
1816 SetRemovedFromStudy( false );
1817 children.swap( myChildMeshes );
1821 _pyObject::ClearCommands();
1823 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
1824 for ( ; sm != mySubmeshes.end(); ++sm )
1825 (*sm)->ClearCommands();
1827 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
1828 for ( ; gr != myGroups.end(); ++gr )
1829 (*gr)->ClearCommands();
1831 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1832 for ( ; e != myEditors.end(); ++e )
1833 (*e)->ClearCommands();
1836 //================================================================================
1838 * \brief Add a father mesh by ID
1840 //================================================================================
1842 void _pyMesh::addFatherMesh( const _pyID& meshID )
1844 if ( !meshID.IsEmpty() )
1845 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
1848 //================================================================================
1850 * \brief Add a father mesh
1852 //================================================================================
1854 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
1856 if ( !mesh.IsNull() )
1858 //myFatherMeshes.push_back( mesh );
1859 mesh->myChildMeshes.push_back( this );
1861 // protect last Compute() from clearing by the next Compute()
1862 mesh->myLastComputeCmd.Nullify();
1866 //================================================================================
1868 * \brief MeshEditor convert its commands to ones of mesh
1870 //================================================================================
1872 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
1873 _pyObject( theCreationCmd )
1875 myMesh = theCreationCmd->GetObject();
1876 myCreationCmdStr = theCreationCmd->GetString();
1877 theCreationCmd->Clear();
1879 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
1880 if ( !mesh.IsNull() )
1881 mesh->AddEditor( this );
1884 //================================================================================
1886 * \brief convert its commands to ones of mesh
1888 //================================================================================
1890 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
1892 // names of SMESH_MeshEditor methods fully equal to methods of python class Mesh, so
1893 // commands calling this methods are converted to calls of methods of Mesh
1894 static TStringSet sameMethods;
1895 if ( sameMethods.empty() ) {
1896 const char * names[] = {
1897 "RemoveElements","RemoveNodes","RemoveOrphanNodes","AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace",
1898 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","MoveNode", "MoveClosestNodeToPoint",
1899 "InverseDiag","DeleteDiag","Reorient","ReorientObject","TriToQuad","SplitQuad","SplitQuadObject",
1900 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
1901 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
1902 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
1903 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
1904 "ExtrusionAlongPath","ExtrusionAlongPathObject","ExtrusionAlongPathX",
1905 "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
1906 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
1907 "FindCoincidentNodes",/*"FindCoincidentNodesOnPart",*/"MergeNodes","FindEqualElements",
1908 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
1909 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
1910 "GetLastCreatedElems",
1911 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh",
1912 "TranslateObjectMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
1913 "MakeBoundaryElements"
1914 ,"" }; // <- mark of the end
1915 sameMethods.Insert( names );
1918 // names of SMESH_MeshEditor methods which differ from methods of class Mesh
1919 // only by last two arguments
1920 static TStringSet diffLastTwoArgsMethods;
1921 if (diffLastTwoArgsMethods.empty() ) {
1922 const char * names[] = {
1923 "MirrorMakeGroups","MirrorObjectMakeGroups",
1924 "TranslateMakeGroups","TranslateObjectMakeGroups",
1925 "RotateMakeGroups","RotateObjectMakeGroups",
1926 ""};// <- mark of the end
1927 diffLastTwoArgsMethods.Insert( names );
1930 const TCollection_AsciiString & method = theCommand->GetMethod();
1931 bool isPyMeshMethod = sameMethods.Contains( method );
1932 if ( !isPyMeshMethod )
1934 //Replace SMESH_MeshEditor "MakeGroups" functions by the Mesh
1935 //functions with the flag "theMakeGroups = True" like:
1936 //SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
1937 int pos = method.Search("MakeGroups");
1940 isPyMeshMethod = true;
1941 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
1942 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
1944 // 1. Remove "MakeGroups" from the Command
1945 TCollection_AsciiString aMethod = theCommand->GetMethod();
1946 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
1949 pos = pos-2; //Remove "0D" from the Command too
1950 aMethod.Trunc(pos-1);
1951 theCommand->SetMethod(aMethod);
1953 // 2. And add last "True" argument(s)
1954 while(nbArgsToAdd--)
1955 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1956 if( is0DmethId || is0DmethObj )
1957 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1961 // ExtrusionSweep0D() -> ExtrusionSweep()
1962 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
1963 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
1964 method == "ExtrusionSweepObject0D" ))
1966 isPyMeshMethod=true;
1967 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
1968 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
1969 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
1971 // set "ExtrusionAlongPathX()" instead of "ExtrusionAlongPathObjX()"
1972 if ( !isPyMeshMethod && method == "ExtrusionAlongPathObjX")
1974 isPyMeshMethod=true;
1975 theCommand->SetMethod("ExtrusionAlongPathX");
1978 // set "FindCoincidentNodesOnPart()" instead of "FindCoincidentNodesOnPartBut()"
1979 if ( !isPyMeshMethod && method == "FindCoincidentNodesOnPartBut")
1981 isPyMeshMethod=true;
1982 theCommand->SetMethod("FindCoincidentNodesOnPart");
1984 // DoubleNodeElemGroupNew() -> DoubleNodeElemGroup()
1985 // DoubleNodeGroupNew() -> DoubleNodeGroup()
1986 // DoubleNodeGroupsNew() -> DoubleNodeGroups()
1987 // DoubleNodeElemGroupsNew() -> DoubleNodeElemGroups()
1988 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
1989 method == "DoubleNodeElemGroupsNew" ||
1990 method == "DoubleNodeGroupNew" ||
1991 method == "DoubleNodeGroupsNew"))
1993 isPyMeshMethod=true;
1994 theCommand->SetMethod( method.SubString( 1, method.Length()-3));
1995 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1997 // ConvertToQuadraticObject(bool,obj) -> ConvertToQuadratic(bool,obj)
1998 // ConvertFromQuadraticObject(obj) -> ConvertFromQuadratic(obj)
1999 if ( !isPyMeshMethod && ( method == "ConvertToQuadraticObject" ||
2000 method == "ConvertFromQuadraticObject" ))
2002 isPyMeshMethod=true;
2003 theCommand->SetMethod( method.SubString( 1, method.Length()-6));
2004 // prevent moving creation of the converted sub-mesh to the end of the script
2005 bool isFromQua = ( method.Value( 8 ) == 'F' );
2006 Handle(_pySubMesh) sm = theGen->FindSubMesh( theCommand->GetArg( isFromQua ? 1 : 2 ));
2008 sm->Process( theCommand );
2010 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2011 // FindElementsByPoint(x, y, z, elementType, meshPart)
2012 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2014 isPyMeshMethod=true;
2015 theCommand->SetMethod( "FindElementsByPoint" );
2016 // make the 1st arg be the last one
2017 _pyID partID = theCommand->GetArg( 1 );
2018 int nbArgs = theCommand->GetNbArgs();
2019 for ( int i = 2; i <= nbArgs; ++i )
2020 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2021 theCommand->SetArg( nbArgs, partID );
2024 // meshes made by *MakeMesh() methods are not wrapped by _pyMesh,
2025 // so let _pyMesh care of it (TMP?)
2026 // if ( theCommand->GetMethod().Search("MakeMesh") != -1 )
2027 // _pyMesh( new _pyCommand( theCommand->GetString(), 0 )); // for theGen->SetAccessorMethod()
2028 if ( isPyMeshMethod )
2030 theCommand->SetObject( myMesh );
2034 // editor creation command is needed only if any editor function is called
2035 theGen->AddMeshAccessorMethod( theCommand ); // for *Object()
2036 if ( !myCreationCmdStr.IsEmpty() ) {
2037 GetCreationCmd()->GetString() = myCreationCmdStr;
2038 myCreationCmdStr.Clear();
2043 //================================================================================
2045 * \brief Return true if my mesh can be removed
2047 //================================================================================
2049 bool _pyMeshEditor::CanClear()
2051 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2052 return mesh.IsNull() ? true : mesh->CanClear();
2055 //================================================================================
2057 * \brief _pyHypothesis constructor
2058 * \param theCreationCmd -
2060 //================================================================================
2062 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2063 _pyObject( theCreationCmd ), myCurCrMethod(0)
2065 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2068 //================================================================================
2070 * \brief Creates algorithm or hypothesis
2071 * \param theCreationCmd - The engine command creating a hypothesis
2072 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2074 //================================================================================
2076 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2078 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2079 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2081 Handle(_pyHypothesis) hyp, algo;
2084 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2085 if ( hypTypeQuoted.IsEmpty() )
2088 TCollection_AsciiString hypType =
2089 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2091 algo = new _pyAlgorithm( theCreationCmd );
2092 hyp = new _pyHypothesis( theCreationCmd );
2094 if ( hypType == "NumberOfSegments" ) {
2095 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2096 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2097 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2098 hyp->AddArgMethod( "SetNumberOfSegments" );
2099 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2100 hyp->AddArgMethod( "SetScaleFactor" );
2101 hyp->AddArgMethod( "SetReversedEdges" );
2102 // same for ""CompositeSegment_1D:
2103 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2104 hyp->AddArgMethod( "SetNumberOfSegments" );
2105 hyp->AddArgMethod( "SetScaleFactor" );
2106 hyp->AddArgMethod( "SetReversedEdges" );
2108 else if ( hypType == "SegmentLengthAroundVertex" ) {
2109 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2110 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2111 hyp->AddArgMethod( "SetLength" );
2112 // same for ""CompositeSegment_1D:
2113 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2114 hyp->AddArgMethod( "SetLength" );
2116 else if ( hypType == "LayerDistribution2D" ) {
2117 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2118 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2120 else if ( hypType == "LayerDistribution" ) {
2121 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2122 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2124 else if ( hypType == "CartesianParameters3D" ) {
2125 hyp = new _pyComplexParamHypo( theCreationCmd );
2126 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2127 for ( int iArg = 0; iArg < 4; ++iArg )
2128 hyp->setCreationArg( iArg+1, "[]");
2132 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2135 return algo->IsValid() ? algo : hyp;
2138 //================================================================================
2140 * \brief Returns true if addition of this hypothesis to a given mesh can be
2141 * wrapped into hypothesis creation
2143 //================================================================================
2145 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2147 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2149 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2150 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2156 //================================================================================
2158 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2159 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2160 * \param theAlgo - The algo that can create this hypo
2161 * \retval bool - false if the command cant be converted
2163 //================================================================================
2165 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2166 const _pyID& theMesh)
2168 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2170 if ( !IsWrappable( theMesh ))
2173 myGeom = theCmd->GetArg( 1 );
2175 Handle(_pyHypothesis) algo;
2177 // find algo created on myGeom in theMesh
2178 algo = theGen->FindAlgo( myGeom, theMesh, this );
2179 if ( algo.IsNull() )
2181 // attach hypothesis creation command to be after algo creation command
2182 // because it can be new created instance of algorithm
2183 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2187 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2188 theCmd->SetResultValue( GetID() );
2189 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2190 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2191 // set args (geom will be set by _pyMesh calling this method)
2192 theCmd->RemoveArgs();
2193 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2194 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2195 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2197 theCmd->SetArg( i+1, "[]");
2199 // set a new creation command
2200 GetCreationCmd()->Clear();
2201 // replace creation command by wrapped instance
2202 // please note, that hypothesis attaches to algo creation command (see upper)
2203 SetCreationCmd( theCmd );
2206 // clear commands setting arg values
2207 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2208 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2211 // set unknown arg commands after hypo creation
2212 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2213 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2214 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2215 afterCmd->AddDependantCmd( *cmd );
2221 //================================================================================
2223 * \brief Remember hypothesis parameter values
2224 * \param theCommand - The called hypothesis method
2226 //================================================================================
2228 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2230 ASSERT( !myIsAlgo );
2231 if ( !theGen->IsToKeepAllCommands() )
2232 rememberCmdOfParameter( theCommand );
2234 bool usedCommand = false;
2235 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2236 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2238 CreationMethod& crMethod = type2meth->second;
2239 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2240 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2242 myArgCommands.push_back( theCommand );
2244 while ( crMethod.myArgs.size() < i+1 )
2245 crMethod.myArgs.push_back( "[]" );
2246 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2251 myUnusedCommands.push_back( theCommand );
2254 //================================================================================
2256 * \brief Finish conversion
2258 //================================================================================
2260 void _pyHypothesis::Flush()
2264 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2265 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2266 // Add access to a wrapped mesh
2267 theGen->AddMeshAccessorMethod( *cmd );
2268 // Add access to a wrapped algorithm
2269 theGen->AddAlgoAccessorMethod( *cmd );
2271 cmd = myUnusedCommands.begin();
2272 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2273 // Add access to a wrapped mesh
2274 theGen->AddMeshAccessorMethod( *cmd );
2275 // Add access to a wrapped algorithm
2276 theGen->AddAlgoAccessorMethod( *cmd );
2279 // forget previous hypothesis modifications
2280 myArgCommands.clear();
2281 myUnusedCommands.clear();
2284 //================================================================================
2286 * \brief clear creation, arg and unkown commands
2288 //================================================================================
2290 void _pyHypothesis::ClearAllCommands()
2292 GetCreationCmd()->Clear();
2293 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2294 for ( ; cmd != myArgCommands.end(); ++cmd )
2296 cmd = myUnusedCommands.begin();
2297 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2302 //================================================================================
2304 * \brief Assign fields of theOther to me except myIsWrapped
2306 //================================================================================
2308 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2309 const _pyID& theMesh )
2311 // myCreationCmd = theOther->myCreationCmd;
2312 myIsAlgo = theOther->myIsAlgo;
2313 myIsWrapped = false;
2314 myGeom = theOther->myGeom;
2316 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2317 //myArgCommands = theOther->myArgCommands;
2318 //myUnusedCommands = theOther->myUnusedCommands;
2319 // init myCurCrMethod
2320 GetCreationMethod( theOther->GetAlgoType() );
2323 //================================================================================
2325 * \brief Analyze my erasability depending on myReferredObjs
2327 //================================================================================
2329 bool _pyHypothesis::CanClear()
2333 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2334 for ( ; obj != myReferredObjs.end(); ++obj )
2335 if ( (*obj)->CanClear() )
2342 //================================================================================
2344 * \brief Clear my commands depending on usage by meshes
2346 //================================================================================
2348 void _pyHypothesis::ClearCommands()
2350 // if ( !theGen->IsToKeepAllCommands() )
2352 // bool isUsed = false;
2353 // int lastComputeOrder = 0;
2354 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2355 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2356 // if ( ! (*cmd)->IsEmpty() )
2359 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2360 // lastComputeOrder = (*cmd)->GetOrderNb();
2364 // SetRemovedFromStudy( true );
2368 // // clear my commands invoked after lastComputeOrder
2369 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2370 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2372 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2373 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2374 // // cmds.back()->Clear();
2378 _pyObject::ClearCommands();
2381 //================================================================================
2383 * \brief Find arguments that are objects like mesh, group, geometry
2384 * \param meshes - referred meshes (directly or indirrectly)
2385 * \retval bool - false if a referred geometry is not in the study
2387 //================================================================================
2389 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2391 if ( IsAlgo() ) return true;
2393 bool geomPublished = true;
2394 vector< _AString > args;
2395 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2396 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2398 CreationMethod& crMethod = type2meth->second;
2399 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2401 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2402 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2403 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2404 args.push_back( (*cmd)->GetArg( nb ));
2407 for ( size_t i = 0; i < args.size(); ++i )
2409 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2410 if ( idList.empty() && !args[ i ].IsEmpty() )
2411 idList.push_back( args[ i ]);
2412 list< _pyID >::iterator id = idList.begin();
2413 for ( ; id != idList.end(); ++id )
2415 Handle(_pyObject) obj = theGen->FindObject( *id );
2416 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2419 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2420 geomPublished = false;
2424 myReferredObjs.push_back( obj );
2425 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2426 if ( !mesh.IsNull() )
2427 meshes.push_back( mesh );
2428 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2429 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2430 obj->SetRemovedFromStudy( false );
2434 return geomPublished;
2437 //================================================================================
2439 * \brief Remember theCommand setting a parameter
2441 //================================================================================
2443 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2445 // parameters are discriminated by method name
2446 TCollection_AsciiString method = theCommand->GetMethod();
2448 // discriminate commands setting different parameters via one method
2449 // by passing parameter names like e.g. SetOption("size", "0.2")
2450 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2451 theCommand->GetNbArgs() > 1 )
2453 // mangle method by appending a 1st textual arg
2454 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2456 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2457 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2458 if ( !isalpha( arg.Value(2))) continue;
2463 // parameters are discriminated by method name
2464 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ theCommand->GetMethod() ];
2465 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2467 cmds.back()->Clear(); // previous parameter value has not been used
2468 cmds.back() = theCommand;
2472 cmds.push_back( theCommand );
2476 //================================================================================
2478 * \brief Return true if a setting parameter command ha been used to compute mesh
2480 //================================================================================
2482 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2483 _pyCommand::TAddr avoidComputeAddr ) const
2485 bool isUsed = false;
2486 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2487 myComputeAddr2Cmds.begin();
2488 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2490 if ( addr2cmds->first == avoidComputeAddr ) continue;
2491 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2492 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2497 //================================================================================
2499 * \brief Save commands setting parameters as they are used for a mesh computation
2501 //================================================================================
2503 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2505 myComputeCmds.push_back( theComputeCmd );
2506 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2508 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2509 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2510 savedCmds.push_back( m2c->second.back() );
2513 //================================================================================
2515 * \brief Clear commands setting parameters as a mesh computed using them is cleared
2517 //================================================================================
2519 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
2521 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2523 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
2524 for ( ; cmd != savedCmds.end(); ++cmd )
2526 // check if a cmd has been used to compute another mesh
2527 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
2529 // check if a cmd is a sole command setting its parameter;
2530 // don't use method name for search as it can change
2531 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
2532 m2cmds = myMeth2Commands.begin();
2533 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
2535 list< Handle(_pyCommand)>& cmds = m2cmds->second;
2536 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
2537 if ( cmdIt != cmds.end() )
2539 if ( cmds.back() != *cmd )
2541 cmds.erase( cmdIt );
2548 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
2551 //================================================================================
2553 * \brief Sets an argNb-th argument of current creation command
2554 * \param argNb - argument index countered from 1
2556 //================================================================================
2558 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
2560 if ( myCurCrMethod )
2562 while ( myCurCrMethod->myArgs.size() < argNb )
2563 myCurCrMethod->myArgs.push_back( "None" );
2564 if ( arg.IsEmpty() )
2565 myCurCrMethod->myArgs[ argNb-1 ] = "None";
2567 myCurCrMethod->myArgs[ argNb-1 ] = arg;
2572 //================================================================================
2574 * \brief Remember hypothesis parameter values
2575 * \param theCommand - The called hypothesis method
2577 //================================================================================
2579 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
2581 if ( GetAlgoType() == "Cartesian_3D" )
2583 // CartesianParameters3D hyp
2585 if ( theCommand->GetMethod() == "SetSizeThreshold" )
2587 setCreationArg( 4, theCommand->GetArg( 1 ));
2588 myArgCommands.push_back( theCommand );
2591 if ( theCommand->GetMethod() == "SetGrid" ||
2592 theCommand->GetMethod() == "SetGridSpacing" )
2594 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
2595 int iArg = axis.Value(1) - '0';
2596 if ( theCommand->GetMethod() == "SetGrid" )
2598 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
2602 myCurCrMethod->myArgs[ iArg ] = "[ ";
2603 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
2604 myCurCrMethod->myArgs[ iArg ] += ", ";
2605 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
2606 myCurCrMethod->myArgs[ iArg ] += "]";
2608 myArgCommands.push_back( theCommand );
2609 rememberCmdOfParameter( theCommand );
2614 if( theCommand->GetMethod() == "SetLength" )
2616 // NOW it is OBSOLETE
2617 // ex: hyp.SetLength(start, 1)
2618 // hyp.SetLength(end, 0)
2619 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
2620 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
2621 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2622 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2624 CreationMethod& crMethod = type2meth->second;
2625 while ( crMethod.myArgs.size() < i+1 )
2626 crMethod.myArgs.push_back( "[]" );
2627 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
2629 myArgCommands.push_back( theCommand );
2633 _pyHypothesis::Process( theCommand );
2636 //================================================================================
2638 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
2640 //================================================================================
2642 void _pyComplexParamHypo::Flush()
2646 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
2647 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2648 if ((*cmd)->GetMethod() == "SetObjectEntry" )
2653 //================================================================================
2655 * \brief Convert methods of 1D hypotheses to my own methods
2656 * \param theCommand - The called hypothesis method
2658 //================================================================================
2660 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
2662 if ( theCommand->GetMethod() != "SetLayerDistribution" )
2665 const _pyID& hyp1dID = theCommand->GetArg( 1 );
2666 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
2667 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
2669 // TCollection_AsciiString cmd =
2670 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
2671 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
2672 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
2675 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
2677 // // 1D hypo is already set, so distribution changes and the old
2678 // // 1D hypo is thrown away
2679 // my1dHyp->ClearAllCommands();
2682 // //my1dHyp->SetRemovedFromStudy( false );
2684 // if ( !myArgCommands.empty() )
2685 // myArgCommands.back()->Clear();
2686 myCurCrMethod->myArgs.push_back( hyp1dID );
2687 myArgCommands.push_back( theCommand );
2690 //================================================================================
2693 * \param theAdditionCmd - command to be converted
2694 * \param theMesh - mesh instance
2695 * \retval bool - status
2697 //================================================================================
2699 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
2700 const _pyID& theMesh)
2702 myIsWrapped = false;
2704 if ( my1dHyp.IsNull() )
2707 // set "SetLayerDistribution()" after addition cmd
2708 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
2710 _pyID geom = theAdditionCmd->GetArg( 1 );
2712 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
2713 if ( !algo.IsNull() )
2715 my1dHyp->SetMesh( theMesh );
2716 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
2717 algo->GetAlgoType().ToCString());
2718 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
2721 // clear "SetLayerDistribution()" cmd
2722 myArgCommands.back()->Clear();
2724 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
2726 // find RadialPrism algo created on <geom> for theMesh
2727 GetCreationCmd()->SetObject( algo->GetID() );
2728 GetCreationCmd()->SetMethod( myAlgoMethod );
2729 GetCreationCmd()->RemoveArgs();
2730 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
2736 //================================================================================
2740 //================================================================================
2742 void _pyLayerDistributionHypo::Flush()
2744 // as creation of 1D hyp was written later then it's edition,
2745 // we need to find all it's edition calls and process them
2746 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2748 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
2750 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
2751 if ( hyp1dID.IsEmpty() ) continue;
2753 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
2755 // make a new name for 1D hyp = "HypType" + "_Distribution"
2757 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
2759 if ( prevNewName.IsEmpty() ) continue;
2760 newName = prevNewName;
2764 if ( hyp1d->IsWrapped() ) {
2765 newName = hyp1d->GetCreationCmd()->GetMethod();
2768 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
2769 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2771 newName += "_Distribution";
2772 prevNewName = newName;
2774 hyp1d->GetCreationCmd()->SetResultValue( newName );
2776 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
2777 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
2778 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
2779 const _pyID& objID = (*cmdIt)->GetObject();
2780 if ( objID == hyp1dID ) {
2781 if ( !hyp1d.IsNull() )
2783 hyp1d->Process( *cmdIt );
2784 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
2786 ( *cmdIt )->SetObject( newName );
2789 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
2790 (*cmd)->SetArg( 1, newName );
2794 //================================================================================
2796 * \brief additionally to Addition2Creation, clears SetDistrType() command
2797 * \param theCmd - AddHypothesis() command
2798 * \param theMesh - mesh to which a hypothesis is added
2799 * \retval bool - convertion result
2801 //================================================================================
2803 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
2804 const _pyID& theMesh)
2806 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
2807 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
2808 bool scaleDistrType = false;
2809 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
2810 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
2811 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
2812 if ( (*cmd)->GetArg( 1 ) == "1" ) {
2813 scaleDistrType = true;
2816 else if ( !scaleDistrType ) {
2817 // distribution type changed: remove scale factor from args
2818 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2819 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2821 CreationMethod& crMethod = type2meth->second;
2822 if ( crMethod.myArgs.size() == 2 )
2823 crMethod.myArgs.pop_back();
2830 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
2833 //================================================================================
2835 * \brief remove repeated commands defining distribution
2837 //================================================================================
2839 void _pyNumberOfSegmentsHyp::Flush()
2841 // find number of the last SetDistrType() command
2842 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
2843 int distrTypeNb = 0;
2844 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
2845 if ( (*cmd)->GetMethod() == "SetDistrType" )
2846 distrTypeNb = (*cmd)->GetOrderNb();
2847 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" )
2850 // clear commands before the last SetDistrType()
2851 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
2852 for ( int i = 0; i < 2; ++i ) {
2853 set<TCollection_AsciiString> uniqueMethods;
2854 list<Handle(_pyCommand)> & cmdList = *cmds[i];
2855 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
2857 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
2858 const TCollection_AsciiString& method = (*cmd)->GetMethod();
2859 if ( !clear || method == "SetNumberOfSegments" ) {
2860 bool isNewInSet = uniqueMethods.insert( method ).second;
2861 clear = !isNewInSet;
2870 //================================================================================
2872 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
2873 * into regular1D.LengthNearVertex( length, vertex )
2874 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
2875 * \param theMesh - The mesh needing this hypo
2876 * \retval bool - false if the command cant be converted
2878 //================================================================================
2880 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
2881 const _pyID& theMeshID)
2883 if ( IsWrappable( theMeshID )) {
2885 _pyID vertex = theCmd->GetArg( 1 );
2887 // the problem here is that segment algo will not be found
2888 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
2889 // geometry where segment algorithm is assigned
2890 Handle(_pyHypothesis) algo;
2891 _pyID geom = vertex;
2892 while ( algo.IsNull() && !geom.IsEmpty()) {
2893 // try to find geom as a father of <vertex>
2894 geom = FatherID( geom );
2895 algo = theGen->FindAlgo( geom, theMeshID, this );
2897 if ( algo.IsNull() )
2898 return false; // also possible to find geom as brother of veretex...
2899 // set geom instead of vertex
2900 theCmd->SetArg( 1, geom );
2902 // set vertex as a second arg
2903 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
2904 setCreationArg( 2, vertex );
2906 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
2907 // theMeshID.LengthNearVertex( length, vertex )
2908 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
2913 //================================================================================
2915 * \brief _pyAlgorithm constructor
2916 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
2918 //================================================================================
2920 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
2921 : _pyHypothesis( theCreationCmd )
2926 //================================================================================
2928 * \brief Convert the command adding an algorithm to mesh
2929 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
2930 * \param theMesh - The mesh needing this algo
2931 * \retval bool - false if the command cant be converted
2933 //================================================================================
2935 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
2936 const _pyID& theMeshID)
2938 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
2939 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
2940 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
2946 //================================================================================
2948 * \brief Return starting position of a part of python command
2949 * \param thePartIndex - The index of command part
2950 * \retval int - Part position
2952 //================================================================================
2954 int _pyCommand::GetBegPos( int thePartIndex )
2958 if ( myBegPos.Length() < thePartIndex )
2960 return myBegPos( thePartIndex );
2963 //================================================================================
2965 * \brief Store starting position of a part of python command
2966 * \param thePartIndex - The index of command part
2967 * \param thePosition - Part position
2969 //================================================================================
2971 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
2973 while ( myBegPos.Length() < thePartIndex )
2974 myBegPos.Append( UNKNOWN );
2975 myBegPos( thePartIndex ) = thePosition;
2978 //================================================================================
2980 * \brief Returns whitespace symbols at the line beginning
2981 * \retval TCollection_AsciiString - result
2983 //================================================================================
2985 TCollection_AsciiString _pyCommand::GetIndentation()
2988 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
2989 GetWord( myString, end, true );
2991 end = GetBegPos( RESULT_IND );
2992 return myString.SubString( 1, end - 1 );
2995 //================================================================================
2997 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
2998 * \retval const TCollection_AsciiString & - ResultValue substring
3000 //================================================================================
3002 const TCollection_AsciiString & _pyCommand::GetResultValue()
3004 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3006 SetBegPos( RESULT_IND, EMPTY );
3007 int begPos, endPos = myString.Location( "=", 1, Length() );
3011 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3012 if ( begPos < endPos )
3014 SetBegPos( RESULT_IND, begPos );
3016 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3017 myRes = myString.SubString( begPos, endPos );
3024 //================================================================================
3026 * \brief Return number of python command result value ResultValue = Obj.Meth()
3029 //================================================================================
3031 const int _pyCommand::GetNbResultValues()
3035 int endPos = myString.Location( "=", 1, Length() );
3036 TCollection_AsciiString str = "";
3037 while ( begPos < endPos) {
3038 str = GetWord( myString, begPos, true );
3039 begPos = begPos+ str.Length();
3046 //================================================================================
3048 * \brief Return substring of python command looking like
3049 * ResultValue1 , ResultValue1,... = Obj.Meth() with res index
3050 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3052 //================================================================================
3053 const TCollection_AsciiString & _pyCommand::GetResultValue(int res)
3057 int endPos = myString.Location( "=", 1, Length() );
3058 while ( begPos < endPos) {
3059 myRes = GetWord( myString, begPos, true );
3060 begPos = begPos + myRes.Length();
3063 myRes.RemoveAll('[');myRes.RemoveAll(']');
3069 return theEmptyString;
3072 //================================================================================
3074 * \brief Return substring of python command looking like ResVal = Object.Meth()
3075 * \retval const TCollection_AsciiString & - Object substring
3077 //================================================================================
3079 const TCollection_AsciiString & _pyCommand::GetObject()
3081 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3084 int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
3086 begPos = myString.Location( "=", 1, Length() ) + 1;
3087 // is '=' in the string argument (for example, name) or not
3088 int nb1 = 0; // number of ' character at the left of =
3089 int nb2 = 0; // number of " character at the left of =
3090 for ( int i = 1; i < begPos-1; i++ ) {
3091 if ( myString.Value( i )=='\'' )
3093 else if ( myString.Value( i )=='"' )
3096 // if number of ' or " is not divisible by 2,
3097 // then get an object at the start of the command
3098 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3101 myObj = GetWord( myString, begPos, true );
3102 // check if object is complex,
3103 // so far consider case like "smesh.smesh.Method()"
3104 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3105 //if ( bracketPos==0 ) bracketPos = Length();
3106 int dotPos = begPos+myObj.Length();
3107 while ( dotPos+1 < bracketPos ) {
3108 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3113 if ( dotPos > begPos+myObj.Length() )
3114 myObj = myString.SubString( begPos, dotPos-1 );
3116 // 1st word after '=' is an object
3117 // else // no method -> no object
3123 SetBegPos( OBJECT_IND, begPos );
3129 //================================================================================
3131 * \brief Return substring of python command looking like ResVal = Obj.Method()
3132 * \retval const TCollection_AsciiString & - Method substring
3134 //================================================================================
3136 const TCollection_AsciiString & _pyCommand::GetMethod()
3138 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3141 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3142 bool forward = true;
3144 begPos = myString.Location( "(", 1, Length() ) - 1;
3148 myMeth = GetWord( myString, begPos, forward );
3149 SetBegPos( METHOD_IND, begPos );
3155 //================================================================================
3157 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3158 * \retval const TCollection_AsciiString & - Arg<index> substring
3160 //================================================================================
3162 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3164 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3168 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3170 pos = myString.Location( "(", 1, Length() );
3174 // we are at or before '(', skip it if present
3176 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3177 if ( pos > Length() )
3181 SetBegPos( ARG1_IND, 0 ); // even no '('
3182 return theEmptyString;
3186 list< TCollection_AsciiString > separatorStack( 1, ",)");
3187 bool ignoreNesting = false;
3189 while ( pos <= Length() )
3191 const char chr = myString.Value( pos );
3193 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3195 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3197 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3199 TCollection_AsciiString arg;
3200 if ( pos-1 >= prevPos ) {
3201 arg = myString.SubString( prevPos, pos-1 );
3202 arg.RightAdjust(); // remove spaces
3205 if ( !arg.IsEmpty() || chr == ',' )
3207 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3208 myArgs.Append( arg );
3214 else // end of nesting args found
3216 separatorStack.pop_back();
3217 ignoreNesting = false;
3220 else if ( !ignoreNesting )
3223 case '(' : separatorStack.push_back(")"); break;
3224 case '[' : separatorStack.push_back("]"); break;
3225 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3226 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3233 if ( myArgs.Length() < index )
3234 return theEmptyString;
3235 return myArgs( index );
3238 //================================================================================
3240 * \brief Check if char is a word part
3241 * \param c - The character to check
3242 * \retval bool - The check result
3244 //================================================================================
3246 static inline bool isWord(const char c, const bool dotIsWord)
3249 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3252 //================================================================================
3254 * \brief Looks for a word in the string and returns word's beginning
3255 * \param theString - The input string
3256 * \param theStartPos - The position to start the search, returning word's beginning
3257 * \param theForward - The search direction
3258 * \retval TCollection_AsciiString - The found word
3260 //================================================================================
3262 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
3264 const bool theForward,
3265 const bool dotIsWord )
3267 int beg = theStartPos, end = theStartPos;
3268 theStartPos = EMPTY;
3269 if ( beg < 1 || beg > theString.Length() )
3270 return theEmptyString;
3272 if ( theForward ) { // search forward
3274 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3276 if ( beg > theString.Length() )
3277 return theEmptyString; // no word found
3280 char begChar = theString.Value( beg );
3281 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3282 char endChar = ( begChar == '[' ) ? ']' : begChar;
3283 // end is at the corresponding quoting mark or bracket
3284 while ( end < theString.Length() &&
3285 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3289 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3294 else { // search backward
3296 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3299 return theEmptyString; // no word found
3301 char endChar = theString.Value( end );
3302 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3303 char begChar = ( endChar == ']' ) ? '[' : endChar;
3304 // beg is at the corresponding quoting mark
3306 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3310 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3316 //cout << theString << " ---- " << beg << " - " << end << endl;
3317 return theString.SubString( beg, end );
3320 //================================================================================
3322 * \brief Returns true if the string looks like a study entry
3324 //================================================================================
3326 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3328 if ( str.Length() < 5 ) return false;
3330 int nbColons = 0, isColon;
3331 for ( int i = 1; i <= str.Length(); ++i )
3333 char c = str.Value(i);
3334 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3336 nbColons += isColon;
3338 return nbColons > 2 && str.Length()-nbColons > 2;
3341 //================================================================================
3343 * \brief Finds entries in a sting
3345 //================================================================================
3347 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3349 std::list< _pyID > resList;
3351 while ( ++pos <= str.Length() )
3353 if ( !isdigit( str.Value( pos ))) continue;
3354 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3357 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3358 _pyID entry = str.SubString( pos, end-1 );
3360 if ( IsStudyEntry( entry ))
3361 resList.push_back( entry );
3366 //================================================================================
3368 * \brief Look for position where not space char is
3369 * \param theString - The string
3370 * \param thePos - The position to search from and which returns result
3371 * \retval bool - false if there are only space after thePos in theString
3375 //================================================================================
3377 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3379 if ( thePos < 1 || thePos > theString.Length() )
3382 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3385 return thePos <= theString.Length();
3388 //================================================================================
3390 * \brief Modify a part of the command
3391 * \param thePartIndex - The index of the part
3392 * \param thePart - The new part string
3393 * \param theOldPart - The old part
3395 //================================================================================
3397 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3398 TCollection_AsciiString& theOldPart)
3400 int pos = GetBegPos( thePartIndex );
3401 if ( pos <= Length() && theOldPart != thePart)
3403 TCollection_AsciiString seperator;
3405 pos = GetBegPos( thePartIndex + 1 );
3406 if ( pos < 1 ) return;
3407 switch ( thePartIndex ) {
3408 case RESULT_IND: seperator = " = "; break;
3409 case OBJECT_IND: seperator = "."; break;
3410 case METHOD_IND: seperator = "()"; break;
3414 myString.Remove( pos, theOldPart.Length() );
3415 if ( !seperator.IsEmpty() )
3416 myString.Insert( pos , seperator );
3417 myString.Insert( pos, thePart );
3418 // update starting positions of the following parts
3419 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3420 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3421 if ( myBegPos( i ) > 0 )
3422 myBegPos( i ) += posDelta;
3424 theOldPart = thePart;
3428 //================================================================================
3430 * \brief Set agrument
3431 * \param index - The argument index, it counts from 1
3432 * \param theArg - The argument string
3434 //================================================================================
3436 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3439 int argInd = ARG1_IND + index - 1;
3440 int pos = GetBegPos( argInd );
3441 if ( pos < 1 ) // no index-th arg exist, append inexistent args
3443 // find a closing parenthesis
3444 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3445 int lastArgInd = GetNbArgs();
3446 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
3447 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3452 while ( pos > 0 && myString.Value( pos ) != ')' )
3455 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3459 while ( myArgs.Length() < index ) {
3460 if ( myArgs.Length() )
3461 myString.Insert( pos++, "," );
3462 myArgs.Append("None");
3463 myString.Insert( pos, myArgs.Last() );
3464 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3465 pos += myArgs.Last().Length();
3468 SetPart( argInd, theArg, myArgs( index ));
3471 //================================================================================
3473 * \brief Empty arg list
3475 //================================================================================
3477 void _pyCommand::RemoveArgs()
3479 if ( int pos = myString.Location( '(', 1, Length() ))
3480 myString.Trunc( pos );
3483 if ( myBegPos.Length() >= ARG1_IND )
3484 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
3487 //================================================================================
3489 * \brief Comment a python command
3491 //================================================================================
3493 void _pyCommand::Comment()
3495 if ( IsEmpty() ) return;
3498 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
3499 if ( i <= Length() )
3501 myString.Insert( i, "#" );
3502 for ( int iPart = 0; iPart < myBegPos.Length(); ++iPart )
3504 int begPos = GetBegPos( iPart );
3505 if ( begPos != UNKNOWN )
3506 SetBegPos( iPart, begPos + 1 );
3511 //================================================================================
3513 * \brief Set dependent commands after this one
3515 //================================================================================
3517 bool _pyCommand::SetDependentCmdsAfter() const
3519 bool orderChanged = false;
3520 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
3521 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
3522 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
3523 orderChanged = true;
3524 theGen->SetCommandAfter( *cmd, this );
3525 (*cmd)->SetDependentCmdsAfter();
3528 return orderChanged;
3530 //================================================================================
3532 * \brief Insert accessor method after theObjectID
3533 * \param theObjectID - id of the accessed object
3534 * \param theAcsMethod - name of the method giving access to the object
3535 * \retval bool - false if theObjectID is not found in the command string
3537 //================================================================================
3539 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
3541 if ( !theAcsMethod )
3543 // start object search from the object, i.e. ignore result
3545 int beg = GetBegPos( OBJECT_IND );
3546 if ( beg < 1 || beg > Length() )
3549 while (( beg = myString.Location( theObjectID, beg, Length() )))
3551 // check that theObjectID is not just a part of a longer ID
3552 int afterEnd = beg + theObjectID.Length();
3553 Standard_Character c = myString.Value( afterEnd );
3554 if ( !isalnum( c ) && c != ':' ) {
3555 // check if accessor method already present
3557 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
3559 int oldLen = Length();
3560 myString.Insert( afterEnd, (char*) theAcsMethod );
3561 myString.Insert( afterEnd, "." );
3562 // update starting positions of the parts following the modified one
3563 int posDelta = Length() - oldLen;
3564 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
3565 if ( myBegPos( i ) > afterEnd )
3566 myBegPos( i ) += posDelta;
3571 beg = afterEnd; // is a part - next search
3576 //================================================================================
3578 * \brief Creates pyObject
3580 //================================================================================
3582 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
3583 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
3588 //================================================================================
3590 * \brief Set up myID and myIsPublished
3592 //================================================================================
3594 void _pyObject::setID(const _pyID& theID)
3597 myIsPublished = !theGen->IsNotPublished( GetID() );
3600 //================================================================================
3602 * \brief Clear myCreationCmd and myProcessedCmds
3604 //================================================================================
3606 void _pyObject::ClearCommands()
3611 if ( !myCreationCmd.IsNull() )
3612 myCreationCmd->Clear();
3614 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
3615 for ( ; cmd != myProcessedCmds.end(); ++cmd )
3619 //================================================================================
3621 * \brief Return method name giving access to an interaface object wrapped by python class
3622 * \retval const char* - method name
3624 //================================================================================
3626 const char* _pyObject::AccessorMethod() const
3630 //================================================================================
3632 * \brief Return ID of a father
3634 //================================================================================
3636 _pyID _pyObject::FatherID(const _pyID & childID)
3638 int colPos = childID.SearchFromEnd(':');
3640 return childID.SubString( 1, colPos-1 );
3644 //================================================================================
3646 * \brief SelfEraser erases creation command if no more it's commands invoked
3648 //================================================================================
3650 void _pySelfEraser::Flush()
3652 if ( GetNbCalls() == 0 )
3653 GetCreationCmd()->Clear();
3656 //================================================================================
3658 * \brief _pySubMesh constructor
3660 //================================================================================
3662 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
3663 _pyObject(theCreationCmd)
3665 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
3668 //================================================================================
3670 * \brief count invoked commands
3672 //================================================================================
3674 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
3676 _pyObject::Process(theCommand); // count calls of Process()
3677 GetCreationCmd()->AddDependantCmd( theCommand );
3680 //================================================================================
3682 * \brief Move creation command depending on invoked commands
3684 //================================================================================
3686 void _pySubMesh::Flush()
3688 if ( GetNbCalls() == 0 ) // move to the end of all commands
3689 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
3690 else if ( !myCreator.IsNull() )
3691 // move to be just after creator
3692 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
3695 //================================================================================
3697 * \brief To convert creation of a group by filter
3699 //================================================================================
3701 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
3703 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
3704 // group = mesh.CreateEmptyGroup( elemType, groupName )
3705 // aFilter.SetMesh(mesh)
3706 // nbAdd = group.AddFrom( aFilter )
3707 Handle(_pyFilter) filter;
3708 if ( theCommand->GetMethod() == "AddFrom" )
3710 _pyID idSource = theCommand->GetArg(1);
3711 // check if idSource is a filter
3712 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
3713 if ( !filter.IsNull() )
3715 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
3716 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
3717 while ( *cmdIt != theCommand ) ++cmdIt;
3718 while ( (*cmdIt)->GetOrderNb() != 1 )
3720 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
3721 if ((setMeshCmd->GetObject() == idSource ||
3722 setMeshCmd->GetObject() == filter->GetNewID() )
3724 setMeshCmd->GetMethod() == "SetMesh")
3726 setMeshCmd->Clear();
3730 // replace 3 commands by one
3731 theCommand->Clear();
3732 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
3733 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
3734 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
3735 makeGroupCmd->SetArg( 1, name );
3736 makeGroupCmd->SetArg( 2, idSource );
3737 // set new name of a filter
3738 filter->Process( makeGroupCmd );
3741 else if ( theCommand->GetMethod() == "SetFilter" )
3743 // set new name of a filter
3744 _pyID filterID = theCommand->GetArg(1);
3745 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
3746 if ( !filter.IsNull() )
3747 filter->Process( theCommand );
3750 if ( !filter.IsNull() )
3751 filter->AddUser( this );
3753 theGen->AddMeshAccessorMethod( theCommand );
3756 //================================================================================
3758 * \brief Constructor of _pyFilter
3760 //================================================================================
3762 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
3763 :_pyObject(theCreationCmd), myNewID( newID )
3767 //================================================================================
3769 * \brief To convert creation of a filter by criteria and
3770 * to replace an old name by a new one
3772 //================================================================================
3774 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
3776 if ( theCommand->GetObject() == GetID() )
3777 _pyObject::Process(theCommand); // count commands
3779 if ( !myNewID.IsEmpty() )
3781 if ( theCommand->GetObject() == GetID() )
3782 theCommand->SetObject( myNewID );
3783 else if ( theCommand->GetResultValue() == GetID() )
3784 theCommand->SetResultValue( myNewID );
3786 for ( int i = 1, nb = theCommand->GetNbArgs(); i <= nb; ++i )
3787 if ( theCommand->GetArg( i ) == GetID() )
3789 theCommand->SetArg( i, myNewID );
3794 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
3795 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
3796 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
3797 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
3798 theCommand->GetMethod() == "SetCriteria")
3800 // aFilter.SetCriteria(aCriteria) ->
3801 // aFilter = smesh.GetFilterFromCriteria(criteria)
3802 if ( myNewID.IsEmpty() )
3803 theCommand->SetResultValue( GetID() );
3805 theCommand->SetResultValue( myNewID );
3806 theCommand->SetObject( SMESH_2smeshpy::GenName() );
3807 theCommand->SetMethod( "GetFilterFromCriteria" );
3809 // Clear aFilterManager.CreateFilter()
3810 GetCreationCmd()->Clear();
3812 else if ( theCommand->GetMethod() == "SetMesh")
3814 theGen->AddMeshAccessorMethod( theCommand );
3818 //================================================================================
3820 * \brief Set new filter name to the creation command
3822 //================================================================================
3824 void _pyFilter::Flush()
3826 if ( !myNewID.IsEmpty() && !GetCreationCmd()->IsEmpty() )
3827 GetCreationCmd()->SetResultValue( myNewID );
3830 //================================================================================
3832 * \brief Return true if all my users can be cleared
3834 //================================================================================
3836 bool _pyFilter::CanClear()
3838 list< Handle(_pyObject) >::iterator obj = myUsers.begin();
3839 for ( ; obj != myUsers.end(); ++obj )
3840 if ( !(*obj)->CanClear() )
3846 //================================================================================
3848 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
3850 //================================================================================
3852 _pyHypothesisReader::_pyHypothesisReader()
3854 // Get paths to xml files of plugins
3855 vector< string > xmlPaths;
3857 if ( const char* meshersList = getenv("SMESH_MeshersList") )
3859 string meshers = meshersList, plugin;
3860 string::size_type from = 0, pos;
3861 while ( from < meshers.size() )
3863 // cut off plugin name
3864 pos = meshers.find( ':', from );
3865 if ( pos != string::npos )
3866 plugin = meshers.substr( from, pos-from );
3868 plugin = meshers.substr( from ), pos = meshers.size();
3871 // get PLUGIN_ROOT_DIR path
3872 string rootDirVar, pluginSubDir = plugin;
3873 if ( plugin == "StdMeshers" )
3874 rootDirVar = "SMESH", pluginSubDir = "smesh";
3876 for ( pos = 0; pos < plugin.size(); ++pos )
3877 rootDirVar += toupper( plugin[pos] );
3878 rootDirVar += "_ROOT_DIR";
3880 const char* rootDir = getenv( rootDirVar.c_str() );
3881 if ( !rootDir || strlen(rootDir) == 0 )
3883 rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
3884 rootDir = getenv( rootDirVar.c_str() );
3885 if ( !rootDir || strlen(rootDir) == 0 ) continue;
3888 // get a separator from rootDir
3889 for ( pos = strlen( rootDir )-1; pos >= 0 && sep.empty(); --pos )
3890 if ( rootDir[pos] == '/' || rootDir[pos] == '\\' )
3895 if (sep.empty() ) sep = "/";
3897 // get a path to resource file
3898 string xmlPath = rootDir;
3899 if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
3901 xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
3902 for ( pos = 0; pos < pluginSubDir.size(); ++pos )
3903 xmlPath += tolower( pluginSubDir[pos] );
3904 xmlPath += sep + plugin + ".xml";
3907 fileOK = (GetFileAttributes(xmlPath.c_str()) != INVALID_FILE_ATTRIBUTES);
3909 fileOK = (access(xmlPath.c_str(), F_OK) == 0);
3912 xmlPaths.push_back( xmlPath );
3917 LDOMParser xmlParser;
3918 for ( size_t i = 0; i < xmlPaths.size(); ++i )
3920 bool error = xmlParser.parse( xmlPaths[i].c_str() );
3924 INFOS( xmlParser.GetError(data) );
3927 // <algorithm type="Regular_1D"
3928 // label-id="Wire discretisation"
3931 // <algo>Regular_1D=Segment()</algo>
3932 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
3934 LDOM_Document xmlDoc = xmlParser.getDocument();
3935 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
3936 for ( int i = 0; i < algoNodeList.getLength(); ++i )
3938 LDOM_Node algoNode = algoNodeList.item( i );
3939 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
3940 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
3941 if ( pyAlgoNodeList.getLength() < 1 ) continue;
3943 _AString text, algoType, method, arg;
3944 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
3946 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
3947 LDOM_Node textNode = pyAlgoNode.getFirstChild();
3948 text = textNode.getNodeValue();
3949 Handle(_pyCommand) algoCmd = new _pyCommand( text );
3950 algoType = algoCmd->GetResultValue();
3951 method = algoCmd->GetMethod();
3952 arg = algoCmd->GetArg(1);
3953 if ( !algoType.IsEmpty() && !method.IsEmpty() )
3955 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
3956 algo->SetConvMethodAndType( method, algoType );
3957 if ( !arg.IsEmpty() )
3958 algo->setCreationArg( 1, arg );
3960 myType2Hyp[ algoType ] = algo;
3964 if ( algoType.IsEmpty() ) continue;
3966 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
3968 Handle( _pyHypothesis ) hyp;
3969 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
3971 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
3972 LDOM_Node textNode = pyHypoNode.getFirstChild();
3973 text = textNode.getNodeValue();
3974 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
3975 hypType = hypoCmd->GetResultValue();
3976 method = hypoCmd->GetMethod();
3977 if ( !hypType.IsEmpty() && !method.IsEmpty() )
3979 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
3980 if ( type2hyp == myType2Hyp.end() )
3981 hyp = new _pyHypothesis( hypoCmd );
3983 hyp = type2hyp->second;
3984 hyp->SetConvMethodAndType( method, algoType );
3985 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
3987 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
3988 _AString argMethod = argCmd.GetMethod();
3989 _AString argNbText = argCmd.GetArg( 1 );
3990 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
3991 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
3993 hyp->AddArgMethod( argMethod,
3994 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
3996 myType2Hyp[ hypType ] = hyp;
4003 //================================================================================
4005 * \brief Returns a new hypothesis initialized according to the read information
4007 //================================================================================
4009 Handle(_pyHypothesis)
4010 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4011 const Handle(_pyCommand)& creationCmd) const
4013 Handle(_pyHypothesis) resHyp, sampleHyp;
4015 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4016 if ( type2hyp != myType2Hyp.end() )
4017 sampleHyp = type2hyp->second;
4019 if ( sampleHyp.IsNull() )
4021 resHyp = new _pyHypothesis(creationCmd);
4025 if ( sampleHyp->IsAlgo() )
4026 resHyp = new _pyAlgorithm( creationCmd );
4028 resHyp = new _pyHypothesis(creationCmd);
4029 resHyp->Assign( sampleHyp, _pyID() );