Threejs - Constructive Solid Geometry

by black strings

HTML

<script src="https://rawgit.com/mrdoob/three.js/dev/build/three.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>
<!--
  resources:
  https://www.jsdelivr.com/package/npm/three-2-csg
  https://www.jsdelivr.com/package/npm/three-csg
  -->

CSS

body {
  margin:0;
}

JavaScript

var objects = []; 
var scene = new THREE.Scene();

var width = window.innerWidth;
var height = window.innerHeight * .75;

var camera = new THREE.PerspectiveCamera( 35, width/height, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();

renderer.setSize( width, height );
renderer.setClearColor( 0xcccccc, 1 ); 
document.body.appendChild( renderer.domElement );
scene.add(camera);

controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.screenSpacePanning = true;
setToFullOrbit(controls)
camera.position.copy(new THREE.Vector3(fti(5), fti(5), fti(5)) );
// fix first frame render issue going invisible
camera.lookAt(new THREE.Vector3(0,0,0));

var axisHelper = new THREE.AxisHelper();
scene.add(axisHelper);

var grid = new THREE.GridHelper(fti(12), 12);
scene.add(grid);
var div;	// for html contents

// represents a single board
class Board {
	constructor(points){
  	this.points = points;
    // untrimmed board, ray cast agains the mesh to know if inside board or not
    this.mesh = createShape(this.points);
    
    // once the board is trimmed, recreate the trimmed mesh and store it here
    this.trimmedLine = null;
    this.trimmedMesh = null;
    
    // the board-line (ray cast against the board lines to know if intersects);
    this.line = createLine(points, 0x0000ff);
  }
  hide(){
  	this.mesh.visible = false;
    this.line.visible = false;
  }
  show(){
  	this.mesh.visible = true;
    this.line.visible = true;
  }
  trim(shapeLine){
  	var raycaster = new THREE.Raycaster();
    var shapeLinePoints = [];
    shapeLine.geometry.vertices.forEach(v => {
    	shapeLinePoints.push(v.clone());
    });
    var poly = [...shapeLinePoints];
    shapeLinePoints.pop();	// shapeLine has one extra point at the end to close the line
   
    // create spheres at shapeLinePoints
    for(var i=0; i<shapeLinePoints.length; i++){
    	createSphereAtPosition(.1, shapeLinePoints[i], 0xff0000);
    }
    
    var hitPoints = [];
    
    // raycast to perform...