earstrip

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: ISC Imports: 6 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-earstrip

Go Reference CI Demo

Polygon triangulation for map data, in pure Go. A port of earstrip by Evgen Bodunov, the triangulator of the GLMap map engine.

earstrip cuts ears along zig-zag strips, so what it writes is triangle strips, about 1.7 indices per triangle instead of 3. When the rings of a polygon cross or touch, as rounding to a tile grid makes them do, it covers the polygon with a constrained Delaunay triangulation instead of keeping whatever triangles the ears left. The ideas behind it are told step by step in Cutting map polygons into triangles.

The port is bit-exact: for every polygon it writes the same strips, strip ends, orientations, status and added points as the C++ header (see Testing).

Live demo: draw or edit a polygon and watch it triangulated in the browser, by the Go code compiled to WebAssembly (see Web demo).

Install

go get github.com/cwbudde/go-earstrip

Pure Go, no dependencies, Go 1.24 or later.

Usage

import "github.com/cwbudde/go-earstrip"

var t earstrip.Triangulator[uint32] // reuse it: buffers only grow
status := t.Run([][][2]float64{
	{{0, 0}, {10, 0}, {10, 10}, {0, 10}}, // outer ring
	{{3, 3}, {7, 3}, {7, 7}, {3, 7}},     // a hole
})
t.Strips()         // [1 5 0 4 3 7 2 6 1 5]: indices of all strips, one after another
t.StripEnds()      // [10]: where each strip ends
t.StripClockwise() // [0]: per strip, whether its first triangle runs clockwise
t.Triangles(nil)   // or as a list, three indices per counter-clockwise triangle
t.Restart(nil, 0xFFFFFFFF) // one index buffer for TRIANGLE_STRIP with primitive restart (WebGL 2, WebGPU)
  • Input: rings of points (Run), flat coordinates with hole starts as earcut takes them (RunFlat), or any type implementing Rings (RunRings). Ring 0 is the outer ring; either orientation is fine, a repeated closing point too. Indices count the vertices of all rings in order.
  • Index type: Triangulator[uint16], [uint32] or [uint64]. A polygon with more vertices than the type can count panics instead of wrapping.
  • One-shot helpers: earstrip.Triangulate(polygon) returns a triangle list; earstrip.Earcut(coords, holeIndices, dim) takes and returns what earcut does, every index an input vertex.
  • Triangle lists: SetTriangleList(true) makes Run fill TriangleList() instead of the strips.
  • A Triangulator is not safe for concurrent use; use one per goroutine. The returned slices alias its buffers and stay valid until the next run. Shrink() gives the memory back.

Compared with earcut

earcut and its ports are the usual choice for polygon triangulation. What go-earstrip does differently:

  • Strips, not a list: about 1.7 indices per triangle (1.66 on z13.bin) instead of 3, or one restart index buffer for a single TRIANGLE_STRIP draw call (about 2 per triangle there). A triangle list is still one call away.
  • Broken input is covered, and says so: map polygons rounded to a tile grid often have rings that touch or cross. earcut patches what it can and cannot tell you whether its triangles still cover the polygon; go-earstrip reports it (Status) and covers the polygon with a constrained Delaunay triangulation by the non-zero winding rule.
  • Large rings stay fast: a smooth ring of 100,000 vertices takes 23 ms, the time growing close to linearly (see Performance).
  • A drop-in for earcut: earstrip.Earcut(coords, holeIndices, dim) takes and returns what earcut does.
  • Checked against the C++ original: bit-exact on 4.4 million real map polygons.

The Performance tab of the demo times both, and libtess.js, on the same polygons in your browser.

Web demo

Try it in the browser: the library compiled to WebAssembly. Pick one of the cases of earstrip's test.cpp or a random polygon, drag, add and delete vertices or draw rings and holes, and watch the strips, the status and the extra points change; the triangles can be stepped through in output order. The Performance tab times go-earstrip, in several settings, against earcut and libtess.js (the GLU tessellator) on generated polygons from 100 to 100,000 vertices or on your own, and compares what they write: triangles, indices, area and extra points. The Showcase tab triangulates live and draws the strips with WebGL 2, straight from the restart index buffer (Triangulator.Restart):

  • World map: every country of Natural Earth (public domain; just naturalearth converts it into web/public/world-*.bin) in one batch call, drawn in one draw call, strip by strip on load.
  • Crater sandbox: blast craters into a tiled terrain. A tile is a square minus every crater that touches it, and the constrained triangulation takes the overlapping holes apart; only changed tiles run again.
  • Spirograph: curves that cross themselves hundreds of times, filled by the non-zero winding rule every frame, with the extra points at the crossings, as a kaleidoscope.
  • Lava lamp: metaballs whose iso-bands become polygons with holes, about 20 calls per frame.
