Giter VIP home page Giter VIP logo

three-bvh-csg's Introduction

three-bvh-csg

npm version build github twitter sponsors

An experimental, in progress, flexible, memory compact, fast and dynamic Constructive Solid Geometry implementation on top of three-mesh-bvh. More than 100 times faster than other BSP-based three.js CSG libraries in complex cases. Contributions welcome!

Note All brush geometry must be two-manifold - or water tight with no triangle interpenetration.

Warning Due to numerical precision and corner cases resulting geometry may not be correctly completely two-manifold.

See projects like Manifold CAD for CAD operations with more robust numercial solutions.

Roadmap / Help Wanted

  • Fix triangle splitting / missing triangle issues #73 #68
  • Polygon splitting & triangulation #51
  • Worker Support #14

And more!

Examples

Simple CSG

Complex Model CSG

Hollow Operations

Multi Material CSG

Multi Operation CSG

Hierarchical Operations

Use

import { SUBTRACTION, Brush, Evaluator } from 'three-bvh-csg';
import { MeshStandardMaterial, Mesh, SphereGeometry, BoxGeometry } from 'three';

const brush1 = new Brush( new SphereGeometry() );
brush1.updateMatrixWorld();

const brush2 = new Brush( new BoxGeometry() );
brush2.position.y = 0.5;
brush2.updateMatrixWorld();

const evaluator = new Evaluator();
const result = evaluator.evaluate( brush1, brush2, SUBTRACTION );

// render the result!

API

Constants

CSGOperations

CSG operations enums for use with Evaluator.

ADDITION              // A ∪ B
SUBTRACTION           // A - B
REVERSE_SUBTRACTION   // B - A
DIFFERENCE            // A ⊕ B
INTERSECTION          // A ∩ B

// "Hollow" operations are non-solid and result in simply removing the geometry
// within Brush B from brush A. For these operations Brush A can be non-manifold
// but it is still required that Brush B be a water-tight, two-manifold mesh.
HOLLOW_SUBTRACTION    // A - B
HOLLOW_INTERSECTION   // A ∩ B

Brush

extends THREE.Mesh

An object with the same interface as THREE.Mesh but used to evaluate CSG operations. Once a brush is created the geometry should not be modified.

Note

It is recommended to remove groups from a geometry before creating a brush if multi-material support is not required.

Operation

extends Brush

This is an extension of the Brush class. With this class is possible to create a mesh and pass the CSG Operation constant to define which operation computes on the mesh. The result is a Mesh whose effect is defined from the operation selected. You can see how it works in the hierarchy example.

.operation

operation = ADDITION : CSGOperation

The operation to perform on the next brush in processing chain when running Evaluater.evaluateHierarchy.

.insertBefore

insertBefore( brush : Brush )

Inserts the brush before the operation element that calls the method, in the list of the children of the operation's parent.

.insertAfter

insertAfter( brush : Brush )

Inserts the brush after the operation element that calls the method, in the list of the children of the operation's parent.

OperationGroup

extends THREE.Group

A class with the same interface as THREE.Group but used to group a list of Operation mesh through the .add method inherited from the THREE.Group class. You can create a group starting from single Operation meshes as in the hierarchy example.

Evaluator

.useGroups

useGroups = true : Boolean

Whether to use geometry groups when processing the geometry. If geometry groups are used then a material array and groups will be assigned to the target Brush after processing. If groups are disabled then a single coherent piece of geometry with no groups will be produced.

.consolidateGroups

consolidateGroups = true : Boolean

If true then any group in the final geometry that shares a common material with another group will be merged into one to reduce the number of draw calls required by the resulting mesh.

.evaluate

evaluate(
	brushA : Brush,
	brushB : Brush,
	operation : CSGOperation,
	target = null : Brush | Mesh
) : Brush | Mesh

// or

evaluate(
	brushA : Brush,
	brushB : Brush,
	operations : Array<CSGOperation>,
	targets : Array<Brush | Mesh>
) : Array<Brush | Mesh>

Performs the given operation on brushA with brushB. If no target is provided then a new Brush will be created with the new geometry. Otherwise the provided Brush will be modified in place and geometry disposed or marked for update as needed.

