Files: 4811bd9f673ac20d7ecf3d72f06c219cef743535 / midpoint.js
1504 bytesRaw
1 | var Cardinal = require('cardinal-spline-js') |
2 | |
3 | function midpointY (a, b, y) { |
4 | if(y < a[1] || y > b[1]) throw new Error('out of bounds in y axis') |
5 | var _y = b[1] - a[1] |
6 | var m = _y/(y-a[1]) |
7 | return [a[0] + (b[0]-a[0])/m, y] |
8 | } |
9 | |
10 | function midpointX (a, b, x) { |
11 | if(x < a[0] || x > b[0]) throw new Error('out of bounds in x axis') |
12 | var _x = b[0] - a[0] |
13 | var m = _x/(y-a[0]) |
14 | return [x, a[1] + (b[1]-a[1])/m] |
15 | } |
16 | |
17 | exports.midpointX = midpointX |
18 | exports.midpointY = midpointY |
19 | |
20 | function snap (points, size, dimension) { |
21 | dimension = 1 |
22 | var output = [], max = points[0][dimension] |
23 | for(var i = 1; i < points.length; i ++) |
24 | while(max <= points[i][dimension]) { |
25 | output.push(midpointY(points[i-1], points[i], max)) |
26 | max += size |
27 | } |
28 | |
29 | return output |
30 | } |
31 | |
32 | exports.snapY = snap |
33 | |
34 | function smooth2D (points, tension, sides) { |
35 | tension = tension || 0.5 |
36 | sides = sides || 5 |
37 | var p = Cardinal.getCurvePoints(points.reduce(function (a, b) { |
38 | return a.concat(b) |
39 | }), tension, sides) |
40 | |
41 | var o = [] |
42 | for(var i = 0; i < p.length; i+=2) |
43 | o.push([p[i],p[i+1]]) |
44 | |
45 | return o |
46 | } |
47 | |
48 | var m = require('./midpoint') |
49 | |
50 | function smooth (points, step, tension) { |
51 | step = step || 1 |
52 | var smoothX = m.snapY(smooth2D(points.map(function (e) { |
53 | return [e[0],e[1]] |
54 | }), tension, 10), step) |
55 | var smoothZ = m.snapY(smooth2D(points.map(function (e) { |
56 | return [e[2],e[1]] |
57 | }), tension, 10), step) |
58 | |
59 | return smoothX.map(function (e, i) { |
60 | return [e[0],e[1], smoothZ[i][0]] |
61 | }) |
62 | } |
63 | |
64 | exports.smooth = smooth |
65 |
Built with git-ssb-web