forked from Beakerboy/OSMBuilding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildingShapeUtils.js
More file actions
462 lines (428 loc) · 12.6 KB
/
BuildingShapeUtils.js
File metadata and controls
462 lines (428 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import {
Shape,
ShapeUtils,
} from 'three';
class BuildingShapeUtils extends ShapeUtils {
/**
* Create the shape of this way.
*
* @param {DOM.Element} way - OSM XML way element.
* @param {[number, number]} nodelist - list of all nodes
* @param augmentedNodelist - list of nodes outside bbox
*
* @return {THREE.Shape} shape - the shape
*/
static createShape(way, nodelist, augmentedNodelist = {}) {
// Initialize objects
const shape = new Shape();
var ref;
var node = [];
// Get all the nodes in the way of interest
const elements = way.getElementsByTagName('nd');
// Get the coordinates of all the nodes and add them to the shape outline.
for (let i = 0; i < elements.length; i++) {
ref = elements[i].getAttribute('ref');
node = nodelist[ref] ?? augmentedNodelist[ref];
// The first node requires a differnet function call.
if (i === 0) {
shape.moveTo(parseFloat(node[0]), parseFloat(node[1]));
} else {
shape.lineTo(parseFloat(node[0]), parseFloat(node[1]));
}
}
return shape;
}
/**
* Check if a way is a closed shape.
*
* @param {DOM.Element} way - OSM XML way element.
*
* @return {boolean}
*/
static isClosed(way) {
// Get all the nodes in the way of interest
const elements = way.getElementsByTagName('nd');
return elements[0].getAttribute('ref') === elements[elements.length - 1].getAttribute('ref');
}
/**
* Check if a way is self-intersecting.
*
* @param {DOM.Element} way - OSM XML way element.
*
* @return {boolean}
*/
static isSelfIntersecting(way) {
const nodes = Array.from(way.getElementsByTagName('nd'));
if (BuildingShapeUtils.isClosed(way)){
nodes.pop();
}
const refs = new Set();
for (const node of nodes) {
const ref = node.getAttribute('ref');
if (refs.has(ref)){
return true;
}
refs.add(ref);
}
return false;
}
/**
* Walk through an array and seperate any closed ways.
* Attempt to find matching open ways to enclose them.
*
* @param {[DOM.Element]} array - list of OSM XML way elements.
*
* @return {[DOM.Element]} array of closed ways.
*/
static combineWays(ways) {
const closedWays = [];
const wayBegins = {};
const wayEnds = {};
ways.forEach(w => {
const firstNodeID = w.querySelector('nd').getAttribute('ref');
if (wayBegins[firstNodeID]) {
wayBegins[firstNodeID].push(w);
} else {
wayBegins[firstNodeID] = [w];
}
const lastNodeID = w.querySelector('nd:last-of-type').getAttribute('ref');
if (wayEnds[lastNodeID]) {
wayEnds[lastNodeID].push(w);
} else {
wayEnds[lastNodeID] = [w];
}
});
const usedWays = new Set();
function tryMakeRing(currentRingWays) {
if (currentRingWays[0].querySelector('nd').getAttribute('ref') ===
currentRingWays[currentRingWays.length - 1].querySelector('nd:last-of-type').getAttribute('ref')) {
return currentRingWays;
}
const lastWay = currentRingWays[currentRingWays.length - 1];
const lastNodeID = lastWay.querySelector('nd:last-of-type').getAttribute('ref');
for (let way of wayBegins[lastNodeID] ?? []) {
const wayID = way.getAttribute('id');
if (usedWays.has(wayID)) {
continue;
}
usedWays.add(wayID);
currentRingWays.push(way);
if (tryMakeRing(currentRingWays).length) {
return currentRingWays;
}
currentRingWays.pop();
usedWays.delete(wayID);
}
for (let way of wayEnds[lastNodeID] ?? []) {
const wayID = way.getAttribute('id');
if (usedWays.has(wayID)) {
continue;
}
usedWays.add(wayID);
currentRingWays.push(BuildingShapeUtils.reverseWay(way));
if (tryMakeRing(currentRingWays).length) {
return currentRingWays;
}
currentRingWays.pop();
usedWays.delete(wayID);
}
return [];
}
ways.forEach(w => {
const wayID = w.getAttribute('id');
if (usedWays.has(wayID)){
return;
}
usedWays.add(wayID);
const result = tryMakeRing([w]);
if (result.length) {
let ring = result[0];
result.slice(1).forEach(w => {
ring = this.joinWays(ring, w);
});
closedWays.push(ring);
}
});
return closedWays;
}
/**
* Append the nodes from one way into another.
*
* @param {DOM.Element} way1 - an open, non self-intersecring way
* @param {DOM.Element} way2
*
* @return {DOM.Element} way
*/
static joinWays(way1, way2) {
const elements = way2.getElementsByTagName('nd');
for (let i = 1; i < elements.length; i++) {
let elem = elements[i].cloneNode();
way1.appendChild(elem);
}
return way1;
}
/**
* Reverse the order of nodes in a way.
*
* @param {DOM.Element} way - a way
*
* @return {DOM.Element} way
*/
static reverseWay(way) {
const elements = way.getElementsByTagName('nd');
const newWay = way.cloneNode(true);
newWay.innerHTML = '';
for (let i = 0; i < elements.length; i++) {
let elem = elements[elements.length - 1 - i].cloneNode();
newWay.appendChild(elem);
}
return newWay;
}
/**
* Find the center of a closed way
*
* @param {THREE.Shape} shape - the shape
*
* @return {[number, number]} xy - x/y coordinates of the center
*/
static center(shape) {
const extents = BuildingShapeUtils.extents(shape);
const center = [(extents[0] + extents[2] ) / 2, (extents[1] + extents[3] ) / 2];
return center;
}
/**
* Return the longest cardinal side length.
*
* @param {THREE.Shape} shape - the shape
*/
static getWidth(shape) {
const xy = BuildingShapeUtils.combineCoordinates(shape);
const x = xy[0];
const y = xy[1];
return Math.max(Math.max(...x) - Math.min(...x), Math.max(...y) - Math.min(...y));
}
/**
* can points be an array of shapes?
*/
static combineCoordinates(shape) {
//console.log('Shape: ' + JSON.stringify(shape));
const points = shape.extractPoints().shape;
var x = [];
var y = [];
var vec;
for (let i = 0; i < points.length; i++) {
vec = points[i];
x.push(vec.x);
y.push(vec.y);
}
return [x, y];
}
/**
* Calculate the Cartesian extents of the shape after rotaing couterclockwise by a given angle.
*
* @param {THREE.Shape} pts - the shape or Array of shapes.
* @param {number} angle - angle in radians to rotate shape
*
* @return {[number, number, number, number]} the extents of the object.
*/
static extents(shape, angle = 0) {
if (!Array.isArray(shape)) {
shape = [shape];
}
var x = [];
var y = [];
var vec;
for (let i = 0; i < shape.length; i++) {
const points = shape[i].extractPoints().shape;
for (let i = 0; i < points.length; i++) {
vec = points[i];
x.push(vec.x * Math.cos(angle) - vec.y * Math.sin(angle));
y.push(vec.x * Math.sin(angle) + vec.y * Math.cos(angle));
}
}
const left = Math.min(...x);
const bottom = Math.min(...y);
const right = Math.max(...x);
const top = Math.max(...y);
return [left, bottom, right, top];
}
/**
* Assuming the shape is all right angles,
* Find the orientation of the longest edge.
*/
static primaryDirection(shape) {
const points = shape.extractPoints().shape;
}
/**
* Calculate the length of each of a shape's edge
*
* @param {THREE.Shape} shape - the shape
*
* @return {[number, ...]} the esge lwngths.
*/
static edgeLength(shape) {
const points = shape.extractPoints().shape;
const lengths = [];
var p1;
var p2;
for (let i = 0; i < points.length - 1; i++) {
p1 = points[i];
p2 = points[i + 1];
lengths.push(Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2));
}
p1 = points[points.length - 1];
p2 = points[0];
lengths.push(Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2));
return lengths;
}
/**
* Calculate the angle at each of a shape's vertex.
* The angle will be PI > x >= -PI
*
* @param {THREE.Shape} shape - the shape
*
* @return {[number, ...]} the angles in radians.
*/
static vertexAngle(shape) {
const points = shape.extractPoints().shape;
const angles = [];
var p0;
var p1;
var p2;
function calcAngle(p0, p1, p2) {
let angle = Math.atan2(p2.y - p1.y, p2.x - p1.x) - Math.atan2(p0.y - p1.y, p0.x - p1.x);
if (angle >= Math.PI) {
angle -= 2 * Math.PI;
} else if (angle < -Math.PI) {
angle += 2 * Math.PI;
}
return angle;
}
p0 = points[points.length - 1];
p1 = points[0];
p2 = points[1];
angles.push(calcAngle(p0, p1, p2));
for (let i = 1; i < points.length; i++) {
p0 = points[i - 1];
p1 = points[i];
p2 = points[(i + 1) % points.length];
angles.push(calcAngle(p0, p1, p2));
}
return angles;
}
/**
* Calculate the angle of each of a shape's edge.
* the angle will be PI > x >= -PI
*
* @param {THREE.Shape} shape - the shape
*
* @return {[number, ...]} the angles in radians.
*/
static edgeDirection(shape) {
const points = shape.extractPoints().shape;
points.push(points[0]);
const angles = [];
var p1;
var p2;
for (let i = 0; i < points.length - 1; i++) {
p1 = points[i];
p2 = points[i + 1];
let angle = Math.atan2((p2.y - p1.y), (p2.x - p1.x));
if (angle >= Math.PI / 2) {
angle -= Math.PI;
} else if (angle < -Math.PI / 2) {
angle += Math.PI;
}
angles.push(angle);
}
return angles;
}
/**
* Is the given point within the given shape?
*
* @param {THREE.Shape} shape - the shape
* @param {[number, number]} point - an x, y pair.
*
* @return {boolean}
*/
static surrounds(shape, point) {
var count = 0;
const vecs = shape.extractPoints().shape;
var vec;
var nextvec;
for (let i = 0; i < vecs.length - 1; i++) {
vec = vecs[i];
nextvec = vecs[i+1];
if (vec.x === point[0] && vec.y === point[1]) {
return true;
}
const slope = (nextvec.y - vec.y) / (nextvec.x - vec.x);
const intercept = vec.y / slope / vec.x;
const intersection = (point[1] - intercept) / slope;
if (intersection > point[0]) {
count++;
} else if (intersection === point[0]) {
return true;
}
}
return count % 2 === 1;
}
/**
* Calculate the radius of a circle that can fit within a shape.
*
* @param {THREE.Shape} shape - the shape
*/
static calculateRadius(shape) {
const extents = BuildingShapeUtils.extents(shape);
// return half of the shorter side-length.
return Math.min(extents[2] - extents[0], extents[3] - extents[1]) / 2;
}
/**
* Calculate the angle of the longest side of a shape with 90° vertices.
* is begining / end duplicated?
*
* @param {THREE.Shape} shape - the shape
* @return {number}
*/
static longestSideAngle(shape) {
const vecs = shape.extractPoints().shape;
const lengths = BuildingShapeUtils.edgeLength(shape);
const directions = BuildingShapeUtils.edgeDirection(shape);
var index;
var maxLength = 0;
for (let i = 0; i < lengths.length; i++) {
if (lengths[i] > maxLength) {
index = i;
maxLength = lengths[i];
}
}
var angle = directions[index];
const extents = BuildingShapeUtils.extents(shape, -angle);
// If the shape is taller than it is wide after rotation, we are off by 90 degrees.
if ((extents[3] - extents[1]) > (extents[2] - extents[0])) {
angle = angle > 0 ? angle - Math.PI / 2 : angle + Math.PI / 2;
}
return angle;
}
/**
* Rotate lat/lon to reposition the home point onto 0,0.
*
* @param {[number, number]} lonLat - The longitute and latitude of a point.
*
* @return {[number, number]} x, y in meters
*/
static repositionPoint(lonLat, home) {
const R = 6371 * 1000; // Earth radius in m
const circ = 2 * Math.PI * R; // Circumference
const phi = 90 - lonLat[1];
const theta = lonLat[0] - home[0];
const thetaPrime = home[1] / 180 * Math.PI;
const x = R * Math.sin(theta / 180 * Math.PI) * Math.sin(phi / 180 * Math.PI);
const y = R * Math.cos(phi / 180 * Math.PI);
const z = R * Math.sin(phi / 180 * Math.PI) * Math.cos(theta / 180 * Math.PI);
const abs = Math.sqrt(z**2 + y**2);
const arg = Math.atan(y / z) - thetaPrime;
return [x, Math.sin(arg) * abs];
}
}
export {BuildingShapeUtils};