just dev-demo     # cmd/demo as js/wasm, then Vite's dev server at http://localhost:5173/go-earstrip/
just build-demo   # the static site in web/dist (needs Node.js 22)

cmd/demo is the js/wasm entry point, internal/demo what it computes, web/ the React front end.

Polygons that are not simple

Run reports how a polygon was covered:

Status Meaning
Exact the triangles cover the polygon exactly
HolesLeftOut a hole could not be joined to the boundary (it lies outside or crosses it) and is left out
Constrained covered by the constrained triangulation: the rings cross, a hole could not be joined, or there are more than 128 rings. It fills what lies inside the outer ring by the non-zero winding rule and outside every hole
Approximate the ears ran out (the polygon is not simple) and the rest was cut by forced cuts
Refused as Approximate, with forced cuts switched off: the strips cover only what the ears did

Where two edges cross, the constrained triangulation adds a point next to the crossing: ExtraPoints() has their coordinates, and index n + k in the strips is point k, n being the number of input vertices. SetExtraPoints(false) keeps every index an input vertex, SetConstrained(false) turns the constrained triangulation off (such polygons are then untangled and cut by forced cuts), and SetForcedCuts(false) stops there instead (Refused). The predicates are exact for integer coordinates within ±2²⁵ in the ears and for 32-bit integers in the constrained triangulation, which rounds other input to a 2³⁰ grid over the polygon's bounding box. Coordinates must be finite.

Performance

OpenStreetMap polygons in tile coordinates, best of 7 runs on one thread of an Apple M5 Pro, default settings, measured with go run ./cmd/earstrip-bench data/<file> -r 7 and the C++ bench/bench.cpp (clang -O3):

Data Polygons go-earstrip earstrip (C++)
Masovian Voivodeship, zoom 13 (z13.bin) 3,740,425 686 ms 447 ms
the same at zoom 9 (z9.bin) 683,742 93 ms 65 ms
world map tiles, up to 11,675 holes in one (world.bin) 56,472 530 ms 432 ms
an older build with crossing rings (gom4old.bin) 1,212,030 564 ms 378 ms

On these files the Go port runs at about two thirds of the C++ speed (four fifths on world.bin). For comparison, the C++ earstrip is 13% faster than earcut.hpp on z13.bin.

Large rings are another matter. The C++ tests each ear against a slab of its spatial index that spans one axis, and the zig-zag strips of a large ring cut long thin ears whose slab holds much of the ring, so the time grows with the square of the vertices: 1.15 s for a smooth ring of 100,000 vertices. go-earstrip answers these tests from a kd tree instead, and bridges holes and sorts the constrained triangulation's vertices with faster structures, each giving exactly the answer of the C++ code it replaces. The same ring takes 23 ms (go test ./internal/demo -bench Workloads times the demo's polygon families from 1,000 to 100,000 vertices).

A reused Triangulator allocates nothing once it has seen the largest polygon.

Testing

just test          # unit tests: test.cpp ported, constrained tests, examples
just fetch-data    # the benchmark polygons (OpenStreetMap, ODbL; 147 MB packed) into data/
just conformance   # 4.4 million polygons hash-identical to the C++ results stored with the data
just test-oracle   # bit-exact differential tests against the C++ header through cgo (needs a C++17 compiler)
just fuzz          # invariants fuzzing; `just fuzz-diff` fuzzes Go against the C++
just bench         # Go benchmarks; `just bench-file data/z13.bin -r 7` mirrors bench/bench.cpp

The C++ header is vendored in third_party/earstrip for the oracle only; the library itself is pure Go. The benchmark data comes from the bench-data-1 release of earstrip and is not redistributed here.

Differences from the C++:

  • A polygon with more vertices than the index type can count panics; the C++ lets the indices wrap.
  • RunFlat panics on hole starts that decrease or lie past the vertices.
  • The triangle list is cleared on every run (the C++ keeps a stale list after switching from list mode to strips on a polygon with more than 128 rings).
  • Ties in the hole order follow libc++'s std::sort, so results are identical to a C++ build against libc++ (Clang/Apple); a libstdc++ build may order holes with the same rightmost point differently.

License

ISC, see LICENSE. Original C++ © 2026 Evgen Bodunov; Go port © 2026 Christian Budde. The benchmark polygons are © OpenStreetMap contributors under the ODbL.

