• Stars
    star
    416
  • Rank 100,543 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Decompose 2D polygons into convex pieces.

poly-decomp.js

Library for decomposing a 2D polygon into convex pieces.

Decomposing a convcave polygon into convex regions

Launch the demo!

Donate

The library implements two algorithms, one optimal (but slow) and one less optimal (but fast). It's is a manual port of the C++ library Poly Decomp by Mark Penner.

Install

Browser

Download decomp.js or decomp.min.js and include the script in your HTML:

<script src="decomp.js" type="text/javascript"></script>
<!-- or: -->
<script src="decomp.min.js" type="text/javascript"></script>

Then you can use the decomp global.

Node.js
npm install poly-decomp

Then require it like so:

var decomp = require('poly-decomp');

Basic usage

// Create a concave polygon
var concavePolygon = [
  [ -1,   1],
  [ -1,   0],
  [  1,   0],
  [  1,   1],
  [0.5, 0.5]
];

// Make sure the polygon has counter-clockwise winding. Skip this step if you know it's already counter-clockwise.
decomp.makeCCW(concavePolygon);

// Decompose into convex polygons, using the faster algorithm
var convexPolygons = decomp.quickDecomp(concavePolygon);

// ==> [  [[1,0],[1,1],[0.5,0.5]],  [[0.5,0.5],[-1,1],[-1,0],[1,0]]  ]

// Decompose using the slow (but optimal) algorithm
var convexPolygons = decomp.decomp(concavePolygon);

// ==> [  [[-1,1],[-1,0],[1,0],[0.5,0.5]],  [[1,0],[1,1],[0.5,0.5]]  ]

Advanced usage

// Get user input as an array of points.
var polygon = getUserInput();

// Check if the polygon self-intersects
if(decomp.isSimple(polygon)){
    
    // Reverse the polygon to make sure it uses counter-clockwise winding
    decomp.makeCCW(polygon);
    
    // Decompose into convex pieces
    var convexPolygons = decomp.quickDecomp(polygon);
    
    // Draw each point on an HTML5 Canvas context
    for(var i=0; i<convexPolygons.length; i++){
        var convexPolygon = convexPolygons[i];
        
        ctx.beginPath();
        var firstPoint = convexPolygon[0];
        ctx.moveTo(firstPoint[0], firstPoint[1]);
        
        for(var j=1; j<convexPolygon.length; j++){
            var point = convexPolygon[j];
            var x = point[0];
            var y = point[1];
            c.lineTo(x, y);
        }
        ctx.closePath();
        ctx.fill();
    }
}

Documentation

quickDecomp(polygon: Array<Point>): Array<Array<Point>>

var convexPolygons = decomp.quickDecomp(polygon);

Slices the polygon into convex sub-polygons, using a fast algorithm. Note that the input points objects will be re-used in the result array.

decomp(polygon: Array<Point>): Array<Array<Point>>

var convexPolygons = decomp.quickDecomp(polygon);

Decomposes the polygon into one or more convex sub-polygons using an optimal algorithm. Note that the input points objects will be re-used in the result array.

isSimple(polygon: Array<Point>): boolean

if(decomp.isSimple(polygon)){
    // Polygon does not self-intersect - it's safe to decompose.
    var convexPolygons = decomp.quickDecomp(polygon);
}

Returns true if any of the line segments in the polygon intersects. Use this to check if the input polygon is OK to decompose.

makeCCW(polygon: Array<Point>): void

console.log('Polygon with clockwise winding:', polygon);
decomp.makeCCW(polygon);
console.log('Polygon with counter-clockwise winding:', polygon);

Reverses the polygon, if its vertices are not ordered counter-clockwise. Note that the input polygon array will be modified in place.

removeCollinearPoints(polygon: Array<Point>, thresholdAngle: number): void

var before = polygon.length;
decomp.removeCollinearPoints(polygon, 0.1);
var numRemoved = before - polygon.length;
console.log(numRemoved + ' collinear points could be removed');

Removes collinear points in the polygon. This means that if three points are placed along the same line, the middle one will be removed. The thresholdAngle is measured in radians and determines whether the points are collinear or not. Note that the input array will be modified in place.

removeDuplicatePoints(polygon: Array<Point>, precision: number): void

var polygon = [
    [0,0],
    [1,1],
    [2,2],
    [0,0]
];
decomp.removeDuplicatePoints(polygon, 0.01);

// polygon is now [[1,1],[2,2],[0,0]]

Change log

0.3.0
  • Added removeDuplicatePoints.
  • makeCCW now returns true if the polygon was changed.
  • Fixed case 5 mentioned here and discussed here.
0.2.1
  • Fixed bug in the collinear point removal, after this fix the algorithm is more agressive and more correct.
0.2.0
  • Rewrote the class based API to a minimal array-based one. See docs.
0.1
  • Added method Polygon.prototype.removeCollinearPoints.
  • Added optional parameter thresholdAngle to Point.collinear(a,b,c,thresholdAngle).

Contribute

Make sure you have git, Node.js, NPM and grunt installed.

git clone https://github.com/schteppe/poly-decomp.js.git; # Clone the repo
cd poly-decomp.js;
npm install;                                     # Install dependencies
                                                 # (make changes to source)
grunt;                                           # Builds build/decomp.js

The most recent commits are currently pushed to the master branch. Thanks for contributing!

More Repositories

1

cannon.js

A lightweight 3D physics engine written in JavaScript.
JavaScript
4,584
star
2

p2.js

JavaScript 2D physics library
JavaScript
2,607
star
3

gpu-physics.js

GPGPU physics for Three.js
JavaScript
280
star
4

ammo.js-demos

Demo application base class and 3D physics demos based on ammo.js. Support for several scenegraphs including Three.js and SceneJS.
JavaScript
114
star
5

imgui-wasm

imgui/wasm boilerplate
C++
42
star
6

cartridge.js

HTML5 retro game engine
JavaScript
38
star
7

codegif

Use Canvas API to make a gif animation
JavaScript
36
star
8

motionblur

WebGL shader effect
JavaScript
34
star
9

remote-physics

A node.js app that runs a physics engine and lets clients download physics data in real time.
JavaScript
24
star
10

occlusion-culling.js

Occlusion culling tests using three.js
JavaScript
20
star
11

vehicle-editor

A goofy vehicle editor made using Cannon.js physics and Goo Create.
JavaScript
19
star
12

floatcompress.js

Simple library for doing lossy compress of floats. Can be used to pack floats into a typed array when high precision is not needed.
JavaScript
16
star
13

goo-cannon-softbody

Experimenting with soft body simulation using Cannon.js in Goo Create
JavaScript
16
star
14

physicstoy

2D physics editor
JavaScript
12
star
15

voronoi-cube

Exploding cube in WebGL/GooEngine using 3D Voronoi tessellation data. (Goofy Day project)
JavaScript
12
star
16

sweep-and-prune

2D collision detection for AABBs
HTML
11
star
17

doc.js

Web based on-the-fly documentation generator targeted for JavaScript.
JavaScript
11
star
18

gpu-springs

GPU accelerated spring simulation
JavaScript
9
star
19

smart-signal-routing

Orthogonal connector routing for use in interactive diagram editors
JavaScript
8
star
20

m.js

JavaScript matrix math library that uses typed arrays.
JavaScript
7
star
21

velvet-drop

GPU cloth simulation (a.k.a Velvet Drop) made in Goo Create
JavaScript
6
star
22

tinygoon

8-bit style WebGL multiplayer game using the GamePad API
JavaScript
5
star
23

CreateForge

Visual shader editor for Goo Engine
HTML
5
star
24

dansa

Dance game for the web
JavaScript
5
star
25

taptruck

Mobile 2D WebGL game. Drive the truck to the goal without tipping over.
JavaScript
5
star
26

jox

Source code documentation generator for JavaScript
JavaScript
5
star
27

hyper-cube

Spinning Cube made with Goo Create
JavaScript
4
star
28

goo-p2-platformer

Simple physics based platformer scene built using Goo Create and engine.
JavaScript
4
star
29

refract

2D WebGL puzzle game. Guide the laser beam to the goal.
JavaScript
4
star
30

goo-bunnymark

Tribute to Pixi.js bunnymark. This time in 3D, made with Goo Engine.
HTML
3
star
31

multibody-xml

An XML markup language for descibing a physical multibody system.
3
star
32

bomb-sorting-game

Sort the boxes into their containers!
JavaScript
3
star
33

fuffrboxing

3D WebGL mobile game made for Fuffr
JavaScript
2
star
34

schteppe.github.com

2
star
35

node-mysql-querycache

Query caching to relax your MySQL database. Layer on top of node-mysql.
JavaScript
1
star
36

wasm_test

WebAssembly
1
star
37

ragdoll-goon

Almost-working goofy project. Need to be fixed!
JavaScript
1
star
38

goon-yoga

Yoga for the Goon. Built with Goo Engine.
JavaScript
1
star
39

fb-node-issues

Public Issue tracker
1
star