WriteSTL

VTKExamples/Java/IO/WriteSTL


Description

vtkSTLWriter object writes Stereo Lithography (.stl) files in either ASCII or binary form.

An STL file describes a triangulated three-dimensional surface by the unit normal and vertices (ordered by the right-hand rule) of the triangles.

This example saves a 3D geometric data stored in a to an STL file.

Other Languages

See (Cxx), (Python)

Question

If you have a simple question about this example contact us at VTKExamplesProject If your question is more complex and may require extended discussion, please use the VTK Discourse Forum

Code

WriteSTL.java

import vtk.vtkNativeLibrary;
import vtk.vtkRenderWindow;
import vtk.vtkRenderWindowInteractor;
import vtk.vtkRenderer;
import vtk.vtkActor;
import vtk.vtkNamedColors;
import vtk.vtkPolyDataMapper;
import vtk.vtkSTLReader;
import vtk.vtkSTLWriter;
import vtk.vtkSphereSource;


public class WriteSTL
{
  // -----------------------------------------------------------------
  // Load VTK library and print which library was not properly loaded
  static 
  {
    if (!vtkNativeLibrary.LoadAllNativeLibraries()) 
    {
      for (vtkNativeLibrary lib : vtkNativeLibrary.values()) 
      {
        if (!lib.IsLoaded()) 
        {
          System.out.println(lib.GetLibraryName() + " not loaded");
        }
      }
    }
    vtkNativeLibrary.DisableOutputWindow(null);
  }
  // -----------------------------------------------------------------

  public static void main(String args[]) 
  {

    //parse command line arguments
    if (args.length != 1) 
    {
      System.err.println("Usage: java -classpath ... Filename(.stl) e.g sphere.stl");
      return;
    }
    String Filename = args[0];

    vtkNamedColors Color = new vtkNamedColors(); 

    //Renderer Background Color
    double BgColor[] = new double[4];

    //Change Color Name to Use your own Color for Renderer Background
    Color.GetColor("Seagreen",BgColor);

    vtkSphereSource sphereSource = new vtkSphereSource();
    sphereSource.Update();

    vtkSTLWriter stlWriter = new vtkSTLWriter();
    stlWriter.SetFileName(Filename);
    stlWriter.SetInputConnection(sphereSource.GetOutputPort());
    stlWriter.Write();

    //Read and display for verification
    vtkSTLReader reader = new vtkSTLReader();
    reader.SetFileName(Filename);
    reader.Update();

    //Create a mapper and actor
    vtkPolyDataMapper mapper = new vtkPolyDataMapper();
    mapper.SetInputConnection(reader.GetOutputPort());

    vtkActor actor = new vtkActor();
    actor.SetMapper(mapper);

    // Create the renderer, render window and interactor.
    vtkRenderer ren = new vtkRenderer();
    vtkRenderWindow renWin = new vtkRenderWindow();
    renWin.AddRenderer(ren);
    vtkRenderWindowInteractor iren = new vtkRenderWindowInteractor();
    iren.SetRenderWindow(renWin);

    ren.AddActor(actor);
    ren.SetBackground(BgColor);

    renWin.SetSize(300,300);
    renWin.Render();

    iren.Initialize();
    iren.Start();

  }
}