1 // Copyright (C) 2007-2013 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 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
54 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
57 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
65 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
67 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
84 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
87 using SMESH::TPythonDump;
90 * \brief Container of commands into which the initial script is split.
91 * It also contains data coresponding to SMESH_Gen contents
93 static Handle(_pyGen) theGen;
95 static TCollection_AsciiString theEmptyString;
97 //#define DUMP_CONVERSION
99 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
100 #undef DUMP_CONVERSION
106 //================================================================================
108 * \brief Set of TCollection_AsciiString initialized by C array of C strings
110 //================================================================================
112 struct TStringSet: public set<TCollection_AsciiString>
115 * \brief Filling. The last string must be ""
117 void Insert(const char* names[]) {
118 for ( int i = 0; names[i][0] ; ++i )
119 insert( (char*) names[i] );
122 * \brief Check if a string is in
124 bool Contains(const TCollection_AsciiString& name ) {
125 return find( name ) != end();
129 //================================================================================
131 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
132 * Odd items of the C array are map keys, and even items are values
134 //================================================================================
136 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
139 * \brief Filling. The last string must be ""
141 void Insert(const char* names_values[]) {
142 for ( int i = 0; names_values[i][0] ; i += 2 )
143 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
146 * \brief Check if a string is in
148 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
149 map< _AString, _AString >::iterator it = find( name );
150 return it == end() ? "" : it->second;
154 //================================================================================
156 * \brief Returns a mesh by object
158 //================================================================================
160 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
164 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
165 return Handle(_pyMesh)::DownCast( obj );
166 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
167 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
168 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
169 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
171 return Handle(_pyMesh)();
174 //================================================================================
176 * \brief Check if objects used as args have been created by previous commands
178 //================================================================================
180 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
182 // either comment or erase a command including NotPublishedObjectName()
183 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
185 bool isResultPublished = false;
186 for ( int i = 0; i < cmd->GetNbResultValues(); i++ )
188 _pyID objID = cmd->GetResultValue( i+1 );
189 if ( cmd->IsStudyEntry( objID ))
190 isResultPublished = (! theGen->IsNotPublished( objID ));
191 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
193 if ( isResultPublished )
199 // comment a command having not created args
200 for ( int iArg = cmd->GetNbArgs(); iArg; --iArg )
202 const _pyID& arg = cmd->GetArg( iArg );
203 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
205 list< _pyID > idList = cmd->GetStudyEntries( arg );
206 list< _pyID >::iterator id = idList.begin();
207 for ( ; id != idList.end(); ++id )
208 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
211 cmd->GetString() += " ### " ;
212 cmd->GetString() += *id + " has not been yet created";
213 for ( int i = 0; i < cmd->GetNbResultValues(); i++ ) {
214 _pyID objID = cmd->GetResultValue( i+1 );
215 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
220 // comment a command having not created Object
221 const _pyID& obj = cmd->GetObject();
222 if ( !obj.IsEmpty() && cmd->IsStudyEntry( obj ) && !presentObjects.count( obj ))
225 cmd->GetString() += " ### not created object" ;
226 for ( int i = 0; i < cmd->GetNbResultValues(); i++ ) {
227 _pyID objID = cmd->GetResultValue( i+1 );
228 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
231 const _pyID& result = cmd->GetResultValue();
232 if ( result.IsEmpty() || result.Value( 1 ) == '"' || result.Value( 1 ) == '\'' )
234 list< _pyID > idList = cmd->GetStudyEntries( result );
235 list< _pyID >::iterator id = idList.begin();
236 for ( ; id != idList.end(); ++id )
237 presentObjects.insert( *id );
240 //================================================================================
242 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
244 //================================================================================
246 void fixFunctorType( TCollection_AsciiString& Type,
247 TCollection_AsciiString& Compare,
248 TCollection_AsciiString& UnaryOp,
249 TCollection_AsciiString& BinaryOp )
251 // The problem is that dumps of old studies created using filters becomes invalid
252 // when new items are inserted in the enum SMESH::FunctorType since values
253 // of this enum are dumped as integer values.
254 // This function corrects enum values of old studies given as args (Type,Compare,...)
255 // We can find out how to correct them by value of BinaryOp which can have only two
256 // values: FT_Undefined or FT_LogicalNOT.
257 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
258 // where PythonDump appeared
259 // v 3.0.0: FT_Undefined == 25
260 // v 3.1.0: FT_Undefined == 26, new items:
262 // v 4.1.2: FT_Undefined == 27, new items:
263 // - FT_BelongToGenSurface = 17
264 // v 5.1.1: FT_Undefined == 32, new items:
265 // - FT_FreeNodes = 10
266 // - FT_FreeFaces = 11
267 // - FT_LinearOrQuadratic = 23
268 // - FT_GroupColor = 24
269 // - FT_ElemGeomType = 25
270 // v 5.1.5: FT_Undefined == 33, new items:
271 // - FT_CoplanarFaces = 26
272 // v 6.2.0: FT_Undefined == 39, new items:
273 // - FT_MaxElementLength2D = 8
274 // - FT_MaxElementLength3D = 9
275 // - FT_BareBorderVolume = 25
276 // - FT_BareBorderFace = 26
277 // - FT_OverConstrainedVolume = 27
278 // - FT_OverConstrainedFace = 28
279 // v 6.5.0: FT_Undefined == 43, new items:
280 // - FT_EqualNodes = 14
281 // - FT_EqualEdges = 15
282 // - FT_EqualFaces = 16
283 // - FT_EqualVolumes = 17
284 // v 6.6.0: FT_Undefined == 44, new items:
285 // - FT_BallDiameter = 37
286 // v 6.7.1: FT_Undefined == 45, new items:
287 // - FT_EntityType = 36
288 // v 7.3.0: FT_Undefined == 46, new items:
289 // - FT_ConnectedElements = 39
291 // It's necessary to continue recording this history and to fill
292 // undef2newItems (see below) accordingly.
294 typedef map< int, vector< int > > TUndef2newItems;
295 static TUndef2newItems undef2newItems;
296 if ( undef2newItems.empty() )
298 undef2newItems[ 26 ].push_back( 7 );
299 undef2newItems[ 27 ].push_back( 17 );
300 { int items[] = { 10, 11, 23, 24, 25 };
301 undef2newItems[ 32 ].assign( items, items+5 ); }
302 undef2newItems[ 33 ].push_back( 26 );
303 { int items[] = { 8, 9, 25, 26, 27, 28 };
304 undef2newItems[ 39 ].assign( items, items+6 ); }
305 { int items[] = { 14, 15, 16, 17 };
306 undef2newItems[ 43 ].assign( items, items+4 ); }
307 undef2newItems[ 44 ].push_back( 37 );
308 undef2newItems[ 45 ].push_back( 36 );
309 undef2newItems[ 46 ].push_back( 39 );
312 int iType = Type.IntegerValue();
313 int iCompare = Compare.IntegerValue();
314 int iUnaryOp = UnaryOp.IntegerValue();
315 int iBinaryOp = BinaryOp.IntegerValue();
317 // find out integer value of FT_Undefined at the moment of dump
318 int oldUndefined = iBinaryOp;
319 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
322 // apply history to args
323 TUndef2newItems::const_iterator undef_items =
324 undef2newItems.upper_bound( oldUndefined );
325 if ( undef_items != undef2newItems.end() )
327 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
328 for ( ; undef_items != undef2newItems.end(); ++undef_items )
330 const vector< int > & addedItems = undef_items->second;
331 for ( size_t i = 0; i < addedItems.size(); ++i )
332 for ( int iArg = 0; iArg < 4; ++iArg )
334 int& arg = *pArg[iArg];
335 if ( arg >= addedItems[i] )
339 Type = TCollection_AsciiString( iType );
340 Compare = TCollection_AsciiString( iCompare );
341 UnaryOp = TCollection_AsciiString( iUnaryOp );
342 BinaryOp = TCollection_AsciiString( iBinaryOp );
346 //================================================================================
348 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
349 * arguments of a given command by a list "[x,y,z]" if the list is accesible
352 //================================================================================
354 void StructToList( Handle( _pyCommand)& theCommand )
356 static TStringSet methodsAcceptingList;
357 if ( methodsAcceptingList.empty() ) {
358 const char * methodNames[] = {
359 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
360 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
361 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
362 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
363 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
364 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
365 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
366 "Translate","TranslateMakeGroups","TranslateMakeMesh",
367 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh"
368 ,"" }; // <- mark of the end
369 methodsAcceptingList.Insert( methodNames );
371 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
373 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
375 const _AString & arg = theCommand->GetArg( i );
376 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
377 arg.Search( "SMESH.DirStruct" ) == 1 )
379 Handle(_pyCommand) workCmd = new _pyCommand( arg );
380 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
382 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
384 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
386 _AString newArg = "[ ";
387 newArg += ( workCmd->GetArg( 1 ) + ", " +
388 workCmd->GetArg( 2 ) + ", " +
389 workCmd->GetArg( 3 ) + " ]");
390 theCommand->SetArg( i, newArg );
396 //================================================================================
398 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
399 * a list "[id1,id2]" if the list is an accesible type of argument.
401 //================================================================================
403 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
405 static TStringSet methodsAcceptingList;
406 if ( methodsAcceptingList.empty() ) {
407 const char * methodNames[] = {
408 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
409 "ExportCGNS","ExportGMF",
410 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
411 "ScaleMakeGroups","Scale","ScaleMakeMesh",
412 "FindCoincidentNodesOnPartBut","DoubleElements"
413 ,"" }; // <- mark of the end
414 methodsAcceptingList.Insert( methodNames );
416 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
418 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
420 _pyCommand argCmd( theCommand->GetArg( i ));
421 if ( argCmd.GetMethod() == "GetIDSource" &&
422 argCmd.GetNbArgs() == 2 )
424 theCommand->SetArg( i, argCmd.GetArg( 1 ));
431 //================================================================================
433 * \brief Convert a python script using commands of smeshBuilder.py
434 * \param theScript - Input script
435 * \param theEntry2AccessorMethod - returns method names to access to
436 * objects wrapped with python class
437 * \param theObjectNames - names of objects
438 * \param theRemovedObjIDs - entries of objects whose created commands were removed
439 * \param theHistoricalDump - true means to keep all commands, false means
440 * to exclude commands relating to objects removed from study
441 * \retval TCollection_AsciiString - Convertion result
443 //================================================================================
445 TCollection_AsciiString
446 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
447 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
448 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
449 std::set< TCollection_AsciiString >& theRemovedObjIDs,
450 SALOMEDS::Study_ptr& theStudy,
451 const bool theToKeepAllCommands)
453 theGen = new _pyGen( theEntry2AccessorMethod,
457 theToKeepAllCommands );
459 // split theScript into separate commands
461 SMESH_NoteBook * aNoteBook = new SMESH_NoteBook();
463 int from = 1, end = theScript.Length(), to;
464 while ( from < end && ( to = theScript.Location( "\n", from, end )))
467 // cut out and store a command
468 aNoteBook->AddCommand( theScript.SubString( from, to - 1 ));
472 aNoteBook->ReplaceVariables();
474 TCollection_AsciiString aNoteScript = aNoteBook->GetResultScript();
478 // split theScript into separate commands
479 from = 1, end = aNoteScript.Length();
480 while ( from < end && ( to = aNoteScript.Location( "\n", from, end )))
483 // cut out and store a command
484 theGen->AddCommand( aNoteScript.SubString( from, to - 1 ));
490 #ifdef DUMP_CONVERSION
491 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
494 // clean commmands of removed objects depending on myIsPublished flag
495 theGen->ClearCommands();
497 // reorder commands after conversion
498 list< Handle(_pyCommand) >::iterator cmd;
501 orderChanges = false;
502 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
503 if ( (*cmd)->SetDependentCmdsAfter() )
505 } while ( orderChanges );
507 // concat commands back into a script
508 TCollection_AsciiString aScript, aPrevCmd;
509 set<_pyID> createdObjects;
510 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
512 #ifdef DUMP_CONVERSION
513 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
515 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
516 CheckObjectPresence( *cmd, createdObjects );
517 aPrevCmd = (*cmd)->GetString();
530 //================================================================================
532 * \brief _pyGen constructor
534 //================================================================================
536 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
537 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
538 std::set< TCollection_AsciiString >& theRemovedObjIDs,
539 SALOMEDS::Study_ptr& theStudy,
540 const bool theToKeepAllCommands)
541 : _pyObject( new _pyCommand( "", 0 )),
543 myID2AccessorMethod( theEntry2AccessorMethod ),
544 myObjectNames( theObjectNames ),
545 myRemovedObjIDs( theRemovedObjIDs ),
547 myToKeepAllCommands( theToKeepAllCommands ),
548 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
549 myGeomIDNb(0), myGeomIDIndex(-1)
551 // make that GetID() to return TPythonDump::SMESHGenName()
552 GetCreationCmd()->Clear();
553 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
554 GetCreationCmd()->GetString() += "=";
556 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
557 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
561 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
562 if ( geomComp->_is_nil() ) return;
563 CORBA::String_var entry = geomComp->GetID();
566 // find a SMESH entry
568 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
569 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
570 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
573 // find 1st difference between smeshID and geomID
574 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
575 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
576 if ( geomID.Value( i ) != smeshID.Value( i ))
578 myGeomIDNb = geomID.Value( i );
584 //================================================================================
586 * \brief name of SMESH_Gen in smeshBuilder.py
588 //================================================================================
590 const char* _pyGen::AccessorMethod() const
592 return SMESH_2smeshpy::GenName();
595 //================================================================================
597 * \brief Convert a command using a specific converter
598 * \param theCommand - the command to convert
600 //================================================================================
602 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
604 // store theCommand in the sequence
605 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
607 Handle(_pyCommand) aCommand = myCommands.back();
608 #ifdef DUMP_CONVERSION
609 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
612 const _pyID& objID = aCommand->GetObject();
614 if ( objID.IsEmpty() )
617 // Prevent moving a command creating a sub-mesh to the end of the script
618 // if the sub-mesh is used in theCommand as argument
619 if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
621 PlaceSubmeshAfterItsCreation( aCommand );
624 // Method( SMESH.PointStruct(x,y,z) -> Method( [x,y,z]
625 StructToList( aCommand );
627 // Find an object to process theCommand
630 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
632 this->Process( aCommand );
633 addFilterUser( aCommand, theGen ); // protect filters from clearing
637 // SMESH_Mesh method?
638 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
639 if ( id_mesh != myMeshes.end() )
641 //id_mesh->second->AddProcessedCmd( aCommand );
643 // check for mesh editor object
644 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
645 _pyID editorID = aCommand->GetResultValue();
646 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
647 myMeshEditors.insert( make_pair( editorID, editor ));
650 // check for SubMesh objects
651 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
652 _pyID subMeshID = aCommand->GetResultValue();
653 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
654 myObjects.insert( make_pair( subMeshID, subMesh ));
657 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
658 GetIDSourceToList( aCommand );
660 addFilterUser( aCommand, theGen ); // protect filters from clearing
662 id_mesh->second->Process( aCommand );
663 id_mesh->second->AddProcessedCmd( aCommand );
667 // SMESH_MeshEditor method?
668 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
669 if ( id_editor != myMeshEditors.end() )
671 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
672 GetIDSourceToList( aCommand );
674 addFilterUser( aCommand, theGen ); // protect filters from clearing
676 const TCollection_AsciiString& method = aCommand->GetMethod();
678 // some commands of SMESH_MeshEditor create meshes and groups
679 _pyID meshID, groups;
680 if ( method.Search("MakeMesh") != -1 )
681 meshID = aCommand->GetResultValue();
682 else if ( method == "MakeBoundaryMesh")
683 meshID = aCommand->GetResultValue(1);
684 else if ( method == "MakeBoundaryElements")
685 meshID = aCommand->GetResultValue(2);
687 if ( method.Search("MakeGroups") != -1 ||
688 method == "ExtrusionAlongPathX" ||
689 method == "ExtrusionAlongPathObjX" ||
690 method == "DoubleNodeGroupNew" ||
691 method == "DoubleNodeGroupsNew" ||
692 method == "DoubleNodeElemGroupNew" ||
693 method == "DoubleNodeElemGroupsNew"||
694 method == "DoubleNodeElemGroup2New"||
695 method == "DoubleNodeElemGroups2New"
697 groups = aCommand->GetResultValue();
698 else if ( method == "MakeBoundaryMesh" )
699 groups = aCommand->GetResultValue(2);
700 else if ( method == "MakeBoundaryElements")
701 groups = aCommand->GetResultValue(3);
702 else if ( method == "Create0DElementsOnAllNodes" &&
703 aCommand->GetArg(2).Length() > 2 ) // group name != ''
704 groups = aCommand->GetResultValue();
706 id_editor->second->Process( aCommand );
707 id_editor->second->AddProcessedCmd( aCommand );
710 if ( !meshID.IsEmpty() &&
711 !myMeshes.count( meshID ) &&
712 aCommand->IsStudyEntry( meshID ))
714 TCollection_AsciiString processedCommand = aCommand->GetString();
715 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
716 myMeshes.insert( make_pair( meshID, mesh ));
718 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
721 if ( !groups.IsEmpty() )
723 if ( !aCommand->IsStudyEntry( meshID ))
724 meshID = id_editor->second->GetMesh();
725 Handle(_pyMesh) mesh = myMeshes[ meshID ];
727 list< _pyID > idList = aCommand->GetStudyEntries( groups );
728 list< _pyID >::iterator grID = idList.begin();
729 for ( ; grID != idList.end(); ++grID )
730 if ( !myObjects.count( *grID ))
732 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
734 if ( !mesh.IsNull() ) mesh->AddGroup( group );
738 } // SMESH_MeshEditor methods
740 // SMESH_Hypothesis method?
741 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
742 for ( ; hyp != myHypos.end(); ++hyp )
743 if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
744 (*hyp)->Process( aCommand );
745 (*hyp)->AddProcessedCmd( aCommand );
749 // aFilterManager.CreateFilter() ?
750 if ( aCommand->GetMethod() == "CreateFilter" )
752 // Set a more human readable name to a filter
753 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
754 _pyID newID, filterID = aCommand->GetResultValue();
755 int pos = filterID.Search( "0x" );
757 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
759 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
763 // other object method?
764 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
765 if ( id_obj != myObjects.end() ) {
766 id_obj->second->Process( aCommand );
767 id_obj->second->AddProcessedCmd( aCommand );
771 // Add access to a wrapped mesh
772 AddMeshAccessorMethod( aCommand );
774 // Add access to a wrapped algorithm
775 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
777 // PAL12227. PythonDump was not updated at proper time; result is
778 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
779 // TypeError: __init__() takes exactly 11 arguments (10 given)
780 const char wrongCommand[] = "SMESH.Filter.Criterion(";
781 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
783 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
784 // there must be 10 arguments, 5-th arg ThresholdID is missing,
785 const int wrongNbArgs = 9, missingArg = 5;
786 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
788 for ( int i = wrongNbArgs; i > missingArg; --i )
789 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
790 tmpCmd.SetArg( missingArg, "''");
791 aCommand->GetString().Trunc( beg - 1 );
792 aCommand->GetString() += tmpCmd.GetString();
795 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
797 // instead of "SMESH.Filter.Criterion(
798 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
799 // 1 2 3 4 5 6 7 8 9 10
800 // in order to avoid the problem of type mismatch of long and FunctorType
801 const TCollection_AsciiString
802 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
803 TCollection_AsciiString
804 Type = aCommand->GetArg(1), // long
805 Compare = aCommand->GetArg(2), // long
806 Threshold = aCommand->GetArg(3), // double
807 ThresholdStr = aCommand->GetArg(4), // string
808 ThresholdID = aCommand->GetArg(5), // string
809 UnaryOp = aCommand->GetArg(6), // long
810 BinaryOp = aCommand->GetArg(7), // long
811 Tolerance = aCommand->GetArg(8), // double
812 TypeOfElement = aCommand->GetArg(9), // ElementType
813 Precision = aCommand->GetArg(10); // long
814 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
815 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
816 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
817 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
818 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
820 if ( Compare == "SMESH.FT_EqualTo" )
823 aCommand->RemoveArgs();
824 aCommand->SetObject( SMESH_2smeshpy::GenName() );
825 aCommand->SetMethod( "GetCriterion" );
827 aCommand->SetArg( 1, TypeOfElement );
828 aCommand->SetArg( 2, Type );
829 aCommand->SetArg( 3, Compare );
831 if ( Threshold.IsIntegerValue() )
833 int iGeom = Threshold.IntegerValue();
834 if ( Type == "SMESH.FT_ElemGeomType" )
836 // set SMESH.GeometryType instead of a numerical Threshold
837 const char* types[SMESH::Geom_BALL+1] = {
838 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
839 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
840 "Geom_POLYHEDRA", "Geom_BALL" };
841 if ( -1 < iGeom && iGeom < SMESH::Geom_POLYHEDRA+1 )
842 Threshold = SMESH + types[ iGeom ];
844 if (Type == "SMESH.FT_EntityType")
846 // set SMESH.EntityType instead of a numerical Threshold
847 const char* types[SMESH::Entity_Ball+1] = {
848 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
849 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
850 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
851 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
852 "Entity_Pyramid", "Entity_Quad_Pyramid",
853 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
854 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
855 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
856 if ( -1 < iGeom && iGeom < SMESH::Entity_Quad_Polyhedra+1 )
857 Threshold = SMESH + types[ iGeom ];
860 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
861 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
862 else if ( ThresholdStr.Length() != 2 )
863 aCommand->SetArg( 4, ThresholdStr );
864 else if ( ThresholdID.Length() != 2 )
865 aCommand->SetArg( 4, ThresholdID );
867 aCommand->SetArg( 4, Threshold );
868 // find the last not default arg
870 if ( Tolerance == dfltTol ) {
872 if ( BinaryOp == dfltFunctor ) {
874 if ( UnaryOp == dfltFunctor )
878 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
879 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
880 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
881 if ( Precision != dfltPreci )
883 TCollection_AsciiString crit = aCommand->GetResultValue();
884 aCommand->GetString() += "; ";
885 aCommand->GetString() += crit + ".Precision = " + Precision;
891 //================================================================================
893 * \brief Convert the command or remember it for later conversion
894 * \param theCommand - The python command calling a method of SMESH_Gen
896 //================================================================================
898 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
900 // there are methods to convert:
901 // CreateMesh( shape )
902 // Concatenate( [mesh1, ...], ... )
903 // CreateHypothesis( theHypType, theLibName )
904 // Compute( mesh, geom )
905 // Evaluate( mesh, geom )
907 TCollection_AsciiString method = theCommand->GetMethod();
909 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
911 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
912 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
915 if ( method == "CreateMeshesFromUNV" ||
916 method == "CreateMeshesFromSTL" ||
917 method == "CopyMesh" ) // command result is a mesh
919 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
920 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
923 if( method == "CreateMeshesFromMED" ||
924 method == "CreateMeshesFromSAUV"||
925 method == "CreateMeshesFromCGNS" ||
926 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
928 for ( int ind = 0; ind < theCommand->GetNbResultValues(); ind++ )
930 _pyID meshID = theCommand->GetResultValue(ind+1);
931 if ( !theCommand->IsStudyEntry( meshID ) ) continue;
932 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind+1));
933 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
935 if ( method == "CreateMeshesFromGMF" )
937 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
938 // CreateMeshesFromGMF( theFileName )
939 _AString file = theCommand->GetArg(1);
940 theCommand->RemoveArgs();
941 theCommand->SetArg( 1, file );
945 // CreateHypothesis()
946 if ( method == "CreateHypothesis" )
948 // issue 199929, remove standard library name (default parameter)
949 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
950 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
951 // keep first argument
952 TCollection_AsciiString arg = theCommand->GetArg( 1 );
953 theCommand->RemoveArgs();
954 theCommand->SetArg( 1, arg );
957 myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
961 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
962 if ( method == "Compute" )
964 const _pyID& meshID = theCommand->GetArg( 1 );
965 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
966 if ( id_mesh != myMeshes.end() ) {
967 theCommand->SetObject( meshID );
968 theCommand->RemoveArgs();
969 id_mesh->second->Process( theCommand );
970 id_mesh->second->AddProcessedCmd( theCommand );
975 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
976 if ( method == "Evaluate" )
978 const _pyID& meshID = theCommand->GetArg( 1 );
979 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
980 if ( id_mesh != myMeshes.end() ) {
981 theCommand->SetObject( meshID );
982 _pyID geom = theCommand->GetArg( 2 );
983 theCommand->RemoveArgs();
984 theCommand->SetArg( 1, geom );
985 id_mesh->second->AddProcessedCmd( theCommand );
990 // objects erasing creation command if no more its commands invoked:
991 // SMESH_Pattern, FilterManager
992 if ( method == "GetPattern" ||
993 method == "CreateFilterManager" ||
994 method == "CreateMeasurements" ) {
995 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
996 if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
997 theCommand->Clear(); // already created
999 // Concatenate( [mesh1, ...], ... )
1000 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1002 if ( method == "ConcatenateWithGroups" ) {
1003 theCommand->SetMethod( "Concatenate" );
1004 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1006 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1007 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
1008 AddMeshAccessorMethod( theCommand );
1010 else if ( method == "SetName" ) // SetName(obj,name)
1012 // store theCommand as one of object commands to erase it along with the object
1013 const _pyID& objID = theCommand->GetArg( 1 );
1014 Handle(_pyObject) obj = FindObject( objID );
1015 if ( !obj.IsNull() )
1016 obj->AddProcessedCmd( theCommand );
1019 // Replace name of SMESH_Gen
1021 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1022 static TStringSet smeshpyMethods;
1023 if ( smeshpyMethods.empty() ) {
1024 const char * names[] =
1025 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1026 "GetPattern","GetSubShapesId",
1027 "" }; // <- mark of array end
1028 smeshpyMethods.Insert( names );
1030 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1031 // smeshgen.Method() --> smesh.Method()
1032 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1034 // smeshgen.Method() --> smesh.Method()
1035 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1038 //================================================================================
1040 * \brief Convert the remembered commands
1042 //================================================================================
1044 void _pyGen::Flush()
1046 // create an empty command
1047 myLastCommand = new _pyCommand();
1049 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1050 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1051 list< Handle(_pyHypothesis) >::iterator hyp;
1053 if ( IsToKeepAllCommands() ) // historical dump
1055 // set myIsPublished = true to all objects
1056 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1057 id_mesh->second->SetRemovedFromStudy( false );
1058 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1059 (*hyp)->SetRemovedFromStudy( false );
1060 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1061 id_obj->second->SetRemovedFromStudy( false );
1065 // let hypotheses find referred objects in order to prevent clearing
1066 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1067 list< Handle(_pyMesh) > fatherMeshes;
1068 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1069 if ( !hyp->IsNull() )
1070 (*hyp)->GetReferredMeshesAndGeom( fatherMeshes );
1072 // set myIsPublished = false to all objects depending on
1073 // meshes built on a removed geometry
1074 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1075 if ( id_mesh->second->IsNotGeomPublished() )
1076 id_mesh->second->SetRemovedFromStudy( true );
1079 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1080 if ( ! id_mesh->second.IsNull() )
1081 id_mesh->second->Flush();
1084 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1085 if ( !hyp->IsNull() ) {
1087 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1088 if ( !(*hyp)->IsWrapped() )
1089 (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1092 // Flush other objects
1093 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1094 if ( ! id_obj->second.IsNull() )
1095 id_obj->second->Flush();
1097 myLastCommand->SetOrderNb( ++myNbCommands );
1098 myCommands.push_back( myLastCommand );
1101 //================================================================================
1103 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1104 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1106 //================================================================================
1108 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1110 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1111 for ( ; id_obj != myObjects.end(); ++id_obj )
1113 if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1114 for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1116 const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1117 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1119 list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1120 list< _pyID >::iterator id = idList.begin();
1121 for ( ; id != idList.end(); ++id )
1122 if ( id_obj->first == *id )
1123 // _pySubMesh::Process() does what we need
1124 Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1129 //================================================================================
1131 * \brief Clean commmands of removed objects depending on myIsPublished flag
1133 //================================================================================
1135 void _pyGen::ClearCommands()
1137 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1138 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1139 id_mesh->second->ClearCommands();
1141 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1142 for ( ; hyp != myHypos.end(); ++hyp )
1143 if ( !hyp->IsNull() )
1144 (*hyp)->ClearCommands();
1146 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1147 for ( ; id_obj != myObjects.end(); ++id_obj )
1148 id_obj->second->ClearCommands();
1151 //================================================================================
1153 * \brief Release mutual handles of objects
1155 //================================================================================
1159 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1160 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1161 id_mesh->second->Free();
1164 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1165 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1166 id_ed->second->Free();
1167 myMeshEditors.clear();
1169 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1170 for ( ; id_obj != myObjects.end(); ++id_obj )
1171 id_obj->second->Free();
1174 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1175 for ( ; hyp != myHypos.end(); ++hyp )
1176 if ( !hyp->IsNull() )
1180 myFile2ExportedMesh.clear();
1183 //================================================================================
1185 * \brief Add access method to mesh that is an argument
1186 * \param theCmd - command to add access method
1187 * \retval bool - true if added
1189 //================================================================================
1191 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1194 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1195 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1196 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1202 //================================================================================
1204 * \brief Add access method to algo that is an object or an argument
1205 * \param theCmd - command to add access method
1206 * \retval bool - true if added
1208 //================================================================================
1210 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1213 list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
1214 for ( ; hyp != myHypos.end(); ++hyp ) {
1215 if ( (*hyp)->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1216 theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
1222 //================================================================================
1224 * \brief Find hypothesis by ID (entry)
1225 * \param theHypID - The hypothesis ID
1226 * \retval Handle(_pyHypothesis) - The found hypothesis
1228 //================================================================================
1230 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1232 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1233 for ( ; hyp != myHypos.end(); ++hyp )
1234 if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
1236 return Handle(_pyHypothesis)();
1239 //================================================================================
1241 * \brief Find algorithm the created algorithm
1242 * \param theGeom - The shape ID the algorithm was created on
1243 * \param theMesh - The mesh ID that created the algorithm
1244 * \param dim - The algo dimension
1245 * \retval Handle(_pyHypothesis) - The found algo
1247 //================================================================================
1249 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1250 const Handle(_pyHypothesis)& theHypothesis )
1252 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1253 for ( ; hyp != myHypos.end(); ++hyp )
1254 if ( !hyp->IsNull() &&
1256 theHypothesis->CanBeCreatedBy( (*hyp)->GetAlgoType() ) &&
1257 (*hyp)->GetGeom() == theGeom &&
1258 (*hyp)->GetMesh() == theMesh )
1263 //================================================================================
1265 * \brief Find subMesh by ID (entry)
1266 * \param theSubMeshID - The subMesh ID
1267 * \retval Handle(_pySubMesh) - The found subMesh
1269 //================================================================================
1271 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1273 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1274 if ( id_subMesh != myObjects.end() )
1275 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1276 return Handle(_pySubMesh)();
1280 //================================================================================
1282 * \brief Change order of commands in the script
1283 * \param theCmd1 - One command
1284 * \param theCmd2 - Another command
1286 //================================================================================
1288 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1290 list< Handle(_pyCommand) >::iterator pos1, pos2;
1291 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1292 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1293 myCommands.insert( pos1, theCmd2 );
1294 myCommands.insert( pos2, theCmd1 );
1295 myCommands.erase( pos1 );
1296 myCommands.erase( pos2 );
1298 int nb1 = theCmd1->GetOrderNb();
1299 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1300 theCmd2->SetOrderNb( nb1 );
1301 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1302 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1305 //================================================================================
1307 * \brief Set one command after the other
1308 * \param theCmd - Command to move
1309 * \param theAfterCmd - Command ater which to insert the first one
1311 //================================================================================
1313 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1315 setNeighbourCommand( theCmd, theAfterCmd, true );
1318 //================================================================================
1320 * \brief Set one command before the other
1321 * \param theCmd - Command to move
1322 * \param theBeforeCmd - Command before which to insert the first one
1324 //================================================================================
1326 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1328 setNeighbourCommand( theCmd, theBeforeCmd, false );
1331 //================================================================================
1333 * \brief Set one command before or after the other
1334 * \param theCmd - Command to move
1335 * \param theOtherCmd - Command ater or before which to insert the first one
1337 //================================================================================
1339 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1340 Handle(_pyCommand)& theOtherCmd,
1341 const bool theIsAfter )
1343 list< Handle(_pyCommand) >::iterator pos;
1344 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1345 myCommands.erase( pos );
1346 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1347 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1350 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1351 (*pos)->SetOrderNb( i++ );
1354 //================================================================================
1356 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1358 //================================================================================
1360 void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1362 const char filterPrefix[] = "aFilter0x";
1363 if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1366 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1368 const _AString & arg = theCommand->GetArg( i );
1369 // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1370 if ( arg.Search( filterPrefix ) != 1 )
1373 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1374 if ( !filter.IsNull() )
1376 filter->AddUser( user );
1377 if ( !filter->GetNewID().IsEmpty() )
1378 theCommand->SetArg( i, filter->GetNewID() );
1383 //================================================================================
1385 * \brief Set command be last in list of commands
1386 * \param theCmd - Command to be last
1388 //================================================================================
1390 Handle(_pyCommand)& _pyGen::GetLastCommand()
1392 return myLastCommand;
1395 //================================================================================
1397 * \brief Set method to access to object wrapped with python class
1398 * \param theID - The wrapped object entry
1399 * \param theMethod - The accessor method
1401 //================================================================================
1403 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1405 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1408 //================================================================================
1410 * \brief Generated new ID for object and assign with existing name
1411 * \param theID - ID of existing object
1413 //================================================================================
1415 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1420 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1422 while ( myObjectNames.IsBound( aNewID ) );
1424 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1425 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1426 : _pyID( "A" ) + aNewID );
1430 //================================================================================
1432 * \brief Stores theObj in myObjects
1434 //================================================================================
1436 void _pyGen::AddObject( Handle(_pyObject)& theObj )
1438 if ( theObj.IsNull() ) return;
1440 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1441 myMeshes.insert( make_pair( theObj->GetID(), Handle(_pyMesh)::DownCast( theObj )));
1443 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1444 myMeshEditors.insert( make_pair( theObj->GetID(), Handle(_pyMeshEditor)::DownCast( theObj )));
1447 myObjects.insert( make_pair( theObj->GetID(), theObj ));
1450 //================================================================================
1452 * \brief Re-register an object with other ID to make it Process() commands of
1453 * other object having this ID
1455 //================================================================================
1457 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1459 if ( theObj.IsNull() ) return;
1461 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1462 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1464 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1465 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1468 myObjects.insert( make_pair( theID, theObj ));
1471 //================================================================================
1473 * \brief Finds a _pyObject by ID
1475 //================================================================================
1477 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1480 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1481 if ( id_obj != myObjects.end() )
1482 return id_obj->second;
1485 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1486 if ( id_obj != myMeshes.end() )
1487 return id_obj->second;
1490 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1491 // if ( id_obj != myMeshEditors.end() )
1492 // return id_obj->second;
1494 return Handle(_pyObject)();
1497 //================================================================================
1499 * \brief Check if a study entry is under GEOM component
1501 //================================================================================
1503 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1507 return ( myGeomIDIndex <= theObjID.Length() &&
1508 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1509 _pyCommand::IsStudyEntry( theObjID ));
1514 //================================================================================
1516 * \brief Returns true if an object is not present in a study
1518 //================================================================================
1520 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1522 if ( theObjID.IsEmpty() ) return false;
1524 if ( myObjectNames.IsBound( theObjID ))
1525 return false; // SMESH object is in study
1527 // either the SMESH object is not in study or it is a GEOM object
1528 if ( IsGeomObject( theObjID ))
1530 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1531 if ( so->_is_nil() ) return true;
1532 CORBA::Object_var obj = so->GetObject();
1533 return CORBA::is_nil( obj );
1535 return true; // SMESH object not in study
1538 //================================================================================
1540 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1541 * this object is not dumped
1542 * \param [in] theObjID - entry of the object whose creation command was eliminated
1544 //================================================================================
1546 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1548 myRemovedObjIDs.insert( theObjID );
1551 //================================================================================
1553 * \brief Return reader of hypotheses of plugins
1555 //================================================================================
1557 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1559 if (myHypReader.IsNull() )
1560 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1566 //================================================================================
1568 * \brief Mesh created by SMESH_Gen
1570 //================================================================================
1572 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1573 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1575 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1576 myGeomNotInStudy = true;
1578 // convert my creation command --> smeshpy.Mesh(...)
1579 Handle(_pyCommand) creationCmd = GetCreationCmd();
1580 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1581 creationCmd->SetMethod( "Mesh" );
1582 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1585 //================================================================================
1587 * \brief Mesh created by SMESH_MeshEditor
1589 //================================================================================
1591 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1592 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1594 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1596 // this mesh depends on the exported mesh
1597 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1598 if ( !file.IsEmpty() )
1600 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1601 addFatherMesh( exportData.myMesh );
1602 if ( !exportData.myLastComputeCmd.IsNull() )
1604 // restore cleared Compute() by which the exported mesh was generated
1605 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1606 // protect that Compute() cmd from clearing
1607 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1608 exportData.myMesh->myLastComputeCmd.Nullify();
1612 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1614 // this mesh depends on concatenated meshes
1615 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1616 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1617 list< _pyID >::iterator meshID = idList.begin();
1618 for ( ; meshID != idList.end(); ++meshID )
1619 addFatherMesh( *meshID );
1621 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1623 // this mesh depends on a copied IdSource
1624 const _pyID& objID = theCreationCmd->GetArg( 1 );
1625 addFatherMesh( objID );
1627 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1628 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1629 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1631 // this mesh depends on a source mesh
1632 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1633 const _pyID& meshID = theCreationCmd->GetObject();
1634 addFatherMesh( meshID );
1637 // convert my creation command
1638 Handle(_pyCommand) creationCmd = GetCreationCmd();
1639 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1640 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1643 //================================================================================
1645 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1646 * \param theCommand - Engine method called for this mesh
1648 //================================================================================
1650 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1652 // some methods of SMESH_Mesh interface needs special conversion
1653 // to methods of Mesh python class
1655 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1656 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1657 // 2. AddHypothesis(geom, hyp)
1658 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1659 // 3. CreateGroupFromGEOM(type, name, grp)
1660 // --> in Mesh.Group(grp, name="")
1661 // 4. ExportToMED(f, auto_groups, version)
1662 // --> in Mesh.ExportMED( f, auto_groups, version )
1665 const TCollection_AsciiString& method = theCommand->GetMethod();
1666 // ----------------------------------------------------------------------
1667 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1669 if ( !theGen->IsToKeepAllCommands() ) // !historical
1671 list< Handle(_pyHypothesis) >::iterator hyp;
1672 if ( !myLastComputeCmd.IsNull() )
1674 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1675 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1677 myLastComputeCmd->Clear();
1679 myLastComputeCmd = theCommand;
1681 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1682 (*hyp)->MeshComputed( myLastComputeCmd );
1686 // ----------------------------------------------------------------------
1687 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1689 if ( !theGen->IsToKeepAllCommands() ) // !historical
1692 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1693 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1694 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1696 if ( !myLastComputeCmd.IsNull() )
1698 list< Handle(_pyHypothesis) >::iterator hyp;
1699 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1700 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1702 myLastComputeCmd->Clear();
1705 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1706 for ( ; e != myEditors.end(); ++e )
1708 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1709 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1710 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1711 if ( !(*cmd)->IsEmpty() )
1713 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1717 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1720 // ----------------------------------------------------------------------
1721 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1722 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1723 if ( !subMesh.IsNull() ) {
1724 subMesh->SetCreator( this );
1725 mySubmeshes.push_back( subMesh );
1728 // ----------------------------------------------------------------------
1729 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1730 myAddHypCmds.push_back( theCommand );
1732 const _pyID& hypID = theCommand->GetArg( 2 );
1733 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1734 if ( !hyp.IsNull() ) {
1735 myHypos.push_back( hyp );
1736 if ( hyp->GetMesh().IsEmpty() )
1737 hyp->SetMesh( this->GetID() );
1740 // ----------------------------------------------------------------------
1741 else if ( method == "CreateGroup" ||
1742 method == "CreateGroupFromGEOM" ||
1743 method == "CreateGroupFromFilter" )
1745 Handle(_pyGroup) group = new _pyGroup( theCommand );
1746 myGroups.push_back( group );
1747 theGen->AddObject( group );
1749 // ----------------------------------------------------------------------
1750 // update list of groups
1751 else if ( method == "GetGroups" )
1753 bool allGroupsRemoved = true;
1754 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1755 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1756 list< _pyID >::iterator grID = idList.begin();
1757 const int nbGroupsBefore = myGroups.size();
1758 Handle(_pyObject) obj;
1759 for ( ; grID != idList.end(); ++grID )
1761 obj = theGen->FindObject( *grID );
1764 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1765 theGen->AddObject( group );
1766 myGroups.push_back( group );
1769 if ( !obj->CanClear() )
1770 allGroupsRemoved = false;
1772 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1773 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1775 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1777 // check if the preceding command is Compute();
1778 // if GetGroups() is just after Compute(), this can mean that the groups
1779 // were created by some algorithm and hence Compute() should not be discarded
1780 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1781 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1782 while ( (*cmd)->GetMethod() == "GetGroups" )
1784 if ( myLastComputeCmd == (*cmd))
1785 // protect last Compute() from clearing by the next Compute()
1786 myLastComputeCmd.Nullify();
1789 // ----------------------------------------------------------------------
1790 // notify a group about full removal
1791 else if ( method == "RemoveGroupWithContents" ||
1792 method == "RemoveGroup")
1794 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1795 const _pyID groupID = theCommand->GetArg( 1 );
1796 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1797 if ( !grp.IsNull() )
1799 if ( method == "RemoveGroupWithContents" )
1800 grp->RemovedWithContents();
1801 // to clear RemoveGroup() if the group creation is cleared
1802 grp->AddProcessedCmd( theCommand );
1806 // ----------------------------------------------------------------------
1807 else if ( theCommand->MethodStartsFrom( "Export" ))
1809 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1810 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1812 theCommand->SetMethod( "ExportMED" );
1813 if ( theCommand->GetNbArgs() == 5 )
1815 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1816 _AString autoDimension = theCommand->GetArg( 5 );
1817 theCommand->SetArg( 5, "None" );
1818 theCommand->SetArg( 6, autoDimension );
1821 else if ( method == "ExportCGNS" )
1822 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1823 _pyID partID = theCommand->GetArg( 1 );
1824 int nbArgs = theCommand->GetNbArgs();
1825 for ( int i = 2; i <= nbArgs; ++i )
1826 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1827 theCommand->SetArg( nbArgs, partID );
1829 else if ( method == "ExportGMF" )
1830 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1831 _pyID partID = theCommand->GetArg( 1 );
1832 _AString file = theCommand->GetArg( 2 );
1833 theCommand->RemoveArgs();
1834 theCommand->SetArg( 1, file );
1835 theCommand->SetArg( 2, partID );
1837 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1838 { // ExportPartTo*(part, ...) -> Export*(..., part)
1840 // remove "PartTo" from the method
1841 TCollection_AsciiString newMethod = method;
1842 newMethod.Remove( 7, 6 );
1843 theCommand->SetMethod( newMethod );
1844 // make the 1st arg be the last one (or last but one for ExportMED())
1845 _pyID partID = theCommand->GetArg( 1 );
1846 int nbArgs = theCommand->GetNbArgs() - (newMethod == "ExportMED");
1847 for ( int i = 2; i <= nbArgs; ++i )
1848 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1849 theCommand->SetArg( nbArgs, partID );
1851 // remember file name
1852 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1853 ExportedMeshData( this, myLastComputeCmd ));
1855 // ----------------------------------------------------------------------
1856 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1858 _pyID hypID = theCommand->GetArg( 2 );
1859 _pyID geomID = theCommand->GetArg( 1 );
1860 bool isLocal = ( geomID != GetGeom() );
1862 // check if this mesh still has corresponding addition command
1863 Handle(_pyCommand) addCmd;
1864 list< Handle(_pyCommand) >::iterator cmd;
1865 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1866 for ( int i = 0; i < 2; ++i )
1868 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1869 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1871 bool sameHyp = true;
1872 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1873 sameHyp = false; // other hyp
1874 if ( (*cmd)->GetNbArgs() == 2 &&
1875 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1876 sameHyp = false; // other geom
1877 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
1878 sameHyp = false; // other geom
1882 cmd = addHypCmds.erase( cmd );
1883 if ( !theGen->IsToKeepAllCommands() ) {
1885 theCommand->Clear();
1894 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1895 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
1896 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1897 _pyID geom = theCommand->GetArg( 1 );
1898 theCommand->RemoveArgs();
1899 theCommand->SetArg( 1, hypID );
1900 if ( geom != GetGeom() )
1901 theCommand->SetArg( 2, geom );
1903 // remove hyp from myHypos
1904 myHypos.remove( hyp );
1906 // check for SubMesh order commands
1907 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
1909 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1910 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1911 // commands are moved at the end of the script
1912 TCollection_AsciiString subIDs =
1913 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
1914 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
1915 list< _pyID >::iterator subID = idList.begin();
1916 for ( ; subID != idList.end(); ++subID )
1918 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
1919 if ( !subMesh.IsNull() )
1920 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
1923 // add accessor method if necessary
1926 if ( NeedMeshAccess( theCommand ))
1927 // apply theCommand to the mesh wrapped by smeshpy mesh
1928 AddMeshAccess( theCommand );
1932 //================================================================================
1934 * \brief Return True if addition of accesor method is needed
1936 //================================================================================
1938 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
1940 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
1941 // so no conversion is needed for them at all:
1942 static TStringSet sameMethods;
1943 if ( sameMethods.empty() ) {
1944 const char * names[] =
1945 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
1946 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
1947 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
1948 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
1949 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
1950 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
1951 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
1952 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
1953 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
1954 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
1955 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
1956 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
1957 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
1958 ,"" }; // <- mark of end
1959 sameMethods.Insert( names );
1962 return !sameMethods.Contains( theCommand->GetMethod() );
1965 //================================================================================
1967 * \brief Convert creation and addition of all algos and hypos
1969 //================================================================================
1971 void _pyMesh::Flush()
1974 // get the meshes this mesh depends on via hypotheses
1975 list< Handle(_pyMesh) > fatherMeshes;
1976 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1977 for ( ; hyp != myHypos.end(); ++hyp )
1978 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
1979 myGeomNotInStudy = true;
1981 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
1982 for ( ; m != fatherMeshes.end(); ++m )
1983 addFatherMesh( *m );
1984 // if ( removedGeom )
1985 // SetRemovedFromStudy(); // as reffered geometry not in study
1987 if ( myGeomNotInStudy )
1990 list < Handle(_pyCommand) >::iterator cmd;
1992 // try to convert algo addition like this:
1993 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
1994 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1996 Handle(_pyCommand) addCmd = *cmd;
1998 _pyID algoID = addCmd->GetArg( 2 );
1999 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2000 if ( algo.IsNull() || !algo->IsAlgo() )
2003 // check and create new algorithm instance if it is already wrapped
2004 if ( algo->IsWrapped() ) {
2005 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2006 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2007 TCollection_AsciiString( " = " ) + theGen->GetID() +
2008 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2009 TCollection_AsciiString( "\" )" );
2011 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2012 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2013 if ( !newAlgo.IsNull() ) {
2014 newAlgo->Assign( algo, this->GetID() );
2015 newAlgo->SetCreationCmd( newCmd );
2017 // set algorithm creation
2018 theGen->SetCommandBefore( newCmd, addCmd );
2019 myHypos.push_back( newAlgo );
2020 if ( !myLastComputeCmd.IsNull() &&
2021 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2022 newAlgo->MeshComputed( myLastComputeCmd );
2027 _pyID geom = addCmd->GetArg( 1 );
2028 bool isLocalAlgo = ( geom != GetGeom() );
2031 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2033 // wrapped algo is created after mesh creation
2034 GetCreationCmd()->AddDependantCmd( addCmd );
2036 if ( isLocalAlgo ) {
2037 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2038 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2039 TCollection_AsciiString( "geom=" ) + geom );
2040 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2041 list < Handle(_pySubMesh) >::iterator smIt;
2042 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2043 Handle(_pySubMesh) subMesh = *smIt;
2044 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2045 if ( geom == subCmd->GetArg( 1 )) {
2046 subCmd->SetObject( algo->GetID() );
2047 subCmd->RemoveArgs();
2048 subMesh->SetCreator( algo );
2053 else // KO - ALGO was already created
2055 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2056 addCmd->RemoveArgs();
2057 addCmd->SetArg( 1, algoID );
2059 addCmd->SetArg( 2, geom );
2060 myNotConvertedAddHypCmds.push_back( addCmd );
2064 // try to convert hypo addition like this:
2065 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2066 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2068 Handle(_pyCommand) addCmd = *cmd;
2069 _pyID hypID = addCmd->GetArg( 2 );
2070 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2071 if ( hyp.IsNull() || hyp->IsAlgo() )
2073 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2075 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2076 _pyID geom = addCmd->GetArg( 1 );
2077 addCmd->RemoveArgs();
2078 addCmd->SetArg( 1, hypID );
2079 if ( geom != GetGeom() )
2080 addCmd->SetArg( 2, geom );
2081 myNotConvertedAddHypCmds.push_back( addCmd );
2085 myAddHypCmds.clear();
2086 mySubmeshes.clear();
2089 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2090 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2094 //================================================================================
2096 * \brief Sets myIsPublished of me and of all objects depending on me.
2098 //================================================================================
2100 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2102 _pyObject::SetRemovedFromStudy(isRemoved);
2104 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2105 for ( ; sm != mySubmeshes.end(); ++sm )
2106 (*sm)->SetRemovedFromStudy(isRemoved);
2108 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2109 for ( ; gr != myGroups.end(); ++gr )
2110 (*gr)->SetRemovedFromStudy(isRemoved);
2112 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2113 for ( ; m != myChildMeshes.end(); ++m )
2114 (*m)->SetRemovedFromStudy(isRemoved);
2116 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2117 for ( ; e != myEditors.end(); ++e )
2118 (*e)->SetRemovedFromStudy(isRemoved);
2121 //================================================================================
2123 * \brief Return true if none of myChildMeshes is in study
2125 //================================================================================
2127 bool _pyMesh::CanClear()
2132 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2133 for ( ; m != myChildMeshes.end(); ++m )
2134 if ( !(*m)->CanClear() )
2140 //================================================================================
2142 * \brief Clear my commands and commands of mesh editor
2144 //================================================================================
2146 void _pyMesh::ClearCommands()
2152 // mark all sub-objects as not removed, except child meshes
2153 list< Handle(_pyMesh) > children;
2154 children.swap( myChildMeshes );
2155 SetRemovedFromStudy( false );
2156 children.swap( myChildMeshes );
2160 _pyObject::ClearCommands();
2162 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2163 for ( ; sm != mySubmeshes.end(); ++sm )
2164 (*sm)->ClearCommands();
2166 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2167 for ( ; gr != myGroups.end(); ++gr )
2168 (*gr)->ClearCommands();
2170 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2171 for ( ; e != myEditors.end(); ++e )
2172 (*e)->ClearCommands();
2175 //================================================================================
2177 * \brief Add a father mesh by ID
2179 //================================================================================
2181 void _pyMesh::addFatherMesh( const _pyID& meshID )
2183 if ( !meshID.IsEmpty() && meshID != GetID() )
2184 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2187 //================================================================================
2189 * \brief Add a father mesh
2191 //================================================================================
2193 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2195 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2197 //myFatherMeshes.push_back( mesh );
2198 mesh->myChildMeshes.push_back( this );
2200 // protect last Compute() from clearing by the next Compute()
2201 mesh->myLastComputeCmd.Nullify();
2205 //================================================================================
2207 * \brief MeshEditor convert its commands to ones of mesh
2209 //================================================================================
2211 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2212 _pyObject( theCreationCmd )
2214 myMesh = theCreationCmd->GetObject();
2215 myCreationCmdStr = theCreationCmd->GetString();
2216 theCreationCmd->Clear();
2218 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2219 if ( !mesh.IsNull() )
2220 mesh->AddEditor( this );
2223 //================================================================================
2225 * \brief convert its commands to ones of mesh
2227 //================================================================================
2229 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2231 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2232 // commands calling these methods are converted to calls of Mesh methods without
2233 // additional modifs, only object is changed from MeshEditor to Mesh.
2234 static TStringSet sameMethods;
2235 if ( sameMethods.empty() ) {
2236 const char * names[] = {
2237 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2238 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2239 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2240 "MoveNode", "MoveClosestNodeToPoint",
2241 "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2242 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2243 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2244 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2245 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2246 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2247 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2248 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2249 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2250 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2251 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2252 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2253 "GetLastCreatedElems",
2254 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2255 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2256 "MakeBoundaryElements", "SplitVolumesIntoTetra",
2257 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2258 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2259 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2260 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2261 ,"" }; // <- mark of the end
2262 sameMethods.Insert( names );
2265 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2266 TStringMap diffMethods;
2267 if ( diffMethods.empty() ) {
2268 const char * orig2newName[] = {
2269 // original name --------------> new name
2270 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2271 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2272 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2273 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2274 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2275 ""};// <- mark of the end
2276 diffMethods.Insert( orig2newName );
2279 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2280 // only by last two arguments
2281 static TStringSet diffLastTwoArgsMethods;
2282 if (diffLastTwoArgsMethods.empty() ) {
2283 const char * names[] = {
2284 "MirrorMakeGroups","MirrorObjectMakeGroups",
2285 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2286 "RotateMakeGroups","RotateObjectMakeGroups",
2287 ""};// <- mark of the end
2288 diffLastTwoArgsMethods.Insert( names );
2291 // only a method name is to change?
2292 const TCollection_AsciiString & method = theCommand->GetMethod();
2293 bool isPyMeshMethod = sameMethods.Contains( method );
2294 if ( !isPyMeshMethod )
2296 TCollection_AsciiString newMethod = diffMethods.Value( method );
2297 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2298 theCommand->SetMethod( newMethod );
2300 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2301 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2303 isPyMeshMethod = true;
2304 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2305 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2308 if ( !isPyMeshMethod )
2310 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2311 // functions with the flag "theMakeGroups = True" like:
2312 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2313 int pos = method.Search("MakeGroups");
2316 isPyMeshMethod = true;
2317 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2318 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2320 // 1. Remove "MakeGroups" from the Command
2321 TCollection_AsciiString aMethod = theCommand->GetMethod();
2322 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2325 pos = pos-2; //Remove "0D" from the Command too
2326 aMethod.Trunc(pos-1);
2327 theCommand->SetMethod(aMethod);
2329 // 2. And add last "True" argument(s)
2330 while(nbArgsToAdd--)
2331 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2332 if( is0DmethId || is0DmethObj )
2333 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2337 // ExtrusionSweep0D() -> ExtrusionSweep()
2338 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2339 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2340 method == "ExtrusionSweepObject0D" ))
2342 isPyMeshMethod = true;
2343 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2344 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2345 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2348 // DoubleNode...New(...) -> DoubleNode...(...,True)
2349 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2350 method == "DoubleNodeElemGroupsNew" ||
2351 method == "DoubleNodeGroupNew" ||
2352 method == "DoubleNodeGroupsNew" ||
2353 method == "DoubleNodeElemGroup2New" ||
2354 method == "DoubleNodeElemGroups2New"))
2356 isPyMeshMethod = true;
2357 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2358 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2359 if ( excessLen == 3 )
2361 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2363 else if ( theCommand->GetArg(4) == "0" ||
2364 theCommand->GetArg(5) == "0" )
2366 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2367 // Group = DoubleNodeGroup2New(,,,False, True)
2368 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2369 theCommand->SetResultValue( groupID );
2372 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2373 // FindElementsByPoint(x, y, z, elementType, meshPart)
2374 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2376 isPyMeshMethod = true;
2377 theCommand->SetMethod( "FindElementsByPoint" );
2378 // make the 1st arg be the last one
2379 _pyID partID = theCommand->GetArg( 1 );
2380 int nbArgs = theCommand->GetNbArgs();
2381 for ( int i = 2; i <= nbArgs; ++i )
2382 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2383 theCommand->SetArg( nbArgs, partID );
2385 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2386 if ( !isPyMeshMethod && method == "Reorient2D" )
2388 isPyMeshMethod = true;
2389 _AString mesh = theCommand->GetArg( 1 );
2390 _AString dir = theCommand->GetArg( 2 );
2391 _AString face = theCommand->GetArg( 3 );
2392 _AString point = theCommand->GetArg( 4 );
2393 theCommand->RemoveArgs();
2394 theCommand->SetArg( 1, mesh );
2395 theCommand->SetArg( 2, dir );
2396 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2397 theCommand->SetArg( 3, point );
2399 theCommand->SetArg( 3, face );
2402 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2404 isPyMeshMethod = true;
2405 int crit_arg = theCommand->GetNbArgs();
2406 const _AString& crit = theCommand->GetArg(crit_arg);
2407 if (crit.Search("MaxElementLength2D") != -1)
2408 theCommand->SetArg(crit_arg, "");
2411 if ( isPyMeshMethod )
2413 theCommand->SetObject( myMesh );
2417 // editor creation command is needed only if any editor function is called
2418 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2419 if ( !myCreationCmdStr.IsEmpty() ) {
2420 GetCreationCmd()->GetString() = myCreationCmdStr;
2421 myCreationCmdStr.Clear();
2426 //================================================================================
2428 * \brief Return true if my mesh can be removed
2430 //================================================================================
2432 bool _pyMeshEditor::CanClear()
2434 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2435 return mesh.IsNull() ? true : mesh->CanClear();
2438 //================================================================================
2440 * \brief _pyHypothesis constructor
2441 * \param theCreationCmd -
2443 //================================================================================
2445 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2446 _pyObject( theCreationCmd ), myCurCrMethod(0)
2448 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2451 //================================================================================
2453 * \brief Creates algorithm or hypothesis
2454 * \param theCreationCmd - The engine command creating a hypothesis
2455 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2457 //================================================================================
2459 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2461 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2462 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2464 Handle(_pyHypothesis) hyp, algo;
2467 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2468 if ( hypTypeQuoted.IsEmpty() )
2471 TCollection_AsciiString hypType =
2472 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2474 algo = new _pyAlgorithm( theCreationCmd );
2475 hyp = new _pyHypothesis( theCreationCmd );
2477 if ( hypType == "NumberOfSegments" ) {
2478 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2479 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2480 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2481 hyp->AddArgMethod( "SetNumberOfSegments" );
2482 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2483 hyp->AddArgMethod( "SetScaleFactor" );
2484 hyp->AddArgMethod( "SetReversedEdges" );
2485 // same for ""CompositeSegment_1D:
2486 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2487 hyp->AddArgMethod( "SetNumberOfSegments" );
2488 hyp->AddArgMethod( "SetScaleFactor" );
2489 hyp->AddArgMethod( "SetReversedEdges" );
2491 else if ( hypType == "SegmentLengthAroundVertex" ) {
2492 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2493 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2494 hyp->AddArgMethod( "SetLength" );
2495 // same for ""CompositeSegment_1D:
2496 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2497 hyp->AddArgMethod( "SetLength" );
2499 else if ( hypType == "LayerDistribution2D" ) {
2500 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2501 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2503 else if ( hypType == "LayerDistribution" ) {
2504 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2505 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2507 else if ( hypType == "CartesianParameters3D" ) {
2508 hyp = new _pyComplexParamHypo( theCreationCmd );
2509 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2510 for ( int iArg = 0; iArg < 4; ++iArg )
2511 hyp->setCreationArg( iArg+1, "[]");
2515 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2518 return algo->IsValid() ? algo : hyp;
2521 //================================================================================
2523 * \brief Returns true if addition of this hypothesis to a given mesh can be
2524 * wrapped into hypothesis creation
2526 //================================================================================
2528 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2530 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2532 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2533 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2539 //================================================================================
2541 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2542 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2543 * \param theAlgo - The algo that can create this hypo
2544 * \retval bool - false if the command cant be converted
2546 //================================================================================
2548 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2549 const _pyID& theMesh)
2551 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2553 if ( !IsWrappable( theMesh ))
2556 myGeom = theCmd->GetArg( 1 );
2558 Handle(_pyHypothesis) algo;
2560 // find algo created on myGeom in theMesh
2561 algo = theGen->FindAlgo( myGeom, theMesh, this );
2562 if ( algo.IsNull() )
2564 // attach hypothesis creation command to be after algo creation command
2565 // because it can be new created instance of algorithm
2566 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2570 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2571 theCmd->SetResultValue( GetID() );
2572 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2573 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2574 // set args (geom will be set by _pyMesh calling this method)
2575 theCmd->RemoveArgs();
2576 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2577 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2578 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2580 theCmd->SetArg( i+1, "[]");
2582 // set a new creation command
2583 GetCreationCmd()->Clear();
2584 // replace creation command by wrapped instance
2585 // please note, that hypothesis attaches to algo creation command (see upper)
2586 SetCreationCmd( theCmd );
2589 // clear commands setting arg values
2590 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2591 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2594 // set unknown arg commands after hypo creation
2595 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2596 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2597 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2598 afterCmd->AddDependantCmd( *cmd );
2604 //================================================================================
2606 * \brief Remember hypothesis parameter values
2607 * \param theCommand - The called hypothesis method
2609 //================================================================================
2611 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2613 ASSERT( !myIsAlgo );
2614 if ( !theGen->IsToKeepAllCommands() )
2615 rememberCmdOfParameter( theCommand );
2617 bool usedCommand = false;
2618 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2619 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2621 CreationMethod& crMethod = type2meth->second;
2622 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2623 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2625 myArgCommands.push_back( theCommand );
2627 while ( crMethod.myArgs.size() < i+1 )
2628 crMethod.myArgs.push_back( "[]" );
2629 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2634 myUnusedCommands.push_back( theCommand );
2637 //================================================================================
2639 * \brief Finish conversion
2641 //================================================================================
2643 void _pyHypothesis::Flush()
2647 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2648 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2649 // Add access to a wrapped mesh
2650 theGen->AddMeshAccessorMethod( *cmd );
2651 // Add access to a wrapped algorithm
2652 theGen->AddAlgoAccessorMethod( *cmd );
2654 cmd = myUnusedCommands.begin();
2655 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2656 // Add access to a wrapped mesh
2657 theGen->AddMeshAccessorMethod( *cmd );
2658 // Add access to a wrapped algorithm
2659 theGen->AddAlgoAccessorMethod( *cmd );
2662 // forget previous hypothesis modifications
2663 myArgCommands.clear();
2664 myUnusedCommands.clear();
2667 //================================================================================
2669 * \brief clear creation, arg and unkown commands
2671 //================================================================================
2673 void _pyHypothesis::ClearAllCommands()
2675 GetCreationCmd()->Clear();
2676 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2677 for ( ; cmd != myArgCommands.end(); ++cmd )
2679 cmd = myUnusedCommands.begin();
2680 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2685 //================================================================================
2687 * \brief Assign fields of theOther to me except myIsWrapped
2689 //================================================================================
2691 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2692 const _pyID& theMesh )
2694 // myCreationCmd = theOther->myCreationCmd;
2695 myIsAlgo = theOther->myIsAlgo;
2696 myIsWrapped = false;
2697 myGeom = theOther->myGeom;
2699 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2700 myAccumulativeMethods = theOther->myAccumulativeMethods;
2701 //myUnusedCommands = theOther->myUnusedCommands;
2702 // init myCurCrMethod
2703 GetCreationMethod( theOther->GetAlgoType() );
2706 //================================================================================
2708 * \brief Analyze my erasability depending on myReferredObjs
2710 //================================================================================
2712 bool _pyHypothesis::CanClear()
2716 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2717 for ( ; obj != myReferredObjs.end(); ++obj )
2718 if ( (*obj)->CanClear() )
2725 //================================================================================
2727 * \brief Clear my commands depending on usage by meshes
2729 //================================================================================
2731 void _pyHypothesis::ClearCommands()
2733 // if ( !theGen->IsToKeepAllCommands() )
2735 // bool isUsed = false;
2736 // int lastComputeOrder = 0;
2737 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2738 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2739 // if ( ! (*cmd)->IsEmpty() )
2742 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2743 // lastComputeOrder = (*cmd)->GetOrderNb();
2747 // SetRemovedFromStudy( true );
2751 // // clear my commands invoked after lastComputeOrder
2752 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2753 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2755 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2756 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2757 // // cmds.back()->Clear();
2761 _pyObject::ClearCommands();
2764 //================================================================================
2766 * \brief Find arguments that are objects like mesh, group, geometry
2767 * \param meshes - referred meshes (directly or indirrectly)
2768 * \retval bool - false if a referred geometry is not in the study
2770 //================================================================================
2772 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2774 if ( IsAlgo() ) return true;
2776 bool geomPublished = true;
2777 vector< _AString > args;
2778 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2779 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2781 CreationMethod& crMethod = type2meth->second;
2782 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2784 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2785 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2786 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2787 args.push_back( (*cmd)->GetArg( nb ));
2790 for ( size_t i = 0; i < args.size(); ++i )
2792 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2793 if ( idList.empty() && !args[ i ].IsEmpty() )
2794 idList.push_back( args[ i ]);
2795 list< _pyID >::iterator id = idList.begin();
2796 for ( ; id != idList.end(); ++id )
2798 Handle(_pyObject) obj = theGen->FindObject( *id );
2799 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2802 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2803 geomPublished = false;
2807 myReferredObjs.push_back( obj );
2808 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2809 if ( !mesh.IsNull() )
2810 meshes.push_back( mesh );
2811 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2812 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2813 obj->SetRemovedFromStudy( false );
2817 return geomPublished;
2820 //================================================================================
2822 * \brief Remember theCommand setting a parameter
2824 //================================================================================
2826 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2828 // parameters are discriminated by method name
2829 _AString method = theCommand->GetMethod();
2830 if ( myAccumulativeMethods.count( method ))
2831 return; // this method adds values and not override the previus value
2833 // discriminate commands setting different parameters via one method
2834 // by passing parameter names like e.g. SetOption("size", "0.2")
2835 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2836 theCommand->GetNbArgs() > 1 )
2838 // mangle method by appending a 1st textual arg
2839 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2841 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2842 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2843 if ( !isalpha( arg.Value(2))) continue;
2848 // parameters are discriminated by method name
2849 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2850 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2852 cmds.back()->Clear(); // previous parameter value has not been used
2853 cmds.back() = theCommand;
2857 cmds.push_back( theCommand );
2861 //================================================================================
2863 * \brief Return true if a setting parameter command ha been used to compute mesh
2865 //================================================================================
2867 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2868 _pyCommand::TAddr avoidComputeAddr ) const
2870 bool isUsed = false;
2871 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2872 myComputeAddr2Cmds.begin();
2873 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2875 if ( addr2cmds->first == avoidComputeAddr ) continue;
2876 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2877 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2882 //================================================================================
2884 * \brief Save commands setting parameters as they are used for a mesh computation
2886 //================================================================================
2888 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2890 myComputeCmds.push_back( theComputeCmd );
2891 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2893 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2894 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2895 savedCmds.push_back( m2c->second.back() );
2898 //================================================================================
2900 * \brief Clear commands setting parameters as a mesh computed using them is cleared
2902 //================================================================================
2904 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
2906 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2908 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
2909 for ( ; cmd != savedCmds.end(); ++cmd )
2911 // check if a cmd has been used to compute another mesh
2912 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
2914 // check if a cmd is a sole command setting its parameter;
2915 // don't use method name for search as it can change
2916 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
2917 m2cmds = myMeth2Commands.begin();
2918 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
2920 list< Handle(_pyCommand)>& cmds = m2cmds->second;
2921 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
2922 if ( cmdIt != cmds.end() )
2924 if ( cmds.back() != *cmd )
2926 cmds.erase( cmdIt );
2933 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
2936 //================================================================================
2938 * \brief Sets an argNb-th argument of current creation command
2939 * \param argNb - argument index countered from 1
2941 //================================================================================
2943 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
2945 if ( myCurCrMethod )
2947 while ( myCurCrMethod->myArgs.size() < argNb )
2948 myCurCrMethod->myArgs.push_back( "None" );
2949 if ( arg.IsEmpty() )
2950 myCurCrMethod->myArgs[ argNb-1 ] = "None";
2952 myCurCrMethod->myArgs[ argNb-1 ] = arg;
2957 //================================================================================
2959 * \brief Remember hypothesis parameter values
2960 * \param theCommand - The called hypothesis method
2962 //================================================================================
2964 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
2966 if ( GetAlgoType() == "Cartesian_3D" )
2968 // CartesianParameters3D hyp
2970 if ( theCommand->GetMethod() == "SetSizeThreshold" )
2972 setCreationArg( 4, theCommand->GetArg( 1 ));
2973 myArgCommands.push_back( theCommand );
2976 if ( theCommand->GetMethod() == "SetGrid" ||
2977 theCommand->GetMethod() == "SetGridSpacing" )
2979 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
2980 int iArg = axis.Value(1) - '0';
2981 if ( theCommand->GetMethod() == "SetGrid" )
2983 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
2987 myCurCrMethod->myArgs[ iArg ] = "[ ";
2988 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
2989 myCurCrMethod->myArgs[ iArg ] += ", ";
2990 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
2991 myCurCrMethod->myArgs[ iArg ] += "]";
2993 myArgCommands.push_back( theCommand );
2994 rememberCmdOfParameter( theCommand );
2999 if( theCommand->GetMethod() == "SetLength" )
3001 // NOW it is OBSOLETE
3002 // ex: hyp.SetLength(start, 1)
3003 // hyp.SetLength(end, 0)
3004 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3005 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3006 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3007 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3009 CreationMethod& crMethod = type2meth->second;
3010 while ( crMethod.myArgs.size() < i+1 )
3011 crMethod.myArgs.push_back( "[]" );
3012 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3014 myArgCommands.push_back( theCommand );
3018 _pyHypothesis::Process( theCommand );
3021 //================================================================================
3023 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3025 //================================================================================
3027 void _pyComplexParamHypo::Flush()
3031 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
3032 for ( ; cmd != myUnusedCommands.end(); ++cmd )
3033 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3038 //================================================================================
3040 * \brief Convert methods of 1D hypotheses to my own methods
3041 * \param theCommand - The called hypothesis method
3043 //================================================================================
3045 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3047 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3050 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3051 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3052 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3054 // TCollection_AsciiString cmd =
3055 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3056 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3057 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3060 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3062 // // 1D hypo is already set, so distribution changes and the old
3063 // // 1D hypo is thrown away
3064 // my1dHyp->ClearAllCommands();
3067 // //my1dHyp->SetRemovedFromStudy( false );
3069 // if ( !myArgCommands.empty() )
3070 // myArgCommands.back()->Clear();
3071 myCurCrMethod->myArgs.push_back( hyp1dID );
3072 myArgCommands.push_back( theCommand );
3075 //================================================================================
3078 * \param theAdditionCmd - command to be converted
3079 * \param theMesh - mesh instance
3080 * \retval bool - status
3082 //================================================================================
3084 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3085 const _pyID& theMesh)
3087 myIsWrapped = false;
3089 if ( my1dHyp.IsNull() )
3092 // set "SetLayerDistribution()" after addition cmd
3093 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3095 _pyID geom = theAdditionCmd->GetArg( 1 );
3097 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3098 if ( !algo.IsNull() )
3100 my1dHyp->SetMesh( theMesh );
3101 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3102 algo->GetAlgoType().ToCString());
3103 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3106 // clear "SetLayerDistribution()" cmd
3107 myArgCommands.back()->Clear();
3109 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3111 // find RadialPrism algo created on <geom> for theMesh
3112 GetCreationCmd()->SetObject( algo->GetID() );
3113 GetCreationCmd()->SetMethod( myAlgoMethod );
3114 GetCreationCmd()->RemoveArgs();
3115 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3121 //================================================================================
3125 //================================================================================
3127 void _pyLayerDistributionHypo::Flush()
3129 // as creation of 1D hyp was written later then it's edition,
3130 // we need to find all it's edition calls and process them
3131 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3133 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3135 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3136 if ( hyp1dID.IsEmpty() ) continue;
3138 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3140 // make a new name for 1D hyp = "HypType" + "_Distribution"
3142 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3144 if ( prevNewName.IsEmpty() ) continue;
3145 newName = prevNewName;
3149 if ( hyp1d->IsWrapped() ) {
3150 newName = hyp1d->GetCreationCmd()->GetMethod();
3153 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3154 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3156 newName += "_Distribution";
3157 prevNewName = newName;
3159 hyp1d->GetCreationCmd()->SetResultValue( newName );
3161 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3162 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3163 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3164 const _pyID& objID = (*cmdIt)->GetObject();
3165 if ( objID == hyp1dID ) {
3166 if ( !hyp1d.IsNull() )
3168 hyp1d->Process( *cmdIt );
3169 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3171 ( *cmdIt )->SetObject( newName );
3174 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3175 (*cmd)->SetArg( 1, newName );
3179 //================================================================================
3181 * \brief additionally to Addition2Creation, clears SetDistrType() command
3182 * \param theCmd - AddHypothesis() command
3183 * \param theMesh - mesh to which a hypothesis is added
3184 * \retval bool - convertion result
3186 //================================================================================
3188 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3189 const _pyID& theMesh)
3191 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3192 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3193 bool scaleDistrType = false;
3194 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3195 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3196 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3197 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3198 scaleDistrType = true;
3201 else if ( !scaleDistrType ) {
3202 // distribution type changed: remove scale factor from args
3203 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3204 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3206 CreationMethod& crMethod = type2meth->second;
3207 if ( crMethod.myArgs.size() == 2 )
3208 crMethod.myArgs.pop_back();
3215 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3218 //================================================================================
3220 * \brief remove repeated commands defining distribution
3222 //================================================================================
3224 void _pyNumberOfSegmentsHyp::Flush()
3226 // find number of the last SetDistrType() command
3227 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3228 int distrTypeNb = 0;
3229 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3230 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3231 if ( cmd != myUnusedCommands.rbegin() )
3232 distrTypeNb = (*cmd)->GetOrderNb();
3234 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3237 // clear commands before the last SetDistrType()
3238 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3239 set< int > treatedCmdNbs; // avoid treating same cmd twice
3240 for ( int i = 0; i < 2; ++i ) {
3241 set<TCollection_AsciiString> uniqueMethods;
3242 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3243 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3245 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3246 continue;// avoid treating same cmd twice
3247 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3248 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3249 if ( !clear || method == "SetNumberOfSegments" ) {
3250 bool isNewInSet = uniqueMethods.insert( method ).second;
3251 clear = !isNewInSet;
3260 //================================================================================
3262 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3263 * into regular1D.LengthNearVertex( length, vertex )
3264 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3265 * \param theMesh - The mesh needing this hypo
3266 * \retval bool - false if the command cant be converted
3268 //================================================================================
3270 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3271 const _pyID& theMeshID)
3273 if ( IsWrappable( theMeshID )) {
3275 _pyID vertex = theCmd->GetArg( 1 );
3277 // the problem here is that segment algo will not be found
3278 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3279 // geometry where segment algorithm is assigned
3280 Handle(_pyHypothesis) algo;
3281 _pyID geom = vertex;
3282 while ( algo.IsNull() && !geom.IsEmpty()) {
3283 // try to find geom as a father of <vertex>
3284 geom = FatherID( geom );
3285 algo = theGen->FindAlgo( geom, theMeshID, this );
3287 if ( algo.IsNull() )
3288 return false; // also possible to find geom as brother of veretex...
3289 // set geom instead of vertex
3290 theCmd->SetArg( 1, geom );
3292 // set vertex as a second arg
3293 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3294 setCreationArg( 2, vertex );
3296 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3297 // theMeshID.LengthNearVertex( length, vertex )
3298 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3303 //================================================================================
3305 * \brief _pyAlgorithm constructor
3306 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3308 //================================================================================
3310 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3311 : _pyHypothesis( theCreationCmd )
3316 //================================================================================
3318 * \brief Convert the command adding an algorithm to mesh
3319 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3320 * \param theMesh - The mesh needing this algo
3321 * \retval bool - false if the command cant be converted
3323 //================================================================================
3325 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3326 const _pyID& theMeshID)
3328 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3329 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3330 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3336 //================================================================================
3338 * \brief Return starting position of a part of python command
3339 * \param thePartIndex - The index of command part
3340 * \retval int - Part position
3342 //================================================================================
3344 int _pyCommand::GetBegPos( int thePartIndex )
3348 if ( myBegPos.Length() < thePartIndex )
3350 return myBegPos( thePartIndex );
3353 //================================================================================
3355 * \brief Store starting position of a part of python command
3356 * \param thePartIndex - The index of command part
3357 * \param thePosition - Part position
3359 //================================================================================
3361 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3363 while ( myBegPos.Length() < thePartIndex )
3364 myBegPos.Append( UNKNOWN );
3365 myBegPos( thePartIndex ) = thePosition;
3368 //================================================================================
3370 * \brief Returns whitespace symbols at the line beginning
3371 * \retval TCollection_AsciiString - result
3373 //================================================================================
3375 TCollection_AsciiString _pyCommand::GetIndentation()
3378 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3379 GetWord( myString, end, true );
3381 end = GetBegPos( RESULT_IND );
3382 return myString.SubString( 1, end - 1 );
3385 //================================================================================
3387 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3388 * \retval const TCollection_AsciiString & - ResultValue substring
3390 //================================================================================
3392 const TCollection_AsciiString & _pyCommand::GetResultValue()
3394 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3396 SetBegPos( RESULT_IND, EMPTY );
3397 int begPos, endPos = myString.Location( "=", 1, Length() );
3401 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3402 if ( begPos < endPos )
3404 SetBegPos( RESULT_IND, begPos );
3406 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3407 myRes = myString.SubString( begPos, endPos );
3414 //================================================================================
3416 * \brief Return number of python command result value ResultValue = Obj.Meth()
3418 //================================================================================
3420 int _pyCommand::GetNbResultValues()
3424 int endPos = myString.Location( "=", 1, Length() );
3425 while ( begPos < endPos )
3427 _AString str = GetWord( myString, begPos, true );
3428 begPos = begPos+ str.Length();
3435 //================================================================================
3437 * \brief Return substring of python command looking like
3438 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3439 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3441 //================================================================================
3442 TCollection_AsciiString _pyCommand::GetResultValue(int res)
3445 if ( SkipSpaces( myString, begPos ) && myString.Value( begPos ) == '[' )
3446 ++begPos; // skip [, else the whole list is returned
3447 int endPos = myString.Location( "=", 1, Length() );
3449 while ( begPos < endPos) {
3450 _AString result = GetWord( myString, begPos, true );
3451 begPos = begPos + result.Length();
3454 result.RemoveAll('[');
3455 result.RemoveAll(']');
3461 return theEmptyString;
3464 //================================================================================
3466 * \brief Return substring of python command looking like ResVal = Object.Meth()
3467 * \retval const TCollection_AsciiString & - Object substring
3469 //================================================================================
3471 const TCollection_AsciiString & _pyCommand::GetObject()
3473 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3476 int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
3478 begPos = myString.Location( "=", 1, Length() ) + 1;
3479 // is '=' in the string argument (for example, name) or not
3480 int nb1 = 0; // number of ' character at the left of =
3481 int nb2 = 0; // number of " character at the left of =
3482 for ( int i = 1; i < begPos-1; i++ ) {
3483 if ( myString.Value( i )=='\'' )
3485 else if ( myString.Value( i )=='"' )
3488 // if number of ' or " is not divisible by 2,
3489 // then get an object at the start of the command
3490 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3493 myObj = GetWord( myString, begPos, true );
3494 if ( begPos != EMPTY )
3496 // check if object is complex,
3497 // so far consider case like "smesh.Method()"
3498 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3499 //if ( bracketPos==0 ) bracketPos = Length();
3500 int dotPos = begPos+myObj.Length();
3501 while ( dotPos+1 < bracketPos ) {
3502 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3507 if ( dotPos > begPos+myObj.Length() )
3508 myObj = myString.SubString( begPos, dotPos-1 );
3511 // 1st word after '=' is an object
3512 // else // no method -> no object
3518 SetBegPos( OBJECT_IND, begPos );
3524 //================================================================================
3526 * \brief Return substring of python command looking like ResVal = Obj.Method()
3527 * \retval const TCollection_AsciiString & - Method substring
3529 //================================================================================
3531 const TCollection_AsciiString & _pyCommand::GetMethod()
3533 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3536 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3537 bool forward = true;
3539 begPos = myString.Location( "(", 1, Length() ) - 1;
3543 myMeth = GetWord( myString, begPos, forward );
3544 SetBegPos( METHOD_IND, begPos );
3550 //================================================================================
3552 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3553 * \retval const TCollection_AsciiString & - Arg<index> substring
3555 //================================================================================
3557 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3559 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3563 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3565 pos = myString.Location( "(", 1, Length() );
3569 // we are at or before '(', skip it if present
3571 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3572 if ( pos > Length() )
3576 SetBegPos( ARG1_IND, 0 ); // even no '('
3577 return theEmptyString;
3581 list< TCollection_AsciiString > separatorStack( 1, ",)");
3582 bool ignoreNesting = false;
3584 while ( pos <= Length() )
3586 const char chr = myString.Value( pos );
3588 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3590 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3592 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3594 TCollection_AsciiString arg;
3595 if ( pos-1 >= prevPos ) {
3596 arg = myString.SubString( prevPos, pos-1 );
3597 arg.RightAdjust(); // remove spaces
3600 if ( !arg.IsEmpty() || chr == ',' )
3602 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3603 myArgs.Append( arg );
3609 else // end of nesting args found
3611 separatorStack.pop_back();
3612 ignoreNesting = false;
3615 else if ( !ignoreNesting )
3618 case '(' : separatorStack.push_back(")"); break;
3619 case '[' : separatorStack.push_back("]"); break;
3620 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3621 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3628 if ( myArgs.Length() < index )
3629 return theEmptyString;
3630 return myArgs( index );
3633 //================================================================================
3635 * \brief Check if char is a word part
3636 * \param c - The character to check
3637 * \retval bool - The check result
3639 //================================================================================
3641 static inline bool isWord(const char c, const bool dotIsWord)
3644 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3647 //================================================================================
3649 * \brief Looks for a word in the string and returns word's beginning
3650 * \param theString - The input string
3651 * \param theStartPos - The position to start the search, returning word's beginning
3652 * \param theForward - The search direction
3653 * \retval TCollection_AsciiString - The found word
3655 //================================================================================
3657 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3659 const bool theForward,
3660 const bool dotIsWord )
3662 int beg = theStartPos, end = theStartPos;
3663 theStartPos = EMPTY;
3664 if ( beg < 1 || beg > theString.Length() )
3665 return theEmptyString;
3667 if ( theForward ) { // search forward
3669 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3671 if ( beg > theString.Length() )
3672 return theEmptyString; // no word found
3675 char begChar = theString.Value( beg );
3676 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3677 char endChar = ( begChar == '[' ) ? ']' : begChar;
3678 // end is at the corresponding quoting mark or bracket
3679 while ( end < theString.Length() &&
3680 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3684 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3689 else { // search backward
3691 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3694 return theEmptyString; // no word found
3696 char endChar = theString.Value( end );
3697 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3698 char begChar = ( endChar == ']' ) ? '[' : endChar;
3699 // beg is at the corresponding quoting mark
3701 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3705 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3711 //cout << theString << " ---- " << beg << " - " << end << endl;
3712 return theString.SubString( beg, end );
3715 //================================================================================
3717 * \brief Returns true if the string looks like a study entry
3719 //================================================================================
3721 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3723 if ( str.Length() < 5 ) return false;
3725 int nbColons = 0, isColon;
3726 for ( int i = 1; i <= str.Length(); ++i )
3728 char c = str.Value(i);
3729 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3731 nbColons += isColon;
3733 return nbColons > 2 && str.Length()-nbColons > 2;
3736 //================================================================================
3738 * \brief Finds entries in a sting
3740 //================================================================================
3742 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3744 std::list< _pyID > resList;
3746 while ( ++pos <= str.Length() )
3748 if ( !isdigit( str.Value( pos ))) continue;
3749 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3752 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3753 _pyID entry = str.SubString( pos, end-1 );
3755 if ( IsStudyEntry( entry ))
3756 resList.push_back( entry );
3761 //================================================================================
3763 * \brief Look for position where not space char is
3764 * \param theString - The string
3765 * \param thePos - The position to search from and which returns result
3766 * \retval bool - false if there are only space after thePos in theString
3768 //================================================================================
3770 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3772 if ( thePos < 1 || thePos > theString.Length() )
3775 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3778 return thePos <= theString.Length();
3781 //================================================================================
3783 * \brief Modify a part of the command
3784 * \param thePartIndex - The index of the part
3785 * \param thePart - The new part string
3786 * \param theOldPart - The old part
3788 //================================================================================
3790 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3791 TCollection_AsciiString& theOldPart)
3793 int pos = GetBegPos( thePartIndex );
3794 if ( pos <= Length() && theOldPart != thePart)
3796 TCollection_AsciiString seperator;
3798 pos = GetBegPos( thePartIndex + 1 );
3799 if ( pos < 1 ) return;
3800 switch ( thePartIndex ) {
3801 case RESULT_IND: seperator = " = "; break;
3802 case OBJECT_IND: seperator = "."; break;
3803 case METHOD_IND: seperator = "()"; break;
3807 myString.Remove( pos, theOldPart.Length() );
3808 if ( !seperator.IsEmpty() )
3809 myString.Insert( pos , seperator );
3810 myString.Insert( pos, thePart );
3811 // update starting positions of the following parts
3812 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3813 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3814 if ( myBegPos( i ) > 0 )
3815 myBegPos( i ) += posDelta;
3817 theOldPart = thePart;
3821 //================================================================================
3823 * \brief Set agrument
3824 * \param index - The argument index, it counts from 1
3825 * \param theArg - The argument string
3827 //================================================================================
3829 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3832 int argInd = ARG1_IND + index - 1;
3833 int pos = GetBegPos( argInd );
3834 if ( pos < 1 ) // no index-th arg exist, append inexistent args
3836 // find a closing parenthesis
3837 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3838 int lastArgInd = GetNbArgs();
3839 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
3840 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3845 while ( pos > 0 && myString.Value( pos ) != ')' )
3848 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3852 while ( myArgs.Length() < index ) {
3853 if ( myArgs.Length() )
3854 myString.Insert( pos++, "," );
3855 myArgs.Append("None");
3856 myString.Insert( pos, myArgs.Last() );
3857 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3858 pos += myArgs.Last().Length();
3861 SetPart( argInd, theArg, myArgs( index ));
3864 //================================================================================
3866 * \brief Empty arg list
3868 //================================================================================
3870 void _pyCommand::RemoveArgs()
3872 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
3873 myString.Trunc( pos );
3876 if ( myBegPos.Length() >= ARG1_IND )
3877 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
3880 //================================================================================
3882 * \brief Comment a python command
3884 //================================================================================
3886 void _pyCommand::Comment()
3888 if ( IsEmpty() ) return;
3891 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
3892 if ( i <= Length() )
3894 myString.Insert( i, "#" );
3895 for ( int iPart = 0; iPart < myBegPos.Length(); ++iPart )
3897 int begPos = GetBegPos( iPart + 1 );
3898 if ( begPos != UNKNOWN )
3899 SetBegPos( iPart + 1, begPos + 1 );
3904 //================================================================================
3906 * \brief Set dependent commands after this one
3908 //================================================================================
3910 bool _pyCommand::SetDependentCmdsAfter() const
3912 bool orderChanged = false;
3913 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
3914 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
3915 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
3916 orderChanged = true;
3917 theGen->SetCommandAfter( *cmd, this );
3918 (*cmd)->SetDependentCmdsAfter();
3921 return orderChanged;
3923 //================================================================================
3925 * \brief Insert accessor method after theObjectID
3926 * \param theObjectID - id of the accessed object
3927 * \param theAcsMethod - name of the method giving access to the object
3928 * \retval bool - false if theObjectID is not found in the command string
3930 //================================================================================
3932 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
3934 if ( !theAcsMethod )
3936 // start object search from the object, i.e. ignore result
3938 int beg = GetBegPos( OBJECT_IND );
3939 if ( beg < 1 || beg > Length() )
3942 while (( beg = myString.Location( theObjectID, beg, Length() )))
3944 // check that theObjectID is not just a part of a longer ID
3945 int afterEnd = beg + theObjectID.Length();
3946 Standard_Character c = myString.Value( afterEnd );
3947 if ( !isalnum( c ) && c != ':' ) {
3948 // check if accessor method already present
3950 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
3952 int oldLen = Length();
3953 myString.Insert( afterEnd, (char*) theAcsMethod );
3954 myString.Insert( afterEnd, "." );
3955 // update starting positions of the parts following the modified one
3956 int posDelta = Length() - oldLen;
3957 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
3958 if ( myBegPos( i ) > afterEnd )
3959 myBegPos( i ) += posDelta;
3964 beg = afterEnd; // is a part - next search
3969 //================================================================================
3971 * \brief Creates pyObject
3973 //================================================================================
3975 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
3976 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
3981 //================================================================================
3983 * \brief Set up myID and myIsPublished
3985 //================================================================================
3987 void _pyObject::setID(const _pyID& theID)
3990 myIsPublished = !theGen->IsNotPublished( GetID() );
3993 //================================================================================
3995 * \brief Clear myCreationCmd and myProcessedCmds
3997 //================================================================================
3999 void _pyObject::ClearCommands()
4004 if ( !myCreationCmd.IsNull() )
4005 myCreationCmd->Clear();
4007 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4008 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4012 //================================================================================
4014 * \brief Return method name giving access to an interaface object wrapped by python class
4015 * \retval const char* - method name
4017 //================================================================================
4019 const char* _pyObject::AccessorMethod() const
4023 //================================================================================
4025 * \brief Return ID of a father
4027 //================================================================================
4029 _pyID _pyObject::FatherID(const _pyID & childID)
4031 int colPos = childID.SearchFromEnd(':');
4033 return childID.SubString( 1, colPos-1 );
4037 //================================================================================
4039 * \brief SelfEraser erases creation command if no more it's commands invoked
4041 //================================================================================
4043 void _pySelfEraser::Flush()
4045 int nbCalls = GetNbCalls();
4048 // ignore cleared commands
4049 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4050 std::list< Handle(_pyCommand) >::const_iterator cmd = cmds.begin();
4051 for ( ; cmd != cmds.end(); ++cmd )
4052 nbCalls -= (*cmd)->IsEmpty();
4055 GetCreationCmd()->Clear();
4058 //================================================================================
4060 * \brief _pySubMesh constructor
4062 //================================================================================
4064 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
4065 _pyObject(theCreationCmd)
4067 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4070 //================================================================================
4072 * \brief Return true if a sub-mesh can be used as argument of the given method
4074 //================================================================================
4076 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4078 // names of all methods where a sub-mesh can be used as argument
4079 static TStringSet methods;
4080 if ( methods.empty() ) {
4081 const char * names[] = {
4082 // methods of SMESH_Gen
4084 // methods of SMESH_Group
4086 // methods of SMESH_Measurements
4088 // methods of SMESH_Mesh
4089 "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4091 // methods of SMESH_MeshEditor
4092 "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4093 "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4094 "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4095 "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4096 "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4097 "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4098 "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4099 "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4100 "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4101 "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4102 "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4103 "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4104 "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4105 "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4106 "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4107 "" }; // <- mark of end
4108 methods.Insert( names );
4110 return methods.Contains( theMethodName );
4113 //================================================================================
4115 * \brief count invoked commands
4117 //================================================================================
4119 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4121 _pyObject::Process(theCommand); // count calls of Process()
4122 GetCreationCmd()->AddDependantCmd( theCommand );
4125 //================================================================================
4127 * \brief Move creation command depending on invoked commands
4129 //================================================================================
4131 void _pySubMesh::Flush()
4133 if ( GetNbCalls() == 0 ) // move to the end of all commands
4134 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4135 else if ( !myCreator.IsNull() )
4136 // move to be just after creator
4137 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4140 //================================================================================
4142 * \brief Creates _pyGroup
4144 //================================================================================
4146 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4147 :_pySubMesh(theCreationCmd)
4149 if ( !id.IsEmpty() )
4152 myCanClearCreationCmd = true;
4154 const _AString& method = theCreationCmd->GetMethod();
4155 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4157 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4159 // ----------------------------------------------------------------------
4160 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4162 _pyID geom = theCreationCmd->GetArg( 3 );
4163 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4164 // next if(){...} section is commented
4165 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4166 // theCreationCmd->SetMethod( "Group" );
4167 // theCreationCmd->RemoveArgs();
4168 // theCreationCmd->SetArg( 1, geom );
4171 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4172 _pyID type = theCreationCmd->GetArg( 1 );
4173 _pyID name = theCreationCmd->GetArg( 2 );
4174 theCreationCmd->SetMethod( "GroupOnGeom" );
4175 theCreationCmd->RemoveArgs();
4176 theCreationCmd->SetArg( 1, geom );
4177 theCreationCmd->SetArg( 2, name );
4178 theCreationCmd->SetArg( 3, type );
4181 else if ( method == "CreateGroupFromFilter" )
4183 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4184 theCreationCmd->SetMethod( "GroupOnFilter" );
4186 _pyID filterID = theCreationCmd->GetArg(3);
4187 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4188 if ( !filter.IsNull())
4190 if ( !filter->GetNewID().IsEmpty() )
4191 theCreationCmd->SetArg( 3, filter->GetNewID() );
4192 filter->AddUser( this );
4196 else if ( method == "GetGroups" )
4198 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4202 // theCreationCmd does something else apart from creation of this group
4203 // and thus it can't be cleared if this group is removed
4204 myCanClearCreationCmd = false;
4208 //================================================================================
4210 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4213 //================================================================================
4215 bool _pyGroup::CanClear()
4220 if ( !myCanClearCreationCmd && myCreationCmd->GetMethod() == "GetGroups" )
4222 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4223 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4224 list< _pyID >::iterator grID = idList.begin();
4225 if ( GetID() == *grID )
4227 myCanClearCreationCmd = true;
4228 list< Handle(_pyGroup ) > groups;
4229 for ( ; grID != idList.end(); ++grID )
4231 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4232 if ( group.IsNull() ) continue;
4233 groups.push_back( group );
4234 if ( group->IsInStudy() )
4235 myCanClearCreationCmd = false;
4237 // set myCanClearCreationCmd == true to all groups
4238 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4239 for ( ; group != groups.end(); ++group )
4240 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4244 return myCanClearCreationCmd;
4247 //================================================================================
4249 * \brief set myCanClearCreationCmd = true if the main action of the creation
4250 * command is discarded
4252 //================================================================================
4254 void _pyGroup::RemovedWithContents()
4256 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4257 // via a created group
4258 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4259 // myCanClearCreationCmd = true;
4262 //================================================================================
4264 * \brief To convert creation of a group by filter
4266 //================================================================================
4268 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4270 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4271 // group = mesh.CreateEmptyGroup( elemType, groupName )
4272 // aFilter.SetMesh(mesh)
4273 // nbAdd = group.AddFrom( aFilter )
4274 Handle(_pyFilter) filter;
4275 if ( theCommand->GetMethod() == "AddFrom" )
4277 _pyID idSource = theCommand->GetArg(1);
4278 // check if idSource is a filter
4279 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4280 if ( !filter.IsNull() )
4282 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4283 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4284 while ( *cmdIt != theCommand ) ++cmdIt;
4285 while ( (*cmdIt)->GetOrderNb() != 1 )
4287 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4288 if ((setMeshCmd->GetObject() == idSource ||
4289 setMeshCmd->GetObject() == filter->GetNewID() )
4291 setMeshCmd->GetMethod() == "SetMesh")
4293 setMeshCmd->Clear();
4297 // replace 3 commands by one
4298 theCommand->Clear();
4299 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4300 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4301 if ( !filter->GetNewID().IsEmpty() )
4302 idSource = filter->GetNewID();
4303 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4304 makeGroupCmd->SetArg( 1, name );
4305 makeGroupCmd->SetArg( 2, idSource );
4308 else if ( theCommand->GetMethod() == "SetFilter" )
4310 // set new name of a filter or clear the command if the same filter is set
4311 _pyID filterID = theCommand->GetArg(1);
4312 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4313 if ( !myFilter.IsNull() && filter == myFilter )
4314 theCommand->Clear();
4315 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4316 theCommand->SetArg( 1, filter->GetNewID() );
4319 else if ( theCommand->GetMethod() == "GetFilter" )
4321 // GetFilter() returns a filter with other ID, make myFilter process
4322 // calls of the returned filter
4323 if ( !myFilter.IsNull() )
4325 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4326 theCommand->Clear();
4330 if ( !filter.IsNull() )
4331 filter->AddUser( this );
4333 theGen->AddMeshAccessorMethod( theCommand );
4336 //================================================================================
4338 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4340 //================================================================================
4342 void _pyGroup::Flush()
4344 if ( !theGen->IsToKeepAllCommands() &&
4345 myCreationCmd && !myCanClearCreationCmd )
4347 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4351 //================================================================================
4353 * \brief Constructor of _pyFilter
4355 //================================================================================
4357 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4358 :_pyObject(theCreationCmd), myNewID( newID )
4362 //================================================================================
4364 * \brief To convert creation of a filter by criteria and
4365 * to replace an old name by a new one
4367 //================================================================================
4369 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4371 if ( theCommand->GetObject() == GetID() )
4372 _pyObject::Process(theCommand); // count commands
4374 if ( !myNewID.IsEmpty() )
4375 theCommand->SetObject( myNewID );
4377 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4378 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4379 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4380 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4381 theCommand->GetMethod() == "SetCriteria")
4383 // aFilter.SetCriteria(aCriteria) ->
4384 // aFilter = smesh.GetFilterFromCriteria(criteria)
4385 if ( myNewID.IsEmpty() )
4386 theCommand->SetResultValue( GetID() );
4388 theCommand->SetResultValue( myNewID );
4389 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4390 theCommand->SetMethod( "GetFilterFromCriteria" );
4392 // Clear aFilterManager.CreateFilter()
4393 GetCreationCmd()->Clear();
4395 else if ( theCommand->GetMethod() == "SetMesh" )
4397 if ( myMesh == theCommand->GetArg( 1 ))
4398 theCommand->Clear();
4400 myMesh = theCommand->GetArg( 1 );
4401 theGen->AddMeshAccessorMethod( theCommand );
4405 //================================================================================
4407 * \brief Set new filter name to the creation command
4409 //================================================================================
4411 void _pyFilter::Flush()
4413 if ( !myNewID.IsEmpty() && !GetCreationCmd()->IsEmpty() )
4414 GetCreationCmd()->SetResultValue( myNewID );
4417 //================================================================================
4419 * \brief Return true if all my users can be cleared
4421 //================================================================================
4423 bool _pyFilter::CanClear()
4425 list< Handle(_pyObject) >::iterator obj = myUsers.begin();
4426 for ( ; obj != myUsers.end(); ++obj )
4427 if ( !(*obj)->CanClear() )
4433 //================================================================================
4435 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4437 //================================================================================
4439 _pyHypothesisReader::_pyHypothesisReader()
4442 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4443 LDOMParser xmlParser;
4444 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4446 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4450 INFOS( xmlParser.GetError(data) );
4453 // <algorithm type="Regular_1D"
4454 // label-id="Wire discretisation"
4457 // <algo>Regular_1D=Segment()</algo>
4458 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4460 LDOM_Document xmlDoc = xmlParser.getDocument();
4461 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4462 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4464 LDOM_Node algoNode = algoNodeList.item( i );
4465 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4466 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4467 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4469 _AString text, algoType, method, arg;
4470 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4472 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4473 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4474 text = textNode.getNodeValue();
4475 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4476 algoType = algoCmd->GetResultValue();
4477 method = algoCmd->GetMethod();
4478 arg = algoCmd->GetArg(1);
4479 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4481 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4482 algo->SetConvMethodAndType( method, algoType );
4483 if ( !arg.IsEmpty() )
4484 algo->setCreationArg( 1, arg );
4486 myType2Hyp[ algoType ] = algo;
4490 if ( algoType.IsEmpty() ) continue;
4492 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4494 Handle( _pyHypothesis ) hyp;
4495 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4497 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4498 LDOM_Node textNode = pyHypoNode.getFirstChild();
4499 text = textNode.getNodeValue();
4500 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4501 hypType = hypoCmd->GetResultValue();
4502 method = hypoCmd->GetMethod();
4503 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4505 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4506 if ( type2hyp == myType2Hyp.end() )
4507 hyp = new _pyHypothesis( hypoCmd );
4509 hyp = type2hyp->second;
4510 hyp->SetConvMethodAndType( method, algoType );
4511 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4513 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4514 _AString argMethod = argCmd.GetMethod();
4515 _AString argNbText = argCmd.GetArg( 1 );
4516 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4517 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4519 hyp->AddArgMethod( argMethod,
4520 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4522 myType2Hyp[ hypType ] = hyp;
4526 // <hypothesis type="BLSURF_Parameters"
4530 // <accumulative-methods>
4531 // SetEnforcedVertex,
4532 // SetEnforcedVertexNamed
4533 // </accumulative-methods>
4537 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4538 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4540 LDOM_Node hypNode = hypNodeList.item( i );
4541 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4542 _AString hypType = hypElem.getAttribute("type");
4543 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4544 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4546 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4547 if ( type2hyp == myType2Hyp.end() ) continue;
4549 LDOM_Node methNode = methNodeList.item( 0 );
4550 LDOM_Node textNode = methNode.getFirstChild();
4551 _AString text = textNode.getNodeValue();
4555 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4556 pos += method.Length();
4557 type2hyp->second->AddAccumulativeMethod( method );
4559 while ( !method.IsEmpty() );
4562 } // loop on xmlPaths
4565 //================================================================================
4567 * \brief Returns a new hypothesis initialized according to the read information
4569 //================================================================================
4571 Handle(_pyHypothesis)
4572 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4573 const Handle(_pyCommand)& creationCmd) const
4575 Handle(_pyHypothesis) resHyp, sampleHyp;
4577 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4578 if ( type2hyp != myType2Hyp.end() )
4579 sampleHyp = type2hyp->second;
4581 if ( sampleHyp.IsNull() )
4583 resHyp = new _pyHypothesis(creationCmd);
4587 if ( sampleHyp->IsAlgo() )
4588 resHyp = new _pyAlgorithm( creationCmd );
4590 resHyp = new _pyHypothesis(creationCmd);
4591 resHyp->Assign( sampleHyp, _pyID() );