forked from mrdoob/three.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypedArrayUtils.js
602 lines (364 loc) · 12.3 KB
/
TypedArrayUtils.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
THREE.TypedArrayUtils = {};
/**
* In-place quicksort for typed arrays (e.g. for Float32Array)
* provides fast sorting
* useful e.g. for a custom shader and/or BufferGeometry
*
* @author Roman Bolzern <[email protected]>, 2013
* @author I4DS http://www.fhnw.ch/i4ds, 2013
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
*
* Complexity: http://bigocheatsheet.com/ see Quicksort
*
* Example:
* points: [x, y, z, x, y, z, x, y, z, ...]
* eleSize: 3 //because of (x, y, z)
* orderElement: 0 //order according to x
*/
THREE.TypedArrayUtils.quicksortIP = function ( arr, eleSize, orderElement ) {
var stack = [];
var sp = - 1;
var left = 0;
var right = arr.length / eleSize - 1;
var tmp = 0.0, x = 0, y = 0;
var swapF = function ( a, b ) {
a *= eleSize; b *= eleSize;
for ( y = 0; y < eleSize; y ++ ) {
tmp = arr[ a + y ];
arr[ a + y ] = arr[ b + y ];
arr[ b + y ] = tmp;
}
};
var i, j, swap = new Float32Array( eleSize ), temp = new Float32Array( eleSize );
while ( true ) {
if ( right - left <= 25 ) {
for ( j = left + 1; j <= right; j ++ ) {
for ( x = 0; x < eleSize; x ++ ) {
swap[ x ] = arr[ j * eleSize + x ];
}
i = j - 1;
while ( i >= left && arr[ i * eleSize + orderElement ] > swap[ orderElement ] ) {
for ( x = 0; x < eleSize; x ++ ) {
arr[ ( i + 1 ) * eleSize + x ] = arr[ i * eleSize + x ];
}
i --;
}
for ( x = 0; x < eleSize; x ++ ) {
arr[ ( i + 1 ) * eleSize + x ] = swap[ x ];
}
}
if ( sp == - 1 ) break;
right = stack[ sp -- ]; //?
left = stack[ sp -- ];
} else {
var median = ( left + right ) >> 1;
i = left + 1;
j = right;
swapF( median, i );
if ( arr[ left * eleSize + orderElement ] > arr[ right * eleSize + orderElement ] ) {
swapF( left, right );
}
if ( arr[ i * eleSize + orderElement ] > arr[ right * eleSize + orderElement ] ) {
swapF( i, right );
}
if ( arr[ left * eleSize + orderElement ] > arr[ i * eleSize + orderElement ] ) {
swapF( left, i );
}
for ( x = 0; x < eleSize; x ++ ) {
temp[ x ] = arr[ i * eleSize + x ];
}
while ( true ) {
do i ++; while ( arr[ i * eleSize + orderElement ] < temp[ orderElement ] );
do j --; while ( arr[ j * eleSize + orderElement ] > temp[ orderElement ] );
if ( j < i ) break;
swapF( i, j );
}
for ( x = 0; x < eleSize; x ++ ) {
arr[ ( left + 1 ) * eleSize + x ] = arr[ j * eleSize + x ];
arr[ j * eleSize + x ] = temp[ x ];
}
if ( right - i + 1 >= j - left ) {
stack[ ++ sp ] = i;
stack[ ++ sp ] = right;
right = j - 1;
} else {
stack[ ++ sp ] = left;
stack[ ++ sp ] = j - 1;
left = i;
}
}
}
return arr;
};
/**
* k-d Tree for typed arrays (e.g. for Float32Array), in-place
* provides fast nearest neighbour search
* useful e.g. for a custom shader and/or BufferGeometry, saves tons of memory
* has no insert and remove, only buildup and neares neighbour search
*
* Based on https://github.com/ubilabs/kd-tree-javascript by Ubilabs
*
* @author Roman Bolzern <[email protected]>, 2013
* @author I4DS http://www.fhnw.ch/i4ds, 2013
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
*
* Requires typed array quicksort
*
* Example:
* points: [x, y, z, x, y, z, x, y, z, ...]
* metric: function(a, b){ return Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2) + Math.pow(a[2] - b[2], 2); } //Manhatten distance
* eleSize: 3 //because of (x, y, z)
*
* Further information (including mathematical properties)
* http://en.wikipedia.org/wiki/Binary_tree
* http://en.wikipedia.org/wiki/K-d_tree
*
* If you want to further minimize memory usage, remove Node.depth and replace in search algorithm with a traversal to root node (see comments at THREE.TypedArrayUtils.Kdtree.prototype.Node)
*/
THREE.TypedArrayUtils.Kdtree = function ( points, metric, eleSize ) {
var self = this;
var maxDepth = 0;
var getPointSet = function ( points, pos ) {
return points.subarray( pos * eleSize, pos * eleSize + eleSize );
};
function buildTree( points, depth, parent, pos ) {
var dim = depth % eleSize,
median,
node,
plength = points.length / eleSize;
if ( depth > maxDepth ) maxDepth = depth;
if ( plength === 0 ) return null;
if ( plength === 1 ) {
return new self.Node( getPointSet( points, 0 ), depth, parent, pos );
}
THREE.TypedArrayUtils.quicksortIP( points, eleSize, dim );
median = Math.floor( plength / 2 );
node = new self.Node( getPointSet( points, median ), depth, parent, median + pos );
node.left = buildTree( points.subarray( 0, median * eleSize ), depth + 1, node, pos );
node.right = buildTree( points.subarray( ( median + 1 ) * eleSize, points.length ), depth + 1, node, pos + median + 1 );
return node;
}
this.root = buildTree( points, 0, null, 0 );
this.getMaxDepth = function () {
return maxDepth;
};
this.nearest = function ( point, maxNodes, maxDistance ) {
/* point: array of size eleSize
maxNodes: max amount of nodes to return
maxDistance: maximum distance to point result nodes should have
condition (not implemented): function to test node before it's added to the result list, e.g. test for view frustum
*/
var i,
result,
bestNodes;
bestNodes = new THREE.TypedArrayUtils.Kdtree.BinaryHeap(
function ( e ) {
return - e[ 1 ];
}
);
function nearestSearch( node ) {
var bestChild,
dimension = node.depth % eleSize,
ownDistance = metric( point, node.obj ),
linearDistance = 0,
otherChild,
i,
linearPoint = [];
function saveNode( node, distance ) {
bestNodes.push( [ node, distance ] );
if ( bestNodes.size() > maxNodes ) {
bestNodes.pop();
}
}
for ( i = 0; i < eleSize; i += 1 ) {
if ( i === node.depth % eleSize ) {
linearPoint[ i ] = point[ i ];
} else {
linearPoint[ i ] = node.obj[ i ];
}
}
linearDistance = metric( linearPoint, node.obj );
// if it's a leaf
if ( node.right === null && node.left === null ) {
if ( bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[ 1 ] ) {
saveNode( node, ownDistance );
}
return;
}
if ( node.right === null ) {
bestChild = node.left;
} else if ( node.left === null ) {
bestChild = node.right;
} else {
if ( point[ dimension ] < node.obj[ dimension ] ) {
bestChild = node.left;
} else {
bestChild = node.right;
}
}
// recursive search
nearestSearch( bestChild );
if ( bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[ 1 ] ) {
saveNode( node, ownDistance );
}
// if there's still room or the current distance is nearer than the best distance
if ( bestNodes.size() < maxNodes || Math.abs( linearDistance ) < bestNodes.peek()[ 1 ] ) {
if ( bestChild === node.left ) {
otherChild = node.right;
} else {
otherChild = node.left;
}
if ( otherChild !== null ) {
nearestSearch( otherChild );
}
}
}
if ( maxDistance ) {
for ( i = 0; i < maxNodes; i += 1 ) {
bestNodes.push( [ null, maxDistance ] );
}
}
nearestSearch( self.root );
result = [];
for ( i = 0; i < maxNodes; i += 1 ) {
if ( bestNodes.content[ i ][ 0 ] ) {
result.push( [ bestNodes.content[ i ][ 0 ], bestNodes.content[ i ][ 1 ] ] );
}
}
return result;
};
};
/**
* If you need to free up additional memory and agree with an additional O( log n ) traversal time you can get rid of "depth" and "pos" in Node:
* Depth can be easily done by adding 1 for every parent (care: root node has depth 0, not 1)
* Pos is a bit tricky: Assuming the tree is balanced (which is the case when after we built it up), perform the following steps:
* By traversing to the root store the path e.g. in a bit pattern (01001011, 0 is left, 1 is right)
* From buildTree we know that "median = Math.floor( plength / 2 );", therefore for each bit...
* 0: amountOfNodesRelevantForUs = Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
* 1: amountOfNodesRelevantForUs = Math.ceil( (pamountOfNodesRelevantForUs - 1) / 2 );
* pos += Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
* when recursion done, we still need to add all left children of target node:
* pos += Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
* and I think you need to +1 for the current position, not sure.. depends, try it out ^^
*
* I experienced that for 200'000 nodes you can get rid of 4 MB memory each, leading to 8 MB memory saved.
*/
THREE.TypedArrayUtils.Kdtree.prototype.Node = function ( obj, depth, parent, pos ) {
this.obj = obj;
this.left = null;
this.right = null;
this.parent = parent;
this.depth = depth;
this.pos = pos;
};
/**
* Binary heap implementation
* @author http://eloquentjavascript.net/appendix2.htm
*/
THREE.TypedArrayUtils.Kdtree.BinaryHeap = function ( scoreFunction ) {
this.content = [];
this.scoreFunction = scoreFunction;
};
THREE.TypedArrayUtils.Kdtree.BinaryHeap.prototype = {
push: function ( element ) {
// Add the new element to the end of the array.
this.content.push( element );
// Allow it to bubble up.
this.bubbleUp( this.content.length - 1 );
},
pop: function () {
// Store the first element so we can return it later.
var result = this.content[ 0 ];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it sink down.
if ( this.content.length > 0 ) {
this.content[ 0 ] = end;
this.sinkDown( 0 );
}
return result;
},
peek: function () {
return this.content[ 0 ];
},
remove: function ( node ) {
var len = this.content.length;
// To remove a value, we must search through the array to find it.
for ( var i = 0; i < len; i ++ ) {
if ( this.content[ i ] == node ) {
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if ( i != len - 1 ) {
this.content[ i ] = end;
if ( this.scoreFunction( end ) < this.scoreFunction( node ) ) {
this.bubbleUp( i );
} else {
this.sinkDown( i );
}
}
return;
}
}
throw new Error( "Node not found." );
},
size: function () {
return this.content.length;
},
bubbleUp: function ( n ) {
// Fetch the element that has to be moved.
var element = this.content[ n ];
// When at 0, an element can not go up any further.
while ( n > 0 ) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor( ( n + 1 ) / 2 ) - 1,
parent = this.content[ parentN ];
// Swap the elements if the parent is greater.
if ( this.scoreFunction( element ) < this.scoreFunction( parent ) ) {
this.content[ parentN ] = element;
this.content[ n ] = parent;
// Update 'n' to continue at the new position.
n = parentN;
} else {
// Found a parent that is less, no need to move it further.
break;
}
}
},
sinkDown: function ( n ) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[ n ],
elemScore = this.scoreFunction( element );
while ( true ) {
// Compute the indices of the child elements.
var child2N = ( n + 1 ) * 2, child1N = child2N - 1;
// This is used to store the new position of the element, if any.
var swap = null;
// If the first child exists (is inside the array)...
if ( child1N < length ) {
// Look it up and compute its score.
var child1 = this.content[ child1N ],
child1Score = this.scoreFunction( child1 );
// If the score is less than our element's, we need to swap.
if ( child1Score < elemScore ) swap = child1N;
}
// Do the same checks for the other child.
if ( child2N < length ) {
var child2 = this.content[ child2N ],
child2Score = this.scoreFunction( child2 );
if ( child2Score < ( swap === null ? elemScore : child1Score ) ) swap = child2N;
}
// If the element needs to be moved, swap it, and continue.
if ( swap !== null ) {
this.content[ n ] = this.content[ swap ];
this.content[ swap ] = element;
n = swap;
} else {
// Otherwise, we are done.
break;
}
}
}
};