1 // Copyright (C) 2007-2012 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 <Resource_DataMapOfAsciiStringAsciiString.hxx>
34 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
36 #include "SMESH_Gen_i.hxx"
37 /* SALOME headers that include CORBA headers that include windows.h
38 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
39 * that declare methods named GetObject - to apply the same rules of GetObject renaming
40 * and thus to avoid mess with GetObject symbol on Windows */
42 #include <LDOMParser.hxx>
51 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
52 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
53 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
54 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
55 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
56 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
57 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
63 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
64 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
68 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
71 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
84 using SMESH::TPythonDump;
87 * \brief Container of commands into which the initial script is split.
88 * It also contains data coresponding to SMESH_Gen contents
90 static Handle(_pyGen) theGen;
92 static TCollection_AsciiString theEmptyString;
94 //#define DUMP_CONVERSION
96 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
97 #undef DUMP_CONVERSION
103 //================================================================================
105 * \brief Set of TCollection_AsciiString initialized by C array of C strings
107 //================================================================================
109 struct TStringSet: public set<TCollection_AsciiString>
112 * \brief Filling. The last string must be ""
114 void Insert(const char* names[]) {
115 for ( int i = 0; names[i][0] ; ++i )
116 insert( (char*) names[i] );
119 * \brief Check if a string is in
121 bool Contains(const TCollection_AsciiString& name ) {
122 return find( name ) != end();
126 //================================================================================
128 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
129 * Odd items of the C array are map keys, and even items are values
131 //================================================================================
133 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
136 * \brief Filling. The last string must be ""
138 void Insert(const char* names_values[]) {
139 for ( int i = 0; names_values[i][0] ; i += 2 )
140 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
143 * \brief Check if a string is in
145 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
146 map< _AString, _AString >::iterator it = find( name );
147 return it == end() ? "" : it->second;
151 //================================================================================
153 * \brief Returns a mesh by object
155 //================================================================================
157 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
161 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
162 return Handle(_pyMesh)::DownCast( obj );
163 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
164 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
165 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
166 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
168 return Handle(_pyMesh)();
171 //================================================================================
173 * \brief Check if objects used as args have been created by previous commands
175 //================================================================================
177 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
179 // either comment or erase a command including NotPublishedObjectName()
180 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
182 bool isResultPublished = false;
183 for ( int i = 0; i < cmd->GetNbResultValues(); i++ )
185 _pyID objID = cmd->GetResultValue( i+1 );
186 if ( cmd->IsStudyEntry( objID ))
187 isResultPublished = (! theGen->IsNotPublished( objID ));
188 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
190 if ( isResultPublished )
196 // check if an Object was created in the script
198 const _pyID& obj = cmd->GetObject();
199 const bool isMethodCall = cmd->IsMethodCall();
200 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
202 comment = "not created Object";
203 theGen->ObjectCreationRemoved( obj );
205 // check if a command has not created args
206 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
208 const _pyID& arg = cmd->GetArg( iArg );
209 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
211 list< _pyID > idList = cmd->GetStudyEntries( arg );
212 list< _pyID >::iterator id = idList.begin();
213 for ( ; id != idList.end(); ++id )
214 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
216 comment += *id + " has not been yet created";
219 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
220 // comment += arg + " has not been yet created";
222 // treat result objects
223 const _pyID& result = cmd->GetResultValue();
224 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
226 list< _pyID > idList = cmd->GetStudyEntries( result );
227 list< _pyID >::iterator id = idList.begin();
228 for ( ; id != idList.end(); ++id )
230 if ( comment.IsEmpty() )
231 presentObjects.insert( *id );
233 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
235 if ( idList.empty() && cmd->IsID( result ))
236 presentObjects.insert( result );
238 // comment the command
239 if ( !comment.IsEmpty() )
242 cmd->GetString() += " ### ";
243 cmd->GetString() += comment;
247 //================================================================================
249 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
251 //================================================================================
253 void fixFunctorType( TCollection_AsciiString& Type,
254 TCollection_AsciiString& Compare,
255 TCollection_AsciiString& UnaryOp,
256 TCollection_AsciiString& BinaryOp )
258 // The problem is that dumps of old studies created using filters becomes invalid
259 // when new items are inserted in the enum SMESH::FunctorType since values
260 // of this enum are dumped as integer values.
261 // This function corrects enum values of old studies given as args (Type,Compare,...)
262 // We can find out how to correct them by value of BinaryOp which can have only two
263 // values: FT_Undefined or FT_LogicalNOT.
264 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
265 // where PythonDump appeared
266 // v 3.0.0: FT_Undefined == 25
267 // v 3.1.0: FT_Undefined == 26, new items:
269 // v 4.1.2: FT_Undefined == 27, new items:
270 // - FT_BelongToGenSurface = 17
271 // v 5.1.1: FT_Undefined == 32, new items:
272 // - FT_FreeNodes = 10
273 // - FT_FreeFaces = 11
274 // - FT_LinearOrQuadratic = 23
275 // - FT_GroupColor = 24
276 // - FT_ElemGeomType = 25
277 // v 5.1.5: FT_Undefined == 33, new items:
278 // - FT_CoplanarFaces = 26
279 // v 6.2.0: FT_Undefined == 39, new items:
280 // - FT_MaxElementLength2D = 8
281 // - FT_MaxElementLength3D = 9
282 // - FT_BareBorderVolume = 25
283 // - FT_BareBorderFace = 26
284 // - FT_OverConstrainedVolume = 27
285 // - FT_OverConstrainedFace = 28
286 // v 6.5.0: FT_Undefined == 43, new items:
287 // - FT_EqualNodes = 14
288 // - FT_EqualEdges = 15
289 // - FT_EqualFaces = 16
290 // - FT_EqualVolumes = 17
291 // v 6.6.0: FT_Undefined == 44, new items:
292 // - FT_BallDiameter = 37
293 // v 6.7.1: FT_Undefined == 45, new items:
294 // - FT_EntityType = 36
295 // v 7.3.0: FT_Undefined == 46, new items:
296 // - FT_ConnectedElements = 39
298 // It's necessary to continue recording this history and to fill
299 // undef2newItems (see below) accordingly.
301 typedef map< int, vector< int > > TUndef2newItems;
302 static TUndef2newItems undef2newItems;
303 if ( undef2newItems.empty() )
305 undef2newItems[ 26 ].push_back( 7 );
306 undef2newItems[ 27 ].push_back( 17 );
307 { int items[] = { 10, 11, 23, 24, 25 };
308 undef2newItems[ 32 ].assign( items, items+5 ); }
309 undef2newItems[ 33 ].push_back( 26 );
310 { int items[] = { 8, 9, 25, 26, 27, 28 };
311 undef2newItems[ 39 ].assign( items, items+6 ); }
312 { int items[] = { 14, 15, 16, 17 };
313 undef2newItems[ 43 ].assign( items, items+4 ); }
316 int iType = Type.IntegerValue();
317 int iCompare = Compare.IntegerValue();
318 int iUnaryOp = UnaryOp.IntegerValue();
319 int iBinaryOp = BinaryOp.IntegerValue();
321 // find out integer value of FT_Undefined at the moment of dump
322 int oldUndefined = iBinaryOp;
323 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
326 // apply history to args
327 TUndef2newItems::const_iterator undef_items =
328 undef2newItems.upper_bound( oldUndefined );
329 if ( undef_items != undef2newItems.end() )
331 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
332 for ( ; undef_items != undef2newItems.end(); ++undef_items )
334 const vector< int > & addedItems = undef_items->second;
335 for ( size_t i = 0; i < addedItems.size(); ++i )
336 for ( int iArg = 0; iArg < 4; ++iArg )
338 int& arg = *pArg[iArg];
339 if ( arg >= addedItems[i] )
343 Type = TCollection_AsciiString( iType );
344 Compare = TCollection_AsciiString( iCompare );
345 UnaryOp = TCollection_AsciiString( iUnaryOp );
346 BinaryOp = TCollection_AsciiString( iBinaryOp );
350 //================================================================================
352 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
353 * arguments of a given command by a list "[x,y,z]" if the list is accesible
356 //================================================================================
358 void StructToList( Handle( _pyCommand)& theCommand )
360 static TStringSet methodsAcceptingList;
361 if ( methodsAcceptingList.empty() ) {
362 const char * methodNames[] = {
363 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
364 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
365 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
366 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
367 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
368 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
369 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
370 "Translate","TranslateMakeGroups","TranslateMakeMesh",
371 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
372 "ExtrusionAlongPathX","ExtrusionAlongPathObjX"
373 ,"" }; // <- mark of the end
374 methodsAcceptingList.Insert( methodNames );
376 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
378 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
380 const _AString & arg = theCommand->GetArg( i );
381 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
382 arg.Search( "SMESH.DirStruct" ) == 1 )
384 Handle(_pyCommand) workCmd = new _pyCommand( arg );
385 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
387 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
389 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
391 _AString newArg = "[ ";
392 newArg += ( workCmd->GetArg( 1 ) + ", " +
393 workCmd->GetArg( 2 ) + ", " +
394 workCmd->GetArg( 3 ) + " ]");
395 theCommand->SetArg( i, newArg );
401 //================================================================================
403 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
404 * a list "[id1,id2]" if the list is an accesible type of argument.
406 //================================================================================
408 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
410 static TStringSet methodsAcceptingList;
411 if ( methodsAcceptingList.empty() ) {
412 const char * methodNames[] = {
413 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
414 "ExportCGNS","ExportGMF",
415 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
416 "ScaleMakeGroups","Scale","ScaleMakeMesh",
417 "FindCoincidentNodesOnPartBut","DoubleElements"
418 ,"" }; // <- mark of the end
419 methodsAcceptingList.Insert( methodNames );
421 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
423 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
425 _pyCommand argCmd( theCommand->GetArg( i ));
426 if ( argCmd.GetMethod() == "GetIDSource" &&
427 argCmd.GetNbArgs() == 2 )
429 theCommand->SetArg( i, argCmd.GetArg( 1 ));
436 //================================================================================
438 * \brief Convert a python script using commands of smesh.py
439 * \param theScript - Input script
440 * \param theEntry2AccessorMethod - returns method names to access to
441 * objects wrapped with python class
442 * \param theObjectNames - names of objects
443 * \param theRemovedObjIDs - entries of objects whose created commands were removed
444 * \param theHistoricalDump - true means to keep all commands, false means
445 * to exclude commands relating to objects removed from study
446 * \retval TCollection_AsciiString - Convertion result
448 //================================================================================
451 SMESH_2smeshpy::ConvertScript(TCollection_AsciiString& theScript,
452 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
453 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
454 std::set< TCollection_AsciiString >& theRemovedObjIDs,
455 SALOMEDS::Study_ptr& theStudy,
456 const bool theToKeepAllCommands)
458 // process notebook variables
460 SMESH_NoteBook aNoteBook;
462 int from = 1, end = theScript.Length(), to;
463 while ( from < end && ( to = theScript.Location( "\n", from, end )))
466 // cut out and store a command
467 aNoteBook.AddCommand( theScript.SubString( from, to - 1 ));
472 aNoteBook.ReplaceVariables();
474 theScript = aNoteBook.GetResultScript();
477 // convert to smeshBuilder.py API
479 theGen = new _pyGen( theEntry2AccessorMethod,
483 theToKeepAllCommands );
485 // split theScript into separate commands
486 int from = 1, end = theScript.Length(), to;
487 while ( from < end && ( to = theScript.Location( "\n", from, end )))
490 // cut out and store a command
491 theGen->AddCommand( theScript.SubString( from, to - 1 ));
498 #ifdef DUMP_CONVERSION
499 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
502 // clean commmands of removed objects depending on myIsPublished flag
503 theGen->ClearCommands();
505 // reorder commands after conversion
506 list< Handle(_pyCommand) >::iterator cmd;
509 orderChanges = false;
510 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
511 if ( (*cmd)->SetDependentCmdsAfter() )
513 } while ( orderChanges );
515 // concat commands back into a script
516 TCollection_AsciiString aPrevCmd;
517 set<_pyID> createdObjects;
518 createdObjects.insert( "smeshBuilder" );
519 createdObjects.insert( "smesh" );
520 createdObjects.insert( "theStudy" );
521 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
523 #ifdef DUMP_CONVERSION
524 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
526 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
527 CheckObjectPresence( *cmd, createdObjects );
528 if ( !(*cmd)->IsEmpty() ) {
529 aPrevCmd = (*cmd)->GetString();
531 theScript += aPrevCmd;
541 //================================================================================
543 * \brief _pyGen constructor
545 //================================================================================
547 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
548 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
549 std::set< TCollection_AsciiString >& theRemovedObjIDs,
550 SALOMEDS::Study_ptr& theStudy,
551 const bool theToKeepAllCommands)
552 : _pyObject( new _pyCommand( "", 0 )),
554 myID2AccessorMethod( theEntry2AccessorMethod ),
555 myObjectNames( theObjectNames ),
556 myRemovedObjIDs( theRemovedObjIDs ),
558 myToKeepAllCommands( theToKeepAllCommands ),
559 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
560 myGeomIDNb(0), myGeomIDIndex(-1)
562 // make that GetID() to return TPythonDump::SMESHGenName()
563 GetCreationCmd()->Clear();
564 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
565 GetCreationCmd()->GetString() += "=";
567 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
568 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
572 SALOMEDS::SComponent_var geomComp = theStudy->FindComponent("GEOM");
573 if ( geomComp->_is_nil() ) return;
574 CORBA::String_var entry = geomComp->GetID();
577 // find a SMESH entry
579 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
580 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
581 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
584 // find 1st difference between smeshID and geomID
585 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
586 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
587 if ( geomID.Value( i ) != smeshID.Value( i ))
589 myGeomIDNb = geomID.Value( i );
595 //================================================================================
597 * \brief name of SMESH_Gen in smesh.py
599 //================================================================================
601 const char* _pyGen::AccessorMethod() const
603 return SMESH_2smeshpy::GenName();
606 //================================================================================
608 * \brief Convert a command using a specific converter
609 * \param theCommand - the command to convert
611 //================================================================================
613 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
615 // store theCommand in the sequence
616 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
618 Handle(_pyCommand) aCommand = myCommands.back();
619 #ifdef DUMP_CONVERSION
620 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
623 const _pyID& objID = aCommand->GetObject();
625 if ( objID.IsEmpty() )
628 // Prevent moving a command creating a sub-mesh to the end of the script
629 // if the sub-mesh is used in theCommand as argument
630 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
632 // PlaceSubmeshAfterItsCreation( aCommand );
635 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
636 //StructToList( aCommand );
638 // not to erase _pySelfEraser's etc. used as args in some commands
640 #ifdef USE_STRING_FAMILY
642 if ( myKeepAgrCmdsIDs.IsIn( theCommand, objID ))
644 Handle(_pyObject) obj = FindObject( objID );
647 obj->AddArgCmd( aCommand );
648 //cout << objID << " found in " << theCommand << endl;
652 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
653 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
654 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
656 Handle(_pyObject) obj = FindObject( *id );
658 obj->AddArgCmd( aCommand );
663 // Find an object to process theCommand
666 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
668 this->Process( aCommand );
669 //addFilterUser( aCommand, theGen ); // protect filters from clearing
673 // SMESH_Mesh method?
674 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
675 if ( id_mesh != myMeshes.end() )
677 //id_mesh->second->AddProcessedCmd( aCommand );
679 // check for mesh editor object
680 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
681 _pyID editorID = aCommand->GetResultValue();
682 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
683 myMeshEditors.insert( make_pair( editorID, editor ));
686 // check for SubMesh objects
687 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
688 _pyID subMeshID = aCommand->GetResultValue();
689 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
690 CheckObjectIsReCreated( subMesh );
691 myObjects.insert( make_pair( subMeshID, subMesh ));
694 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
695 //GetIDSourceToList( aCommand );
697 //addFilterUser( aCommand, theGen ); // protect filters from clearing
699 id_mesh->second->Process( aCommand );
700 id_mesh->second->AddProcessedCmd( aCommand );
704 // SMESH_MeshEditor method?
705 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
706 if ( id_editor != myMeshEditors.end() )
708 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
709 //GetIDSourceToList( aCommand );
711 //addFilterUser( aCommand, theGen ); // protect filters from clearing
713 const TCollection_AsciiString& method = aCommand->GetMethod();
715 // some commands of SMESH_MeshEditor create meshes and groups
716 _pyID meshID, groups;
717 if ( method.Search("MakeMesh") != -1 )
718 meshID = aCommand->GetResultValue();
719 else if ( method == "MakeBoundaryMesh")
720 meshID = aCommand->GetResultValue(1);
721 else if ( method == "MakeBoundaryElements")
722 meshID = aCommand->GetResultValue(2);
724 if ( method.Search("MakeGroups") != -1 ||
725 method == "ExtrusionAlongPathX" ||
726 method == "ExtrusionAlongPathObjX" ||
727 method == "DoubleNodeGroupNew" ||
728 method == "DoubleNodeGroupsNew" ||
729 method == "DoubleNodeElemGroupNew" ||
730 method == "DoubleNodeElemGroupsNew"||
731 method == "DoubleNodeElemGroup2New"||
732 method == "DoubleNodeElemGroups2New"
734 groups = aCommand->GetResultValue();
735 else if ( method == "MakeBoundaryMesh" )
736 groups = aCommand->GetResultValue(2);
737 else if ( method == "MakeBoundaryElements")
738 groups = aCommand->GetResultValue(3);
739 else if ( method == "Create0DElementsOnAllNodes" &&
740 aCommand->GetArg(2).Length() > 2 ) // group name != ''
741 groups = aCommand->GetResultValue();
743 id_editor->second->Process( aCommand );
744 id_editor->second->AddProcessedCmd( aCommand );
747 if ( !meshID.IsEmpty() &&
748 !myMeshes.count( meshID ) &&
749 aCommand->IsStudyEntry( meshID ))
751 _AString processedCommand = aCommand->GetString();
752 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
753 CheckObjectIsReCreated( mesh );
754 myMeshes.insert( make_pair( meshID, mesh ));
756 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
759 if ( !groups.IsEmpty() )
761 if ( !aCommand->IsStudyEntry( meshID ))
762 meshID = id_editor->second->GetMesh();
763 Handle(_pyMesh) mesh = myMeshes[ meshID ];
765 list< _pyID > idList = aCommand->GetStudyEntries( groups );
766 list< _pyID >::iterator grID = idList.begin();
767 for ( ; grID != idList.end(); ++grID )
768 if ( !myObjects.count( *grID ))
770 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
772 if ( !mesh.IsNull() ) mesh->AddGroup( group );
776 } // SMESH_MeshEditor methods
778 // SMESH_Hypothesis method?
779 Handle(_pyHypothesis) hyp = FindHyp( objID );
780 if ( !hyp.IsNull() && !hyp->IsAlgo() )
782 hyp->Process( aCommand );
783 hyp->AddProcessedCmd( aCommand );
787 // aFilterManager.CreateFilter() ?
788 if ( aCommand->GetMethod() == "CreateFilter" )
790 // Set a more human readable name to a filter
791 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
792 _pyID newID, filterID = aCommand->GetResultValue();
793 int pos = filterID.Search( "0x" );
795 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
797 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
800 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
801 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
803 // create _pySelfEraser for functors
804 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
805 functor->IgnoreOwnCalls(); // to erase if not used as an argument
806 AddObject( functor );
809 // other object method?
810 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
811 if ( id_obj != myObjects.end() ) {
812 id_obj->second->Process( aCommand );
813 id_obj->second->AddProcessedCmd( aCommand );
817 // Add access to a wrapped mesh
818 AddMeshAccessorMethod( aCommand );
820 // Add access to a wrapped algorithm
821 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
823 // PAL12227. PythonDump was not updated at proper time; result is
824 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
825 // TypeError: __init__() takes exactly 11 arguments (10 given)
826 const char wrongCommand[] = "SMESH.Filter.Criterion(";
827 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
829 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
830 // there must be 10 arguments, 5-th arg ThresholdID is missing,
831 const int wrongNbArgs = 9, missingArg = 5;
832 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
834 for ( int i = wrongNbArgs; i > missingArg; --i )
835 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
836 tmpCmd.SetArg( missingArg, "''");
837 aCommand->GetString().Trunc( beg - 1 );
838 aCommand->GetString() += tmpCmd.GetString();
841 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
843 // instead of "SMESH.Filter.Criterion(
844 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
845 // 1 2 3 4 5 6 7 8 9 10
846 // in order to avoid the problem of type mismatch of long and FunctorType
847 const TCollection_AsciiString
848 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
849 TCollection_AsciiString
850 Type = aCommand->GetArg(1), // long
851 Compare = aCommand->GetArg(2), // long
852 Threshold = aCommand->GetArg(3), // double
853 ThresholdStr = aCommand->GetArg(4), // string
854 ThresholdID = aCommand->GetArg(5), // string
855 UnaryOp = aCommand->GetArg(6), // long
856 BinaryOp = aCommand->GetArg(7), // long
857 Tolerance = aCommand->GetArg(8), // double
858 TypeOfElement = aCommand->GetArg(9), // ElementType
859 Precision = aCommand->GetArg(10); // long
860 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
861 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
862 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
863 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
864 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
866 if ( Compare == "SMESH.FT_EqualTo" )
869 aCommand->RemoveArgs();
870 aCommand->SetObject( SMESH_2smeshpy::GenName() );
871 aCommand->SetMethod( "GetCriterion" );
873 aCommand->SetArg( 1, TypeOfElement );
874 aCommand->SetArg( 2, Type );
875 aCommand->SetArg( 3, Compare );
877 if ( Threshold.IsIntegerValue() )
879 int iGeom = Threshold.IntegerValue();
880 if ( Type == "SMESH.FT_ElemGeomType" )
882 // set SMESH.GeometryType instead of a numerical Threshold
883 const int nbTypes = SMESH::Geom_POLYHEDRA+1;
884 const char* types[nbTypes] = {
885 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
886 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
888 if ( -1 < iGeom && iGeom < nbTypes )
889 Threshold = SMESH + types[ iGeom ];
892 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
893 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
894 else if ( ThresholdStr.Length() != 2 )
895 aCommand->SetArg( 4, ThresholdStr );
896 else if ( ThresholdID.Length() != 2 )
897 aCommand->SetArg( 4, ThresholdID );
899 aCommand->SetArg( 4, Threshold );
900 // find the last not default arg
902 if ( Tolerance == dfltTol ) {
904 if ( BinaryOp == dfltFunctor ) {
906 if ( UnaryOp == dfltFunctor )
910 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
911 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
912 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
913 if ( Precision != dfltPreci )
915 TCollection_AsciiString crit = aCommand->GetResultValue();
916 aCommand->GetString() += "; ";
917 aCommand->GetString() += crit + ".Precision = " + Precision;
923 //================================================================================
925 * \brief Convert the command or remember it for later conversion
926 * \param theCommand - The python command calling a method of SMESH_Gen
928 //================================================================================
930 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
932 // there are methods to convert:
933 // CreateMesh( shape )
934 // Concatenate( [mesh1, ...], ... )
935 // CreateHypothesis( theHypType, theLibName )
936 // Compute( mesh, geom )
937 // Evaluate( mesh, geom )
939 TCollection_AsciiString method = theCommand->GetMethod();
941 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
943 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
947 if ( method == "CreateMeshesFromUNV" ||
948 method == "CreateMeshesFromSTL" ||
949 method == "CopyMesh" ) // command result is a mesh
951 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
955 if( method == "CreateMeshesFromMED" ||
956 method == "CreateMeshesFromSAUV"||
957 method == "CreateMeshesFromCGNS" ||
958 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
960 for ( int ind = 0; ind < theCommand->GetNbResultValues(); ind++ )
962 _pyID meshID = theCommand->GetResultValue(ind+1);
963 if ( !theCommand->IsStudyEntry( meshID ) ) continue;
964 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind+1));
967 if ( method == "CreateMeshesFromGMF" )
969 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
970 // CreateMeshesFromGMF( theFileName )
971 _AString file = theCommand->GetArg(1);
972 theCommand->RemoveArgs();
973 theCommand->SetArg( 1, file );
977 // CreateHypothesis()
978 if ( method == "CreateHypothesis" )
980 // issue 199929, remove standard library name (default parameter)
981 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
982 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
983 // keep the first argument
984 TCollection_AsciiString arg = theCommand->GetArg( 1 );
985 theCommand->RemoveArgs();
986 theCommand->SetArg( 1, arg );
989 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
990 CheckObjectIsReCreated( hyp );
991 myHypos.insert( make_pair( hyp->GetID(), hyp ));
996 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
997 if ( method == "Compute" )
999 const _pyID& meshID = theCommand->GetArg( 1 );
1000 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1001 if ( id_mesh != myMeshes.end() ) {
1002 theCommand->SetObject( meshID );
1003 theCommand->RemoveArgs();
1004 id_mesh->second->Process( theCommand );
1005 id_mesh->second->AddProcessedCmd( theCommand );
1010 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1011 if ( method == "Evaluate" )
1013 const _pyID& meshID = theCommand->GetArg( 1 );
1014 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1015 if ( id_mesh != myMeshes.end() ) {
1016 theCommand->SetObject( meshID );
1017 _pyID geom = theCommand->GetArg( 2 );
1018 theCommand->RemoveArgs();
1019 theCommand->SetArg( 1, geom );
1020 id_mesh->second->AddProcessedCmd( theCommand );
1025 // objects erasing creation command if no more its commands invoked:
1026 // SMESH_Pattern, FilterManager
1027 if ( method == "GetPattern" ||
1028 method == "CreateFilterManager" ||
1029 method == "CreateMeasurements" )
1031 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1032 if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
1033 theCommand->Clear(); // already created
1035 // Concatenate( [mesh1, ...], ... )
1036 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1038 if ( method == "ConcatenateWithGroups" ) {
1039 theCommand->SetMethod( "Concatenate" );
1040 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1042 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1044 AddMeshAccessorMethod( theCommand );
1046 else if ( method == "SetName" ) // SetName(obj,name)
1048 // store theCommand as one of object commands to erase it along with the object
1049 const _pyID& objID = theCommand->GetArg( 1 );
1050 Handle(_pyObject) obj = FindObject( objID );
1051 if ( !obj.IsNull() )
1052 obj->AddProcessedCmd( theCommand );
1055 // Replace name of SMESH_Gen
1057 // names of SMESH_Gen methods fully equal to methods defined in smesh.py
1058 static TStringSet smeshpyMethods;
1059 if ( smeshpyMethods.empty() ) {
1060 const char * names[] =
1061 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1062 "GetPattern","GetSubShapesId",
1063 "" }; // <- mark of array end
1064 smeshpyMethods.Insert( names );
1066 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1067 // smeshgen.Method() --> smesh.Method()
1068 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1070 // smeshgen.Method() --> smesh.smesh.Method()
1071 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1074 //================================================================================
1076 * \brief Convert the remembered commands
1078 //================================================================================
1080 void _pyGen::Flush()
1082 // create an empty command
1083 myLastCommand = new _pyCommand();
1085 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1086 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1087 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1089 if ( IsToKeepAllCommands() ) // historical dump
1091 // set myIsPublished = true to all objects
1092 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1093 id_mesh->second->SetRemovedFromStudy( false );
1094 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1095 id_hyp->second->SetRemovedFromStudy( false );
1096 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1097 id_obj->second->SetRemovedFromStudy( false );
1101 // let hypotheses find referred objects in order to prevent clearing
1102 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1103 list< Handle(_pyMesh) > fatherMeshes;
1104 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1105 if ( !id_hyp->second.IsNull() )
1106 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1108 // set myIsPublished = false to all objects depending on
1109 // meshes built on a removed geometry
1110 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1111 if ( id_mesh->second->IsNotGeomPublished() )
1112 id_mesh->second->SetRemovedFromStudy( true );
1115 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1116 if ( ! id_mesh->second.IsNull() )
1117 id_mesh->second->Flush();
1120 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1121 if ( !id_hyp->second.IsNull() ) {
1122 id_hyp->second->Flush();
1123 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1124 if ( !id_hyp->second->IsWrapped() )
1125 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1128 // Flush other objects
1129 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1130 if ( ! id_obj->second.IsNull() )
1131 id_obj->second->Flush();
1133 myLastCommand->SetOrderNb( ++myNbCommands );
1134 myCommands.push_back( myLastCommand );
1137 //================================================================================
1139 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1140 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1142 //================================================================================
1144 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1146 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1147 for ( ; id_obj != myObjects.end(); ++id_obj )
1149 if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1150 for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1152 const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1153 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1155 list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1156 list< _pyID >::iterator id = idList.begin();
1157 for ( ; id != idList.end(); ++id )
1158 if ( id_obj->first == *id )
1159 // _pySubMesh::Process() does what we need
1160 Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1165 //================================================================================
1167 * \brief Clean commmands of removed objects depending on myIsPublished flag
1169 //================================================================================
1171 void _pyGen::ClearCommands()
1173 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1174 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1175 id_mesh->second->ClearCommands();
1177 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1178 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1179 if ( !id_hyp->second.IsNull() )
1180 id_hyp->second->ClearCommands();
1182 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1183 for ( ; id_obj != myObjects.end(); ++id_obj )
1184 id_obj->second->ClearCommands();
1187 //================================================================================
1189 * \brief Release mutual handles of objects
1191 //================================================================================
1195 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1196 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1197 id_mesh->second->Free();
1200 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1201 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1202 id_ed->second->Free();
1203 myMeshEditors.clear();
1205 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1206 for ( ; id_obj != myObjects.end(); ++id_obj )
1207 id_obj->second->Free();
1210 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1211 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1212 if ( !id_hyp->second.IsNull() )
1213 id_hyp->second->Free();
1216 myFile2ExportedMesh.clear();
1218 //myKeepAgrCmdsIDs.Print();
1221 //================================================================================
1223 * \brief Add access method to mesh that is an argument
1224 * \param theCmd - command to add access method
1225 * \retval bool - true if added
1227 //================================================================================
1229 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1232 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1233 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1234 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1240 //================================================================================
1242 * \brief Add access method to algo that is an object or an argument
1243 * \param theCmd - command to add access method
1244 * \retval bool - true if added
1246 //================================================================================
1248 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1251 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1252 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1253 if ( !id_hyp->second.IsNull() &&
1254 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1255 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1256 id_hyp->second->AccessorMethod() ))
1262 //================================================================================
1264 * \brief Find hypothesis by ID (entry)
1265 * \param theHypID - The hypothesis ID
1266 * \retval Handle(_pyHypothesis) - The found hypothesis
1268 //================================================================================
1270 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1272 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1273 if ( id_hyp != myHypos.end() &&
1274 !id_hyp->second.IsNull() &&
1275 theHypID == id_hyp->second->GetID() )
1276 return id_hyp->second;
1277 return Handle(_pyHypothesis)();
1280 //================================================================================
1282 * \brief Find algorithm able to create a hypothesis
1283 * \param theGeom - The shape ID the algorithm was created on
1284 * \param theMesh - The mesh ID that created the algorithm
1285 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1286 * \retval Handle(_pyHypothesis) - The found algo
1288 //================================================================================
1290 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1291 const Handle(_pyHypothesis)& theHypothesis )
1293 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1294 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1295 if ( !id_hyp->second.IsNull() &&
1296 id_hyp->second->IsAlgo() &&
1297 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1298 id_hyp->second->GetGeom() == theGeom &&
1299 id_hyp->second->GetMesh() == theMesh )
1300 return id_hyp->second;
1301 return Handle(_pyHypothesis)();
1304 //================================================================================
1306 * \brief Find subMesh by ID (entry)
1307 * \param theSubMeshID - The subMesh ID
1308 * \retval Handle(_pySubMesh) - The found subMesh
1310 //================================================================================
1312 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1314 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1315 if ( id_subMesh != myObjects.end() )
1316 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1317 return Handle(_pySubMesh)();
1321 //================================================================================
1323 * \brief Change order of commands in the script
1324 * \param theCmd1 - One command
1325 * \param theCmd2 - Another command
1327 //================================================================================
1329 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1331 list< Handle(_pyCommand) >::iterator pos1, pos2;
1332 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1333 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1334 myCommands.insert( pos1, theCmd2 );
1335 myCommands.insert( pos2, theCmd1 );
1336 myCommands.erase( pos1 );
1337 myCommands.erase( pos2 );
1339 int nb1 = theCmd1->GetOrderNb();
1340 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1341 theCmd2->SetOrderNb( nb1 );
1342 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1343 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1346 //================================================================================
1348 * \brief Set one command after the other
1349 * \param theCmd - Command to move
1350 * \param theAfterCmd - Command ater which to insert the first one
1352 //================================================================================
1354 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1356 setNeighbourCommand( theCmd, theAfterCmd, true );
1359 //================================================================================
1361 * \brief Set one command before the other
1362 * \param theCmd - Command to move
1363 * \param theBeforeCmd - Command before which to insert the first one
1365 //================================================================================
1367 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1369 setNeighbourCommand( theCmd, theBeforeCmd, false );
1372 //================================================================================
1374 * \brief Set one command before or after the other
1375 * \param theCmd - Command to move
1376 * \param theOtherCmd - Command ater or before which to insert the first one
1378 //================================================================================
1380 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1381 Handle(_pyCommand)& theOtherCmd,
1382 const bool theIsAfter )
1384 list< Handle(_pyCommand) >::iterator pos;
1385 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1386 myCommands.erase( pos );
1387 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1388 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1391 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1392 (*pos)->SetOrderNb( i++ );
1395 //================================================================================
1397 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1399 //================================================================================
1401 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1403 // No more needed after adding _pyObject::myArgCommands
1405 // const char filterPrefix[] = "aFilter0x";
1406 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1409 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1411 // const _AString & arg = theCommand->GetArg( i );
1412 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1413 // if ( arg.Search( filterPrefix ) != 1 )
1416 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1417 // if ( !filter.IsNull() )
1419 // filter->AddUser( user );
1420 // if ( !filter->GetNewID().IsEmpty() )
1421 // theCommand->SetArg( i, filter->GetNewID() );
1426 //================================================================================
1428 * \brief Set command be last in list of commands
1429 * \param theCmd - Command to be last
1431 //================================================================================
1433 Handle(_pyCommand)& _pyGen::GetLastCommand()
1435 return myLastCommand;
1438 //================================================================================
1440 * \brief Set method to access to object wrapped with python class
1441 * \param theID - The wrapped object entry
1442 * \param theMethod - The accessor method
1444 //================================================================================
1446 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1448 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1451 //================================================================================
1453 * \brief Generated new ID for object and assign with existing name
1454 * \param theID - ID of existing object
1456 //================================================================================
1458 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1463 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1465 while ( myObjectNames.IsBound( aNewID ) );
1467 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1468 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1469 : _pyID( "A" ) + aNewID );
1473 //================================================================================
1475 * \brief Stores theObj in myObjects
1477 //================================================================================
1479 void _pyGen::AddObject( Handle(_pyObject)& theObj )
1481 if ( theObj.IsNull() ) return;
1483 CheckObjectIsReCreated( theObj );
1485 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1486 myMeshes.insert( make_pair( theObj->GetID(), Handle(_pyMesh)::DownCast( theObj )));
1488 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1489 myMeshEditors.insert( make_pair( theObj->GetID(), Handle(_pyMeshEditor)::DownCast( theObj )));
1492 myObjects.insert( make_pair( theObj->GetID(), theObj ));
1495 //================================================================================
1497 * \brief Erases an existing object with the same ID. This method should be called
1498 * before storing theObj in _pyGen
1500 //================================================================================
1502 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1504 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1507 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1508 Handle(_pyObject) existing =
1509 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1510 if ( !existing.IsNull() && existing != theObj )
1512 existing->SetRemovedFromStudy( true );
1513 existing->ClearCommands();
1516 if ( myHypos.count( theObj->GetID() ))
1517 myHypos.erase( theObj->GetID() );
1519 else if ( myMeshes.count( theObj->GetID() ))
1521 myMeshes.erase( theObj->GetID() );
1523 else if ( myObjects.count( theObj->GetID() ))
1525 myObjects.erase( theObj->GetID() );
1530 //================================================================================
1532 * \brief Re-register an object with other ID to make it Process() commands of
1533 * other object having this ID
1535 //================================================================================
1537 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1539 if ( theObj.IsNull() ) return;
1541 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1542 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1544 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1545 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1548 myObjects.insert( make_pair( theID, theObj ));
1551 //================================================================================
1553 * \brief Finds a _pyObject by ID
1555 //================================================================================
1557 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1560 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1561 if ( id_obj != myObjects.end() )
1562 return id_obj->second;
1565 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1566 if ( id_obj != myMeshes.end() )
1567 return id_obj->second;
1570 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1571 // if ( id_obj != myMeshEditors.end() )
1572 // return id_obj->second;
1574 return Handle(_pyObject)();
1577 //================================================================================
1579 * \brief Check if a study entry is under GEOM component
1581 //================================================================================
1583 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1587 return ( myGeomIDIndex <= theObjID.Length() &&
1588 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1589 _pyCommand::IsStudyEntry( theObjID ));
1594 //================================================================================
1596 * \brief Returns true if an object is not present in a study
1598 //================================================================================
1600 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1602 if ( theObjID.IsEmpty() ) return false;
1604 if ( myObjectNames.IsBound( theObjID ))
1605 return false; // SMESH object is in study
1607 // either the SMESH object is not in study or it is a GEOM object
1608 if ( IsGeomObject( theObjID ))
1610 SALOMEDS::SObject_var so = myStudy->FindObjectID( theObjID.ToCString() );
1611 if ( so->_is_nil() ) return true;
1612 CORBA::Object_var obj = so->GetObject();
1613 return CORBA::is_nil( obj );
1615 return true; // SMESH object not in study
1618 //================================================================================
1620 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1621 * this object is not dumped
1622 * \param [in] theObjID - entry of the object whose creation command was eliminated
1624 //================================================================================
1626 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1628 myRemovedObjIDs.insert( theObjID );
1631 //================================================================================
1633 * \brief Return reader of hypotheses of plugins
1635 //================================================================================
1637 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1639 if (myHypReader.IsNull() )
1640 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1646 //================================================================================
1648 * \brief Mesh created by SMESH_Gen
1650 //================================================================================
1652 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1653 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1655 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1656 myGeomNotInStudy = true;
1658 // convert my creation command --> smeshpy.Mesh(...)
1659 Handle(_pyCommand) creationCmd = GetCreationCmd();
1660 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1661 creationCmd->SetMethod( "Mesh" );
1662 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1665 //================================================================================
1667 * \brief Mesh created by SMESH_MeshEditor
1669 //================================================================================
1671 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1672 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1674 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1676 // this mesh depends on the exported mesh
1677 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1678 if ( !file.IsEmpty() )
1680 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1681 addFatherMesh( exportData.myMesh );
1682 if ( !exportData.myLastComputeCmd.IsNull() )
1684 // restore cleared Compute() by which the exported mesh was generated
1685 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1686 // protect that Compute() cmd from clearing
1687 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1688 exportData.myMesh->myLastComputeCmd.Nullify();
1692 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1694 // this mesh depends on concatenated meshes
1695 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1696 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1697 list< _pyID >::iterator meshID = idList.begin();
1698 for ( ; meshID != idList.end(); ++meshID )
1699 addFatherMesh( *meshID );
1701 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1703 // this mesh depends on a copied IdSource
1704 const _pyID& objID = theCreationCmd->GetArg( 1 );
1705 addFatherMesh( objID );
1707 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1708 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1709 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1711 // this mesh depends on a source mesh
1712 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1713 const _pyID& meshID = theCreationCmd->GetObject();
1714 addFatherMesh( meshID );
1717 // convert my creation command
1718 Handle(_pyCommand) creationCmd = GetCreationCmd();
1719 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1720 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1723 //================================================================================
1725 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1726 * \param theCommand - Engine method called for this mesh
1728 //================================================================================
1730 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1732 // some methods of SMESH_Mesh interface needs special conversion
1733 // to methods of Mesh python class
1735 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1736 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1737 // 2. AddHypothesis(geom, hyp)
1738 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1739 // 3. CreateGroupFromGEOM(type, name, grp)
1740 // --> in Mesh.Group(grp, name="")
1741 // 4. ExportToMED(f, auto_groups, version)
1742 // --> in Mesh.ExportMED( f, auto_groups, version )
1745 const TCollection_AsciiString& method = theCommand->GetMethod();
1746 // ----------------------------------------------------------------------
1747 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1749 if ( !theGen->IsToKeepAllCommands() ) // !historical
1751 list< Handle(_pyHypothesis) >::iterator hyp;
1752 if ( !myLastComputeCmd.IsNull() )
1754 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1755 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1757 myLastComputeCmd->Clear();
1759 myLastComputeCmd = theCommand;
1761 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1762 (*hyp)->MeshComputed( myLastComputeCmd );
1766 // ----------------------------------------------------------------------
1767 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1769 if ( !theGen->IsToKeepAllCommands() ) // !historical
1772 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1773 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1774 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1776 if ( !myLastComputeCmd.IsNull() )
1778 list< Handle(_pyHypothesis) >::iterator hyp;
1779 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1780 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1782 myLastComputeCmd->Clear();
1785 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1786 for ( ; e != myEditors.end(); ++e )
1788 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1789 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1790 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1791 if ( !(*cmd)->IsEmpty() )
1793 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1797 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1800 // ----------------------------------------------------------------------
1801 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1802 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1803 if ( !subMesh.IsNull() ) {
1804 subMesh->SetCreator( this );
1805 mySubmeshes.push_back( subMesh );
1808 // ----------------------------------------------------------------------
1809 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1810 myAddHypCmds.push_back( theCommand );
1812 const _pyID& hypID = theCommand->GetArg( 2 );
1813 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1814 if ( !hyp.IsNull() ) {
1815 myHypos.push_back( hyp );
1816 if ( hyp->GetMesh().IsEmpty() )
1817 hyp->SetMesh( this->GetID() );
1820 // ----------------------------------------------------------------------
1821 else if ( method == "CreateGroup" ||
1822 method == "CreateGroupFromGEOM" ||
1823 method == "CreateGroupFromFilter" )
1825 Handle(_pyGroup) group = new _pyGroup( theCommand );
1826 myGroups.push_back( group );
1827 theGen->AddObject( group );
1829 // ----------------------------------------------------------------------
1830 // update list of groups
1831 else if ( method == "GetGroups" )
1833 bool allGroupsRemoved = true;
1834 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1835 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1836 list< _pyID >::iterator grID = idList.begin();
1837 const int nbGroupsBefore = myGroups.size();
1838 Handle(_pyObject) obj;
1839 for ( ; grID != idList.end(); ++grID )
1841 obj = theGen->FindObject( *grID );
1844 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1845 theGen->AddObject( group );
1846 myGroups.push_back( group );
1849 if ( !obj->CanClear() )
1850 allGroupsRemoved = false;
1852 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1853 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1855 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1857 // check if the preceding command is Compute();
1858 // if GetGroups() is just after Compute(), this can mean that the groups
1859 // were created by some algorithm and hence Compute() should not be discarded
1860 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1861 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1862 while ( (*cmd)->GetMethod() == "GetGroups" )
1864 if ( myLastComputeCmd == (*cmd))
1865 // protect last Compute() from clearing by the next Compute()
1866 myLastComputeCmd.Nullify();
1869 // ----------------------------------------------------------------------
1870 // notify a group about full removal
1871 else if ( method == "RemoveGroupWithContents" ||
1872 method == "RemoveGroup")
1874 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1875 const _pyID groupID = theCommand->GetArg( 1 );
1876 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1877 if ( !grp.IsNull() )
1879 if ( method == "RemoveGroupWithContents" )
1880 grp->RemovedWithContents();
1881 // to clear RemoveGroup() if the group creation is cleared
1882 grp->AddProcessedCmd( theCommand );
1886 // ----------------------------------------------------------------------
1887 else if ( theCommand->MethodStartsFrom( "Export" ))
1889 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1890 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1892 theCommand->SetMethod( "ExportMED" );
1893 if ( theCommand->GetNbArgs() == 5 )
1895 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1896 _AString autoDimension = theCommand->GetArg( 5 );
1897 theCommand->SetArg( 5, "None" );
1898 theCommand->SetArg( 6, autoDimension );
1901 else if ( method == "ExportCGNS" )
1902 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1903 _pyID partID = theCommand->GetArg( 1 );
1904 int nbArgs = theCommand->GetNbArgs();
1905 for ( int i = 2; i <= nbArgs; ++i )
1906 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1907 theCommand->SetArg( nbArgs, partID );
1909 else if ( method == "ExportGMF" )
1910 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1911 _pyID partID = theCommand->GetArg( 1 );
1912 _AString file = theCommand->GetArg( 2 );
1913 theCommand->RemoveArgs();
1914 theCommand->SetArg( 1, file );
1915 theCommand->SetArg( 2, partID );
1917 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1918 { // ExportPartTo*(part, ...) -> Export*(..., part)
1920 // remove "PartTo" from the method
1921 TCollection_AsciiString newMethod = method;
1922 newMethod.Remove( 7, 6 );
1923 theCommand->SetMethod( newMethod );
1924 // make the 1st arg be the last one (or last but one for ExportMED())
1925 _pyID partID = theCommand->GetArg( 1 );
1926 int nbArgs = theCommand->GetNbArgs() - (newMethod == "ExportMED");
1927 for ( int i = 2; i <= nbArgs; ++i )
1928 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1929 theCommand->SetArg( nbArgs, partID );
1931 // remember file name
1932 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1933 ExportedMeshData( this, myLastComputeCmd ));
1935 // ----------------------------------------------------------------------
1936 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1938 _pyID hypID = theCommand->GetArg( 2 );
1939 _pyID geomID = theCommand->GetArg( 1 );
1940 bool isLocal = ( geomID != GetGeom() );
1942 // check if this mesh still has corresponding addition command
1943 Handle(_pyCommand) addCmd;
1944 list< Handle(_pyCommand) >::iterator cmd;
1945 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1946 for ( int i = 0; i < 2; ++i )
1948 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1949 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1951 bool sameHyp = true;
1952 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1953 sameHyp = false; // other hyp
1954 if ( (*cmd)->GetNbArgs() == 2 &&
1955 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1956 sameHyp = false; // other geom
1957 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
1958 sameHyp = false; // other geom
1962 cmd = addHypCmds.erase( cmd );
1963 if ( !theGen->IsToKeepAllCommands() ) {
1965 theCommand->Clear();
1974 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1975 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
1976 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1977 _pyID geom = theCommand->GetArg( 1 );
1978 theCommand->RemoveArgs();
1979 theCommand->SetArg( 1, hypID );
1980 if ( geom != GetGeom() )
1981 theCommand->SetArg( 2, geom );
1983 // remove hyp from myHypos
1984 myHypos.remove( hyp );
1986 // check for SubMesh order commands
1987 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
1989 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1990 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1991 // commands are moved at the end of the script
1992 TCollection_AsciiString subIDs =
1993 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
1994 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
1995 list< _pyID >::iterator subID = idList.begin();
1996 for ( ; subID != idList.end(); ++subID )
1998 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
1999 if ( !subMesh.IsNull() )
2000 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2003 // add accessor method if necessary
2006 if ( NeedMeshAccess( theCommand ))
2007 // apply theCommand to the mesh wrapped by smeshpy mesh
2008 AddMeshAccess( theCommand );
2012 //================================================================================
2014 * \brief Return True if addition of accesor method is needed
2016 //================================================================================
2018 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2020 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2021 // so no conversion is needed for them at all:
2022 static TStringSet sameMethods;
2023 if ( sameMethods.empty() ) {
2024 const char * names[] =
2025 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2026 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
2027 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2028 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2029 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2030 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2031 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2032 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2033 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2034 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2035 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2036 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2037 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2038 ,"" }; // <- mark of end
2039 sameMethods.Insert( names );
2042 return !sameMethods.Contains( theCommand->GetMethod() );
2045 //================================================================================
2047 * \brief Convert creation and addition of all algos and hypos
2049 //================================================================================
2051 void _pyMesh::Flush()
2054 // get the meshes this mesh depends on via hypotheses
2055 list< Handle(_pyMesh) > fatherMeshes;
2056 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2057 for ( ; hyp != myHypos.end(); ++hyp )
2058 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2059 myGeomNotInStudy = true;
2061 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2062 for ( ; m != fatherMeshes.end(); ++m )
2063 addFatherMesh( *m );
2064 // if ( removedGeom )
2065 // SetRemovedFromStudy(); // as reffered geometry not in study
2067 if ( myGeomNotInStudy )
2070 list < Handle(_pyCommand) >::iterator cmd;
2072 // try to convert algo addition like this:
2073 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2074 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2076 Handle(_pyCommand) addCmd = *cmd;
2078 _pyID algoID = addCmd->GetArg( 2 );
2079 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2080 if ( algo.IsNull() || !algo->IsAlgo() )
2083 // check and create new algorithm instance if it is already wrapped
2084 if ( algo->IsWrapped() ) {
2085 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2086 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2087 TCollection_AsciiString( " = " ) + theGen->GetID() +
2088 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2089 TCollection_AsciiString( "\" )" );
2091 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2092 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2093 if ( !newAlgo.IsNull() ) {
2094 newAlgo->Assign( algo, this->GetID() );
2095 newAlgo->SetCreationCmd( newCmd );
2097 // set algorithm creation
2098 theGen->SetCommandBefore( newCmd, addCmd );
2099 myHypos.push_back( newAlgo );
2100 if ( !myLastComputeCmd.IsNull() &&
2101 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2102 newAlgo->MeshComputed( myLastComputeCmd );
2107 _pyID geom = addCmd->GetArg( 1 );
2108 bool isLocalAlgo = ( geom != GetGeom() );
2111 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2113 // wrapped algo is created after mesh creation
2114 GetCreationCmd()->AddDependantCmd( addCmd );
2116 if ( isLocalAlgo ) {
2117 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2118 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2119 TCollection_AsciiString( "geom=" ) + geom );
2120 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2121 list < Handle(_pySubMesh) >::iterator smIt;
2122 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2123 Handle(_pySubMesh) subMesh = *smIt;
2124 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2125 if ( geom == subCmd->GetArg( 1 )) {
2126 subCmd->SetObject( algo->GetID() );
2127 subCmd->RemoveArgs();
2128 subMesh->SetCreator( algo );
2133 else // KO - ALGO was already created
2135 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2136 addCmd->RemoveArgs();
2137 addCmd->SetArg( 1, algoID );
2139 addCmd->SetArg( 2, geom );
2140 myNotConvertedAddHypCmds.push_back( addCmd );
2144 // try to convert hypo addition like this:
2145 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2146 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2148 Handle(_pyCommand) addCmd = *cmd;
2149 _pyID hypID = addCmd->GetArg( 2 );
2150 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2151 if ( hyp.IsNull() || hyp->IsAlgo() )
2153 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2155 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2156 _pyID geom = addCmd->GetArg( 1 );
2157 addCmd->RemoveArgs();
2158 addCmd->SetArg( 1, hypID );
2159 if ( geom != GetGeom() )
2160 addCmd->SetArg( 2, geom );
2161 myNotConvertedAddHypCmds.push_back( addCmd );
2165 myAddHypCmds.clear();
2166 mySubmeshes.clear();
2169 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2170 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2174 //================================================================================
2176 * \brief Sets myIsPublished of me and of all objects depending on me.
2178 //================================================================================
2180 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2182 _pyObject::SetRemovedFromStudy(isRemoved);
2184 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2185 for ( ; sm != mySubmeshes.end(); ++sm )
2186 (*sm)->SetRemovedFromStudy(isRemoved);
2188 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2189 for ( ; gr != myGroups.end(); ++gr )
2190 (*gr)->SetRemovedFromStudy(isRemoved);
2192 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2193 for ( ; m != myChildMeshes.end(); ++m )
2194 (*m)->SetRemovedFromStudy(isRemoved);
2196 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2197 for ( ; e != myEditors.end(); ++e )
2198 (*e)->SetRemovedFromStudy(isRemoved);
2201 //================================================================================
2203 * \brief Return true if none of myChildMeshes is in study
2205 //================================================================================
2207 bool _pyMesh::CanClear()
2212 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2213 for ( ; m != myChildMeshes.end(); ++m )
2214 if ( !(*m)->CanClear() )
2220 //================================================================================
2222 * \brief Clear my commands and commands of mesh editor
2224 //================================================================================
2226 void _pyMesh::ClearCommands()
2232 // mark all sub-objects as not removed, except child meshes
2233 list< Handle(_pyMesh) > children;
2234 children.swap( myChildMeshes );
2235 SetRemovedFromStudy( false );
2236 children.swap( myChildMeshes );
2240 _pyObject::ClearCommands();
2242 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2243 for ( ; sm != mySubmeshes.end(); ++sm )
2244 (*sm)->ClearCommands();
2246 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2247 for ( ; gr != myGroups.end(); ++gr )
2248 (*gr)->ClearCommands();
2250 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2251 for ( ; e != myEditors.end(); ++e )
2252 (*e)->ClearCommands();
2255 //================================================================================
2257 * \brief Add a father mesh by ID
2259 //================================================================================
2261 void _pyMesh::addFatherMesh( const _pyID& meshID )
2263 if ( !meshID.IsEmpty() && meshID != GetID() )
2264 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2267 //================================================================================
2269 * \brief Add a father mesh
2271 //================================================================================
2273 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2275 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2277 //myFatherMeshes.push_back( mesh );
2278 mesh->myChildMeshes.push_back( this );
2280 // protect last Compute() from clearing by the next Compute()
2281 mesh->myLastComputeCmd.Nullify();
2285 //================================================================================
2287 * \brief MeshEditor convert its commands to ones of mesh
2289 //================================================================================
2291 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2292 _pyObject( theCreationCmd )
2294 myMesh = theCreationCmd->GetObject();
2295 myCreationCmdStr = theCreationCmd->GetString();
2296 theCreationCmd->Clear();
2298 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2299 if ( !mesh.IsNull() )
2300 mesh->AddEditor( this );
2303 //================================================================================
2305 * \brief convert its commands to ones of mesh
2307 //================================================================================
2309 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2311 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2312 // commands calling these methods are converted to calls of Mesh methods without
2313 // additional modifs, only object is changed from MeshEditor to Mesh.
2314 static TStringSet sameMethods;
2315 if ( sameMethods.empty() ) {
2316 const char * names[] = {
2317 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2318 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2319 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2320 "MoveNode", "MoveClosestNodeToPoint",
2321 "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2322 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2323 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2324 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2325 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2326 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2327 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2328 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2329 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2330 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2331 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2332 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2333 "GetLastCreatedElems",
2334 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2335 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2336 "MakeBoundaryElements", "SplitVolumesIntoTetra",
2337 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2338 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2339 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2340 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2341 ,"" }; // <- mark of the end
2342 sameMethods.Insert( names );
2345 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2346 TStringMap diffMethods;
2347 if ( diffMethods.empty() ) {
2348 const char * orig2newName[] = {
2349 // original name --------------> new name
2350 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2351 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2352 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2353 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2354 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2355 ""};// <- mark of the end
2356 diffMethods.Insert( orig2newName );
2359 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2360 // only by last two arguments
2361 static TStringSet diffLastTwoArgsMethods;
2362 if (diffLastTwoArgsMethods.empty() ) {
2363 const char * names[] = {
2364 "MirrorMakeGroups","MirrorObjectMakeGroups",
2365 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2366 "RotateMakeGroups","RotateObjectMakeGroups",
2367 ""};// <- mark of the end
2368 diffLastTwoArgsMethods.Insert( names );
2371 // only a method name is to change?
2372 const TCollection_AsciiString & method = theCommand->GetMethod();
2373 bool isPyMeshMethod = sameMethods.Contains( method );
2374 if ( !isPyMeshMethod )
2376 TCollection_AsciiString newMethod = diffMethods.Value( method );
2377 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2378 theCommand->SetMethod( newMethod );
2380 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2381 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2383 isPyMeshMethod = true;
2384 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2385 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2388 if ( !isPyMeshMethod )
2390 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2391 // functions with the flag "theMakeGroups = True" like:
2392 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2393 int pos = method.Search("MakeGroups");
2396 isPyMeshMethod = true;
2397 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2398 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2400 // 1. Remove "MakeGroups" from the Command
2401 TCollection_AsciiString aMethod = theCommand->GetMethod();
2402 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2405 pos = pos-2; //Remove "0D" from the Command too
2406 aMethod.Trunc(pos-1);
2407 theCommand->SetMethod(aMethod);
2409 // 2. And add last "True" argument(s)
2410 while(nbArgsToAdd--)
2411 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2412 if( is0DmethId || is0DmethObj )
2413 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2417 // ExtrusionSweep0D() -> ExtrusionSweep()
2418 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2419 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2420 method == "ExtrusionSweepObject0D" ))
2422 isPyMeshMethod = true;
2423 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2424 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2425 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2428 // DoubleNode...New(...) -> DoubleNode...(...,True)
2429 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2430 method == "DoubleNodeElemGroupsNew" ||
2431 method == "DoubleNodeGroupNew" ||
2432 method == "DoubleNodeGroupsNew" ||
2433 method == "DoubleNodeElemGroup2New" ||
2434 method == "DoubleNodeElemGroups2New"))
2436 isPyMeshMethod = true;
2437 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2438 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2439 if ( excessLen == 3 )
2441 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2443 else if ( theCommand->GetArg(4) == "0" ||
2444 theCommand->GetArg(5) == "0" )
2446 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2447 // Group = DoubleNodeGroup2New(,,,False, True)
2448 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2449 theCommand->SetResultValue( groupID );
2452 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2453 // FindElementsByPoint(x, y, z, elementType, meshPart)
2454 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2456 isPyMeshMethod = true;
2457 theCommand->SetMethod( "FindElementsByPoint" );
2458 // make the 1st arg be the last one
2459 _pyID partID = theCommand->GetArg( 1 );
2460 int nbArgs = theCommand->GetNbArgs();
2461 for ( int i = 2; i <= nbArgs; ++i )
2462 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2463 theCommand->SetArg( nbArgs, partID );
2465 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2466 if ( !isPyMeshMethod && method == "Reorient2D" )
2468 isPyMeshMethod = true;
2469 _AString mesh = theCommand->GetArg( 1 );
2470 _AString dir = theCommand->GetArg( 2 );
2471 _AString face = theCommand->GetArg( 3 );
2472 _AString point = theCommand->GetArg( 4 );
2473 theCommand->RemoveArgs();
2474 theCommand->SetArg( 1, mesh );
2475 theCommand->SetArg( 2, dir );
2476 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2477 theCommand->SetArg( 3, point );
2479 theCommand->SetArg( 3, face );
2482 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2484 isPyMeshMethod = true;
2485 int crit_arg = theCommand->GetNbArgs();
2486 const _AString& crit = theCommand->GetArg(crit_arg);
2487 if (crit.Search("MaxElementLength2D") != -1)
2488 theCommand->SetArg(crit_arg, "");
2491 if ( isPyMeshMethod )
2493 theCommand->SetObject( myMesh );
2497 // editor creation command is needed only if any editor function is called
2498 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2499 if ( !myCreationCmdStr.IsEmpty() ) {
2500 GetCreationCmd()->GetString() = myCreationCmdStr;
2501 myCreationCmdStr.Clear();
2506 //================================================================================
2508 * \brief Return true if my mesh can be removed
2510 //================================================================================
2512 bool _pyMeshEditor::CanClear()
2514 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2515 return mesh.IsNull() ? true : mesh->CanClear();
2518 //================================================================================
2520 * \brief _pyHypothesis constructor
2521 * \param theCreationCmd -
2523 //================================================================================
2525 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2526 _pyObject( theCreationCmd ), myCurCrMethod(0)
2528 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2531 //================================================================================
2533 * \brief Creates algorithm or hypothesis
2534 * \param theCreationCmd - The engine command creating a hypothesis
2535 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2537 //================================================================================
2539 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2541 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2542 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2544 Handle(_pyHypothesis) hyp, algo;
2547 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2548 if ( hypTypeQuoted.IsEmpty() )
2551 TCollection_AsciiString hypType =
2552 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2554 algo = new _pyAlgorithm( theCreationCmd );
2555 hyp = new _pyHypothesis( theCreationCmd );
2557 if ( hypType == "NumberOfSegments" ) {
2558 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2559 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2560 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2561 hyp->AddArgMethod( "SetNumberOfSegments" );
2562 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2563 hyp->AddArgMethod( "SetScaleFactor" );
2564 hyp->AddArgMethod( "SetReversedEdges" );
2565 // same for ""CompositeSegment_1D:
2566 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2567 hyp->AddArgMethod( "SetNumberOfSegments" );
2568 hyp->AddArgMethod( "SetScaleFactor" );
2569 hyp->AddArgMethod( "SetReversedEdges" );
2571 else if ( hypType == "SegmentLengthAroundVertex" ) {
2572 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2573 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2574 hyp->AddArgMethod( "SetLength" );
2575 // same for ""CompositeSegment_1D:
2576 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2577 hyp->AddArgMethod( "SetLength" );
2579 else if ( hypType == "LayerDistribution2D" ) {
2580 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2581 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2583 else if ( hypType == "LayerDistribution" ) {
2584 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2585 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2587 else if ( hypType == "CartesianParameters3D" ) {
2588 hyp = new _pyComplexParamHypo( theCreationCmd );
2589 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2590 for ( int iArg = 0; iArg < 4; ++iArg )
2591 hyp->setCreationArg( iArg+1, "[]");
2595 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2598 return algo->IsValid() ? algo : hyp;
2601 //================================================================================
2603 * \brief Returns true if addition of this hypothesis to a given mesh can be
2604 * wrapped into hypothesis creation
2606 //================================================================================
2608 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2610 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2612 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2613 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2619 //================================================================================
2621 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2622 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2623 * \param theAlgo - The algo that can create this hypo
2624 * \retval bool - false if the command cant be converted
2626 //================================================================================
2628 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2629 const _pyID& theMesh)
2631 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2633 if ( !IsWrappable( theMesh ))
2636 myGeom = theCmd->GetArg( 1 );
2638 Handle(_pyHypothesis) algo;
2640 // find algo created on myGeom in theMesh
2641 algo = theGen->FindAlgo( myGeom, theMesh, this );
2642 if ( algo.IsNull() )
2644 // attach hypothesis creation command to be after algo creation command
2645 // because it can be new created instance of algorithm
2646 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2650 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2651 theCmd->SetResultValue( GetID() );
2652 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2653 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2654 // set args (geom will be set by _pyMesh calling this method)
2655 theCmd->RemoveArgs();
2656 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2657 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2658 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2660 theCmd->SetArg( i+1, "[]");
2662 // set a new creation command
2663 GetCreationCmd()->Clear();
2664 // replace creation command by wrapped instance
2665 // please note, that hypothesis attaches to algo creation command (see upper)
2666 SetCreationCmd( theCmd );
2669 // clear commands setting arg values
2670 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2671 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2674 // set unknown arg commands after hypo creation
2675 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2676 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2677 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2678 afterCmd->AddDependantCmd( *cmd );
2684 //================================================================================
2686 * \brief Remember hypothesis parameter values
2687 * \param theCommand - The called hypothesis method
2689 //================================================================================
2691 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2693 ASSERT( !myIsAlgo );
2694 if ( !theGen->IsToKeepAllCommands() )
2695 rememberCmdOfParameter( theCommand );
2697 bool usedCommand = false;
2698 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2699 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2701 CreationMethod& crMethod = type2meth->second;
2702 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2703 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2705 myArgCommands.push_back( theCommand );
2707 while ( crMethod.myArgs.size() < i+1 )
2708 crMethod.myArgs.push_back( "[]" );
2709 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2714 myUnusedCommands.push_back( theCommand );
2717 //================================================================================
2719 * \brief Finish conversion
2721 //================================================================================
2723 void _pyHypothesis::Flush()
2727 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2728 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2729 // Add access to a wrapped mesh
2730 theGen->AddMeshAccessorMethod( *cmd );
2731 // Add access to a wrapped algorithm
2732 theGen->AddAlgoAccessorMethod( *cmd );
2734 cmd = myUnusedCommands.begin();
2735 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2736 // Add access to a wrapped mesh
2737 theGen->AddMeshAccessorMethod( *cmd );
2738 // Add access to a wrapped algorithm
2739 theGen->AddAlgoAccessorMethod( *cmd );
2742 // forget previous hypothesis modifications
2743 myArgCommands.clear();
2744 myUnusedCommands.clear();
2747 //================================================================================
2749 * \brief clear creation, arg and unkown commands
2751 //================================================================================
2753 void _pyHypothesis::ClearAllCommands()
2755 GetCreationCmd()->Clear();
2756 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2757 for ( ; cmd != myArgCommands.end(); ++cmd )
2759 cmd = myUnusedCommands.begin();
2760 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2765 //================================================================================
2767 * \brief Assign fields of theOther to me except myIsWrapped
2769 //================================================================================
2771 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2772 const _pyID& theMesh )
2774 // myCreationCmd = theOther->myCreationCmd;
2775 myIsAlgo = theOther->myIsAlgo;
2776 myIsWrapped = false;
2777 myGeom = theOther->myGeom;
2779 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2780 myAccumulativeMethods = theOther->myAccumulativeMethods;
2781 //myUnusedCommands = theOther->myUnusedCommands;
2782 // init myCurCrMethod
2783 GetCreationMethod( theOther->GetAlgoType() );
2786 //================================================================================
2788 * \brief Analyze my erasability depending on myReferredObjs
2790 //================================================================================
2792 bool _pyHypothesis::CanClear()
2796 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2797 for ( ; obj != myReferredObjs.end(); ++obj )
2798 if ( (*obj)->CanClear() )
2805 //================================================================================
2807 * \brief Clear my commands depending on usage by meshes
2809 //================================================================================
2811 void _pyHypothesis::ClearCommands()
2813 // if ( !theGen->IsToKeepAllCommands() )
2815 // bool isUsed = false;
2816 // int lastComputeOrder = 0;
2817 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2818 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2819 // if ( ! (*cmd)->IsEmpty() )
2822 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2823 // lastComputeOrder = (*cmd)->GetOrderNb();
2827 // SetRemovedFromStudy( true );
2831 // // clear my commands invoked after lastComputeOrder
2832 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2833 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2835 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2836 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2837 // // cmds.back()->Clear();
2841 _pyObject::ClearCommands();
2844 //================================================================================
2846 * \brief Find arguments that are objects like mesh, group, geometry
2847 * \param meshes - referred meshes (directly or indirrectly)
2848 * \retval bool - false if a referred geometry is not in the study
2850 //================================================================================
2852 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2854 if ( IsAlgo() ) return true;
2856 bool geomPublished = true;
2857 vector< _AString > args;
2858 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2859 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2861 CreationMethod& crMethod = type2meth->second;
2862 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2864 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2865 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2866 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2867 args.push_back( (*cmd)->GetArg( nb ));
2870 for ( size_t i = 0; i < args.size(); ++i )
2872 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2873 if ( idList.empty() && !args[ i ].IsEmpty() )
2874 idList.push_back( args[ i ]);
2875 list< _pyID >::iterator id = idList.begin();
2876 for ( ; id != idList.end(); ++id )
2878 Handle(_pyObject) obj = theGen->FindObject( *id );
2879 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2882 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2883 geomPublished = false;
2887 myReferredObjs.push_back( obj );
2888 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2889 if ( !mesh.IsNull() )
2890 meshes.push_back( mesh );
2891 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2892 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2893 obj->SetRemovedFromStudy( false );
2897 return geomPublished;
2900 //================================================================================
2902 * \brief Remember theCommand setting a parameter
2904 //================================================================================
2906 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2908 // parameters are discriminated by method name
2909 _AString method = theCommand->GetMethod();
2910 if ( myAccumulativeMethods.count( method ))
2911 return; // this method adds values and not override the previus value
2913 // discriminate commands setting different parameters via one method
2914 // by passing parameter names like e.g. SetOption("size", "0.2")
2915 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2916 theCommand->GetNbArgs() > 1 )
2918 // mangle method by appending a 1st textual arg
2919 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2921 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2922 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2923 if ( !isalpha( arg.Value(2))) continue;
2928 // parameters are discriminated by method name
2929 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2930 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2932 cmds.back()->Clear(); // previous parameter value has not been used
2933 cmds.back() = theCommand;
2937 cmds.push_back( theCommand );
2941 //================================================================================
2943 * \brief Return true if a setting parameter command ha been used to compute mesh
2945 //================================================================================
2947 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2948 _pyCommand::TAddr avoidComputeAddr ) const
2950 bool isUsed = false;
2951 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2952 myComputeAddr2Cmds.begin();
2953 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2955 if ( addr2cmds->first == avoidComputeAddr ) continue;
2956 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2957 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2962 //================================================================================
2964 * \brief Save commands setting parameters as they are used for a mesh computation
2966 //================================================================================
2968 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2970 myComputeCmds.push_back( theComputeCmd );
2971 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2973 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2974 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2975 savedCmds.push_back( m2c->second.back() );
2978 //================================================================================
2980 * \brief Clear commands setting parameters as a mesh computed using them is cleared
2982 //================================================================================
2984 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
2986 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2988 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
2989 for ( ; cmd != savedCmds.end(); ++cmd )
2991 // check if a cmd has been used to compute another mesh
2992 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
2994 // check if a cmd is a sole command setting its parameter;
2995 // don't use method name for search as it can change
2996 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
2997 m2cmds = myMeth2Commands.begin();
2998 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3000 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3001 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3002 if ( cmdIt != cmds.end() )
3004 if ( cmds.back() != *cmd )
3006 cmds.erase( cmdIt );
3013 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3016 //================================================================================
3018 * \brief Sets an argNb-th argument of current creation command
3019 * \param argNb - argument index countered from 1
3021 //================================================================================
3023 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3025 if ( myCurCrMethod )
3027 while ( myCurCrMethod->myArgs.size() < argNb )
3028 myCurCrMethod->myArgs.push_back( "None" );
3029 if ( arg.IsEmpty() )
3030 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3032 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3037 //================================================================================
3039 * \brief Remember hypothesis parameter values
3040 * \param theCommand - The called hypothesis method
3042 //================================================================================
3044 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3046 if ( GetAlgoType() == "Cartesian_3D" )
3048 // CartesianParameters3D hyp
3050 if ( theCommand->GetMethod() == "SetSizeThreshold" )
3052 setCreationArg( 4, theCommand->GetArg( 1 ));
3053 myArgCommands.push_back( theCommand );
3056 if ( theCommand->GetMethod() == "SetGrid" ||
3057 theCommand->GetMethod() == "SetGridSpacing" )
3059 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3060 int iArg = axis.Value(1) - '0';
3061 if ( theCommand->GetMethod() == "SetGrid" )
3063 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3067 myCurCrMethod->myArgs[ iArg ] = "[ ";
3068 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3069 myCurCrMethod->myArgs[ iArg ] += ", ";
3070 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3071 myCurCrMethod->myArgs[ iArg ] += "]";
3073 myArgCommands.push_back( theCommand );
3074 rememberCmdOfParameter( theCommand );
3079 if( theCommand->GetMethod() == "SetLength" )
3081 // NOW it is OBSOLETE
3082 // ex: hyp.SetLength(start, 1)
3083 // hyp.SetLength(end, 0)
3084 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3085 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3086 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3087 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3089 CreationMethod& crMethod = type2meth->second;
3090 while ( crMethod.myArgs.size() < i+1 )
3091 crMethod.myArgs.push_back( "[]" );
3092 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3094 myArgCommands.push_back( theCommand );
3098 _pyHypothesis::Process( theCommand );
3101 //================================================================================
3103 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3105 //================================================================================
3107 void _pyComplexParamHypo::Flush()
3111 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
3112 for ( ; cmd != myUnusedCommands.end(); ++cmd )
3113 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3118 //================================================================================
3120 * \brief Convert methods of 1D hypotheses to my own methods
3121 * \param theCommand - The called hypothesis method
3123 //================================================================================
3125 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3127 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3130 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3131 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3132 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3134 // TCollection_AsciiString cmd =
3135 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3136 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3137 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3140 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3142 // // 1D hypo is already set, so distribution changes and the old
3143 // // 1D hypo is thrown away
3144 // my1dHyp->ClearAllCommands();
3147 // //my1dHyp->SetRemovedFromStudy( false );
3149 // if ( !myArgCommands.empty() )
3150 // myArgCommands.back()->Clear();
3151 myCurCrMethod->myArgs.push_back( hyp1dID );
3152 myArgCommands.push_back( theCommand );
3155 //================================================================================
3158 * \param theAdditionCmd - command to be converted
3159 * \param theMesh - mesh instance
3160 * \retval bool - status
3162 //================================================================================
3164 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3165 const _pyID& theMesh)
3167 myIsWrapped = false;
3169 if ( my1dHyp.IsNull() )
3172 // set "SetLayerDistribution()" after addition cmd
3173 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3175 _pyID geom = theAdditionCmd->GetArg( 1 );
3177 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3178 if ( !algo.IsNull() )
3180 my1dHyp->SetMesh( theMesh );
3181 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3182 algo->GetAlgoType().ToCString());
3183 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3186 // clear "SetLayerDistribution()" cmd
3187 myArgCommands.back()->Clear();
3189 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3191 // find RadialPrism algo created on <geom> for theMesh
3192 GetCreationCmd()->SetObject( algo->GetID() );
3193 GetCreationCmd()->SetMethod( myAlgoMethod );
3194 GetCreationCmd()->RemoveArgs();
3195 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3201 //================================================================================
3205 //================================================================================
3207 void _pyLayerDistributionHypo::Flush()
3209 // as creation of 1D hyp was written later then it's edition,
3210 // we need to find all it's edition calls and process them
3211 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3213 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3215 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3216 if ( hyp1dID.IsEmpty() ) continue;
3218 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3220 // make a new name for 1D hyp = "HypType" + "_Distribution"
3222 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3224 if ( prevNewName.IsEmpty() ) continue;
3225 newName = prevNewName;
3229 if ( hyp1d->IsWrapped() ) {
3230 newName = hyp1d->GetCreationCmd()->GetMethod();
3233 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3234 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3236 newName += "_Distribution";
3237 prevNewName = newName;
3239 hyp1d->GetCreationCmd()->SetResultValue( newName );
3241 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3242 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3243 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3244 const _pyID& objID = (*cmdIt)->GetObject();
3245 if ( objID == hyp1dID ) {
3246 if ( !hyp1d.IsNull() )
3248 hyp1d->Process( *cmdIt );
3249 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3251 ( *cmdIt )->SetObject( newName );
3254 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3255 (*cmd)->SetArg( 1, newName );
3259 //================================================================================
3261 * \brief additionally to Addition2Creation, clears SetDistrType() command
3262 * \param theCmd - AddHypothesis() command
3263 * \param theMesh - mesh to which a hypothesis is added
3264 * \retval bool - convertion result
3266 //================================================================================
3268 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3269 const _pyID& theMesh)
3271 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3272 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3273 bool scaleDistrType = false;
3274 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3275 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3276 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3277 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3278 scaleDistrType = true;
3281 else if ( !scaleDistrType ) {
3282 // distribution type changed: remove scale factor from args
3283 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3284 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3286 CreationMethod& crMethod = type2meth->second;
3287 if ( crMethod.myArgs.size() == 2 )
3288 crMethod.myArgs.pop_back();
3295 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3298 //================================================================================
3300 * \brief remove repeated commands defining distribution
3302 //================================================================================
3304 void _pyNumberOfSegmentsHyp::Flush()
3306 // find number of the last SetDistrType() command
3307 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3308 int distrTypeNb = 0;
3309 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3310 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3311 if ( cmd != myUnusedCommands.rbegin() )
3312 distrTypeNb = (*cmd)->GetOrderNb();
3314 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3317 // clear commands before the last SetDistrType()
3318 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3319 set< int > treatedCmdNbs; // avoid treating same cmd twice
3320 for ( int i = 0; i < 2; ++i ) {
3321 set<TCollection_AsciiString> uniqueMethods;
3322 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3323 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3325 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3326 continue;// avoid treating same cmd twice
3327 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3328 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3329 if ( !clear || method == "SetNumberOfSegments" ) {
3330 bool isNewInSet = uniqueMethods.insert( method ).second;
3331 clear = !isNewInSet;
3340 //================================================================================
3342 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3343 * into regular1D.LengthNearVertex( length, vertex )
3344 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3345 * \param theMesh - The mesh needing this hypo
3346 * \retval bool - false if the command cant be converted
3348 //================================================================================
3350 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3351 const _pyID& theMeshID)
3353 if ( IsWrappable( theMeshID )) {
3355 _pyID vertex = theCmd->GetArg( 1 );
3357 // the problem here is that segment algo will not be found
3358 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3359 // geometry where segment algorithm is assigned
3360 Handle(_pyHypothesis) algo;
3361 _pyID geom = vertex;
3362 while ( algo.IsNull() && !geom.IsEmpty()) {
3363 // try to find geom as a father of <vertex>
3364 geom = FatherID( geom );
3365 algo = theGen->FindAlgo( geom, theMeshID, this );
3367 if ( algo.IsNull() )
3368 return false; // also possible to find geom as brother of veretex...
3369 // set geom instead of vertex
3370 theCmd->SetArg( 1, geom );
3372 // set vertex as a second arg
3373 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3374 setCreationArg( 2, vertex );
3376 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3377 // theMeshID.LengthNearVertex( length, vertex )
3378 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3383 //================================================================================
3385 * \brief _pyAlgorithm constructor
3386 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3388 //================================================================================
3390 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3391 : _pyHypothesis( theCreationCmd )
3396 //================================================================================
3398 * \brief Convert the command adding an algorithm to mesh
3399 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3400 * \param theMesh - The mesh needing this algo
3401 * \retval bool - false if the command cant be converted
3403 //================================================================================
3405 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3406 const _pyID& theMeshID)
3408 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3409 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3410 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3416 //================================================================================
3418 * \brief Return starting position of a part of python command
3419 * \param thePartIndex - The index of command part
3420 * \retval int - Part position
3422 //================================================================================
3424 int _pyCommand::GetBegPos( int thePartIndex )
3428 if ( myBegPos.Length() < thePartIndex )
3430 ASSERT( thePartIndex > 0 );
3431 return myBegPos( thePartIndex );
3434 //================================================================================
3436 * \brief Store starting position of a part of python command
3437 * \param thePartIndex - The index of command part
3438 * \param thePosition - Part position
3440 //================================================================================
3442 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3444 while ( myBegPos.Length() < thePartIndex )
3445 myBegPos.Append( UNKNOWN );
3446 ASSERT( thePartIndex > 0 );
3447 myBegPos( thePartIndex ) = thePosition;
3450 //================================================================================
3452 * \brief Returns whitespace symbols at the line beginning
3453 * \retval TCollection_AsciiString - result
3455 //================================================================================
3457 TCollection_AsciiString _pyCommand::GetIndentation()
3460 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3461 GetWord( myString, end, true );
3463 end = GetBegPos( RESULT_IND );
3464 return myString.SubString( 1, end - 1 );
3467 //================================================================================
3469 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3470 * \retval const TCollection_AsciiString & - ResultValue substring
3472 //================================================================================
3474 const TCollection_AsciiString & _pyCommand::GetResultValue()
3476 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3478 SetBegPos( RESULT_IND, EMPTY );
3479 int begPos, endPos = myString.Location( "=", 1, Length() );
3483 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3484 if ( begPos < endPos )
3486 SetBegPos( RESULT_IND, begPos );
3488 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3489 myRes = myString.SubString( begPos, endPos );
3496 //================================================================================
3498 * \brief Return number of python command result value ResultValue = Obj.Meth()
3500 //================================================================================
3502 int _pyCommand::GetNbResultValues()
3506 int endPos = myString.Location( "=", 1, Length() );
3507 while ( begPos < endPos )
3509 _AString str = GetWord( myString, begPos, true );
3510 begPos = begPos+ str.Length();
3517 //================================================================================
3519 * \brief Return substring of python command looking like
3520 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3521 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3523 //================================================================================
3524 TCollection_AsciiString _pyCommand::GetResultValue(int res)
3527 if ( SkipSpaces( myString, begPos ) && myString.Value( begPos ) == '[' )
3528 ++begPos; // skip [, else the whole list is returned
3529 int endPos = myString.Location( "=", 1, Length() );
3531 while ( begPos < endPos) {
3532 _AString result = GetWord( myString, begPos, true );
3533 begPos = begPos + result.Length();
3536 result.RemoveAll('[');
3537 result.RemoveAll(']');
3543 return theEmptyString;
3546 //================================================================================
3548 * \brief Return substring of python command looking like ResVal = Object.Meth()
3549 * \retval const TCollection_AsciiString & - Object substring
3551 //================================================================================
3553 const TCollection_AsciiString & _pyCommand::GetObject()
3555 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3558 int begPos = GetBegPos( RESULT_IND );
3560 begPos = myString.Location( "=", 1, Length() ) + 1;
3561 // is '=' in the string argument (for example, name) or not
3562 int nb1 = 0; // number of ' character at the left of =
3563 int nb2 = 0; // number of " character at the left of =
3564 for ( int i = 1; i < begPos-1; i++ ) {
3565 if ( myString.Value( i )=='\'' )
3567 else if ( myString.Value( i )=='"' )
3570 // if number of ' or " is not divisible by 2,
3571 // then get an object at the start of the command
3572 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3576 begPos += myRes.Length();
3578 myObj = GetWord( myString, begPos, true );
3579 if ( begPos != EMPTY )
3581 // check if object is complex,
3582 // so far consider case like "smesh.Method()"
3583 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3584 //if ( bracketPos==0 ) bracketPos = Length();
3585 int dotPos = begPos+myObj.Length();
3586 while ( dotPos+1 < bracketPos ) {
3587 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3592 if ( dotPos > begPos+myObj.Length() )
3593 myObj = myString.SubString( begPos, dotPos-1 );
3596 // 1st word after '=' is an object
3597 // else // no method -> no object
3603 SetBegPos( OBJECT_IND, begPos );
3609 //================================================================================
3611 * \brief Return substring of python command looking like ResVal = Obj.Method()
3612 * \retval const TCollection_AsciiString & - Method substring
3614 //================================================================================
3616 const TCollection_AsciiString & _pyCommand::GetMethod()
3618 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3621 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3622 bool forward = true;
3624 begPos = myString.Location( "(", 1, Length() ) - 1;
3628 myMeth = GetWord( myString, begPos, forward );
3629 SetBegPos( METHOD_IND, begPos );
3635 //================================================================================
3637 * \brief Returns true if there are brackets after the method
3639 //================================================================================
3641 bool _pyCommand::IsMethodCall()
3643 if ( GetMethod().IsEmpty() )
3645 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3646 return ( s[0] == '(' || s[1] == '(' );
3649 //================================================================================
3651 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3652 * \retval const TCollection_AsciiString & - Arg<index> substring
3654 //================================================================================
3656 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3658 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3662 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3664 pos = myString.Location( "(", 1, Length() );
3668 // we are at or before '(', skip it if present
3670 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3671 if ( pos > Length() )
3675 SetBegPos( ARG1_IND, 0 ); // even no '('
3676 return theEmptyString;
3680 list< TCollection_AsciiString > separatorStack( 1, ",)");
3681 bool ignoreNesting = false;
3683 while ( pos <= Length() )
3685 const char chr = myString.Value( pos );
3687 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3689 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3691 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3693 TCollection_AsciiString arg;
3694 if ( pos-1 >= prevPos ) {
3695 arg = myString.SubString( prevPos, pos-1 );
3696 arg.RightAdjust(); // remove spaces
3699 if ( !arg.IsEmpty() || chr == ',' )
3701 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3702 myArgs.Append( arg );
3708 else // end of nesting args found
3710 separatorStack.pop_back();
3711 ignoreNesting = false;
3714 else if ( !ignoreNesting )
3717 case '(' : separatorStack.push_back(")"); break;
3718 case '[' : separatorStack.push_back("]"); break;
3719 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3720 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3727 if ( myArgs.Length() < index )
3728 return theEmptyString;
3729 return myArgs( index );
3732 //================================================================================
3734 * \brief Check if char is a word part
3735 * \param c - The character to check
3736 * \retval bool - The check result
3738 //================================================================================
3740 static inline bool isWord(const char c, const bool dotIsWord)
3743 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3746 //================================================================================
3748 * \brief Looks for a word in the string and returns word's beginning
3749 * \param theString - The input string
3750 * \param theStartPos - The position to start the search, returning word's beginning
3751 * \param theForward - The search direction
3752 * \retval TCollection_AsciiString - The found word
3754 //================================================================================
3756 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3758 const bool theForward,
3759 const bool dotIsWord )
3761 int beg = theStartPos, end = theStartPos;
3762 theStartPos = EMPTY;
3763 if ( beg < 1 || beg > theString.Length() )
3764 return theEmptyString;
3766 if ( theForward ) { // search forward
3768 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3770 if ( beg > theString.Length() )
3771 return theEmptyString; // no word found
3774 char begChar = theString.Value( beg );
3775 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3776 char endChar = ( begChar == '[' ) ? ']' : begChar;
3777 // end is at the corresponding quoting mark or bracket
3778 while ( end < theString.Length() &&
3779 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3783 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3788 else { // search backward
3790 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3793 return theEmptyString; // no word found
3795 char endChar = theString.Value( end );
3796 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3797 char begChar = ( endChar == ']' ) ? '[' : endChar;
3798 // beg is at the corresponding quoting mark
3800 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3804 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3810 //cout << theString << " ---- " << beg << " - " << end << endl;
3811 return theString.SubString( beg, end );
3814 //================================================================================
3816 * \brief Returns true if the string looks like a study entry
3818 //================================================================================
3820 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3822 if ( str.Length() < 5 ) return false;
3824 int nbColons = 0, isColon;
3825 for ( int i = 1; i <= str.Length(); ++i )
3827 char c = str.Value(i);
3828 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3830 nbColons += isColon;
3832 return nbColons > 2 && str.Length()-nbColons > 2;
3835 //================================================================================
3837 * \brief Returns true if the string looks like an object ID but not like a list,
3838 * string, command etc.
3840 //================================================================================
3842 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3844 if ( str.Length() < 1 ) return false;
3846 if ( isdigit( str.Value( 1 )))
3847 return IsStudyEntry( str );
3849 for ( int i = 1; i <= str.Length(); ++i )
3850 if ( !isalnum( str.Value( i )) && !str.Value( i ) != '_' )
3856 //================================================================================
3858 * \brief Finds entries in a sting
3860 //================================================================================
3862 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3864 std::list< _pyID > resList;
3866 while ( ++pos <= str.Length() )
3868 if ( !isdigit( str.Value( pos ))) continue;
3869 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3872 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3873 _pyID entry = str.SubString( pos, end-1 );
3875 if ( IsStudyEntry( entry ))
3876 resList.push_back( entry );
3881 //================================================================================
3883 * \brief Look for position where not space char is
3884 * \param theString - The string
3885 * \param thePos - The position to search from and which returns result
3886 * \retval bool - false if there are only space after thePos in theString
3888 //================================================================================
3890 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3892 if ( thePos < 1 || thePos > theString.Length() )
3895 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3898 return thePos <= theString.Length();
3901 //================================================================================
3903 * \brief Modify a part of the command
3904 * \param thePartIndex - The index of the part
3905 * \param thePart - The new part string
3906 * \param theOldPart - The old part
3908 //================================================================================
3910 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3911 TCollection_AsciiString& theOldPart)
3913 int pos = GetBegPos( thePartIndex );
3914 if ( pos <= Length() && theOldPart != thePart)
3916 TCollection_AsciiString seperator;
3918 pos = GetBegPos( thePartIndex + 1 );
3919 if ( pos < 1 ) return;
3920 switch ( thePartIndex ) {
3921 case RESULT_IND: seperator = " = "; break;
3922 case OBJECT_IND: seperator = "."; break;
3923 case METHOD_IND: seperator = "()"; break;
3927 myString.Remove( pos, theOldPart.Length() );
3928 if ( !seperator.IsEmpty() )
3929 myString.Insert( pos , seperator );
3930 myString.Insert( pos, thePart );
3931 // update starting positions of the following parts
3932 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3933 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3934 if ( myBegPos( i ) > 0 )
3935 myBegPos( i ) += posDelta;
3937 theOldPart = thePart;
3941 //================================================================================
3943 * \brief Set agrument
3944 * \param index - The argument index, it counts from 1
3945 * \param theArg - The argument string
3947 //================================================================================
3949 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3952 int argInd = ARG1_IND + index - 1;
3953 int pos = GetBegPos( argInd );
3954 if ( pos < 1 ) // no index-th arg exist, append inexistent args
3956 // find a closing parenthesis
3957 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3958 int lastArgInd = GetNbArgs();
3959 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
3960 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3965 while ( pos > 0 && myString.Value( pos ) != ')' )
3968 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3972 while ( myArgs.Length() < index ) {
3973 if ( myArgs.Length() )
3974 myString.Insert( pos++, "," );
3975 myArgs.Append("None");
3976 myString.Insert( pos, myArgs.Last() );
3977 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3978 pos += myArgs.Last().Length();
3981 SetPart( argInd, theArg, myArgs( index ));
3984 //================================================================================
3986 * \brief Empty arg list
3988 //================================================================================
3990 void _pyCommand::RemoveArgs()
3992 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
3993 myString.Trunc( pos );
3996 if ( myBegPos.Length() >= ARG1_IND )
3997 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4000 //================================================================================
4002 * \brief Comment a python command
4004 //================================================================================
4006 void _pyCommand::Comment()
4008 if ( IsEmpty() ) return;
4011 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4012 if ( i <= Length() )
4014 myString.Insert( i, "#" );
4015 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4017 int begPos = GetBegPos( iPart + 1 );
4018 if ( begPos != UNKNOWN )
4019 SetBegPos( iPart + 1, begPos + 1 );
4024 //================================================================================
4026 * \brief Set dependent commands after this one
4028 //================================================================================
4030 bool _pyCommand::SetDependentCmdsAfter() const
4032 bool orderChanged = false;
4033 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4034 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4035 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4036 orderChanged = true;
4037 theGen->SetCommandAfter( *cmd, this );
4038 (*cmd)->SetDependentCmdsAfter();
4041 return orderChanged;
4043 //================================================================================
4045 * \brief Insert accessor method after theObjectID
4046 * \param theObjectID - id of the accessed object
4047 * \param theAcsMethod - name of the method giving access to the object
4048 * \retval bool - false if theObjectID is not found in the command string
4050 //================================================================================
4052 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4054 if ( !theAcsMethod )
4056 // start object search from the object, i.e. ignore result
4058 int beg = GetBegPos( OBJECT_IND );
4059 if ( beg < 1 || beg > Length() )
4062 while (( beg = myString.Location( theObjectID, beg, Length() )))
4064 // check that theObjectID is not just a part of a longer ID
4065 int afterEnd = beg + theObjectID.Length();
4066 Standard_Character c = myString.Value( afterEnd );
4067 if ( !isalnum( c ) && c != ':' ) {
4068 // check if accessor method already present
4070 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4072 int oldLen = Length();
4073 myString.Insert( afterEnd, (char*) theAcsMethod );
4074 myString.Insert( afterEnd, "." );
4075 // update starting positions of the parts following the modified one
4076 int posDelta = Length() - oldLen;
4077 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4078 if ( myBegPos( i ) > afterEnd )
4079 myBegPos( i ) += posDelta;
4084 beg = afterEnd; // is a part - next search
4089 //================================================================================
4091 * \brief Creates pyObject
4093 //================================================================================
4095 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4096 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4101 //================================================================================
4103 * \brief Set up myID and myIsPublished
4105 //================================================================================
4107 void _pyObject::setID(const _pyID& theID)
4110 myIsPublished = !theGen->IsNotPublished( GetID() );
4113 //================================================================================
4115 * \brief Clear myCreationCmd and myProcessedCmds
4117 //================================================================================
4119 void _pyObject::ClearCommands()
4124 if ( !myCreationCmd.IsNull() )
4125 myCreationCmd->Clear();
4127 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4128 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4132 //================================================================================
4134 * \brief Return method name giving access to an interaface object wrapped by python class
4135 * \retval const char* - method name
4137 //================================================================================
4139 const char* _pyObject::AccessorMethod() const
4143 //================================================================================
4145 * \brief Return ID of a father
4147 //================================================================================
4149 _pyID _pyObject::FatherID(const _pyID & childID)
4151 int colPos = childID.SearchFromEnd(':');
4153 return childID.SubString( 1, colPos-1 );
4157 //================================================================================
4159 * \brief SelfEraser erases creation command if no more it's commands invoked
4161 //================================================================================
4163 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4164 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4166 myIsPublished = true; // prevent clearing as a not published
4167 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4170 //================================================================================
4172 * \brief SelfEraser erases creation command if no more it's commands invoked
4174 //================================================================================
4176 void _pySelfEraser::Flush()
4178 bool toErase = false;
4179 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4182 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4183 for ( ; cmd != myArgCmds.end(); ++cmd )
4184 nbArgUses += !(*cmd)->IsEmpty();
4185 toErase = ( nbArgUses < 1 );
4189 int nbCalls = GetNbCalls();
4192 // ignore cleared commands
4193 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4194 std::list< Handle(_pyCommand) >::const_iterator cmd = cmds.begin();
4195 for ( ; cmd != cmds.end(); ++cmd )
4196 nbCalls -= (*cmd)->IsEmpty();
4198 toErase = ( nbCalls < 1 );
4202 myIsPublished = false;
4203 _pyObject::ClearCommands();
4207 //================================================================================
4209 * \brief _pySubMesh constructor
4211 //================================================================================
4213 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4214 _pyObject(theCreationCmd)
4216 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4217 if ( toKeepAgrCmds )
4218 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4221 //================================================================================
4223 * \brief Return true if a sub-mesh can be used as argument of the given method
4225 //================================================================================
4227 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4230 // // names of all methods where a sub-mesh can be used as argument
4231 // static TStringSet methods;
4232 // if ( methods.empty() ) {
4233 // const char * names[] = {
4234 // // methods of SMESH_Gen
4236 // // methods of SMESH_Group
4238 // // methods of SMESH_Measurements
4240 // // methods of SMESH_Mesh
4241 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4243 // // methods of SMESH_MeshEditor
4244 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4245 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4246 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4247 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4248 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4249 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4250 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4251 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4252 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4253 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4254 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4255 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4256 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4257 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4258 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4259 // "" }; // <- mark of end
4260 // methods.Insert( names );
4262 // return methods.Contains( theMethodName );
4265 //================================================================================
4267 * \brief count invoked commands
4269 //================================================================================
4271 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4273 _pyObject::Process(theCommand); // count calls of Process()
4276 //================================================================================
4278 * \brief Move creation command depending on invoked commands
4280 //================================================================================
4282 void _pySubMesh::Flush()
4284 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4285 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4286 else if ( !myCreator.IsNull() )
4287 // move to be just after creator
4288 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4290 // move sub-mesh usage after creation cmd
4291 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4292 for ( ; cmd != myArgCmds.end(); ++cmd )
4293 if ( !(*cmd)->IsEmpty() )
4294 GetCreationCmd()->AddDependantCmd( *cmd );
4297 //================================================================================
4299 * \brief Creates _pyGroup
4301 //================================================================================
4303 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4304 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4306 if ( !id.IsEmpty() )
4309 myCanClearCreationCmd = true;
4311 const _AString& method = theCreationCmd->GetMethod();
4312 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4314 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4316 // ----------------------------------------------------------------------
4317 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4319 _pyID geom = theCreationCmd->GetArg( 3 );
4320 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4321 // next if(){...} section is commented
4322 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4323 // theCreationCmd->SetMethod( "Group" );
4324 // theCreationCmd->RemoveArgs();
4325 // theCreationCmd->SetArg( 1, geom );
4328 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4329 _pyID type = theCreationCmd->GetArg( 1 );
4330 _pyID name = theCreationCmd->GetArg( 2 );
4331 theCreationCmd->SetMethod( "GroupOnGeom" );
4332 theCreationCmd->RemoveArgs();
4333 theCreationCmd->SetArg( 1, geom );
4334 theCreationCmd->SetArg( 2, name );
4335 theCreationCmd->SetArg( 3, type );
4338 else if ( method == "CreateGroupFromFilter" )
4340 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4341 theCreationCmd->SetMethod( "GroupOnFilter" );
4343 _pyID filterID = theCreationCmd->GetArg(3);
4344 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4345 if ( !filter.IsNull())
4347 if ( !filter->GetNewID().IsEmpty() )
4348 theCreationCmd->SetArg( 3, filter->GetNewID() );
4349 //filter->AddUser( this );
4353 else if ( method == "GetGroups" )
4355 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4359 // theCreationCmd does something else apart from creation of this group
4360 // and thus it can't be cleared if this group is removed
4361 myCanClearCreationCmd = false;
4365 //================================================================================
4367 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4370 //================================================================================
4372 bool _pyGroup::CanClear()
4377 if ( !myCanClearCreationCmd &&
4378 !myCreationCmd.IsNull() &&
4379 myCreationCmd->GetMethod() == "GetGroups" )
4381 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4382 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4383 list< _pyID >::iterator grID = idList.begin();
4384 if ( GetID() == *grID )
4386 myCanClearCreationCmd = true;
4387 list< Handle(_pyGroup ) > groups;
4388 for ( ; grID != idList.end(); ++grID )
4390 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4391 if ( group.IsNull() ) continue;
4392 groups.push_back( group );
4393 if ( group->IsInStudy() )
4394 myCanClearCreationCmd = false;
4396 // set myCanClearCreationCmd == true to all groups
4397 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4398 for ( ; group != groups.end(); ++group )
4399 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4403 return myCanClearCreationCmd;
4406 //================================================================================
4408 * \brief set myCanClearCreationCmd = true if the main action of the creation
4409 * command is discarded
4411 //================================================================================
4413 void _pyGroup::RemovedWithContents()
4415 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4416 // via a created group
4417 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4418 // myCanClearCreationCmd = true;
4421 //================================================================================
4423 * \brief To convert creation of a group by filter
4425 //================================================================================
4427 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4429 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4430 // group = mesh.CreateEmptyGroup( elemType, groupName )
4431 // aFilter.SetMesh(mesh)
4432 // nbAdd = group.AddFrom( aFilter )
4433 Handle(_pyFilter) filter;
4434 if ( theCommand->GetMethod() == "AddFrom" )
4436 _pyID idSource = theCommand->GetArg(1);
4437 // check if idSource is a filter
4438 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4439 if ( !filter.IsNull() )
4441 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4442 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4443 while ( *cmdIt != theCommand ) ++cmdIt;
4444 while ( (*cmdIt)->GetOrderNb() != 1 )
4446 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4447 if ((setMeshCmd->GetObject() == idSource ||
4448 setMeshCmd->GetObject() == filter->GetNewID() )
4450 setMeshCmd->GetMethod() == "SetMesh")
4452 setMeshCmd->Clear();
4456 // replace 3 commands by one
4457 theCommand->Clear();
4458 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4459 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4460 if ( !filter->GetNewID().IsEmpty() )
4461 idSource = filter->GetNewID();
4462 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4463 makeGroupCmd->SetArg( 1, name );
4464 makeGroupCmd->SetArg( 2, idSource );
4465 filter->AddArgCmd( makeGroupCmd );
4468 else if ( theCommand->GetMethod() == "SetFilter" )
4470 // set new name of a filter or clear the command if the same filter is set
4471 _pyID filterID = theCommand->GetArg(1);
4472 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4473 if ( !myFilter.IsNull() && filter == myFilter )
4474 theCommand->Clear();
4475 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4476 theCommand->SetArg( 1, filter->GetNewID() );
4479 else if ( theCommand->GetMethod() == "GetFilter" )
4481 // GetFilter() returns a filter with other ID, make myFilter process
4482 // calls of the returned filter
4483 if ( !myFilter.IsNull() )
4485 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4486 theCommand->Clear();
4490 // if ( !filter.IsNull() )
4491 // filter->AddUser( this );
4493 theGen->AddMeshAccessorMethod( theCommand );
4496 //================================================================================
4498 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4500 //================================================================================
4502 void _pyGroup::Flush()
4504 if ( !theGen->IsToKeepAllCommands() &&
4505 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4507 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4511 //================================================================================
4513 * \brief Constructor of _pyFilter
4515 //================================================================================
4517 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4518 :_pyObject(theCreationCmd), myNewID( newID )
4520 //myIsPublished = true; // prevent clearing as a not published
4521 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4524 //================================================================================
4526 * \brief To convert creation of a filter by criteria and
4527 * to replace an old name by a new one
4529 //================================================================================
4531 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4533 if ( theCommand->GetObject() == GetID() )
4534 _pyObject::Process(theCommand); // count commands
4536 if ( !myNewID.IsEmpty() )
4537 theCommand->SetObject( myNewID );
4539 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4540 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4541 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4542 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4543 theCommand->GetMethod() == "SetCriteria")
4545 // aFilter.SetCriteria(aCriteria) ->
4546 // aFilter = smesh.GetFilterFromCriteria(criteria)
4547 if ( myNewID.IsEmpty() )
4548 theCommand->SetResultValue( GetID() );
4550 theCommand->SetResultValue( myNewID );
4551 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4552 theCommand->SetMethod( "GetFilterFromCriteria" );
4554 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4555 GetCreationCmd()->Clear();
4556 GetCreationCmd()->GetString() = theCommand->GetString();
4557 theCommand->Clear();
4558 theCommand->AddDependantCmd( GetCreationCmd() );
4560 else if ( theCommand->GetMethod() == "SetMesh" )
4562 if ( myMesh == theCommand->GetArg( 1 ))
4563 theCommand->Clear();
4565 myMesh = theCommand->GetArg( 1 );
4566 theGen->AddMeshAccessorMethod( theCommand );
4570 //================================================================================
4572 * \brief Set new filter name to the creation command and to myArgCmds
4574 //================================================================================
4576 void _pyFilter::Flush()
4578 if ( myNewID.IsEmpty() ) return;
4580 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4581 for ( ; cmd != myArgCmds.end(); ++cmd )
4582 if ( !(*cmd)->IsEmpty() )
4584 _AString cmdStr = (*cmd)->GetString();
4585 _AString id = GetID();
4586 int pos = cmdStr.Search( id );
4589 cmdStr.Remove( pos, id.Length() );
4590 cmdStr.Insert( pos, myNewID );
4593 (*cmd)->GetString() = cmdStr;
4596 if ( !GetCreationCmd()->IsEmpty() )
4597 GetCreationCmd()->SetResultValue( myNewID );
4600 //================================================================================
4602 * \brief Return true if all my users can be cleared
4604 //================================================================================
4606 bool _pyObject::CanClear()
4608 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4609 for ( ; cmd != myArgCmds.end(); ++cmd )
4610 if ( !(*cmd)->IsEmpty() )
4612 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4613 if ( !obj.IsNull() && !obj->CanClear() )
4616 return ( !myIsPublished );
4619 //================================================================================
4621 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4623 //================================================================================
4625 _pyHypothesisReader::_pyHypothesisReader()
4627 // Get paths to xml files of plugins
4628 vector< string > xmlPaths;
4630 if ( const char* meshersList = getenv("SMESH_MeshersList") )
4632 string meshers = meshersList, plugin;
4633 string::size_type from = 0, pos;
4634 while ( from < meshers.size() )
4636 // cut off plugin name
4637 pos = meshers.find( ':', from );
4638 if ( pos != string::npos )
4639 plugin = meshers.substr( from, pos-from );
4641 plugin = meshers.substr( from ), pos = meshers.size();
4644 // get PLUGIN_ROOT_DIR path
4645 string rootDirVar, pluginSubDir = plugin;
4646 if ( plugin == "StdMeshers" )
4647 rootDirVar = "SMESH", pluginSubDir = "smesh";
4649 for ( pos = 0; pos < plugin.size(); ++pos )
4650 rootDirVar += toupper( plugin[pos] );
4651 rootDirVar += "_ROOT_DIR";
4653 const char* rootDir = getenv( rootDirVar.c_str() );
4654 if ( !rootDir || strlen(rootDir) == 0 )
4656 rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
4657 rootDir = getenv( rootDirVar.c_str() );
4658 if ( !rootDir || strlen(rootDir) == 0 ) continue;
4661 // get a separator from rootDir
4662 for ( pos = strlen( rootDir )-1; pos >= 0 && sep.empty(); --pos )
4663 if ( rootDir[pos] == '/' || rootDir[pos] == '\\' )
4669 if (sep.empty() ) sep = "\\";
4671 if (sep.empty() ) sep = "/";
4674 // get a path to resource file
4675 string xmlPath = rootDir;
4676 if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
4678 xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
4679 for ( pos = 0; pos < pluginSubDir.size(); ++pos )
4680 xmlPath += tolower( pluginSubDir[pos] );
4681 xmlPath += sep + plugin + ".xml";
4684 fileOK = (GetFileAttributes(xmlPath.c_str()) != INVALID_FILE_ATTRIBUTES);
4686 fileOK = (access(xmlPath.c_str(), F_OK) == 0);
4689 xmlPaths.push_back( xmlPath );
4694 LDOMParser xmlParser;
4695 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4697 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4701 INFOS( xmlParser.GetError(data) );
4704 // <algorithm type="Regular_1D"
4705 // label-id="Wire discretisation"
4708 // <algo>Regular_1D=Segment()</algo>
4709 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4711 LDOM_Document xmlDoc = xmlParser.getDocument();
4712 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4713 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4715 LDOM_Node algoNode = algoNodeList.item( i );
4716 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4717 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4718 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4720 _AString text, algoType, method, arg;
4721 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4723 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4724 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4725 text = textNode.getNodeValue();
4726 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4727 algoType = algoCmd->GetResultValue();
4728 method = algoCmd->GetMethod();
4729 arg = algoCmd->GetArg(1);
4730 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4732 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4733 algo->SetConvMethodAndType( method, algoType );
4734 if ( !arg.IsEmpty() )
4735 algo->setCreationArg( 1, arg );
4737 myType2Hyp[ algoType ] = algo;
4741 if ( algoType.IsEmpty() ) continue;
4743 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4745 Handle( _pyHypothesis ) hyp;
4746 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4748 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4749 LDOM_Node textNode = pyHypoNode.getFirstChild();
4750 text = textNode.getNodeValue();
4751 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4752 hypType = hypoCmd->GetResultValue();
4753 method = hypoCmd->GetMethod();
4754 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4756 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4757 if ( type2hyp == myType2Hyp.end() )
4758 hyp = new _pyHypothesis( hypoCmd );
4760 hyp = type2hyp->second;
4761 hyp->SetConvMethodAndType( method, algoType );
4762 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4764 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4765 _AString argMethod = argCmd.GetMethod();
4766 _AString argNbText = argCmd.GetArg( 1 );
4767 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4768 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4770 hyp->AddArgMethod( argMethod,
4771 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4773 myType2Hyp[ hypType ] = hyp;
4777 // <hypothesis type="BLSURF_Parameters"
4781 // <accumulative-methods>
4782 // SetEnforcedVertex,
4783 // SetEnforcedVertexNamed
4784 // </accumulative-methods>
4788 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4789 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4791 LDOM_Node hypNode = hypNodeList.item( i );
4792 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4793 _AString hypType = hypElem.getAttribute("type");
4794 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4795 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4797 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4798 if ( type2hyp == myType2Hyp.end() ) continue;
4800 LDOM_Node methNode = methNodeList.item( 0 );
4801 LDOM_Node textNode = methNode.getFirstChild();
4802 _AString text = textNode.getNodeValue();
4806 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4807 pos += method.Length();
4808 type2hyp->second->AddAccumulativeMethod( method );
4810 while ( !method.IsEmpty() );
4813 } // loop on xmlPaths
4816 //================================================================================
4818 * \brief Returns a new hypothesis initialized according to the read information
4820 //================================================================================
4822 Handle(_pyHypothesis)
4823 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4824 const Handle(_pyCommand)& creationCmd) const
4826 Handle(_pyHypothesis) resHyp, sampleHyp;
4828 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4829 if ( type2hyp != myType2Hyp.end() )
4830 sampleHyp = type2hyp->second;
4832 if ( sampleHyp.IsNull() )
4834 resHyp = new _pyHypothesis(creationCmd);
4838 if ( sampleHyp->IsAlgo() )
4839 resHyp = new _pyAlgorithm( creationCmd );
4841 resHyp = new _pyHypothesis(creationCmd);
4842 resHyp->Assign( sampleHyp, _pyID() );
4847 //================================================================================
4849 * \brief Adds an object ID to some family of IDs with a common prefix
4850 * \param [in] str - the object ID
4851 * \return bool - \c false if \a str does not have the same prefix as \a this family
4852 * (for internal usage)
4854 //================================================================================
4856 bool _pyStringFamily::Add( const char* str )
4858 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4859 return false; // expected prefix is missing
4861 str += _prefix.Length(); // skip _prefix
4863 // try to add to some of child falimies
4864 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4865 for ( ; itSub != _subFams.end(); ++itSub )
4866 if ( itSub->Add( str ))
4869 // no suitable family found - add str to _strings or create a new child family
4871 // look for a proper place within sorted _strings
4872 std::list< _AString >::iterator itStr = _strings.begin();
4873 while ( itStr != _strings.end() && itStr->IsLess( str ))
4875 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4876 return true; // same ID already kept
4878 const int minPrefixSize = 4;
4880 // count "smaller" strings with the same prefix
4881 std::list< _AString >::iterator itLess = itStr; --itLess;
4883 for ( ; itLess != _strings.end(); --itLess )
4884 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4889 // count "greater" strings with the same prefix
4890 std::list< _AString >::iterator itMore = itStr;
4892 for ( ; itMore != _strings.end(); ++itMore )
4893 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4898 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4900 // look for a maximal prefix length
4901 // int lessPrefSize = 3, morePrefSize = 3;
4902 // if ( nbLess > 0 )
4903 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
4905 // if ( nbMore > 0 )
4906 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
4908 // int prefixSize = 3;
4909 // if ( nbLess == 0 )
4910 // prefixSize = morePrefSize;
4911 // else if ( nbMore == 0 )
4912 // prefixSize = lessPrefSize;
4914 // prefixSize = Min( lessPrefSize, morePrefSize );
4915 int prefixSize = minPrefixSize;
4916 _AString newPrefix ( str, prefixSize );
4918 // look for a proper place within _subFams sorted by _prefix
4919 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
4920 if ( !itSub->_prefix.IsLess( newPrefix ))
4923 // add the new _pyStringFamily
4924 itSub = _subFams.insert( itSub, _pyStringFamily());
4925 _pyStringFamily& newSubFam = *itSub;
4926 newSubFam._prefix = newPrefix;
4928 // pass this->_strings to newSubFam._strings
4929 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
4930 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4931 newSubFam._strings.push_back( str + prefixSize );
4932 for ( ; nbMore > 0; --nbMore, ++itStr )
4933 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4935 _strings.erase( itLess, ++itMore );
4937 else // to few string to make a family fot them
4939 _strings.insert( itStr, str );
4944 //================================================================================
4946 * \brief Finds an object ID in the command
4947 * \param [in] longStr - the command string
4948 * \param [out] subStr - the found object ID
4949 * \return bool - \c true if the object ID found
4951 //================================================================================
4953 bool _pyStringFamily::IsIn( const _AString& longStr, _AString& subStr )
4955 const char* s = longStr.ToCString();
4958 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4960 for ( ; itSub != _subFams.end(); ++itSub )
4962 if (( pos = longStr.Search( itSub->_prefix )-1) > 6-1 ) // 6 = strlen("a=b.c(")
4963 if (( len = itSub->isIn( s + pos + itSub->_prefix.Length() )) >= 0 )
4965 subStr = _AString( s + pos, len + itSub->_prefix.Length() );
4969 // look among _strings
4970 std::list< _AString >::iterator itStr = _strings.begin();
4971 for ( ; itStr != _strings.end(); ++itStr )
4972 if ( longStr.Search( *itStr ) > itStr->Length() )
4980 //================================================================================
4982 * \brief Return remainder length of the object ID after my _prefix
4983 * \param [in] str - remainder of the command after my _prefix
4984 * \return int - length of the object ID or -1 if not found
4986 //================================================================================
4988 int _pyStringFamily::isIn( const char* str )
4990 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4992 for ( ; itSub != _subFams.end(); ++itSub )
4994 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
4997 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
4998 return itSub->_prefix.Length() + len;
5003 if ( !_strings.empty() )
5005 std::list< _AString >::iterator itStr = _strings.begin();
5006 bool firstEmpty = itStr->IsEmpty();
5009 for ( ; itStr != _strings.end(); ++itStr )
5011 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5013 return itStr->Length();
5024 //================================================================================
5028 //================================================================================
5030 void _pyStringFamily::Print( int level )
5032 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5033 std::list< _AString >::iterator itStr = _strings.begin();
5034 for ( ; itStr != _strings.end(); ++itStr )
5035 cout << *itStr << " | ";
5037 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5038 for ( ; itSub != _subFams.end(); ++itSub )
5039 itSub->Print( level + 1 );
5041 cout << string( 70, '-' ) << endl;