├── .eslintrc
├── .gitignore
├── index.html
├── package.json
├── readme.md
├── src
├── drawScene.js
├── endpointCompare.js
├── lineIntersection.js
├── loadMap.js
├── main.js
├── segmentInFrontOf.js
├── types.js
└── visibility.js
└── webpack.config.js
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "ecmaFeatures": {
3 | "jsx": true,
4 | "modules": true,
5 | "experimentalObjectRestSpread": true
6 | },
7 | "env": {
8 | "browser": true,
9 | "node": true,
10 | "es6": true,
11 | "mocha": true
12 | },
13 | "rules": {
14 | "indent": [2, 2, {"SwitchCase": 1}],
15 | "strict": 0,
16 | "no-underscore-dangle": 0,
17 | "quotes": [2, "single"],
18 | "key-spacing": [0],
19 | "eol-last": 1,
20 | "no-use-before-define": 0,
21 | "no-shadow": 0,
22 | "curly": 0,
23 | "no-multi-spaces": 0,
24 | "dot-notation": 0,
25 | "comma-dangle": 0,
26 | "constructor-super": 1
27 | }
28 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.sublime-project
3 | *.sublime-workspace
4 | bundle.js
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Boom
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "2d-visibility-demo",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "main.js",
6 | "scripts": {
7 | "start": "webpack-dev-server --hot --inline --content-base ."
8 | },
9 | "keywords": [],
10 | "author": "Cyril Silverman",
11 | "license": "MIT",
12 | "babel": {
13 | "presets": [
14 | "stage-0",
15 | "stage-1",
16 | "stage-2",
17 | "stage-3",
18 | "es2015"
19 | ]
20 | },
21 | "devDependencies": {
22 | "babel": "^6.3.26",
23 | "babel-core": "^6.3.26",
24 | "babel-loader": "^6.2.0",
25 | "babel-preset-es2015": "^6.3.13",
26 | "babel-preset-stage-0": "^6.3.13",
27 | "babel-preset-stage-1": "^6.3.13",
28 | "babel-preset-stage-2": "^6.3.13",
29 | "babel-preset-stage-3": "^6.3.13",
30 | "webpack": "^1.12.9",
31 | "webpack-dev-server": "^1.14.0"
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # 2D Visibility Algorithm Demo
2 |
3 | ## Description
4 |
5 | This is a 2d visibility algorithm described in [this article](http://www.redblobgames.com/articles/visibility/), ported by hand to JavaScript (ES2016) and refactored significantly to suit my taste better. I went for a more functional approach and renamed/reorganized some things, so it's not quite a 1-to-1 port.
6 |
7 | I highly suggest reading the article. It's very well explained with some really awesome interactive examples and provides the code in multiple languages. The original code was written in Haxe, which can compile into JavaScript but I found the generated JS to be rather difficult to read and comes with an (unnecessary) doubly linked list implementation.
8 |
9 | There's also a [fork of this repo in TypeScript](https://github.com/Petah/2d-visibility).
10 |
11 | ## Building the demo
12 |
13 | 
14 |
15 | Clone the repo, `npm install` then run `webpack-dev-server --content-base .` and navigate to `localhost:8080`
16 |
17 | ## License
18 |
19 | The MIT License (MIT)
20 |
21 | Copyright (c) 2016 Cyril Silverman
22 |
23 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
24 |
25 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
26 |
27 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 |
--------------------------------------------------------------------------------
/src/drawScene.js:
--------------------------------------------------------------------------------
1 | const drawRectangle =
2 | (ctx, color, {x, y, width, height}) => {
3 | ctx.save();
4 | ctx.strokeStyle = 'black';
5 | ctx.strokeRect(x, y, width, height);
6 | ctx.restore();
7 | };
8 |
9 | const drawSegment =
10 | (ctx, color, {p1, p2}) => {
11 | ctx.save();
12 | ctx.beginPath();
13 | ctx.strokeStyle = 'black';
14 | ctx.moveTo(p1.x, p1.y);
15 | ctx.lineTo(p2.x, p2.y);
16 | ctx.closePath();
17 | ctx.stroke();
18 | ctx.restore();
19 | }
20 |
21 | const drawVisibilityTriangles =
22 | (ctx, color, lightSource, visibilityOutput) => {
23 | ctx.save();
24 | ctx.strokeStyle = color;
25 | for(var i = 0; i < visibilityOutput.length; i += 1) {
26 | let [p1, p2] = visibilityOutput[i];
27 | ctx.beginPath();
28 | ctx.moveTo(lightSource.x, lightSource.y);
29 | ctx.lineTo(p1.x, p1.y);
30 | ctx.lineTo(p2.x, p2.y);
31 | ctx.closePath()
32 | ctx.stroke();
33 | }
34 | ctx.restore();
35 | };
36 |
37 | export const drawScene =
38 | (ctx, room, lightSource, blocks, walls, visibilityOutput, showAll) => {
39 | ctx.clearRect(-10000, -10000, 20000, 20000);
40 | drawRectangle(ctx, 'black', room);
41 | blocks.forEach(drawRectangle.bind(null, ctx, 'black'));
42 | walls.forEach(drawSegment.bind(null, ctx, 'black'));
43 | drawVisibilityTriangles(ctx, 'gray', lightSource, visibilityOutput);
44 | };
45 |
--------------------------------------------------------------------------------
/src/endpointCompare.js:
--------------------------------------------------------------------------------
1 | export const endpointCompare = (pointA, pointB) => {
2 | if (pointA.angle > pointB.angle) return 1;
3 | if (pointA.angle < pointB.angle) return -1;
4 | if (!pointA.beginsSegment && pointB.beginsSegment) return 1;
5 | if (pointA.beginsSegment && !pointB.beginsSegment) return -1;
6 | return 0;
7 | };
8 |
--------------------------------------------------------------------------------
/src/lineIntersection.js:
--------------------------------------------------------------------------------
1 | import { Point } from './types';
2 |
3 | export const lineIntersection = (point1, point2, point3, point4) => {
4 | const s = (
5 | (point4.x - point3.x) * (point1.y - point3.y) -
6 | (point4.y - point3.y) * (point1.x - point3.x)
7 | ) / (
8 | (point4.y - point3.y) * (point2.x - point1.x) -
9 | (point4.x - point3.x) * (point2.y - point1.y)
10 | );
11 |
12 | return Point(
13 | point1.x + s * (point2.x - point1.x),
14 | point1.y + s * (point2.y - point1.y)
15 | );
16 | };
17 |
--------------------------------------------------------------------------------
/src/loadMap.js:
--------------------------------------------------------------------------------
1 | import { Segment } from './types';
2 |
3 | const { atan2, PI: π } = Math;
4 |
5 | const flatMap =
6 | (cb, array) =>
7 | array.reduce((flatArray, item) => flatArray.concat(cb(item)), []);
8 |
9 | const getCorners = ({x, y, width, height}) => ({
10 | nw: [x, y],
11 | sw: [x, y + height],
12 | ne: [x + width, y],
13 | se: [x + width, y + height]
14 | });
15 |
16 | const segmentsFromCorners =
17 | ({ nw, sw, ne, se }) => ([
18 | Segment(...nw, ...ne),
19 | Segment(...nw, ...sw),
20 | Segment(...ne, ...se),
21 | Segment(...sw, ...se)
22 | ]);
23 |
24 | const rectangleToSegments =
25 | (rectangle) => segmentsFromCorners(getCorners(rectangle));
26 |
27 | const calculateEndPointAngles = (lightSource, segment) => {
28 | const { x, y } = lightSource;
29 | const dx = 0.5 * (segment.p1.x + segment.p2.x) - x;
30 | const dy = 0.5 * (segment.p1.y + segment.p2.y) - y;
31 |
32 | segment.d = (dx * dx) + (dy * dy);
33 | segment.p1.angle = atan2(segment.p1.y - y, segment.p1.x - x);
34 | segment.p2.angle = atan2(segment.p2.y - y, segment.p2.x - x);
35 | };
36 |
37 | const setSegmentBeginning = (segment) => {
38 | let dAngle = segment.p2.angle - segment.p1.angle;
39 |
40 | if (dAngle <= -π) dAngle += 2 * π;
41 | if (dAngle > π) dAngle -= 2 * π;
42 |
43 | segment.p1.beginsSegment = dAngle > 0;
44 | segment.p2.beginsSegment = !segment.p1.beginsSegment;
45 | };
46 |
47 | const processSegments = (lightSource, segments) => {
48 | for (let i = 0; i < segments.length; i += 1) {
49 | let segment = segments[i];
50 | calculateEndPointAngles(lightSource, segment);
51 | setSegmentBeginning(segment);
52 | }
53 |
54 | return segments;
55 | };
56 |
57 | const getSegmentEndPoints =
58 | (segment) => [segment.p1, segment.p2];
59 |
60 | export const loadMap = (room, blocks, walls, lightSource) => {
61 | const segments = processSegments(lightSource, [
62 | ...rectangleToSegments(room),
63 | ...flatMap(rectangleToSegments, blocks),
64 | ...walls
65 | ]);
66 |
67 | const endpoints = flatMap(getSegmentEndPoints, segments);
68 |
69 | return endpoints;
70 | };
71 |
--------------------------------------------------------------------------------
/src/main.js:
--------------------------------------------------------------------------------
1 | import { Room, Block, Segment, Point } from './types';
2 | import { drawScene } from './drawScene';
3 | import { loadMap } from './loadMap';
4 | import { calculateVisibility } from './visibility';
5 |
6 | const spreadMap =
7 | (cb) => (array2d) =>
8 | array2d.map(array1d => cb(...array1d));
9 |
10 | const makeSegments = spreadMap(Segment)
11 | const makeBlocks = spreadMap(Block);
12 |
13 | // Prepare canvas
14 | const canvas = document.getElementById('scene');
15 | const ctx = canvas.getContext('2d');
16 | const xOffset = 0.5;
17 | const yOffset = 0.5;
18 | ctx.translate(xOffset, yOffset);
19 |
20 | // Setup scene
21 | const room = Room(0, 0, 700, 500);
22 |
23 | const walls = makeSegments([
24 | [20, 20, 20, 120],
25 | [20, 20, 100, 20],
26 | [100, 20, 150, 100],
27 | [150, 100, 50, 100],
28 | ]);
29 |
30 | const blocks = makeBlocks([
31 | [ 50, 150, 20, 20],
32 | [150, 150, 40, 80],
33 | [400, 400, 40, 40]
34 | ]);
35 |
36 | const run = (lightSource) => {
37 | const endpoints = loadMap(room, blocks, walls, lightSource);
38 | const visibility = calculateVisibility(lightSource, endpoints);
39 |
40 | requestAnimationFrame(() =>
41 | drawScene(ctx, room, lightSource, blocks, walls, visibility));
42 | };
43 |
44 | canvas.addEventListener('mousemove', ({pageX, pageY}) => {
45 | let lightSource = Point(pageX, pageY);
46 | run(lightSource)
47 | });
48 |
49 | let lightSource = Point(100, 100);
50 | run(lightSource);
51 |
--------------------------------------------------------------------------------
/src/segmentInFrontOf.js:
--------------------------------------------------------------------------------
1 | import { Point } from './types';
2 |
3 | const leftOf = (segment, point) => {
4 | const cross = (segment.p2.x - segment.p1.x) * (point.y - segment.p1.y)
5 | - (segment.p2.y - segment.p1.y) * (point.x - segment.p1.x);
6 | return cross < 0;
7 | };
8 |
9 | const interpolate = (pointA, pointB, f) => {
10 | return Point(
11 | pointA.x*(1-f) + pointB.x*f,
12 | pointA.y*(1-f) + pointB.y*f
13 | );
14 | };
15 |
16 | export const segmentInFrontOf = (segmentA, segmentB, relativePoint) => {
17 | const A1 = leftOf(segmentA, interpolate(segmentB.p1, segmentB.p2, 0.01));
18 | const A2 = leftOf(segmentA, interpolate(segmentB.p2, segmentB.p1, 0.01));
19 | const A3 = leftOf(segmentA, relativePoint);
20 | const B1 = leftOf(segmentB, interpolate(segmentA.p1, segmentA.p2, 0.01));
21 | const B2 = leftOf(segmentB, interpolate(segmentA.p2, segmentA.p1, 0.01));
22 | const B3 = leftOf(segmentB, relativePoint);
23 |
24 | if (B1 === B2 && B2 !== B3) return true;
25 | if (A1 === A2 && A2 === A3) return true;
26 | if (A1 === A2 && A2 !== A3) return false;
27 | if (B1 === B2 && B2 === B3) return false;
28 |
29 | return false;
30 | };
31 |
--------------------------------------------------------------------------------
/src/types.js:
--------------------------------------------------------------------------------
1 | export const Rectangle =
2 | (x, y, width, height) => ({
3 | x,
4 | y,
5 | width,
6 | height
7 | });
8 |
9 | export const Block = Rectangle
10 | export const Room = Rectangle;
11 |
12 | export const Point =
13 | (x, y) => ({
14 | x,
15 | y
16 | });
17 |
18 | export const EndPoint =
19 | (x, y, beginsSegment, segment, angle) => ({
20 | ...Point(x, y),
21 | beginsSegment,
22 | segment,
23 | angle
24 | });
25 |
26 | export const Segment =
27 | (x1, y1, x2, y2) => {
28 | const p1 = EndPoint(x1, y1);
29 | const p2 = EndPoint(x2, y2);
30 | const segment = { p1, p2, d: 0 };
31 |
32 | p1.segment = segment;
33 | p2.segment = segment;
34 |
35 | return segment;
36 | };
37 |
--------------------------------------------------------------------------------
/src/visibility.js:
--------------------------------------------------------------------------------
1 | import { Point } from './types';
2 | import { segmentInFrontOf } from './segmentInFrontOf';
3 | import { endpointCompare } from './endpointCompare';
4 | import { lineIntersection } from './lineIntersection';
5 |
6 | const { cos, sin } = Math;
7 |
8 | const getTrianglePoints = (origin, angle1, angle2, segment) => {
9 | const p1 = origin;
10 | const p2 = Point(origin.x + cos(angle1), origin.y + sin(angle1));
11 | const p3 = Point(0, 0);
12 | const p4 = Point(0, 0);
13 |
14 | if (segment) {
15 | p3.x = segment.p1.x;
16 | p3.y = segment.p1.y;
17 | p4.x = segment.p2.x;
18 | p4.y = segment.p2.y;
19 | } else {
20 | p3.x = origin.x + cos(angle1) * 200;
21 | p3.y = origin.y + sin(angle1) * 200;
22 | p4.x = origin.x + cos(angle2) * 200;
23 | p4.y = origin.y + sin(angle2) * 200;
24 | }
25 |
26 | const pBegin = lineIntersection(p3, p4, p1, p2);
27 |
28 | p2.x = origin.x + cos(angle2);
29 | p2.y = origin.y + sin(angle2);
30 |
31 | const pEnd = lineIntersection(p3, p4, p1, p2);
32 |
33 | return [pBegin, pEnd];
34 | };
35 |
36 | export const calculateVisibility = (origin, endpoints) => {
37 | let openSegments = [];
38 | let output = [];
39 | let beginAngle = 0;
40 |
41 | endpoints.sort(endpointCompare);
42 |
43 | for(let pass = 0; pass < 2; pass += 1) {
44 | for (let i = 0; i < endpoints.length; i += 1) {
45 | let endpoint = endpoints[i];
46 | let openSegment = openSegments[0];
47 |
48 | if (endpoint.beginsSegment) {
49 | let index = 0
50 | let segment = openSegments[index];
51 | while (segment && segmentInFrontOf(endpoint.segment, segment, origin)) {
52 | index += 1;
53 | segment = openSegments[index]
54 | }
55 |
56 | if (!segment) {
57 | openSegments.push(endpoint.segment);
58 | } else {
59 | openSegments.splice(index, 0, endpoint.segment);
60 | }
61 | } else {
62 | let index = openSegments.indexOf(endpoint.segment)
63 | if (index > -1) openSegments.splice(index, 1);
64 | }
65 |
66 | if (openSegment !== openSegments[0]) {
67 | if (pass === 1) {
68 | let trianglePoints = getTrianglePoints(origin, beginAngle, endpoint.angle, openSegment);
69 | output.push(trianglePoints);
70 | }
71 | beginAngle = endpoint.angle;
72 | }
73 | }
74 | }
75 |
76 | return output;
77 | };
78 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | entry: [
3 | './src/main'
4 | ],
5 | output: {
6 | path: '.',
7 | filename: 'bundle.js'
8 | },
9 |
10 | resolve: {
11 | // Allow to omit extensions when requiring these files
12 | extensions: ['', '.js']
13 | },
14 | watchDelay: 0,
15 | watch: true,
16 | externals: {},
17 | devtool: '#inline-source-map',
18 | module: {
19 | loaders: [
20 | {
21 | test: /\.jsx?$/,
22 | exclude: /(node_modules|bower_components)/,
23 | loader: 'babel',
24 | query: {
25 | presets: ['es2015']
26 | }
27 | }
28 | ]
29 | }
30 | };
31 |
--------------------------------------------------------------------------------