miho / JCSG

Java implementation of BSP based CSG (Constructive Solid Geometry)
Other
177 stars 52 forks source link

How to set color to Java JCSG object? [JavaFX] #60

Closed elozev closed 4 years ago

elozev commented 4 years ago

I'm currently using the Java JCSG library to create Constructive Solid Geometry objects such as intersections, unions and difference between 3D objects. Using the JCSG library, I have the following code for creating objects (cube in this case)

private static CSG createCube(double w, double h, double d) { return new Cube(w, h, d).toCSG(); } and whenever I want to set the colour of this specific CSG object I use the following

private static CSG color(CSG shape, Color c) { return shape.color(c); } However when I transform these objects to a MeshView and pass them to the javafx.scene.Group the color is the default one (red): ` Group world = new Group(); System.out.println(this.objects.size()); for (CSG p : this.objects) { var x = p.toJavaFXMesh().getAsMeshViews().get(0);

        for(Material m: p.toJavaFXMesh().getMaterials()){
            System.out.println(m.toString());

            // System.out.println(m1.getDiffuseColor().toString());
            x.setMaterial((PhongMaterial)m);
        }
        world.getChildren().add(x);
    }

    Scene scene = new Scene(world, WIDTH, HEIGHT, true);
    scene.setFill(Color.PALETURQUOISE);
    scene.setCamera(camera);

    // initMouseControl(world, scene, primaryStage);
    addEventHandlers(scene, camera);
    primaryStage.setTitle("Pane");
    primaryStage.setScene(scene);
    primaryStage.show();

Where this.objects holds all the objects that I created in another class. package me.emil;

import javafx.scene.paint.Color; import me.emil.helpers.Pane;

public class App { public static void main(String[] args) { CSGStorage singleton = CSGStorage.getInstance(); var x = singleton.sphere(50); x = singleton.translate(x, 100, 0, 0); x = singleton.color(x, Color.YELLOW); singleton.addPrimitive(x);

    Pane p = new Pane();
    p.launchPane();
}

} `

JuneToJuly commented 4 years ago

Yeah so you are going to need to generate your own MeshViews because the default does not apply your materials. To do that you need access to the materials for your meshes. Access them by converting your CSG to Obj format, then make your own views.

Solution

Cube shape  = new Cube(5).color(Color.PURPLE);
ObjImporter port = new ObjImporter(shape.toCSG().toObj());
List<MeshView> views = new ArrayList<>();

// For each mesh there is a material
for(int i = 0; i < port.getMaterialCollection().size(); i++)
{
    MeshView view = new MeshView(port.getMeshCollection().get(i));
    view.setMaterial(port.getMaterialCollection().get(i));
    views.add(view);
} 
elozev commented 4 years ago

Thanks that worked!