4fc1a67f3ffb9673ffcb9db8d2f32fbd79ea9e41
[occt.git] / samples / mfc / standard / Common / ImportExport / ImportExport.cpp
1 // ImportExport.cpp: implementation of the CImportExport class.
2 //
3 //////////////////////////////////////////////////////////////////////
4
5 #include "stdafx.h"
6 #include "ImportExport.h"
7 #include <OCC_App.h>
8
9 #include "SaveSTEPDlg.h"
10
11 #include "TColStd_SequenceOfAsciiString.hxx"
12 #include "TColStd_SequenceOfExtendedString.hxx"
13 #include "OSD_Timer.hxx"
14
15 #include "IGESControl_Reader.hxx"
16 #include "STEPControl_Controller.hxx"
17
18 #include <BRepAlgo.hxx>
19 #include <IGESControl_Controller.hxx>
20 #include <IGESControl_Writer.hxx>
21 #include <Interface_Static.hxx>
22 #include <STEPControl_Reader.hxx>
23 #include <Geom_Curve.hxx>
24 #include <STEPControl_Writer.hxx>
25 #include <TopoDS_Compound.hxx>
26 #include <Geom_Line.hxx>
27 #include <StlAPI_Writer.hxx>
28 #include <VrmlAPI_Writer.hxx>
29 #include <VrmlData_Scene.hxx>
30 #include <VrmlData_ShapeConvert.hxx>
31 #include <VrmlData_Appearance.hxx>
32 #include <VrmlData_Material.hxx>
33 #include <VrmlData_Group.hxx>
34 #include <VrmlData_ListOfNode.hxx>
35 #include <VrmlData_ShapeNode.hxx>
36
37 #include <XSControl_WorkSession.hxx>
38 #include <XSControl_TransferReader.hxx>
39 #include <STEPConstruct_Styles.hxx>
40 #include <TColStd_HSequenceOfTransient.hxx>
41 #include <STEPConstruct.hxx>
42 #include <StepVisual_StyledItem.hxx>
43
44 #ifdef _DEBUG
45 #undef THIS_FILE
46 static char THIS_FILE[]=__FILE__;
47 //#define new DEBUG_NEW
48 #endif
49
50 //////////////////////////////////////////////////////////////////////
51 // Construction/Destruction
52 //////////////////////////////////////////////////////////////////////
53
54 Handle(TopTools_HSequenceOfShape) CImportExport::BuildSequenceFromContext(const Handle(AIS_InteractiveContext)& anInteractiveContext,
55                                                                           Handle(Quantity_HArray1OfColor)&      anArrayOfColors,
56                                                                           Handle(TColStd_HArray1OfReal)&        anArrayOfTransparencies) 
57 {
58     Handle(TopTools_HSequenceOfShape) aSequence;
59     Standard_Integer nb = anInteractiveContext->NbCurrents(), i = 1;
60     if (!nb)
61         return aSequence;
62
63     aSequence               = new TopTools_HSequenceOfShape();
64     anArrayOfColors         = new Quantity_HArray1OfColor(1, nb);
65     anArrayOfTransparencies = new TColStd_HArray1OfReal  (1, nb);
66
67     Handle(AIS_InteractiveObject) picked;
68     for(anInteractiveContext->InitCurrent();anInteractiveContext->MoreCurrent();anInteractiveContext->NextCurrent())
69       {
70         picked = anInteractiveContext->Current();
71         if (anInteractiveContext->Current()->IsKind(STANDARD_TYPE(AIS_Shape)))
72              {
73             Handle(AIS_Shape) aisShape = Handle(AIS_Shape)::DownCast(picked);
74                 TopoDS_Shape aShape = aisShape->Shape();
75             aSequence->Append(aShape);
76             
77             Quantity_Color color;
78             aisShape->Color(color);
79             anArrayOfColors->SetValue(i, color);
80             
81             Standard_Real transparency = aisShape->Transparency();
82             anArrayOfTransparencies->SetValue(i, transparency);
83
84             i++;
85              }
86       }
87       return aSequence;
88 }
89
90 //======================================================================
91 //=                                                                    =
92 //=                      BREP                                          =
93 //=                                                                    =
94 //======================================================================
95
96 int CImportExport::ReadBREP (const Handle(AIS_InteractiveContext)& anInteractiveContext)
97 {
98     Handle(TopTools_HSequenceOfShape) aSequence = CImportExport::ReadBREP();
99         if(aSequence->IsEmpty())
100                 return 1;
101         Handle(AIS_Shape) aShape;
102     for(int i=1;i<= aSequence->Length();i++){
103                 aShape = new AIS_Shape(aSequence->Value(i));
104                 anInteractiveContext->SetDisplayMode(aShape, 1, Standard_False);
105                 anInteractiveContext->Display(aShape, Standard_False);
106                 anInteractiveContext->SetCurrentObject(aShape, Standard_False);
107         } 
108         return 0;
109 }
110
111 Handle(TopTools_HSequenceOfShape) CImportExport::ReadBREP()
112 {
113   CFileDialog dlg(TRUE,
114                   NULL,
115                   NULL,
116                   OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
117                   L"BREP Files (*.brep , *.rle)|*.brep;  *.BREP; *.rle; *.RLE; |All Files (*.*)|*.*||",
118                   NULL ); 
119
120   CString SHAREPATHValue;
121   SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
122   CString initdir = (SHAREPATHValue + "\\occ");
123
124   dlg.m_ofn.lpstrInitialDir = initdir;
125
126   Handle(TopTools_HSequenceOfShape) aSequence= new TopTools_HSequenceOfShape();
127
128   if (dlg.DoModal() == IDOK) 
129   {
130     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
131     CString filename = dlg.GetPathName();
132     TopoDS_Shape aShape;
133     Standard_Boolean result = ReadBREP (filename, aShape);
134     if (result)
135     {
136       if (!BRepAlgo::IsValid(aShape))
137         MessageBoxW (AfxGetMainWnd()->m_hWnd, L"Warning: The shape is not valid!", L"Cascade Warning", MB_ICONWARNING);
138
139       aSequence->Append(aShape);
140     }
141     else 
142       MessageBoxW (AfxGetMainWnd()->m_hWnd, L"Error: The file was not read", L"Cascade Error", MB_ICONERROR);
143
144     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
145   }
146
147   return aSequence;
148 }
149 //----------------------------------------------------------------------
150
151 Standard_Boolean CImportExport::ReadBREP(CString      aFileName,
152                                         TopoDS_Shape& aShape)
153 {
154   aShape.Nullify();
155
156   std::filebuf aFileBuf;
157   std::istream aStream (&aFileBuf);
158   if (!aFileBuf.open (aFileName, ios::in))
159   {
160     return Standard_False;
161   }
162
163   BRep_Builder aBuilder;
164   BRepTools::Read (aShape, aStream, aBuilder);
165   return !aShape.IsNull();
166 }
167
168 void CImportExport::SaveBREP(const Handle(AIS_InteractiveContext)& anInteractiveContext)
169 {
170         anInteractiveContext->InitCurrent();
171         if (anInteractiveContext->NbCurrents() == 0){
172                 AfxMessageBox (L"No shape selected for export!");
173                 return;
174         }
175         Handle(TopTools_HSequenceOfShape) aHSequenceOfShape;
176     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
177     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
178         aHSequenceOfShape = BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies);
179         int aLength = aHSequenceOfShape->Length();
180         if (aLength == 1){
181                 TopoDS_Shape RES = aHSequenceOfShape->Value(1);
182                 CImportExport::SaveBREP(RES);
183         } else {
184                 TopoDS_Compound RES;
185                 BRep_Builder MKCP;
186                 MKCP.MakeCompound(RES);
187                 for (Standard_Integer i=1;i<=aLength;i++)
188                 {
189                         TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
190                         if ( aShape.IsNull() ) 
191                         {
192                                 continue;
193                         }
194                         MKCP.Add(RES, aShape);
195                 }
196                 CImportExport::SaveBREP(RES);
197         }
198 }
199
200 Standard_Boolean CImportExport::SaveBREP(const TopoDS_Shape& aShape)
201 {
202   CFileDialog dlg (FALSE, L"*.brep",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
203                    L"BREP Files (*.brep)|*.brep;|BREP Files (*.BREP)|*.BREP;||", NULL);
204   
205 CString SHAREPATHValue;
206 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
207 CString initdir = (SHAREPATHValue + "\\occ");
208
209 dlg.m_ofn.lpstrInitialDir = initdir;
210
211   Standard_Boolean result = Standard_False; 
212   if (dlg.DoModal() == IDOK)  
213   { 
214     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT)); 
215     CString filename = dlg.GetPathName(); 
216     result = SaveBREP (filename, aShape);
217     if (!result)  
218        MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd,
219                     L"Error : The shape or shapes were not saved.",
220                     L"CasCade Error", MB_ICONERROR);
221     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); 
222   } 
223   return result;
224 }
225
226 //----------------------------------------------------------------------------------------
227 Standard_Boolean CImportExport::SaveBREP (CString             aFileName,
228                                           const TopoDS_Shape& aShape)
229 {
230   std::filebuf aFileBuf;
231   std::ostream aStream (&aFileBuf);
232   if (!aFileBuf.open (aFileName, ios::out))
233   {
234     return Standard_False;
235   }
236
237   BRepTools::Write (aShape, aStream); 
238   return Standard_True;
239 }
240
241 //======================================================================
242 //=                                                                    =
243 //=                      IGES                                          =
244 //=                                                                    =
245 //======================================================================
246
247
248
249 void CImportExport::ReadIGES(const Handle(AIS_InteractiveContext)& anInteractiveContext)
250 {
251     Handle(TopTools_HSequenceOfShape) aSequence = CImportExport::ReadIGES();
252     for(int i=1;i<= aSequence->Length();i++)
253         anInteractiveContext->Display(new AIS_Shape(aSequence->Value(i)));
254
255 }
256
257 Handle(TopTools_HSequenceOfShape) CImportExport::ReadIGES()// not by reference --> the sequence is created here !!
258 {
259   CFileDialog dlg(TRUE,
260                   NULL,
261                   NULL,
262                   OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
263                   L"IGES Files (*.iges , *.igs)|*.iges; *.igs|All Files (*.*)|*.*||",
264                   NULL );
265
266 CString SHAREPATHValue;
267 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
268 CString initdir = (SHAREPATHValue + "\\iges");
269
270 dlg.m_ofn.lpstrInitialDir = initdir;
271   
272   Handle(TopTools_HSequenceOfShape) aSequence = new TopTools_HSequenceOfShape();
273   if (dlg.DoModal() == IDOK) 
274   {
275     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
276     TCollection_ExtendedString aFileNameW ((Standard_ExtString )(const wchar_t* )dlg.GetPathName());
277     TCollection_AsciiString    aFileName  (aFileNameW, '?');
278     Standard_Integer status = ReadIGES (aFileName.ToCString(), aSequence);
279     if (status != IFSelect_RetDone)
280     {
281       MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Error : The file is not read", L"CasCade Error", MB_ICONERROR);
282     }
283
284         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
285    }
286   return aSequence;
287 }
288 //----------------------------------------------------------------------
289
290 Standard_Integer CImportExport::ReadIGES(const Standard_CString& aFileName,
291                                          Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
292 {
293
294     IGESControl_Reader Reader;
295
296     Standard_Integer status = Reader.ReadFile(aFileName);
297
298     if (status != IFSelect_RetDone) return status;
299     Reader.TransferRoots();
300     TopoDS_Shape aShape = Reader.OneShape();     
301         aHSequenceOfShape->Append(aShape);
302
303     return status;
304 }
305 //----------------------------------------------------------------------
306
307 void CImportExport::SaveIGES(const Handle(AIS_InteractiveContext)& anInteractiveContext)
308 {
309         anInteractiveContext->InitCurrent();
310         if (anInteractiveContext->NbCurrents() == 0){
311                 AfxMessageBox (L"No shape selected for export!");
312                 return;
313         }
314     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
315     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
316     CImportExport::SaveIGES(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies));
317 }
318
319 Standard_Boolean CImportExport::SaveIGES(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
320 {
321     if (aHSequenceOfShape->Length() == 0)
322     {
323         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
324         return Standard_False;
325     }
326
327   CFileDialog dlg(FALSE, L"*.iges",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
328                   L"IGES Files (*.iges )|*.iges;|IGES Files (*.igs )| *.igs;||", NULL);
329
330 CString SHAREPATHValue;
331 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
332 CString initdir = (SHAREPATHValue + "\\iges");
333
334 dlg.m_ofn.lpstrInitialDir = initdir;
335   
336   Standard_Boolean result=Standard_False;
337   if (dlg.DoModal() == IDOK)  
338   { 
339     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT)); 
340
341     TCollection_ExtendedString aFileNameW ((Standard_ExtString )(const wchar_t* )dlg.GetPathName());
342     TCollection_AsciiString    aFileName  (aFileNameW, '?');
343
344     result = SaveIGES (aFileName.ToCString(), aHSequenceOfShape);
345     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
346    }
347     return result;
348 }
349 //----------------------------------------------------------------------
350
351 Standard_Boolean CImportExport::SaveIGES(const Standard_CString& aFileName,
352                                          const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
353 {
354
355     IGESControl_Controller::Init();
356         IGESControl_Writer ICW (Interface_Static::CVal("XSTEP.iges.unit"),
357                Interface_Static::IVal("XSTEP.iges.writebrep.mode"));
358         
359         for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)  
360                 ICW.AddShape (aHSequenceOfShape->Value(i));                      
361
362         ICW.ComputeModel();
363         Standard_Boolean result = ICW.Write(aFileName );
364     return result;
365 }
366
367 //======================================================================
368
369 //======================================================================
370 //=                                                                    =
371 //=                      STEP                                          =
372 //=                                                                    =
373 //======================================================================
374
375 void CImportExport::ReadSTEP(const Handle(AIS_InteractiveContext)& anInteractiveContext)
376 {
377     Handle(TopTools_HSequenceOfShape) aSequence = CImportExport::ReadSTEP();
378                 if (!aSequence.IsNull()) {      
379                         for(int i=1;i<= aSequence->Length();i++)
380         anInteractiveContext->Display(new AIS_Shape(aSequence->Value(i)), Standard_False);
381                 }
382 }
383
384 Handle(TopTools_HSequenceOfShape) CImportExport::ReadSTEP()// not by reference --> the sequence is created here !!
385 {
386   CFileDialog dlg(TRUE,
387                   NULL,
388                   NULL,
389                   OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
390                   L"STEP Files (*.stp;*.step)|*.stp; *.step|All Files (*.*)|*.*||",
391                   NULL );
392
393 CString SHAREPATHValue;
394 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
395 CString initdir = (SHAREPATHValue + "\\step");
396
397 dlg.m_ofn.lpstrInitialDir = initdir;
398   
399   Handle(TopTools_HSequenceOfShape) aSequence= new TopTools_HSequenceOfShape();
400   if (dlg.DoModal() == IDOK) 
401   {
402     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
403     TCollection_ExtendedString aFileNameW ((Standard_ExtString )(const wchar_t* )dlg.GetPathName());
404     TCollection_AsciiString    aFileName  (aFileNameW, '?');
405         IFSelect_ReturnStatus ReturnStatus = ReadSTEP (aFileName.ToCString(), aSequence);
406     switch (ReturnStatus) 
407     {
408        case IFSelect_RetError :
409            MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Not a valid Step file", L"ERROR", MB_ICONWARNING);
410        break;
411        case IFSelect_RetFail :
412            MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Reading has failed", L"ERROR", MB_ICONWARNING);
413        break;
414        case IFSelect_RetVoid :
415             MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Nothing to transfer", L"ERROR", MB_ICONWARNING);
416        break;
417     }
418     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));       
419   }
420   return aSequence;
421 }
422
423 IFSelect_ReturnStatus CImportExport::ReadSTEP(const Standard_CString& aFileName,
424                                               Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
425 {
426   aHSequenceOfShape->Clear();
427
428   // create additional log file
429   STEPControl_Reader aReader;
430   IFSelect_ReturnStatus status = aReader.ReadFile(aFileName);
431   if (status != IFSelect_RetDone)
432     return status;
433
434   aReader.WS()->TransferReader()->TransientProcess()->SetTraceLevel(2); // increase default trace level
435
436   Standard_Boolean failsonly = Standard_False;
437   aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity);
438
439   // Root transfers
440   Standard_Integer nbr = aReader.NbRootsForTransfer();
441   aReader.PrintCheckTransfer (failsonly, IFSelect_ItemsByEntity);
442   for ( Standard_Integer n = 1; n<=nbr; n++) {
443     /*Standard_Boolean ok =*/ aReader.TransferRoot(n);
444   }
445
446   // Collecting resulting entities
447   Standard_Integer nbs = aReader.NbShapes();
448   if (nbs == 0) {
449     return IFSelect_RetVoid;
450   }
451   for (Standard_Integer i=1; i<=nbs; i++) {
452     aHSequenceOfShape->Append(aReader.Shape(i));
453   }
454
455   return status;
456 }
457
458
459 //----------------------------------------------------------------------
460 void CImportExport::SaveSTEP(const Handle(AIS_InteractiveContext)& anInteractiveContext)
461 {
462         anInteractiveContext->InitCurrent();
463         if (anInteractiveContext->NbCurrents() == 0){
464                 AfxMessageBox (L"No shape selected for export!");
465                 return;
466         }
467     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
468     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
469     CImportExport::SaveSTEP(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies));
470 }
471
472 // Return True if no error
473 Standard_Boolean TestFacetedBrep(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
474 {
475         Standard_Boolean OneErrorFound = Standard_False;
476         for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
477         {
478           TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
479
480           TopExp_Explorer Ex(aShape,TopAbs_FACE);
481           while (Ex.More() && !OneErrorFound)
482                 {
483                 // Get the      Geom_Surface outside the TopoDS_Face
484                 Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(Ex.Current()));
485                 // check if it is a plane.
486                 if (!aSurface->IsKind(STANDARD_TYPE(Geom_Plane)))
487                     OneErrorFound=Standard_True;
488                 Ex.Next();
489                 }
490           TopExp_Explorer Ex2(aShape,TopAbs_EDGE);
491           while (Ex2.More() && !OneErrorFound)
492                 {
493                 // Get the      Geom_Curve outside the TopoDS_Face
494                 Standard_Real FirstDummy,LastDummy;
495                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(TopoDS::Edge(Ex2.Current()),FirstDummy,LastDummy);
496                 // check if it is a line.
497                 if (!aCurve->IsKind(STANDARD_TYPE(Geom_Line)))
498                     OneErrorFound=Standard_True;
499                 Ex2.Next();
500                 }
501         }
502         return !OneErrorFound;
503 }
504
505 IFSelect_ReturnStatus CImportExport::SaveSTEP(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
506 {
507     if (aHSequenceOfShape->Length() == 0)
508       {
509         MessageBox (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
510         return IFSelect_RetError;
511       }
512
513     IFSelect_ReturnStatus status = IFSelect_RetVoid;
514
515         CFileSaveSTEPDialog aDlg(NULL);
516
517         aDlg.m_Cc1ModelType = STEPControl_AsIs;
518
519         if (aDlg.DoModal() == IDOK) {
520         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT)); 
521     TCollection_ExtendedString aFileNameW ((Standard_ExtString )(const wchar_t* )aDlg.GetPathName());
522     TCollection_AsciiString    aFileName  (aFileNameW, '?');
523
524                 STEPControl_StepModelType selection = aDlg.m_Cc1ModelType;
525
526         if(selection == STEPControl_FacetedBrep)
527
528         if (!TestFacetedBrep(aHSequenceOfShape))
529             {
530           MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"At least one shape doesn't contain facetes", L"CasCade Warning", MB_ICONWARNING);
531             return IFSelect_RetError;
532             }
533
534
535         status =  SaveSTEP (aFileName.ToCString(), aHSequenceOfShape, selection);
536         switch (status)
537           {
538             case IFSelect_RetError:
539                 MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Incorrect Data", L"ERROR", MB_ICONWARNING); 
540             break;
541             case IFSelect_RetFail:
542                 MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Writing has failed", L"ERROR", MB_ICONWARNING); 
543             break;
544             case IFSelect_RetVoid:
545                 MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Nothing to transfer", L"ERROR", MB_ICONWARNING); 
546             break;
547           }
548         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); 
549   } 
550   return status;
551 }
552 //----------------------------------------------------------------------------------------
553 IFSelect_ReturnStatus CImportExport::SaveSTEP(const Standard_CString& aFileName,
554                                               const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
555
556 const STEPControl_StepModelType aValue /* =TopoDSToCc1Act_ManifoldSolidBrep */ )
557
558 {
559     // CREATE THE WRITER
560
561     STEPControl_Writer aWriter;
562
563         IFSelect_ReturnStatus status;
564         for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)  
565         {
566                         status =  aWriter.Transfer(aHSequenceOfShape->Value(i), aValue);
567             if ( status != IFSelect_RetDone ) return status;
568         }     
569     status = aWriter.Write(aFileName);
570     return status;
571 }
572
573
574
575 //======================================================================
576 //=                                                                    =
577 //=                      STL                                           =
578 //=                                                                    =
579 //======================================================================
580
581 void CImportExport::SaveSTL(const Handle(AIS_InteractiveContext)& anInteractiveContext)
582 {
583     anInteractiveContext->InitCurrent();
584         if (anInteractiveContext->NbCurrents() == 0){
585                 AfxMessageBox (L"No shape selected for export!");
586                 return;
587         }
588     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
589     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
590         CImportExport::SaveSTL(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies));
591 }
592
593 Standard_Boolean CImportExport::SaveSTL(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
594 {
595   CFileDialog dlg(FALSE, L"*.stl", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
596                       L"stl Files (*.stl)|*.stl;|STL Files (*.STL)|*.STL;||", NULL);
597
598 CString SHAREPATHValue;
599 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
600 CString initdir = (SHAREPATHValue + "\\stl");
601
602 dlg.m_ofn.lpstrInitialDir = initdir;
603
604         Standard_Boolean result = Standard_False;
605
606         if (dlg.DoModal() == IDOK) {
607         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT)); 
608         TCollection_ExtendedString aFileNameW ((Standard_ExtString )(const wchar_t* )dlg.GetPathName());
609         TCollection_AsciiString    aFileName  (aFileNameW, '?');
610         TCollection_AsciiString Message;
611         result = SaveSTL (aFileName.ToCString(), aHSequenceOfShape, Message);
612         CString aMsg (Message.ToCString());
613         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, aMsg, result ? L"CasCade" : L"CasCade Error", result ? MB_OK : MB_ICONERROR);
614         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); 
615     } 
616   return result;
617 }
618
619 Standard_Boolean CImportExport::SaveSTL(const Standard_CString& aFileName,
620                                           const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
621                                           TCollection_AsciiString& ReturnMessage)
622 {
623         Standard_Boolean ReturnValue = Standard_True;
624     if (aHSequenceOfShape->Length() == 0)
625     {
626         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
627         return Standard_False;
628     }
629
630     ReturnMessage += "The Object have be saved in the file ";
631     ReturnMessage += aFileName;
632     ReturnMessage += "\n with the names : ";
633
634         TopoDS_Compound RES;
635         BRep_Builder MKCP;
636         MKCP.MakeCompound(RES);
637
638         for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
639         {
640                 TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
641                 TCollection_AsciiString anObjectName("anObjectName_");
642                 anObjectName += i;
643                 ReturnMessage += anObjectName;
644                 ReturnMessage += " \n";
645
646                 if ( aShape.IsNull() ) 
647                 {
648                         ReturnMessage += " Error : Invalid shape \n";
649                         ReturnValue = Standard_False;
650                         continue;
651                  }
652
653                 MKCP.Add(RES, aShape);
654         }
655
656         StlAPI_Writer myStlWriter;
657         myStlWriter.Write(RES, aFileName);
658
659     return ReturnValue;
660 }
661
662
663 //======================================================================
664 //=                                                                    =
665 //=                      VRML                                          =
666 //=                                                                    =
667 //======================================================================
668
669 void CImportExport::SaveVRML(const Handle(AIS_InteractiveContext)& anInteractiveContext)
670 {
671    anInteractiveContext->InitCurrent();
672         if (anInteractiveContext->NbCurrents() == 0){
673                 AfxMessageBox (L"No shape selected for export!");
674                 return;
675         }
676     Handle(Quantity_HArray1OfColor) anArrayOfColors;
677     Handle(TColStd_HArray1OfReal)   anArrayOfTransparencies;
678         CImportExport::SaveVRML(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies),
679                             anArrayOfColors, anArrayOfTransparencies);
680 }
681
682 Standard_Boolean CImportExport::SaveVRML(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
683                                          const Handle(Quantity_HArray1OfColor)&   anArrayOfColors,
684                                          const Handle(TColStd_HArray1OfReal)&     anArrayOfTransparencies)
685 {
686   CFileDialog dlg(FALSE, L"*.vrml", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
687                       L"vrml Files (*.vrml)|*.vrml;|vrm Files (*.vrm)|*.vrm;||", NULL);
688
689 CString SHAREPATHValue;
690 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
691 CString initdir = (SHAREPATHValue + "\\vrml");
692
693 dlg.m_ofn.lpstrInitialDir = initdir;
694   
695   Standard_Boolean result = Standard_False;
696
697         if (dlg.DoModal() == IDOK) {
698         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT)); 
699         TCollection_ExtendedString aFileNameW ((Standard_ExtString )(const wchar_t* )dlg.GetPathName());
700         TCollection_AsciiString    aFileName  (aFileNameW, '?');
701         TCollection_AsciiString Message;
702         result = SaveVRML (aFileName.ToCString(), aHSequenceOfShape, anArrayOfColors, anArrayOfTransparencies, Message);
703         CString aMsg (Message.ToCString());
704         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, aMsg, result ? L"CasCade" : L"CasCade Error", result ? MB_OK : MB_ICONERROR);
705         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); 
706     } 
707   return result;
708 }
709
710 Standard_Boolean CImportExport::SaveVRML(const Standard_CString&                  aFileName,
711                                          const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
712                                          const Handle(Quantity_HArray1OfColor)&   anArrayOfColors,
713                                          const Handle(TColStd_HArray1OfReal)&     anArrayOfTransparencies,
714                                          TCollection_AsciiString&                 ReturnMessage)
715 {
716         Standard_Boolean ReturnValue = Standard_True;
717     if (aHSequenceOfShape->Length() == 0)
718     {
719         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
720         return Standard_False;
721     }
722
723     ReturnMessage += "The Object has been saved in the file ";
724     ReturnMessage += aFileName;
725     ReturnMessage += "\n with the names : ";
726
727     // VRML scene.
728     VrmlData_Scene scene;
729     VrmlData_ShapeConvert converter(scene/*, 0.001*/); // from mm to meters 
730     Standard_Integer iShape = 1; // Counter of shapes
731
732     for (int i = 1; i <= aHSequenceOfShape->Length(); i++)
733     {
734         // Shape
735         TopoDS_Shape shape = aHSequenceOfShape->Value(i);
736         if (shape.IsNull())
737         {
738           ReturnMessage += " Error : Invalid shape \n";
739           ReturnValue = Standard_False;
740           continue;
741         }
742
743         // Color
744         Quantity_Color color; // yellow
745         if (!anArrayOfColors.IsNull())
746             color = anArrayOfColors->Value(i);
747
748         // Transparency
749         Standard_Real transparency = 0.0;
750         if (!anArrayOfTransparencies.IsNull())
751             transparency = anArrayOfTransparencies->Value(i);
752
753         // Give a name to the shape.
754         TCollection_AsciiString name("Shape");
755         name += TCollection_AsciiString(iShape++);
756         converter.AddShape(shape, name.ToCString());
757         ReturnMessage += name;
758         ReturnMessage += '\n';
759
760         // Check presence of faces in the shape.
761         TopExp_Explorer expl(shape, TopAbs_FACE);
762         if (expl.More())
763             converter.Convert(true, false, 0.01); // faces only
764         else
765             converter.Convert(false, true, 0.01); // edges only
766
767         // Name of the color & transparency.
768         // It will be uniquely saved in VRML file.
769         TCollection_AsciiString cname = Quantity_Color::StringName(color.Name());
770         cname += transparency;
771
772         // Make the appearance (VRML attribute)
773         Handle(VrmlData_Appearance) appearance = Handle(VrmlData_Appearance)::DownCast(scene.FindNode(cname.ToCString()));
774         if (appearance.IsNull())
775         {
776             // Not found ... create a new one.
777             Handle(VrmlData_Material) material = new VrmlData_Material(scene, cname.ToCString(), 0.2, 0.2, transparency);
778             material->SetDiffuseColor(color);
779             material->SetEmissiveColor(color);
780             material->SetSpecularColor(color);
781             scene.AddNode(material, false);
782             appearance = new VrmlData_Appearance(scene, cname.ToCString());
783             appearance->SetMaterial(material);
784             scene.AddNode(appearance, false);
785         }
786
787         // Apply the material to the shape of entity.
788         Handle(VrmlData_Group) group = Handle(VrmlData_Group)::DownCast(scene.FindNode(name.ToCString()));
789         if (!group.IsNull())
790         {
791             VrmlData_ListOfNode::Iterator itr = group->NodeIterator();
792             for (; itr.More(); itr.Next())
793             {
794                 Handle(VrmlData_Node) node = itr.Value();
795                 if (node->DynamicType() == STANDARD_TYPE(VrmlData_ShapeNode))
796                 {
797                     Handle(VrmlData_ShapeNode) aShape = Handle(VrmlData_ShapeNode)::DownCast(node);
798                     aShape->SetAppearance(appearance);
799                 }
800                 else if (itr.Value()->DynamicType() == STANDARD_TYPE(VrmlData_Group))
801                 {
802                     Handle(VrmlData_Group) groupc = Handle(VrmlData_Group)::DownCast(itr.Value());
803                     VrmlData_ListOfNode::Iterator itrc = groupc->NodeIterator();
804                     for (; itrc.More(); itrc.Next())
805                     {
806                         Handle(VrmlData_Node) nodec = itrc.Value();
807                         if (nodec->DynamicType() == STANDARD_TYPE(VrmlData_ShapeNode))
808                         {
809                             Handle(VrmlData_ShapeNode) shapec = Handle(VrmlData_ShapeNode)::DownCast(nodec);
810                             shapec->SetAppearance(appearance);
811                         }
812                     } // for of group nodes...
813                 } // if (it is a shape node...
814             } // for of group nodes...
815         } // if (!group.IsNull...
816     } // iterator of shapes
817
818     // Call VRML writer
819     ofstream writer(aFileName);
820     writer<<scene;
821     writer.close();
822
823     /* Old approach to store shapes in VRML (without color & transparency).
824         TopoDS_Compound RES;
825         BRep_Builder MKCP;
826         MKCP.MakeCompound(RES);
827
828         for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
829         {
830                 TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
831                 TCollection_AsciiString anObjectName("anObjectName_");
832                 anObjectName += i;
833                 ReturnMessage += anObjectName;
834                 ReturnMessage += " \n";
835
836                 if ( aShape.IsNull() ) 
837                 {
838                         ReturnMessage += " Error : Invalid shape \n";
839                         ReturnValue = Standard_False;
840                         continue;
841                  }
842
843                 MKCP.Add(RES, aShape);
844         }
845
846         VrmlAPI_Writer myVrmlWriter;
847         myVrmlWriter.Write(RES, aFileName);
848     */
849
850     return ReturnValue;
851 }
852
853
854
855