If arrays are provided for the "targets" and "operations" arguments then multiple results from different operations can be produced at once with minimal additional overhead.

.evaluateHierarchy

evaluateHierarchy(
  root: Operation,
  target = null : Brush | Mesh
) : Brush | Mesh

The method gets as parameters a root, an Operation mesh and a target if it is provided, otherwise, a new Brush will be created. First sets the updateMatrixWolrd of the root to true then calls the traverse function with the root parameter to evaluate the mesh and its children.

evaluate( brush, child, child.operation );

In this case, the arguments passed to evaluate is the root as brushA, the child as brushB and the child.operation as the operation to apply to the mesh.

OperationDebugData

This class is used in the constructor of the Evaluator class. When the Evaluator is defined the constructor creates a debug property of type OperationDebugData and it is used to set the debug context, that is addEdge and addIntersectionTriangles to, for example, an EdgesHelper or a TriangleHelper.

.enabled

enabled = false : Boolean

Whether to collect the debug data during CSG operations which has a performance a memory cost.

.intersectionEdges

intersectionEdges = [] : Line3

A list of edges formed by intersecting triangles during the CSG process.

GridMaterial

extends THREE.MeshPhongMaterial

A material with the same interface as THREE.MeshPhongMaterial. It adds a stylized grid on the mesh for more easily visualizing mesh topology and measurements.

.enableGrid

enableGrid = true : Boolean

Sets the visibility of the grid on the mesh.

HalfEdgeMap

TODO

constructor

constructor( geometry : BufferGeometry = null )

.getSiblingTriangleIndex

getSiblingTriangleIndex( triIndex : Number, edgeIndex : 0 | 1 | 2 ) : Number

.getSiblingEdgeIndex

getSiblingEdgeIndex( triIndex : Number, edgeIndex : 0 | 1 | 2 ) : Number

.updateFrom

updateFrom( geometry : BufferGeometry ) : void

PointsHelper

extends THREE.InstancedMesh

Helper class for generating spheres to display.

.setPoints

setPoints( points : Vector3[] ) : void;

Sets the points, passed as Vector3, and visualizes them as spheres.

EdgesHelper

extends THREE.LineSegments

Helper class for generating a line to display the provided edges.

.setEdges

setEdges( edges : Line3[] ) : void

Sets the list of lines to be visualized.

HalfEdgeMapHelper

extends EdgesHelper

This is a helper class that takes the HalfEdgeMap object and visualizes the connectivity between triangles.

.setHalfEdges

setHalfEdges( geometry : Geometry, halfEdges : HalfEdgeMap ) : void

Sets the half edge map to visualize along with the associated geometry.

TriangleSetHelper

extends THREE.Group

Helper class for displaying a set of triangles. In the Simple CSG example is possible to enable/disable the visibility of the triangles helper via displayTriangleIntersections checkbox.

The helper is composed of two meshes, one is a mesh with a MeshPhongMaterial and the other is a mesh with a LineBasicMaterial.

.setTriangles

setTriangles( triangles:  Triangle[] ) : void

Sets the geometry of the mesh and the line with the position of the triangles passed as a parameter of the method.

Functions

computeMeshVolume

computeMeshVolume( mesh : Mesh | BufferGeometry ) : Number

Computes the volume of the given mesh in world space. The world matrix is expected to be updated before calling this function.

Gotchas

  • All geometry are expected to have all attributes being used and of the same type.
  • Geometry on a Brush should be unique and not be modified after being set.
  • All geometry must be two-manifold - or water tight with no triangle interpenetration.
  • CSG results use Geometry.drawRange to help maintain performance which can cause three.js exporters to fail to export the geometry correctly. It is necessary to convert the geometry to remove the use of draw range before exporting with three.js exporters.

References

three-bvh-csg's People

Contributors

angydev avatar dependabot[bot] avatar frading avatar gkjohnson avatar joe-shajan avatar lgtm-migrator avatar roberts21 avatar toloudis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

three-bvh-csg's Issues

Missing triangle in demo

image

	brush2.position.set( - 0.27300968690619787, 0.5329319712626078, 0 );
	brush2.scale.setScalar( 1 );