Documentation

Overview

Package earstrip triangulates polygons with holes into triangle strips.

It is a Go port of earstrip (https://github.com/GLMap/earstrip) by Evgen Bodunov: ear clipping that cuts ears along zig-zag strips, about 1.7 indices per triangle instead of 3, with a constrained Delaunay triangulation for polygons whose rings cross or touch. The ideas are told step by step in https://globus.software/blog/2026/10/16/cutting-map-polygons/.

A Triangulator is meant to be reused, so that once it has seen the largest polygon it allocates nothing more. It is not safe for concurrent use: use one per goroutine (or a sync.Pool). The slices it returns (Strips, StripEnds, StripClockwise, TriangleList, ExtraPoints) alias its buffers and stay valid until the next run or Shrink.

Coordinates must be finite: NaN or infinite coordinates give arbitrary triangles, possibly with Status Exact.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Earcut

func Earcut(data []float64, holeIndices []int, dim int) []uint32

Earcut takes earcut's arguments, flat coordinates, the vertex index where each hole starts and the numbers per vertex (0 means 2), and returns the same kind of result: three indices per counter-clockwise triangle, every index an input vertex.

Example

Earcut takes earcut's arguments: flat coordinates, the vertex index where each hole starts, numbers per vertex.

package main

import (
	"fmt"

	"github.com/cwbudde/go-earstrip"
)

func main() {
	coords := []float64{0, 0, 10, 0, 10, 10, 0, 10, 3, 3, 7, 3, 7, 7, 3, 7}
	fmt.Println(earstrip.Earcut(coords, []int{4}, 2))
}
Output:
[1 5 0 0 5 4 0 4 3 3 4 7 3 7 2 2 7 6 2 6 1 1 6 5]

func Triangulate

func Triangulate(polygon [][][2]float64) []uint32

Triangulate triangulates a polygon (rings of points, outer ring first) into a triangle list, three indices per counter-clockwise triangle.

Example
package main

import (
	"fmt"

	"github.com/cwbudde/go-earstrip"
)

func main() {
	l := [][][2]float64{{{0, 0}, {10, 0}, {10, 4}, {4, 4}, {4, 10}, {0, 10}}}
	fmt.Println(earstrip.Triangulate(l))
}
Output:
[1 2 0 0 2 3 0 3 5 5 3 4]

Types

type FlatRings

type FlatRings struct {
	Coords     []float64
	Dim        int
	HoleStarts []int
}

FlatRings is a polygon as flat coordinates, Dim numbers per vertex (x and y first; a Dim below 2 means 2), and the vertex index where each hole starts, as earcut takes it. HoleStarts must not decrease and must lie within [0, len(Coords)/Dim]; trailing coordinates of an incomplete vertex are ignored.

func (FlatRings) Count

func (f FlatRings) Count() int

Count returns the number of rings.

func (FlatRings) Size

func (f FlatRings) Size(r int) int

Size returns the number of points of ring r.

func (FlatRings) X

func (f FlatRings) X(r, i int) float64

X returns x of point i of ring r.

func (FlatRings) Y

func (f FlatRings) Y(r, i int) float64

Y returns y of point i of ring r.

type Index

type Index interface {
	~uint16 | ~uint32 | ~uint64
}

Index is the type of the vertex indices in the strips; a polygon may have at most as many vertices as it can count.

type Polygon

type Polygon [][][2]float64

Polygon is a polygon as a slice of rings, each a slice of points; ring 0 is the outer ring.

func (Polygon) Count

func (p Polygon) Count() int

Count returns the number of rings.

func (Polygon) Size

func (p Polygon) Size(r int) int

Size returns the number of points of ring r.

func (Polygon) X

func (p Polygon) X(r, i int) float64

X returns x of point i of ring r.

func (Polygon) Y

func (p Polygon) Y(r, i int) float64

Y returns y of point i of ring r.

type Rings

type Rings interface {
	Count() int         // number of rings
	Size(r int) int     // number of points of ring r
	X(r, i int) float64 // x of point i of ring r
	Y(r, i int) float64 // y of point i of ring r
}

Rings is a polygon as rings of points: ring 0 is the outer ring, the others are holes. Either orientation is fine, a repeated closing point too. Indices in the result count the vertices of all rings in order.

type Status

type Status uint8

Status tells how a polygon was covered.

const (
	// Exact means the triangles cover the polygon exactly.
	Exact Status = iota
	// HolesLeftOut means a hole could not be joined to the boundary (it lies outside or crosses it) and is left out.
	HolesLeftOut
	// Approximate means the boundary ran out of ears (the polygon is not simple); the rest was cut by forced cuts.
	Approximate
	// Refused means as Approximate, with forced cuts switched off: the strips cover only what the ears did.
	Refused
	// Constrained means covered by the constrained triangulation: the rings cross, a hole could not be joined or there
	// are more than 128 rings; what lies inside ring 0 by non-zero winding and outside every hole.
	Constrained
)

func (Status) String

func (s Status) String() string

type Triangulator

type Triangulator[I Index] struct {
	// contains filtered or unexported fields
}

Triangulator triangulates polygons into triangle strips. An instance is meant to be reused: its buffers only grow. The zero value is ready to use, with forced cuts, the constrained triangulation and extra points on.

func (*Triangulator[I]) ExtraPoints

func (t *Triangulator[I]) ExtraPoints() []float64

ExtraPoints returns the points added by the last run as x, y pairs: index n + k in the strips is point k, n being the number of input vertices of all rings.

Example

Rings that cross go to the constrained triangulation, which adds the crossing as a point: index 4 here.

package main

import (
	"fmt"

	"github.com/cwbudde/go-earstrip"
)

func main() {
	var t earstrip.Triangulator[uint32]
	status := t.Run([][][2]float64{{{0, 0}, {10, 10}, {10, 0}, {0, 10}}}) // a bow tie
	fmt.Println(status, "added:", t.ExtraPoints())
	fmt.Println("strips:", t.Strips(), "ends:", t.StripEnds())
}
Output:
Constrained added: [5 5]
strips: [1 4 2 3 0 4] ends: [3 6]

func (*Triangulator[I]) HolesLeftOut

func (t *Triangulator[I]) HolesLeftOut() bool

HolesLeftOut reports whether the last run left out a hole that could not be joined to the boundary.

func (*Triangulator[I]) Restart

func (t *Triangulator[I]) Restart(dst []I, restart I) []I

Restart appends all strips to dst as one index buffer for a triangle strip draw call, restart between strips, as WebGL 2 and WebGPU take it; no restart index comes before the first strip, and dst keeps what it holds. Every triangle is counter-clockwise: a strip that would start clockwise begins with its first index twice.

func (*Triangulator[I]) Run

func (t *Triangulator[I]) Run(polygon [][][2]float64) Status

Run triangulates a polygon given as rings of points, ring 0 the outer ring. It panics when the polygon has more vertices than I can count.

Example

A square with a square hole becomes one strip of ten indices: eight triangles.

package main

import (
	"fmt"

	"github.com/cwbudde/go-earstrip"
)

func main() {
	var t earstrip.Triangulator[uint32]
	status := t.Run([][][2]float64{
		{{0, 0}, {10, 0}, {10, 10}, {0, 10}}, // outer ring
		{{3, 3}, {7, 3}, {7, 7}, {3, 7}},     // hole
	})
	fmt.Println(status)
	fmt.Printf("strips: %v ends: %v clockwise: %v\n", t.Strips(), t.StripEnds(), t.StripClockwise())
	fmt.Println("triangles:", t.Triangles(nil))
}
Output:
Exact
strips: [1 5 0 4 3 7 2 6 1 5] ends: [10] clockwise: [0]
triangles: [1 5 0 0 5 4 0 4 3 3 4 7 3 7 2 2 7 6 2 6 1 1 6 5]

func (*Triangulator[I]) RunFlat

func (t *Triangulator[I]) RunFlat(coords []float64, dim int, holeStarts []int) Status

RunFlat triangulates a polygon given as flat coordinates, dim numbers per vertex (x and y first), and the vertex index where each hole starts (see FlatRings). It panics when the hole starts are out of order or out of range, or when the polygon has more vertices than I can count.

func (*Triangulator[I]) RunRings

func (t *Triangulator[I]) RunRings(rings Rings) Status

RunRings triangulates a polygon given through the Rings interface, which must answer consistently (non-negative sizes, every point in range). It panics when the polygon has more vertices than I can count.

func (*Triangulator[I]) SetConstrained

func (t *Triangulator[I]) SetConstrained(on bool)

SetConstrained sets whether polygons the ears cannot finish, those with a hole the ears leave out (when that covers the rings' area better) and those with more than 128 rings go to the constrained triangulation (default on): Status Constrained.

func (*Triangulator[I]) SetExtraPoints

func (t *Triangulator[I]) SetExtraPoints(on bool)

SetExtraPoints lets the constrained triangulation add points where rings cross (default on); off, such polygons take the ears' way instead, so every index is an input vertex.

func (*Triangulator[I]) SetForcedCuts

func (t *Triangulator[I]) SetForcedCuts(on bool)

SetForcedCuts sets whether, when the boundary runs out of ears, the corners that do the least damage are cut instead of giving up (default on). Only used when the constrained triangulation is off or fails.

func (*Triangulator[I]) SetTriangleList

func (t *Triangulator[I]) SetTriangleList(on bool)

SetTriangleList makes Run write a triangle list instead of strips: Run then fills TriangleList (three indices per triangle, each counter-clockwise, the same as Triangles) and leaves Strips empty.

func (*Triangulator[I]) Shrink

func (t *Triangulator[I]) Shrink()

Shrink frees the buffers, which otherwise keep the size of the largest polygon seen, and the last result; the settings stay. The next run allocates again.

func (*Triangulator[I]) StripClockwise

func (t *Triangulator[I]) StripClockwise() []uint8

StripClockwise returns, per strip, 1 when its first triangle runs clockwise.

func (*Triangulator[I]) StripEnds

func (t *Triangulator[I]) StripEnds() []uint32

StripEnds returns the end of each strip in Strips.

func (*Triangulator[I]) Strips

func (t *Triangulator[I]) Strips() []I

Strips returns the vertex indices of all strips, one after another. Within a strip the triangles alternate as a GPU expects; StripClockwise tells, per strip, whether its first triangle runs clockwise.

func (*Triangulator[I]) TriangleList

func (t *Triangulator[I]) TriangleList() []I

TriangleList returns the triangle list of the last run in triangle list mode.

func (*Triangulator[I]) Triangles

func (t *Triangulator[I]) Triangles(dst []I) []I

Triangles appends the same triangles as a list to dst, keeping what dst holds, three indices each, every one counter-clockwise (positive area with y up).

Directories

Path Synopsis
cmd
demo command
Command demo is the browser demo of go-earstrip: built for js/wasm by "just build-demo" and loaded by web/src/wasm/earstrip.ts, it publishes globalThis.earstrip, whose functions the web app calls.
Command demo is the browser demo of go-earstrip: built for js/wasm by "just build-demo" and loaded by web/src/wasm/earstrip.ts, it publishes globalThis.earstrip, whose functions the web app calls.
earstrip-bench command
Command earstrip-bench times go-earstrip over a PLY1 file of polygons, as earstrip's bench/bench.cpp does.
Command earstrip-bench times go-earstrip over a PLY1 file of polygons, as earstrip's bench/bench.cpp does.
naturalearth command
Command naturalearth converts the admin-0 countries of Natural Earth into the world map of the demo's Showcase tab: web/public/world-110m.bin and world-50m.bin.
Command naturalearth converts the admin-0 countries of Natural Earth into the world map of the demo's Showcase tab: web/public/world-110m.bin and world-50m.bin.
internal
cases
Package cases holds the polygons of earstrip's test/test.cpp (the named cases of main(), its fixtures and its random generators) and further generators for the differential tests, shared by the package tests and the oracle tests.
Package cases holds the polygons of earstrip's test/test.cpp (the named cases of main(), its fixtures and its random generators) and further generators for the differential tests, shared by the package tests and the oracle tests.
demo
Package demo holds what the browser demo (cmd/demo) computes: the preset polygons, the generated ones and a triangulation run with its result and timing.
Package demo holds what the browser demo (cmd/demo) computes: the preset polygons, the generated ones and a triangulation run with its result and timing.
oracle
Package oracle runs the C++ reference implementation (third_party/earstrip/earstrip.hpp) through cgo, for the differential tests of go-earstrip.
Package oracle runs the C++ reference implementation (third_party/earstrip/earstrip.hpp) through cgo, for the differential tests of go-earstrip.
plydata
Package plydata reads the PLY1 polygon files of earstrip's benchmark data (bench-data-1: z13.bin, z9.bin, world.bin, gom4old.bin) and computes the result hash that bench/bench.cpp writes into them.
Package plydata reads the PLY1 polygon files of earstrip's benchmark data (bench-data-1: z13.bin, z9.bin, world.bin, gom4old.bin) and computes the result hash that bench/bench.cpp writes into them.
verify
Package verify holds the invariant checks of the tests, shared by the package tests, the fuzz targets and the oracle tests (which run them on the C++ results to show that the checks themselves are right).
Package verify holds the invariant checks of the tests, shared by the package tests, the fuzz targets and the oracle tests (which run them on the C++ results to show that the checks themselves are right).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL