-
Notifications
You must be signed in to change notification settings - Fork 719
/
Copy pathHeightfield.js
700 lines (609 loc) · 19.1 KB
/
Heightfield.js
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
var Shape = require('./Shape');
var ConvexPolyhedron = require('./ConvexPolyhedron');
var Vec3 = require('../math/Vec3');
var Utils = require('../utils/Utils');
module.exports = Heightfield;
/**
* Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
* @class Heightfield
* @extends Shape
* @constructor
* @param {Array} data An array of Y values that will be used to construct the terrain.
* @param {object} options
* @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
* @param {Number} [options.maxValue] Maximum value.
* @param {Number} [options.elementSize=0.1] World spacing between the data points in X direction.
* @todo Should be possible to use along all axes, not just y
* @todo should be possible to scale along all axes
*
* @example
* // Generate some height data (y-values).
* var data = [];
* for(var i = 0; i < 1000; i++){
* var y = 0.5 * Math.cos(0.2 * i);
* data.push(y);
* }
*
* // Create the heightfield shape
* var heightfieldShape = new Heightfield(data, {
* elementSize: 1 // Distance between the data points in X and Y directions
* });
* var heightfieldBody = new Body();
* heightfieldBody.addShape(heightfieldShape);
* world.addBody(heightfieldBody);
*/
function Heightfield(data, options){
options = Utils.defaults(options, {
maxValue : null,
minValue : null,
elementSize : 1
});
/**
* An array of numbers, or height values, that are spread out along the x axis.
* @property {array} data
*/
this.data = data;
/**
* Max value of the data
* @property {number} maxValue
*/
this.maxValue = options.maxValue;
/**
* Max value of the data
* @property {number} minValue
*/
this.minValue = options.minValue;
/**
* The width of each element
* @property {number} elementSize
* @todo elementSizeX and Y
*/
this.elementSize = options.elementSize;
if(options.minValue === null){
this.updateMinValue();
}
if(options.maxValue === null){
this.updateMaxValue();
}
this.cacheEnabled = true;
Shape.call(this, {
type: Shape.types.HEIGHTFIELD
});
this.pillarConvex = new ConvexPolyhedron();
this.pillarOffset = new Vec3();
this.updateBoundingSphereRadius();
// "i_j_isUpper" => { convex: ..., offset: ... }
// for example:
// _cachedPillars["0_2_1"]
this._cachedPillars = {};
}
Heightfield.prototype = new Shape();
/**
* Call whenever you change the data array.
* @method update
*/
Heightfield.prototype.update = function(){
this._cachedPillars = {};
};
/**
* Update the .minValue property
* @method updateMinValue
*/
Heightfield.prototype.updateMinValue = function(){
var data = this.data;
var minValue = data[0][0];
for(var i=0; i !== data.length; i++){
for(var j=0; j !== data[i].length; j++){
var v = data[i][j];
if(v < minValue){
minValue = v;
}
}
}
this.minValue = minValue;
};
/**
* Update the .maxValue property
* @method updateMaxValue
*/
Heightfield.prototype.updateMaxValue = function(){
var data = this.data;
var maxValue = data[0][0];
for(var i=0; i !== data.length; i++){
for(var j=0; j !== data[i].length; j++){
var v = data[i][j];
if(v > maxValue){
maxValue = v;
}
}
}
this.maxValue = maxValue;
};
/**
* Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
* @method setHeightValueAtIndex
* @param {integer} xi
* @param {integer} yi
* @param {number} value
*/
Heightfield.prototype.setHeightValueAtIndex = function(xi, yi, value){
var data = this.data;
data[xi][yi] = value;
// Invalidate cache
this.clearCachedConvexTrianglePillar(xi, yi, false);
if(xi > 0){
this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
}
if(yi > 0){
this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
}
if(yi > 0 && xi > 0){
this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
}
};
/**
* Get max/min in a rectangle in the matrix data
* @method getRectMinMax
* @param {integer} iMinX
* @param {integer} iMinY
* @param {integer} iMaxX
* @param {integer} iMaxY
* @param {array} [result] An array to store the results in.
* @return {array} The result array, if it was passed in. Minimum will be at position 0 and max at 1.
*/
Heightfield.prototype.getRectMinMax = function (iMinX, iMinY, iMaxX, iMaxY, result) {
result = result || [];
// Get max and min of the data
var data = this.data,
max = this.minValue; // Set first value
for(var i = iMinX; i <= iMaxX; i++){
for(var j = iMinY; j <= iMaxY; j++){
var height = data[i][j];
if(height > max){
max = height;
}
}
}
result[0] = this.minValue;
result[1] = max;
};
/**
* Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.
* @method getIndexOfPosition
* @param {number} x
* @param {number} y
* @param {array} result Two-element array
* @param {boolean} clamp If the position should be clamped to the heightfield edge.
* @return {boolean}
*/
Heightfield.prototype.getIndexOfPosition = function (x, y, result, clamp) {
// Get the index of the data points to test against
var w = this.elementSize;
var data = this.data;
var xi = Math.floor(x / w);
var yi = Math.floor(y / w);
result[0] = xi;
result[1] = yi;
if(clamp){
// Clamp index to edges
if(xi < 0){ xi = 0; }
if(yi < 0){ yi = 0; }
if(xi >= data.length - 1){ xi = data.length - 1; }
if(yi >= data[0].length - 1){ yi = data[0].length - 1; }
}
// Bail out if we are out of the terrain
if(xi < 0 || yi < 0 || xi >= data.length-1 || yi >= data[0].length-1){
return false;
}
return true;
};
var getHeightAt_idx = [];
var getHeightAt_weights = new Vec3();
var getHeightAt_a = new Vec3();
var getHeightAt_b = new Vec3();
var getHeightAt_c = new Vec3();
Heightfield.prototype.getTriangleAt = function(x, y, edgeClamp, a, b, c){
var idx = getHeightAt_idx;
this.getIndexOfPosition(x, y, idx, edgeClamp);
var xi = idx[0];
var yi = idx[1];
var data = this.data;
if(edgeClamp){
xi = Math.min(data.length - 2, Math.max(0, xi));
yi = Math.min(data[0].length - 2, Math.max(0, yi));
}
var elementSize = this.elementSize;
var lowerDist2 = Math.pow(x / elementSize - xi, 2) + Math.pow(y / elementSize - yi, 2);
var upperDist2 = Math.pow(x / elementSize - (xi + 1), 2) + Math.pow(y / elementSize - (yi + 1), 2);
var upper = lowerDist2 > upperDist2;
this.getTriangle(xi, yi, upper, a, b, c);
return upper;
};
var getNormalAt_a = new Vec3();
var getNormalAt_b = new Vec3();
var getNormalAt_c = new Vec3();
var getNormalAt_e0 = new Vec3();
var getNormalAt_e1 = new Vec3();
Heightfield.prototype.getNormalAt = function(x, y, edgeClamp, result){
var a = getNormalAt_a;
var b = getNormalAt_b;
var c = getNormalAt_c;
var e0 = getNormalAt_e0;
var e1 = getNormalAt_e1;
this.getTriangleAt(x, y, edgeClamp, a, b, c);
b.vsub(a, e0);
c.vsub(a, e1);
e0.cross(e1, result);
result.normalize();
};
/**
* Get an AABB of a square in the heightfield
* @param {number} xi
* @param {number} yi
* @param {AABB} result
*/
Heightfield.prototype.getAabbAtIndex = function(xi, yi, result){
var data = this.data;
var elementSize = this.elementSize;
result.lowerBound.set(
xi * elementSize,
yi * elementSize,
data[xi][yi]
);
result.upperBound.set(
(xi + 1) * elementSize,
(yi + 1) * elementSize,
data[xi + 1][yi + 1]
);
};
/**
* Get the height in the heightfield at a given position
* @param {number} x
* @param {number} y
* @param {boolean} edgeClamp
* @return {number}
*/
Heightfield.prototype.getHeightAt = function(x, y, edgeClamp){
var data = this.data;
var a = getHeightAt_a;
var b = getHeightAt_b;
var c = getHeightAt_c;
var idx = getHeightAt_idx;
this.getIndexOfPosition(x, y, idx, edgeClamp);
var xi = idx[0];
var yi = idx[1];
if(edgeClamp){
xi = Math.min(data.length - 2, Math.max(0, xi));
yi = Math.min(data[0].length - 2, Math.max(0, yi));
}
var upper = this.getTriangleAt(x, y, edgeClamp, a, b, c);
barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);
var w = getHeightAt_weights;
if(upper){
// Top triangle verts
return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;
} else {
// Top triangle verts
return data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z;
}
};
// from https://en.wikipedia.org/wiki/Barycentric_coordinate_system
function barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result){
result.x = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
result.y = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
result.z = 1 - result.x - result.y;
}
Heightfield.prototype.getCacheConvexTrianglePillarKey = function(xi, yi, getUpperTriangle){
return xi + '_' + yi + '_' + (getUpperTriangle ? 1 : 0);
};
Heightfield.prototype.getCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
};
Heightfield.prototype.setCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle, convex, offset){
this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
convex: convex,
offset: offset
};
};
Heightfield.prototype.clearCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
};
/**
* Get a triangle from the heightfield
* @param {number} xi
* @param {number} yi
* @param {boolean} upper
* @param {Vec3} a
* @param {Vec3} b
* @param {Vec3} c
*/
Heightfield.prototype.getTriangle = function(xi, yi, upper, a, b, c){
var data = this.data;
var elementSize = this.elementSize;
if(upper){
// Top triangle verts
a.set(
(xi + 1) * elementSize,
(yi + 1) * elementSize,
data[xi + 1][yi + 1]
);
b.set(
xi * elementSize,
(yi + 1) * elementSize,
data[xi][yi + 1]
);
c.set(
(xi + 1) * elementSize,
yi * elementSize,
data[xi + 1][yi]
);
} else {
// Top triangle verts
a.set(
xi * elementSize,
yi * elementSize,
data[xi][yi]
);
b.set(
(xi + 1) * elementSize,
yi * elementSize,
data[xi + 1][yi]
);
c.set(
xi * elementSize,
(yi + 1) * elementSize,
data[xi][yi + 1]
);
}
};
/**
* Get a triangle in the terrain in the form of a triangular convex shape.
* @method getConvexTrianglePillar
* @param {integer} i
* @param {integer} j
* @param {boolean} getUpperTriangle
*/
Heightfield.prototype.getConvexTrianglePillar = function(xi, yi, getUpperTriangle){
var result = this.pillarConvex;
var offsetResult = this.pillarOffset;
if(this.cacheEnabled){
var data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
if(data){
this.pillarConvex = data.convex;
this.pillarOffset = data.offset;
return;
}
result = new ConvexPolyhedron();
// Add shape to shape map. This is a special case for
// heightfields. Normally this happens in
// addShape/addBody. world may be null for some tests.
var world = this.body && this.body.world
if(world){
world.idToShapeMap[result.id] = result;
}
// Assign body so the shape overlap events will have it.
result.body = this.body;
offsetResult = new Vec3();
this.pillarConvex = result;
this.pillarOffset = offsetResult;
} else {
// If the cache is not used, make the pillar map to our shape.
if(!result.body){
this.body.world.idToShapeMap[result.id] = this;
result.body = this.body;
}
}
var data = this.data;
var elementSize = this.elementSize;
var faces = result.faces;
// Reuse verts if possible
result.vertices.length = 6;
for (var i = 0; i < 6; i++) {
if(!result.vertices[i]){
result.vertices[i] = new Vec3();
}
}
// Reuse faces if possible
faces.length = 5;
for (var i = 0; i < 5; i++) {
if(!faces[i]){
faces[i] = [];
}
}
var verts = result.vertices;
var h = (Math.min(
data[xi][yi],
data[xi+1][yi],
data[xi][yi+1],
data[xi+1][yi+1]
) - this.minValue ) / 2 + this.minValue;
if (!getUpperTriangle) {
// Center of the triangle pillar - all polygons are given relative to this one
offsetResult.set(
(xi + 0.25) * elementSize, // sort of center of a triangle
(yi + 0.25) * elementSize,
h // vertical center
);
// Top triangle verts
verts[0].set(
-0.25 * elementSize,
-0.25 * elementSize,
data[xi][yi] - h
);
verts[1].set(
0.75 * elementSize,
-0.25 * elementSize,
data[xi + 1][yi] - h
);
verts[2].set(
-0.25 * elementSize,
0.75 * elementSize,
data[xi][yi + 1] - h
);
// bottom triangle verts
verts[3].set(
-0.25 * elementSize,
-0.25 * elementSize,
-h-1
);
verts[4].set(
0.75 * elementSize,
-0.25 * elementSize,
-h-1
);
verts[5].set(
-0.25 * elementSize,
0.75 * elementSize,
-h-1
);
// top triangle
faces[0][0] = 0;
faces[0][1] = 1;
faces[0][2] = 2;
// bottom triangle
faces[1][0] = 5;
faces[1][1] = 4;
faces[1][2] = 3;
// -x facing quad
faces[2][0] = 0;
faces[2][1] = 2;
faces[2][2] = 5;
faces[2][3] = 3;
// -y facing quad
faces[3][0] = 1;
faces[3][1] = 0;
faces[3][2] = 3;
faces[3][3] = 4;
// +xy facing quad
faces[4][0] = 4;
faces[4][1] = 5;
faces[4][2] = 2;
faces[4][3] = 1;
} else {
// Center of the triangle pillar - all polygons are given relative to this one
offsetResult.set(
(xi + 0.75) * elementSize, // sort of center of a triangle
(yi + 0.75) * elementSize,
h // vertical center
);
// Top triangle verts
verts[0].set(
0.25 * elementSize,
0.25 * elementSize,
data[xi + 1][yi + 1] - h
);
verts[1].set(
-0.75 * elementSize,
0.25 * elementSize,
data[xi][yi + 1] - h
);
verts[2].set(
0.25 * elementSize,
-0.75 * elementSize,
data[xi + 1][yi] - h
);
// bottom triangle verts
verts[3].set(
0.25 * elementSize,
0.25 * elementSize,
- h-1
);
verts[4].set(
-0.75 * elementSize,
0.25 * elementSize,
- h-1
);
verts[5].set(
0.25 * elementSize,
-0.75 * elementSize,
- h-1
);
// Top triangle
faces[0][0] = 0;
faces[0][1] = 1;
faces[0][2] = 2;
// bottom triangle
faces[1][0] = 5;
faces[1][1] = 4;
faces[1][2] = 3;
// +x facing quad
faces[2][0] = 2;
faces[2][1] = 5;
faces[2][2] = 3;
faces[2][3] = 0;
// +y facing quad
faces[3][0] = 3;
faces[3][1] = 4;
faces[3][2] = 1;
faces[3][3] = 0;
// -xy facing quad
faces[4][0] = 1;
faces[4][1] = 4;
faces[4][2] = 5;
faces[4][3] = 2;
}
result.computeNormals();
result.computeEdges();
result.updateBoundingSphereRadius();
this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
};
Heightfield.prototype.calculateLocalInertia = function(mass, target){
target = target || new Vec3();
target.set(0, 0, 0);
return target;
};
Heightfield.prototype.volume = function(){
return Number.MAX_VALUE; // The terrain is infinite
};
Heightfield.prototype.calculateWorldAABB = function(pos, quat, min, max){
// TODO: do it properly
min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
};
Heightfield.prototype.updateBoundingSphereRadius = function(){
// Use the bounding box of the min/max values
var data = this.data,
s = this.elementSize;
this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).norm();
};
/**
* Sets the height values from an image. Currently only supported in browser.
* @method setHeightsFromImage
* @param {Image} image
* @param {Vec3} scale
*/
Heightfield.prototype.setHeightsFromImage = function(image, scale){
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
var imageData = context.getImageData(0, 0, image.width, image.height);
var matrix = this.data;
matrix.length = 0;
this.elementSize = Math.abs(scale.x) / imageData.width;
for(var i=0; i<imageData.height; i++){
var row = [];
for(var j=0; j<imageData.width; j++){
var a = imageData.data[(i*imageData.height + j) * 4];
var b = imageData.data[(i*imageData.height + j) * 4 + 1];
var c = imageData.data[(i*imageData.height + j) * 4 + 2];
var height = (a + b + c) / 4 / 255 * scale.z;
if(scale.x < 0){
row.push(height);
} else {
row.unshift(height);
}
}
if(scale.y < 0){
matrix.unshift(row);
} else {
matrix.push(row);
}
}
this.updateMaxValue();
this.updateMinValue();
this.update();
};