Integration of OCCT 6.5.0 from SVN
[occt.git] / samples / java / src / SampleImportExportPackage / SampleImportExportPackage.cxx
1 // File:        SampleImportExportPackage.cxx
2 // Created:     Tue Nov 23 10:34:43 1999
3 // Author:      UI team
4 //              <ui@zamox.nnov.matra-dtv.fr>
5
6
7 #include <SampleImportExportPackage.ixx>
8
9 #include <AIS_InteractiveContext.hxx>
10 #include <AIS_InteractiveObject.hxx>
11 #include <AIS_Shape.hxx>
12 #include <TopoDS_Shape.hxx>
13 #include <TopTools_HSequenceOfShape.hxx>
14 #include <BRep_Builder.hxx>
15 #include <BRepTools.hxx>
16 #include <FSD_File.hxx>
17 #include <ShapeSchema.hxx>
18 #include <Storage_Data.hxx>
19 #include <Storage_HSeqOfRoot.hxx>
20 #include <Standard_Persistent.hxx>
21 #include <Storage_Root.hxx>
22 #include <PTopoDS_HShape.hxx>
23 #include <PTColStd_PersistentTransientMap.hxx>
24 #include <PTColStd_TransientPersistentMap.hxx>
25 #include <MgtBRep.hxx>
26 #include <Interface_Static.hxx>
27 #include <STEPControl_Controller.hxx>
28 #include <STEPControl_Reader.hxx>
29 #include <STEPControl_Writer.hxx>
30 #include <IGESControl_Controller.hxx>
31 #include <IGESControl_Reader.hxx>
32 #include <IGESControl_Writer.hxx>
33 #include <TopExp_Explorer.hxx>
34 #include <BRep_Tool.hxx>
35 #include <TopoDS.hxx>
36 #include <Geom_Curve.hxx>
37 #include <Geom_Surface.hxx>
38 #include <Geom_Plane.hxx>
39 #include <Geom_Line.hxx>
40 #include <TCollection_AsciiString.hxx>
41 #include <TCollection_ExtendedString.hxx>
42 #include <TColStd_SequenceOfAsciiString.hxx>
43 #include <TColStd_SequenceOfExtendedString.hxx>
44 #include <Aspect_Window.hxx>
45 #include <V3d_View.hxx>
46
47 #ifdef WNT
48 #include <WNT_Window.hxx>
49 #include <WNT_GraphicDevice.hxx>
50 #include <WNT_WDriver.hxx>
51 #include <Graphic3d_WNTGraphicDevice.hxx>
52 #else
53 #include <Xw_Window.hxx>
54 #include <Xw_GraphicDevice.hxx>
55 #include <Xw_Driver.hxx>
56 #include <Graphic3d_GraphicDevice.hxx>
57 #endif
58
59
60
61
62 /*----------------------------------------------------------------------*/
63 #ifdef WNT
64 static Handle(Graphic3d_WNTGraphicDevice) defaultDevice;
65 static Handle(WNT_GraphicDevice) default2dDevice;
66 #else
67 static Handle(Graphic3d_GraphicDevice) defaultDevice;
68 static Handle(Xw_GraphicDevice) default2dDevice;
69 #endif 
70
71
72
73 //===============================================================
74 // Function name: CreateViewer3d
75 //===============================================================
76  Handle(V3d_Viewer) SampleImportExportPackage::CreateViewer3d(const Standard_ExtString aName) 
77 {
78 #ifdef WNT
79   if (defaultDevice.IsNull()) 
80     defaultDevice = new Graphic3d_WNTGraphicDevice();
81   return new V3d_Viewer(defaultDevice, aName);
82 #else
83   if (defaultDevice.IsNull()) 
84     defaultDevice = new Graphic3d_GraphicDevice("");
85   return new V3d_Viewer(defaultDevice, aName);
86 #endif //WNT
87 }
88
89 //===============================================================
90 // Function name: SetWindow3d
91 //===============================================================
92 void SampleImportExportPackage::SetWindow3d (const Handle(V3d_View)& aView,
93                                              const Standard_Integer hiwin,
94                                              const Standard_Integer lowin)
95 {
96 #ifdef WNT
97   Handle(Graphic3d_WNTGraphicDevice) d = 
98     Handle(Graphic3d_WNTGraphicDevice)::DownCast(aView->Viewer()->Device());
99   Handle(WNT_Window) w = new WNT_Window(d,hiwin,lowin);
100 #else
101   Handle(Graphic3d_GraphicDevice) d = 
102     Handle(Graphic3d_GraphicDevice)::DownCast(aView->Viewer()->Device());
103   Handle(Xw_Window) w = new Xw_Window(d,hiwin,lowin,Xw_WQ_3DQUALITY);
104 #endif
105   aView->SetWindow(w);
106 }
107
108
109 /*----------------------------------------------------------------------*/
110
111 Handle(TopTools_HSequenceOfShape) BuildSequenceFromContext(const Handle(AIS_InteractiveContext)& aContext) 
112 {
113   Handle(TopTools_HSequenceOfShape) aSequence = new TopTools_HSequenceOfShape();
114   Handle(AIS_InteractiveObject) picked;
115   for(aContext->InitCurrent();aContext->MoreCurrent();aContext->NextCurrent())
116     {
117       picked = aContext->Current();
118       if (aContext->Current()->IsKind(STANDARD_TYPE(AIS_Shape)))
119         {
120           TopoDS_Shape aShape = Handle(AIS_Shape)::DownCast(picked)->Shape();
121           aSequence->Append(aShape);
122         }
123     }
124   return aSequence;
125 }
126
127
128 //======================================================================
129 //=                                                                    =
130 //=                      BREP                                          =
131 //=                                                                    =
132 //======================================================================
133
134  Standard_Boolean SampleImportExportPackage::ReadBREP(const Standard_CString aFileName,
135                                                       const Handle(AIS_InteractiveContext)& aContext) 
136 {
137   TopoDS_Shape aShape;
138   BRep_Builder aBuilder;
139   Standard_Boolean result = BRepTools::Read(aShape,aFileName,aBuilder);
140   if (result) 
141     aContext->Display(new AIS_Shape(aShape));
142   return result;
143 }
144
145  Standard_Boolean SampleImportExportPackage::SaveBREP(const Standard_CString aFileName,
146                                                       const Handle(AIS_InteractiveContext)& aContext) 
147 {
148   Handle(TopTools_HSequenceOfShape) aSequence = BuildSequenceFromContext(aContext);
149
150   if (aSequence->Length() == 0)
151     return Standard_False;
152
153   TopoDS_Shape aShape = aSequence->Value(1);
154
155   Standard_Boolean result = BRepTools::Write(aShape,aFileName); 
156   return result;
157 }
158
159
160 //======================================================================
161 //=                                                                    =
162 //=                      CSFDB                                         =
163 //=                                                                    =
164 //======================================================================
165 TCollection_AsciiString BuildStorageErrorMessage (Storage_Error anError)
166
167   TCollection_AsciiString aMessage("Storage Status :");
168   switch ( anError ) 
169     {
170       case Storage_VSOk : 
171         aMessage += "no problem \n";
172         break;
173       case Storage_VSOpenError : 
174         aMessage += "OpenError while opening the stream \n";
175         break;
176       case Storage_VSModeError : 
177         aMessage += "the stream is opened with a wrong mode for operation \n";
178         break;
179       case Storage_VSCloseError : 
180         aMessage += "CloseError while closing the stream \n";
181         break;
182       case Storage_VSAlreadyOpen : 
183         aMessage += "stream is already opened \n";
184         break;
185       case Storage_VSNotOpen : 
186         aMessage += "stream not opened \n";
187         break;
188       case Storage_VSSectionNotFound : 
189         aMessage += "the section is not found \n";
190         break;
191       case Storage_VSWriteError : 
192         aMessage += "error during writing \n";
193         break;
194       case Storage_VSFormatError : 
195         aMessage += "wrong format error occured while reading \n";
196         break;
197       case Storage_VSUnknownType : 
198         aMessage += "try to read an unknown type \n";
199         break;
200       case Storage_VSTypeMismatch : 
201         aMessage += "try to read a wrong primitive type (read a char while expecting a real) \n";
202         break;
203       case Storage_VSInternalError : 
204         aMessage += "internal error \n ";
205         break;
206       case Storage_VSExtCharParityError : 
207         aMessage += "problem with 16bit characters, may be an 8bit character is inserted inside a 16bit string \n";
208         break;
209       default :
210             aMessage += "Unknown Status ";
211       aMessage += anError;
212       aMessage += " \n";
213       break;
214     }
215   return aMessage;
216 }
217
218
219  Standard_Boolean SampleImportExportPackage::ReadCSFDB(const Standard_CString aFileName,
220                                                        const Handle(AIS_InteractiveContext)& aContext,
221                                                        TCollection_AsciiString& ReturnMessage) 
222 {
223   Handle(TopTools_HSequenceOfShape) aSequence = new TopTools_HSequenceOfShape();
224   Standard_Integer i;
225
226   // an I/O driver
227   FSD_File f;
228
229   // the applicative Schema
230   Handle(ShapeSchema) s = new ShapeSchema;
231
232   // a Read/Write data object
233   Handle(Storage_Data) d = new Storage_Data;
234
235   d->ClearErrorStatus();
236
237   // Check file type
238   if (FSD_File::IsGoodFileType(aFileName) != Storage_VSOk)  {
239     ReturnMessage = "Bad file type for ";
240     ReturnMessage += aFileName;
241     ReturnMessage += " \n";
242     return Standard_False;
243   }
244
245   // Open the archive, Read mode
246   Storage_Error err = f.Open(aFileName, Storage_VSRead);
247   // Read all the persistent object in the file with the schema
248   if ( err != Storage_VSOk ) {
249     ReturnMessage += BuildStorageErrorMessage(d->ErrorStatus());
250     return Standard_False;
251   }
252
253   d = s->Read( f );
254   err = d->ErrorStatus() ;
255
256   if ( err != Storage_VSOk ) {
257     ReturnMessage += BuildStorageErrorMessage(d->ErrorStatus());
258     return Standard_False;
259   }
260   // Close the file driver
261   f.Close();
262
263   ReturnMessage += "Application Name :"; ReturnMessage += d->ApplicationName();ReturnMessage += "\n";
264   ReturnMessage += "Application Version :"; ReturnMessage += d->ApplicationVersion();ReturnMessage += "\n";
265   ReturnMessage += "Data type :"; ReturnMessage += d->DataType();ReturnMessage += "\n";
266   ReturnMessage += "== User Infos : ==\n";
267   const TColStd_SequenceOfAsciiString& UserInfo = d->UserInfo();
268   for (i=1; i<=UserInfo.Length(); i++)
269     {ReturnMessage += UserInfo(i);ReturnMessage += "\n";}
270   ReturnMessage += "== Comments : ==\n";
271   const TColStd_SequenceOfExtendedString& Comments=d->Comments();
272   for (i=1; i<=Comments.Length(); i++)
273     {ReturnMessage += Comments(i);ReturnMessage += "\n";}
274   ReturnMessage += "----------------\n";
275
276
277   // Read all the root objects
278   // Get the root list
279   Handle(Storage_HSeqOfRoot)  roots = d->Roots();
280   Handle(Standard_Persistent) p;
281   Handle(Storage_Root) r;
282   Handle(PTopoDS_HShape) aPShape;
283   for (i = 1; i <= roots->Length(); i++ ) 
284     {
285       // Get the root
286       r = roots->Value(i);
287       
288       // Get the persistent application object from the root
289       p = r->Object();
290
291       // Display information
292       ReturnMessage += "Persistent Object "; ReturnMessage += i; ReturnMessage += "\n";
293       ReturnMessage += "Name             :"; ReturnMessage += r->Name(); ReturnMessage += "\n";
294       ReturnMessage += "Type             :"; ReturnMessage += r->Type(); ReturnMessage += "\n";
295       
296       aPShape  = Handle(PTopoDS_HShape)::DownCast(p);
297
298       if (!aPShape.IsNull()) 
299         {
300           //   To Be  ReWriten to suppress the cout,
301           //    and provide a CallBack method for dynamic information. 
302           // Get the persistent shape
303           PTColStd_PersistentTransientMap aMap;
304           TopoDS_Shape aTShape;
305           MgtBRep::Translate(aPShape,aMap,aTShape,
306                              MgtBRep_WithTriangle);
307           aSequence->Append(aTShape);
308         } 
309       else
310         {
311           ReturnMessage += "Error -> Unable to read\n";
312         } 
313     }
314
315   // Display shapes
316   for(i=1; i<=aSequence->Length(); i++)
317     aContext->Display(new AIS_Shape(aSequence->Value(i)));
318
319   return Standard_True;
320 }
321
322
323  Standard_Boolean SampleImportExportPackage::SaveCSFDB(const Standard_CString aFileName,
324                                                        const Handle(AIS_InteractiveContext)& aContext,
325                                                        TCollection_AsciiString& ReturnMessage,
326                                                        const MgtBRep_TriangleMode aTriangleMode) 
327 {
328   Handle(TopTools_HSequenceOfShape) aHSequenceOfShape = BuildSequenceFromContext(aContext);
329   Standard_Integer ReturnValue = Standard_True;
330   if (aHSequenceOfShape->Length() == 0)
331     return Standard_False;
332
333   // an I/O driver
334   FSD_File f;
335
336   // the applicative Schema containing 
337   // Pesistent Topology and Geometry
338   Handle(ShapeSchema) s = new ShapeSchema;
339
340   // a Read/Write data object
341   Handle(Storage_Data) d = new Storage_Data;
342
343   d->ClearErrorStatus();
344   
345   //   To Be  ReWriten to suppress the Strings,
346   //    and provide a CallBack method for dynamic information. 
347
348   d->SetApplicationName(TCollection_ExtendedString("SampleImportExport"));
349   d->SetApplicationVersion("1");
350   d->SetDataType(TCollection_ExtendedString("Shapes"));
351   d->AddToUserInfo("Try to store a Persistent set of Shapes in a flat file");
352   d->AddToComments(TCollection_ExtendedString("application is based on CasCade 2.0"));
353   
354   // Open the archive, Write mode
355   Storage_Error err = f.Open(aFileName, Storage_VSWrite);
356
357   if ( err != Storage_VSOk ) {
358     ReturnMessage += BuildStorageErrorMessage(err);
359     return Standard_False;
360   }
361
362   PTColStd_TransientPersistentMap aMap;
363   ReturnMessage += "The Object have be saved in the file ";
364   ReturnMessage += aFileName;
365   ReturnMessage += "\n with the names : ";
366
367   for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
368     {
369       TopoDS_Shape aTShape= aHSequenceOfShape->Value(i);
370       TCollection_AsciiString anObjectName("anObjectName_");
371       anObjectName += i;
372       ReturnMessage += anObjectName;
373       ReturnMessage += " \n";
374
375       if ( aTShape.IsNull() ) 
376         {
377           ReturnMessage += " Error : Invalid shape \n";
378           ReturnValue = Standard_False;
379           continue;
380         }
381
382       //Create the persistent Shape
383
384       Handle(PTopoDS_HShape) aPShape = 
385         MgtBRep::Translate(aTShape, aMap, aTriangleMode);
386
387  
388       // Add the object in the data structure as root
389       //   To Be  ReWriten to suppress the cout,
390       //    and provide a CallBack method for dynamic information. 
391       d->AddRoot(anObjectName, aPShape);
392     }
393
394   // Write the object in the file with the schema
395   s->Write( f, d);
396
397   // Close the driver
398   f.Close();
399
400   if ( d->ErrorStatus() != Storage_VSOk ) 
401     {
402       ReturnMessage += BuildStorageErrorMessage(d->ErrorStatus());
403       return Standard_False;
404     }
405
406   return ReturnValue;
407 }
408
409
410 //======================================================================
411 //=                                                                    =
412 //=                      STEP                                          =
413 //=                                                                    =
414 //======================================================================
415  IFSelect_ReturnStatus SampleImportExportPackage::ReadSTEP(const Standard_CString aFileName,
416                                                            const Handle(AIS_InteractiveContext)& aContext) 
417 {
418   Handle(TopTools_HSequenceOfShape) aSequence = new TopTools_HSequenceOfShape();
419   TopoDS_Shape aShape;
420   STEPControl_Controller::Init();
421   STEPControl_Reader aReader;
422   IFSelect_ReturnStatus status = aReader.ReadFile(aFileName);
423
424   if (status == IFSelect_RetDone)
425     {
426       Standard_Boolean failsonly = Standard_False;
427       aReader.PrintCheckLoad (failsonly, IFSelect_ItemsByEntity);
428       // Root transfers
429       Standard_Integer nbr = aReader.NbRootsForTransfer();
430       aReader.PrintCheckTransfer (failsonly, IFSelect_ItemsByEntity);
431       for ( Standard_Integer n = 1; n<= nbr; n++) 
432         {
433           aReader.TransferRoot(n);
434           // Collecting resulting entities
435           Standard_Integer nbs = aReader.NbShapes();
436           if (nbs == 0) 
437             {
438               aSequence.Nullify();
439               return IFSelect_RetVoid;
440             }
441           else 
442             {
443               for (Standard_Integer i =1; i<=nbs; i++) 
444                 {
445                   aShape=aReader.Shape(i);
446                   aSequence->Append(aShape);
447                 }
448             }
449         }
450     }
451   else
452     {
453       aSequence.Nullify();
454     }
455
456   // Display shapes
457   if (!aSequence.IsNull()) {    
458     for(int i=1;i<= aSequence->Length();i++)
459       aContext->Display(new AIS_Shape(aSequence->Value(i)));
460   }
461
462   return status;
463 }
464
465 Standard_Boolean TestFacetedBrep(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
466 {
467   Standard_Boolean OneErrorFound = Standard_False;
468   for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
469     {
470       TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
471       
472       TopExp_Explorer Ex(aShape,TopAbs_FACE);
473       while (Ex.More() && !OneErrorFound)
474         {
475           // Get the    Geom_Surface outside the TopoDS_Face
476           Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(Ex.Current()));
477           // check if it is a plane.
478           if (!aSurface->IsKind(STANDARD_TYPE(Geom_Plane)))
479             OneErrorFound=Standard_True;
480           Ex.Next();
481         }
482       TopExp_Explorer Ex2(aShape,TopAbs_EDGE);
483       while (Ex2.More() && !OneErrorFound)
484         {
485           // Get the    Geom_Curve outside the TopoDS_Face
486           Standard_Real FirstDummy,LastDummy;
487           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(TopoDS::Edge(Ex2.Current()),FirstDummy,LastDummy);
488           // check if it is a line.
489           if (!aCurve->IsKind(STANDARD_TYPE(Geom_Line)))
490             OneErrorFound=Standard_True;
491           Ex2.Next();
492         }
493     }
494   return !OneErrorFound;
495 }
496
497
498  IFSelect_ReturnStatus SampleImportExportPackage::SaveSTEP(const Standard_CString aFileName,
499                                                            const Handle(AIS_InteractiveContext)& aContext,
500                                                            const STEPControl_StepModelType aValue) 
501 {
502   Handle(TopTools_HSequenceOfShape) aHSequenceOfShape = BuildSequenceFromContext(aContext);
503
504   if (aHSequenceOfShape->Length() == 0)
505     return IFSelect_RetError;
506
507   if (aValue == STEPControl_FacetedBrep)
508     if (!TestFacetedBrep(aHSequenceOfShape))
509       return IFSelect_RetError;
510
511   // CREATE THE WRITER
512   STEPControl_Writer aWriter;
513   IFSelect_ReturnStatus status;
514
515   for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
516     {
517       status =  aWriter.Transfer(aHSequenceOfShape->Value(i), aValue);
518       if ( status != IFSelect_RetDone ) return status;
519     }     
520   status = aWriter.Write(aFileName);
521   return status;
522 }
523
524
525 //======================================================================
526 //=                                                                    =
527 //=                      IGES                                          =
528 //=                                                                    =
529 //======================================================================
530  Standard_Integer SampleImportExportPackage::ReadIGES(const Standard_CString aFileName,
531                                                       const Handle(AIS_InteractiveContext)& aContext) 
532 {
533   Handle(TopTools_HSequenceOfShape) aSequence = new TopTools_HSequenceOfShape();
534   IGESControl_Reader Reader;
535   Standard_Integer status = Reader.ReadFile(aFileName);
536   
537   if (status != IFSelect_RetDone) return status;
538   Reader.TransferRoots();
539   TopoDS_Shape aShape = Reader.OneShape();     
540   aSequence->Append(aShape);
541
542   // Display shapes
543   for(int i=1;i<= aSequence->Length();i++)
544     aContext->Display(new AIS_Shape(aSequence->Value(i)));
545
546   return status;
547 }
548
549
550  Standard_Boolean SampleImportExportPackage::SaveIGES(const Standard_CString aFileName,
551                                                       const Handle(AIS_InteractiveContext)& aContext) 
552 {
553   Handle(TopTools_HSequenceOfShape) aHSequenceOfShape = BuildSequenceFromContext(aContext);
554
555   if (aHSequenceOfShape->Length() == 0)
556     return Standard_False;
557
558   IGESControl_Controller::Init();
559   IGESControl_Writer ICW (Interface_Static::CVal("XSTEP.iges.unit"),
560                              Interface_Static::IVal("XSTEP.iges.writebrep.mode"));
561   
562   for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)  
563     ICW.AddShape (aHSequenceOfShape->Value(i));
564   
565   ICW.ComputeModel();
566   Standard_Boolean result = ICW.Write(aFileName);
567   return result;
568 }
569
570
571 //===============================================================
572 // Function name: SaveImage
573 //===============================================================
574 #ifndef WNT
575  Standard_Boolean SampleImportExportPackage::SaveImage(const Standard_CString ,
576                                                        const Standard_CString ,
577                                                        const Handle(V3d_View)& ) {
578 #else 
579  Standard_Boolean SampleImportExportPackage::SaveImage(const Standard_CString aFileName,
580                                                        const Standard_CString aFormat,
581                                                        const Handle(V3d_View)& aView) 
582 {
583   Handle(Aspect_Window) anAspectWindow = aView->Window();
584   Handle(WNT_Window) aWNTWindow = Handle(WNT_Window)::DownCast(anAspectWindow);
585
586   if (aFormat == "bmp") aWNTWindow->SetOutputFormat(WNT_TOI_BMP);
587   if (aFormat == "gif") aWNTWindow->SetOutputFormat(WNT_TOI_GIF);
588   if (aFormat == "xwd") aWNTWindow->SetOutputFormat(WNT_TOI_XWD);
589
590   aWNTWindow->Dump(aFileName);
591 #endif
592   return Standard_True;
593 }
594