Boolean Operations on Meshes

Contents
[ ]

Boolean Operations on Meshes

Aspose.3D for Java lets you apply boolean operations on meshes through the BooleanOperator class. The supported operation kinds are defined by the BooleanOperation enum:

  • ADD — union of two meshes
  • INTERSECT — the shared volume of two meshes
  • SUB — the first mesh minus the second mesh

Each operand of a boolean operation can be an instance of Node, any entity that implements IMeshConvertible (like Mesh), or a HalfSpace. For two plain meshes the Mesh.doBoolean() static method applies the operation directly, accepting a transformation matrix for each operand.

Union of Two Overlapping Meshes

This code example calculates the union of two overlapping box meshes:

// Create two overlapping box meshes
Mesh a = new Box(1, 1, 1).toMesh();
Mesh b = new Box(1, 1, 1).toMesh();
// Translate the second box by (0.25, 0, 0) so the two boxes overlap
Matrix4 transform = new Matrix4(
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0.25, 0, 0, 1);
// Union of the two boxes
Mesh union = Mesh.doBoolean(BooleanOperation.ADD, a, transform, b, null);
System.out.println("The union mesh has " + union.getPolygonCount() + " polygons");

Cut a Mesh with a Half Space

A HalfSpace represents an infinite space divided by a plane, defined by its normal and a position on the plane. Cutting a mesh with a half space keeps the portion of the mesh on the positive side of the plane — the side the normal points to. Use the BooleanOperation.SUB operation with a HalfSpace operand:

// Create a scene with a box mesh
Scene scene = new Scene();
Node boxNode = scene.getRootNode().createChildNode("box", new Box(2, 2, 2).toMesh());
// Define a half space whose plane passes through (0, 0, 0.5)
// and whose normal points to +Z
HalfSpace halfSpace = new HalfSpace();
halfSpace.setNormal(new Vector3(0, 0, 1));
halfSpace.setPosition(new Vector3(0, 0, 0.5));
// Cut the box, this keeps the part of the box above z = 0.5
BooleanOperator op = new BooleanOperator();
op.setOperator(BooleanOperation.SUB);
op.setFirst(BooleanOperand.of(boxNode));
op.setSecond(BooleanOperand.of(halfSpace));
Mesh cut = op.toMesh();
System.out.println("The cut mesh has " + cut.getPolygonCount() + " polygons");