Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
FogNetwork
GitHub Repository: FogNetwork/Tsunami
Path: blob/main/public/games/files/garbage-collector/js/geometry/polygon.js
1036 views
1
/*globals define*/
2
define([
3
'object2d',
4
'utils'
5
], function( Object2D, Utils ) {
6
'use strict';
7
8
function Polygon( x, y ) {
9
Object2D.call( this, x, y );
10
11
this.vertices = [];
12
}
13
14
Polygon.prototype = new Object2D();
15
Polygon.prototype.constructor = Polygon;
16
17
Polygon.prototype.draw = function( ctx ) {
18
if ( !this.vertices.length ) {
19
return;
20
}
21
22
Object2D.prototype.draw.call( this, ctx );
23
};
24
25
Polygon.prototype.drawPath = function( ctx ) {
26
var vertexCount = this.vertexCount();
27
28
ctx.beginPath();
29
30
ctx.moveTo( this.vertices[0], this.vertices[1] );
31
for ( var i = 1; i < vertexCount; i++ ) {
32
ctx.lineTo( this.vertices[ 2 * i ], this.vertices[ 2 * i + 1 ] );
33
}
34
35
ctx.closePath();
36
};
37
38
Polygon.prototype.drawNormals = function( ctx, options ) {
39
options = options || {};
40
41
var length = options.length || 10,
42
lineWidth = options.lineWidth || 2,
43
stroke = options.stroke || '#0f0';
44
45
var vertexCount = this.vertexCount();
46
47
ctx.beginPath();
48
49
var xi, yi, xj, yj;
50
var mx, my;
51
var normal;
52
for ( var i = 0; i < vertexCount; i++ ) {
53
xi = this.vertices[ 2 * i ];
54
yi = this.vertices[ 2 * i + 1 ];
55
xj = this.vertices[ 2 * ( ( i + 1 ) % vertexCount ) ];
56
yj = this.vertices[ 2 * ( ( i + 1 ) % vertexCount ) + 1 ];
57
58
mx = 0.5 * ( xi + xj );
59
my = 0.5 * ( yi + yj );
60
61
normal = Utils.lineNormal( xi, yi, xj, yj );
62
if ( !normal ) {
63
continue;
64
}
65
66
ctx.moveTo( mx, my );
67
ctx.lineTo( mx + normal.x * length, my + normal.y * length );
68
}
69
70
ctx.lineWidth = lineWidth;
71
ctx.strokeStyle = stroke;
72
ctx.stroke();
73
};
74
75
Polygon.prototype.vertexCount = function() {
76
return 0.5 * this.vertices.length;
77
};
78
79
Polygon.prototype.contains = function( x, y ) {
80
var vertexCount = this.vertexCount();
81
82
var point = this.toLocal( x, y );
83
x = point.x;
84
y = point.y;
85
86
var contains = false;
87
var xi, yi, xj, yj;
88
for ( var i = 0, j = vertexCount - 1; i < vertexCount; j = i++ ) {
89
xi = this.vertices[ 2 * i ];
90
yi = this.vertices[ 2 * i + 1 ];
91
xj = this.vertices[ 2 * j ];
92
yj = this.vertices[ 2 * j + 1 ];
93
94
if ( ( ( yi > y ) !== ( yj > y ) ) &&
95
( x < ( xj - xi ) * ( y - yi ) / ( yj - yi ) + xi ) ) {
96
contains = !contains;
97
}
98
}
99
100
return contains;
101
};
102
103
return Polygon;
104
});
105
106