### csg.js: Constructive Solid Geometry 3d Modeling in JavaScript and WebGL

#### December 5th 2011

Evan Wallace, the same guy who brought us that amazing WebGL water simulation is back at it again, this time with a library called csg.js for doing Constructive Solid Geometry modeling in JavaScript.

Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean operations like union and intersection to combine 3D solids. This library implements CSG operations on meshes elegantly and concisely using BSP trees, and is meant to serve as an easily understandable implementation of the algorithm. All edge cases involving overlapping coplanar polygons in both solids are correctly handled.

From the sounds of it, he wants to eventually build a 3D CSG level editor in the browser similar to UnrealEd (used by the amazing Unreal engine) and Hammer (from Valve). Very cool!

Here is an example of its usage:

```
var cube = CSG.cube();
var sphere = CSG.sphere({ radius: 1.3 });
var polygons = cube.subtract(sphere).toPolygons();
```

As you can see, this creates a cube and subtracts a sphere from it. A more complex example creates the following 5 solids:

With this code:

```
var a = CSG.cube();
var b = CSG.sphere({ radius: 1.35, stacks: 12 });
var c = CSG.cylinder({ radius: 0.7, start: new CSG.Vector(-1, 0, 0), end: new CSG.Vector(1, 0, 0) });
var d = CSG.cylinder({ radius: 0.7, start: new CSG.Vector(0, -1, 0), end: new CSG.Vector(0, 1, 0) });
var e = CSG.cylinder({ radius: 0.7, start: new CSG.Vector(0, 0, -1), end: new CSG.Vector(0, 0, 1) });
```

And then combines them all together into the final image:

With only this code:

`a.intersect(b).subtract(c.union(d).union(e))`

Pretty impressive if you ask me. Be sure to check out the demos, where you can actually drag the rendered output around to rotate it. The code can be found on Github and even annotated by Docco. Check it out!