Import STL file in JavaFX

3.6k views Asked by At

My problem is that I am trying to import a 3D model from an STL file to a JavaFX application. I followed the code in this link How to create 3d shape from STL in JavaFX 8? and it's only working with the jewel file mentioned there, but I've tried with other STL files and it's not working!

I can't see why it's not working with the other files. Can anyone explain this? Any help please, as soon as possible!

1

There are 1 answers

1
José Pereda On BEST ANSWER

As you are already using an STL importer from this site, you will find in the same web a 3D model browser you can use to preview your models before importing them to your JavaFX application.

If they can't be imported with this browser, the problem may be related to a non valid STL format in your files.

If they are imported, then the problem may be in your application. Embed the call in a try-catch and post the exception you may enconter.

StlMeshImporter stlImporter = new StlMeshImporter(); 

try {
    stlImporter.read(this.getClass().getResource("<STLfile>.stl"));
}
catch (ImportException e) {
    e.printStackTrace();
    return;
}

EDIT

If no exception is thrown while reading the model, the next step would be inserting the returned mesh into a MeshView and show it on our scene:

TriangleMesh mesh = stlImporter.getImport();
stlImporter.close();
MeshView mesh=new MeshView(cylinderHeadMesh);
Group root = new Group(mesh);
Scene scene = new Scene(root, 1024, 800, true);
Camera camera = new PerspectiveCamera();
scene.setCamera(camera);
primaryStage.setScene(scene);
primaryStage.show(); 

Since the model could be too small or too big for our scene (related to the camera and the point of view we are using), we should print the bounding box of our model, and then scale it up or down accordingly:

System.out.println("mesh: "+mesh.getBoundsInLocal().toString());
mesh.setScaleX(1d);
mesh.setScaleY(1d);
mesh.setScaleZ(1d);

Or we could change the camera parameters:

double max = Math.max(mesh.getBoundsInLocal().getWidth(),
              Math.max(mesh.getBoundsInLocal().getHeight(),
                       mesh.getBoundsInLocal().getDepth()));
camera.setTranslateZ(-3*max);