From 4243cc0f9c27955b62caf15834f11ff8d0e16eeb Mon Sep 17 00:00:00 2001 From: Pitchaya Boonsarngsuk <2285135b@student.gla.ac.uk> Date: Tue, 6 Feb 2018 13:19:39 +0000 Subject: [PATCH] Link force add end condition --- .../js/src/example-papaparsing/linkForce.js | 4 ++- src/link.js | 34 ++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/examples/js/src/example-papaparsing/linkForce.js b/examples/js/src/example-papaparsing/linkForce.js index be3835f..5df2a64 100644 --- a/examples/js/src/example-papaparsing/linkForce.js +++ b/examples/js/src/example-papaparsing/linkForce.js @@ -14,7 +14,9 @@ function startLinkSimulation() { force = d3.forceLinkFullyConnected() .distance(function (n, m) { return distanceFunction(n, m, props, norm); - }); + }) + .stableVelocity(0.000001) //TODO + .onStableVelo(ended); } else { for (i = nodes.length-1; i >= 1; i--) { diff --git a/src/link.js b/src/link.js index 5c41dc7..5773c82 100644 --- a/src/link.js +++ b/src/link.js @@ -13,11 +13,22 @@ export default function() { distance = constant(30), distances = [], nodes, + stableVelocity = 0, + stableVeloHandler = null, iterations = 1; function force(alpha) { + let n = nodes.length; + // Cache old velocity for comparison later + if (stableVeloHandler!==null && stableVelocity>=0) { + for (let i = n-1, node; i>=0; i--) { + node = nodes[i]; + node.oldvx = node.vx; + node.oldvy = node.vy; + } + } // Each iteration in a tick - for (var k = 0, n = nodes.length, source, target, i, j, x, y, l; k < iterations; ++k) { + for (var k = 0, source, target, i, j, x, y, l; k < iterations; ++k) { // For each link for (i = 1; i < n; i++) for (j = 0; j < i; j++) { // jiggle so l won't be zero and divide by zero error after this @@ -34,6 +45,20 @@ export default function() { source.vy += y; } } + + // Calculate velocity changes, aka force applied. + if (stableVeloHandler!==null && stableVelocity>=0) { + let velocityDiff = 0; + for (let i = n-1, node; i>=0; i--) { + node = nodes[i]; + velocityDiff += Math.abs(Math.hypot(node.vx-node.oldvx, node.vy-node.oldvy)); + } + velocityDiff /= n*(n-1); + + if(velocityDiff