Coding With SabreCSG

SabreCSG is primarily a level creation tool to be used inside Unity. In addition to that however, it’s possible to create brushes, manipulate them and build geometry in the editor through scripting. This is a quick guide to how that works.

Please note: this feature is considered beta so if you have any feedback please let us know and we’ll integrate improvements as quickly as we can.

Core Classes

A quick overview of the classes you’ll work with in order to use SabreCSG programatically. This is in a top down order, where each class object can hold several of the following (the CSGModel can hold many brushes, which in turn hold multiple polygons which are made up of multiple vertices).

CSGModel

The CSGModel is a representation that stores a series of brushes as well as build settings and contextual information. The CSGModel must be created in order to add brushes and build them into final geometry.

PrimitiveBrush

A primitive brush holds a series of polygons that make up a convex 3D shape, it also holds whether the brush is additive or subtractive as well as other settings like if it should have collision.

Polygon

A polygon is a flat shape that contains multiple vertices.

Vertex

A vertex is a point in space that holds: its 3D position, it’s direction (surface normal) and a mapping to a texture coordinate (UV).

Simple Example

 

If you add this script to a game object you will then be able to run it at editor type by clicking the cog from the Inspector and selecting “Execute”.
ExampleScriptInspector

You should then see a prism appear with built geometry:

Screenshot 2015-11-02 17.30.56

Another Example

A slightly more complicated example would be to create a series of brushes and then programatically move them, in this case in to a horizontal circle of 8. The only change in the below code from the previous code example is the new for loop.

Running this code through the same method as above will produce something like this:

Screenshot 2015-11-02 17.52.01

Notes

Polygons cache their plane when created for performance reasons. So if you modify vertex positions after creating the polygon you should call polygon.CalculatePlane() to recalculate the plane, or instead provide the new vertices via polygon.SetVertices() which automatically calls CalculatePlane itself.

Vertices track their own surface normal (so that you can have smooth normals on cylinders, or faceted normals on prisms). So if you modify vertex positions you will need to update the surface normal too. For faceted polygons you can just call polygon.ResetVertexNormals()

In the future we hope to add support for building brushes at runtime too.