-
Notifications
You must be signed in to change notification settings - Fork 23
/
cytoscape-euler.js
1429 lines (1137 loc) · 119 KB
/
cytoscape-euler.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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["cytoscapeEuler"] = factory();
else
root["cytoscapeEuler"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 11);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
for (var _len = arguments.length, srcs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
srcs[_key - 1] = arguments[_key];
}
srcs.forEach(function (src) {
Object.keys(src).forEach(function (k) {
return tgt[k] = src[k];
});
});
return tgt;
};
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assign = __webpack_require__(0);
var defaults = Object.freeze({
source: null,
target: null,
length: 80,
coeff: 0.0002,
weight: 1
});
function makeSpring(spring) {
return assign({}, defaults, spring);
}
function applySpring(spring) {
var body1 = spring.source,
body2 = spring.target,
length = spring.length < 0 ? defaults.length : spring.length,
dx = body2.pos.x - body1.pos.x,
dy = body2.pos.y - body1.pos.y,
r = Math.sqrt(dx * dx + dy * dy);
if (r === 0) {
dx = (Math.random() - 0.5) / 50;
dy = (Math.random() - 0.5) / 50;
r = Math.sqrt(dx * dx + dy * dy);
}
var d = r - length;
var coeff = (!spring.coeff || spring.coeff < 0 ? defaults.springCoeff : spring.coeff) * d / r * spring.weight;
body1.force.x += coeff * dx;
body1.force.y += coeff * dy;
body2.force.x -= coeff * dx;
body2.force.y -= coeff * dy;
}
module.exports = { makeSpring: makeSpring, applySpring: applySpring };
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
The implementation of the Euler layout algorithm
*/
var Layout = __webpack_require__(13);
var assign = __webpack_require__(0);
var defaults = __webpack_require__(4);
var _require = __webpack_require__(10),
_tick = _require.tick;
var _require2 = __webpack_require__(7),
makeQuadtree = _require2.makeQuadtree;
var _require3 = __webpack_require__(3),
makeBody = _require3.makeBody;
var _require4 = __webpack_require__(1),
makeSpring = _require4.makeSpring;
var isFn = function isFn(fn) {
return typeof fn === 'function';
};
var isParent = function isParent(n) {
return n.isParent();
};
var notIsParent = function notIsParent(n) {
return !isParent(n);
};
var isLocked = function isLocked(n) {
return n.locked();
};
var notIsLocked = function notIsLocked(n) {
return !isLocked(n);
};
var isParentEdge = function isParentEdge(e) {
return isParent(e.source()) || isParent(e.target());
};
var notIsParentEdge = function notIsParentEdge(e) {
return !isParentEdge(e);
};
var getBody = function getBody(n) {
return n.scratch('euler').body;
};
var getNonParentDescendants = function getNonParentDescendants(n) {
return isParent(n) ? n.descendants().filter(notIsParent) : n;
};
var getScratch = function getScratch(el) {
var scratch = el.scratch('euler');
if (!scratch) {
scratch = {};
el.scratch('euler', scratch);
}
return scratch;
};
var optFn = function optFn(opt, ele) {
if (isFn(opt)) {
return opt(ele);
} else {
return opt;
}
};
var Euler = function (_Layout) {
_inherits(Euler, _Layout);
function Euler(options) {
_classCallCheck(this, Euler);
return _possibleConstructorReturn(this, (Euler.__proto__ || Object.getPrototypeOf(Euler)).call(this, assign({}, defaults, options)));
}
_createClass(Euler, [{
key: 'prerun',
value: function prerun(state) {
var s = state;
s.quadtree = makeQuadtree();
var bodies = s.bodies = [];
// regular nodes
s.nodes.filter(function (n) {
return notIsParent(n);
}).forEach(function (n) {
var scratch = getScratch(n);
var body = makeBody({
pos: { x: scratch.x, y: scratch.y },
mass: optFn(s.mass, n),
locked: scratch.locked
});
body._cyNode = n;
scratch.body = body;
body._scratch = scratch;
bodies.push(body);
});
var springs = s.springs = [];
// regular edge springs
s.edges.filter(notIsParentEdge).forEach(function (e) {
var spring = makeSpring({
source: getBody(e.source()),
target: getBody(e.target()),
length: optFn(s.springLength, e),
coeff: optFn(s.springCoeff, e)
});
spring._cyEdge = e;
var scratch = getScratch(e);
spring._scratch = scratch;
scratch.spring = spring;
springs.push(spring);
});
// compound edge springs
s.edges.filter(isParentEdge).forEach(function (e) {
var sources = getNonParentDescendants(e.source());
var targets = getNonParentDescendants(e.target());
// just add one spring for perf
sources = [sources[0]];
targets = [targets[0]];
sources.forEach(function (src) {
targets.forEach(function (tgt) {
springs.push(makeSpring({
source: getBody(src),
target: getBody(tgt),
length: optFn(s.springLength, e),
coeff: optFn(s.springCoeff, e)
}));
});
});
});
}
}, {
key: 'tick',
value: function tick(state) {
var movement = _tick(state);
var isDone = movement <= state.movementThreshold;
return isDone;
}
}]);
return Euler;
}(Layout);
module.exports = Euler;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var defaults = Object.freeze({
pos: { x: 0, y: 0 },
prevPos: { x: 0, y: 0 },
force: { x: 0, y: 0 },
velocity: { x: 0, y: 0 },
mass: 1
});
var copyVec = function copyVec(v) {
return { x: v.x, y: v.y };
};
var getValue = function getValue(val, def) {
return val != null ? val : def;
};
var getVec = function getVec(vec, def) {
return copyVec(getValue(vec, def));
};
function makeBody(opts) {
var b = {};
b.pos = getVec(opts.pos, defaults.pos);
b.prevPos = getVec(opts.prevPos, b.pos);
b.force = getVec(opts.force, defaults.force);
b.velocity = getVec(opts.velocity, defaults.velocity);
b.mass = opts.mass != null ? opts.mass : defaults.mass;
b.locked = opts.locked;
return b;
}
module.exports = { makeBody: makeBody };
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var defaults = Object.freeze({
// The ideal legth of a spring
// - This acts as a hint for the edge length
// - The edge length can be longer or shorter if the forces are set to extreme values
springLength: function springLength(edge) {
return 80;
},
// Hooke's law coefficient
// - The value ranges on [0, 1]
// - Lower values give looser springs
// - Higher values give tighter springs
springCoeff: function springCoeff(edge) {
return 0.0008;
},
// The mass of the node in the physics simulation
// - The mass affects the gravity node repulsion/attraction
mass: function mass(node) {
return 4;
},
// Coulomb's law coefficient
// - Makes the nodes repel each other for negative values
// - Makes the nodes attract each other for positive values
gravity: -1.2,
// A force that pulls nodes towards the origin (0, 0)
// Higher values keep the components less spread out
pull: 0.001,
// Theta coefficient from Barnes-Hut simulation
// - Value ranges on [0, 1]
// - Performance is better with smaller values
// - Very small values may not create enough force to give a good result
theta: 0.666,
// Friction / drag coefficient to make the system stabilise over time
dragCoeff: 0.02,
// When the total of the squared position deltas is less than this value, the simulation ends
movementThreshold: 1,
// The amount of time passed per tick
// - Larger values result in faster runtimes but might spread things out too far
// - Smaller values produce more accurate results
timeStep: 20
});
module.exports = defaults;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var defaultCoeff = 0.02;
function applyDrag(body, manualDragCoeff) {
var dragCoeff = void 0;
if (manualDragCoeff != null) {
dragCoeff = manualDragCoeff;
} else if (body.dragCoeff != null) {
dragCoeff = body.dragCoeff;
} else {
dragCoeff = defaultCoeff;
}
body.force.x -= dragCoeff * body.velocity.x;
body.force.y -= dragCoeff * body.velocity.y;
}
module.exports = { applyDrag: applyDrag };
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// use euler method for force integration http://en.wikipedia.org/wiki/Euler_method
// return sum of squared position deltas
function integrate(bodies, timeStep) {
var dx = 0,
tx = 0,
dy = 0,
ty = 0,
i,
max = bodies.length;
if (max === 0) {
return 0;
}
for (i = 0; i < max; ++i) {
var body = bodies[i],
coeff = timeStep / body.mass;
if (body.grabbed) {
continue;
}
if (body.locked) {
body.velocity.x = 0;
body.velocity.y = 0;
} else {
body.velocity.x += coeff * body.force.x;
body.velocity.y += coeff * body.force.y;
}
var vx = body.velocity.x,
vy = body.velocity.y,
v = Math.sqrt(vx * vx + vy * vy);
if (v > 1) {
body.velocity.x = vx / v;
body.velocity.y = vy / v;
}
dx = timeStep * body.velocity.x;
dy = timeStep * body.velocity.y;
body.pos.x += dx;
body.pos.y += dy;
tx += Math.abs(dx);ty += Math.abs(dy);
}
return (tx * tx + ty * ty) / max;
}
module.exports = { integrate: integrate };
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// impl of barnes hut
// http://www.eecs.berkeley.edu/~demmel/cs267/lecture26/lecture26.html
// http://en.wikipedia.org/wiki/Barnes%E2%80%93Hut_simulation
var Node = __webpack_require__(9);
var InsertStack = __webpack_require__(8);
var resetVec = function resetVec(v) {
v.x = 0;v.y = 0;
};
var isSamePosition = function isSamePosition(p1, p2) {
var threshold = 1e-8;
var dx = Math.abs(p1.x - p2.x);
var dy = Math.abs(p1.y - p2.y);
return dx < threshold && dy < threshold;
};
function makeQuadtree() {
var updateQueue = [],
insertStack = new InsertStack(),
nodesCache = [],
currentInCache = 0,
root = newNode();
function newNode() {
// To avoid pressure on GC we reuse nodes.
var node = nodesCache[currentInCache];
if (node) {
node.quad0 = null;
node.quad1 = null;
node.quad2 = null;
node.quad3 = null;
node.body = null;
node.mass = node.massX = node.massY = 0;
node.left = node.right = node.top = node.bottom = 0;
} else {
node = new Node();
nodesCache[currentInCache] = node;
}
++currentInCache;
return node;
}
function update(sourceBody, gravity, theta, pull) {
var queue = updateQueue,
v = void 0,
dx = void 0,
dy = void 0,
r = void 0,
fx = 0,
fy = 0,
queueLength = 1,
shiftIdx = 0,
pushIdx = 1;
queue[0] = root;
resetVec(sourceBody.force);
var px = -sourceBody.pos.x;
var py = -sourceBody.pos.y;
var pr = Math.sqrt(px * px + py * py);
var pv = sourceBody.mass * pull / pr;
fx += pv * px;
fy += pv * py;
while (queueLength) {
var node = queue[shiftIdx],
body = node.body;
queueLength -= 1;
shiftIdx += 1;
var differentBody = body !== sourceBody;
if (body && differentBody) {
// If the current node is a leaf node (and it is not source body),
// calculate the force exerted by the current node on body, and add this
// amount to body's net force.
dx = body.pos.x - sourceBody.pos.x;
dy = body.pos.y - sourceBody.pos.y;
r = Math.sqrt(dx * dx + dy * dy);
if (r === 0) {
// Poor man's protection against zero distance.
dx = (Math.random() - 0.5) / 50;
dy = (Math.random() - 0.5) / 50;
r = Math.sqrt(dx * dx + dy * dy);
}
// This is standard gravition force calculation but we divide
// by r^3 to save two operations when normalizing force vector.
v = gravity * body.mass * sourceBody.mass / (r * r * r);
fx += v * dx;
fy += v * dy;
} else if (differentBody) {
// Otherwise, calculate the ratio s / r, where s is the width of the region
// represented by the internal node, and r is the distance between the body
// and the node's center-of-mass
dx = node.massX / node.mass - sourceBody.pos.x;
dy = node.massY / node.mass - sourceBody.pos.y;
r = Math.sqrt(dx * dx + dy * dy);
if (r === 0) {
// Sorry about code duplucation. I don't want to create many functions
// right away. Just want to see performance first.
dx = (Math.random() - 0.5) / 50;
dy = (Math.random() - 0.5) / 50;
r = Math.sqrt(dx * dx + dy * dy);
}
// If s / r < θ, treat this internal node as a single body, and calculate the
// force it exerts on sourceBody, and add this amount to sourceBody's net force.
if ((node.right - node.left) / r < theta) {
// in the if statement above we consider node's width only
// because the region was squarified during tree creation.
// Thus there is no difference between using width or height.
v = gravity * node.mass * sourceBody.mass / (r * r * r);
fx += v * dx;
fy += v * dy;
} else {
// Otherwise, run the procedure recursively on each of the current node's children.
// I intentionally unfolded this loop, to save several CPU cycles.
if (node.quad0) {
queue[pushIdx] = node.quad0;
queueLength += 1;
pushIdx += 1;
}
if (node.quad1) {
queue[pushIdx] = node.quad1;
queueLength += 1;
pushIdx += 1;
}
if (node.quad2) {
queue[pushIdx] = node.quad2;
queueLength += 1;
pushIdx += 1;
}
if (node.quad3) {
queue[pushIdx] = node.quad3;
queueLength += 1;
pushIdx += 1;
}
}
}
}
sourceBody.force.x += fx;
sourceBody.force.y += fy;
}
function insertBodies(bodies) {
if (bodies.length === 0) {
return;
}
var x1 = Number.MAX_VALUE,
y1 = Number.MAX_VALUE,
x2 = Number.MIN_VALUE,
y2 = Number.MIN_VALUE,
i = void 0,
max = bodies.length;
// To reduce quad tree depth we are looking for exact bounding box of all particles.
i = max;
while (i--) {
var x = bodies[i].pos.x;
var y = bodies[i].pos.y;
if (x < x1) {
x1 = x;
}
if (x > x2) {
x2 = x;
}
if (y < y1) {
y1 = y;
}
if (y > y2) {
y2 = y;
}
}
// Squarify the bounds.
var dx = x2 - x1,
dy = y2 - y1;
if (dx > dy) {
y2 = y1 + dx;
} else {
x2 = x1 + dy;
}
currentInCache = 0;
root = newNode();
root.left = x1;
root.right = x2;
root.top = y1;
root.bottom = y2;
i = max - 1;
if (i >= 0) {
root.body = bodies[i];
}
while (i--) {
insert(bodies[i], root);
}
}
function insert(newBody) {
insertStack.reset();
insertStack.push(root, newBody);
while (!insertStack.isEmpty()) {
var stackItem = insertStack.pop(),
node = stackItem.node,
body = stackItem.body;
if (!node.body) {
// This is internal node. Update the total mass of the node and center-of-mass.
var x = body.pos.x;
var y = body.pos.y;
node.mass = node.mass + body.mass;
node.massX = node.massX + body.mass * x;
node.massY = node.massY + body.mass * y;
// Recursively insert the body in the appropriate quadrant.
// But first find the appropriate quadrant.
var quadIdx = 0,
// Assume we are in the 0's quad.
left = node.left,
right = (node.right + left) / 2,
top = node.top,
bottom = (node.bottom + top) / 2;
if (x > right) {
// somewhere in the eastern part.
quadIdx = quadIdx + 1;
left = right;
right = node.right;
}
if (y > bottom) {
// and in south.
quadIdx = quadIdx + 2;
top = bottom;
bottom = node.bottom;
}
var child = getChild(node, quadIdx);
if (!child) {
// The node is internal but this quadrant is not taken. Add
// subnode to it.
child = newNode();
child.left = left;
child.top = top;
child.right = right;
child.bottom = bottom;
child.body = body;
setChild(node, quadIdx, child);
} else {
// continue searching in this quadrant.
insertStack.push(child, body);
}
} else {
// We are trying to add to the leaf node.
// We have to convert current leaf into internal node
// and continue adding two nodes.
var oldBody = node.body;
node.body = null; // internal nodes do not cary bodies
if (isSamePosition(oldBody.pos, body.pos)) {
// Prevent infinite subdivision by bumping one node
// anywhere in this quadrant
var retriesCount = 3;
do {
var offset = Math.random();
var dx = (node.right - node.left) * offset;
var dy = (node.bottom - node.top) * offset;
oldBody.pos.x = node.left + dx;
oldBody.pos.y = node.top + dy;
retriesCount -= 1;
// Make sure we don't bump it out of the box. If we do, next iteration should fix it
} while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));
if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {
// This is very bad, we ran out of precision.
// if we do not return from the method we'll get into
// infinite loop here. So we sacrifice correctness of layout, and keep the app running
// Next layout iteration should get larger bounding box in the first step and fix this
return;
}
}
// Next iteration should subdivide node further.
insertStack.push(node, oldBody);
insertStack.push(node, body);
}
}
}
return {
insertBodies: insertBodies,
updateBodyForce: update
};
}
function getChild(node, idx) {
if (idx === 0) return node.quad0;
if (idx === 1) return node.quad1;
if (idx === 2) return node.quad2;
if (idx === 3) return node.quad3;
return null;
}
function setChild(node, idx, child) {
if (idx === 0) node.quad0 = child;else if (idx === 1) node.quad1 = child;else if (idx === 2) node.quad2 = child;else if (idx === 3) node.quad3 = child;
}
module.exports = { makeQuadtree: makeQuadtree };
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = InsertStack;
/**
* Our implmentation of QuadTree is non-recursive to avoid GC hit
* This data structure represent stack of elements
* which we are trying to insert into quad tree.
*/
function InsertStack() {
this.stack = [];
this.popIdx = 0;
}
InsertStack.prototype = {
isEmpty: function isEmpty() {
return this.popIdx === 0;
},
push: function push(node, body) {
var item = this.stack[this.popIdx];
if (!item) {
// we are trying to avoid memory pressue: create new element
// only when absolutely necessary
this.stack[this.popIdx] = new InsertStackElement(node, body);
} else {
item.node = node;
item.body = body;
}
++this.popIdx;
},
pop: function pop() {
if (this.popIdx > 0) {
return this.stack[--this.popIdx];
}
},
reset: function reset() {
this.popIdx = 0;
}
};
function InsertStackElement(node, body) {
this.node = node; // QuadTree node
this.body = body; // physical body which needs to be inserted to node
}
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Internal data structure to represent 2D QuadTree node
*/
module.exports = function Node() {
// body stored inside this node. In quad tree only leaf nodes (by construction)
// contain boides:
this.body = null;
// Child nodes are stored in quads. Each quad is presented by number:
// 0 | 1
// -----
// 2 | 3
this.quad0 = null;
this.quad1 = null;
this.quad2 = null;
this.quad3 = null;
// Total mass of current node
this.mass = 0;
// Center of mass coordinates
this.massX = 0;
this.massY = 0;
// bounding box coordinates
this.left = 0;
this.top = 0;
this.bottom = 0;
this.right = 0;
};
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _require = __webpack_require__(6),
integrate = _require.integrate;
var _require2 = __webpack_require__(5),
applyDrag = _require2.applyDrag;
var _require3 = __webpack_require__(1),
applySpring = _require3.applySpring;
function tick(_ref) {
var bodies = _ref.bodies,
springs = _ref.springs,
quadtree = _ref.quadtree,
timeStep = _ref.timeStep,
gravity = _ref.gravity,
theta = _ref.theta,
dragCoeff = _ref.dragCoeff,
pull = _ref.pull;
// update body from scratch in case of any changes
bodies.forEach(function (body) {
var p = body._scratch;
if (!p) {
return;
}
body.locked = p.locked;
body.grabbed = p.grabbed;
body.pos.x = p.x;
body.pos.y = p.y;
});
quadtree.insertBodies(bodies);
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
quadtree.updateBodyForce(body, gravity, theta, pull);
applyDrag(body, dragCoeff);
}
for (var _i = 0; _i < springs.length; _i++) {
var spring = springs[_i];
applySpring(spring);
}
var movement = integrate(bodies, timeStep);
// update scratch positions from body positions
bodies.forEach(function (body) {
var p = body._scratch;
if (!p) {
return;
}
p.x = body.pos.x;
p.y = body.pos.y;
});
return movement;
}
module.exports = { tick: tick };