Example ideas

  • "playground" with simple shapes that are interactive, adjustable scale, rotation, operation
  • CSG against a loaded complex geometry (swiss cheese rabbit, animated, etc) #17
  • interactive hashed out level design block out (ramps, stairs, etc) #16
  • polygon dragout / creation #19
  • basic hierarchical demo (async non async) #18
  • vertex color #20

Missing triangles

	const cylinder1 = new Brush( new THREE.CylinderBufferGeometry( 1, 1, 2, 20 ), blueMaterial );
	cylinder1.updateMatrixWorld();

	const cylinder2 = new Brush( new THREE.CylinderBufferGeometry( 1, 1, 2, 20 ), blueMaterial );
	cylinder2.rotation.x = Math.PI / 2;
	cylinder2.updateMatrixWorld();

	const evaluator = new Evaluator();
	const result = evaluator.evaluate( cylinder1, cylinder2, ADDITION );

image

Add support for propagating groups (and therefore materials)

  • geometry needs to be converted to non-indexed? Make a "Brush" geometry immutable - it owns it and modifies it on creation. Then there's no need for a "prepareGeometry" function?
  • groups should be removed / sidelined when generating the BVH so we have an index that's basically just indirect storage
  • group triangles should all be sequential
  • when accumulating triangle data needed to count which group it's a part of and make sure it's added sequentially?
    • iterate over the ids within 1 group for split and non split triangles first, then move to the next OR
    • perform the gathering of every triangle group into separate arrays and then concatenate
  • Likely means the operations functions will have to assume that the index is entirely indirect and not intended to be rendered with so the group triangles are coherent. #10

Missing triangles with torus case

image

Possibly a clipping issue. Set both brushes to "torus" and lowest complexity.

	brush2.position.set( - 0.27300968690619787, 0.5329319712626078, 0 );
	brush2.scale.setScalar( 1 );

TriangleSplitter: Enable symmetrical clipping along connected edges

Related to #49

Requirements

  • Add a variation of TriangleSplitter that will clip triangles such that edges are symmetrically split so the edges line up and can be connected in the HalfEdgeMap.

Approach

  • When clipping triangles construct polygons from connected loops of edges from the edges derived from triangle intersections.
  • Once all polygons have been found from the split determine whether they're inside or outside the model using the existing determination method (raycasting).
  • For the polygons to keep run the three.js built-in Earcut method to triangulate the polygon to add to the final geometry.

Notes

Add vertex colors to basic demo

Just add a basic demo with cubes and colors at each corner - it should make it easy to verify the interpolation of the vertex values.

three-mesh-bvh: provide option to skip creating an index and store it internally

  • Then three-mesh-bvh can support groups more easily since we won't have to align the index with the groups providing a more optimal BVH.
  • Check to see performance degradation when using a BVH with groups (seems significant).
  • Can then throw an error if index, groups, and respecting groups.
  • OR we can flub it here and add / remove the index when needed (but won't work with other bvh functions)

Add utility to confirm manifold / solid-ness of a geometry

Related to #3

  • check for self intersections
  • check for mesh edge overlap

Thoughts

  • Can the existing half edge structure be used to produce the 1-to-many edge map more quickly?
  • Can we store the 1-to-many edge map to perform fast half-edge traversal for CSG?

Also see #96

Another missing triangle

image

Looks like it's due to a splitter issue, probably

  • brush1 complexity: 0
  • brush1 shape: torus
  • brush2 position: -0.9710495828020456, -0.17902368686930203, 0`

Hierarchical operations

  • Track the last-known calculation state / position associated with each sub node
  • When recomputing traverse the hierarchy (or track ahead of time?) to find which nodes are dirty and bubble it up the hierarchy.
  • Also find which nodes are touching to determine what needs to be recomputed?
  • Recompute the dirty nodes from the bottom up.
  • Unchanged / non-intersecting geometry can just be propagated up.
  • Should operations be declared on the children (ie perform this operation to the parent) or on the parent to perform on the children? I'm leaning towards the former.

See how Godot handles this?
https://docs.godotengine.org/en/stable/tutorials/3d/csg_tools.html

And RealtimeCSG

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.