Skip to content

Commit fb4b690

Browse files
committed
refactor contour/plot for smaller functions
- so we might be able to reuse them for contourcarpet - and test getVisibleSegment
1 parent 4db549c commit fb4b690

File tree

4 files changed

+325
-169
lines changed

4 files changed

+325
-169
lines changed

src/lib/geometry2d.js

+25-6
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,17 @@ exports.clearLocationCache = function() {
126126
* given by `bounds` {left, right, top, bottom}, to within a
127127
* precision of `buffer` px
128128
*
129-
* returns {
129+
* returns: undefined if nothing is visible, else object:
130+
* {
130131
* min: position where the path first enters bounds, or 0 if it
131132
* starts within bounds
132133
* max: position where the path last exits bounds, or the path length
133134
* if it finishes within bounds
135+
* len: max - min, ie the length of visible path
134136
* total: the total path length - just included so the caller doesn't
135137
* need to call path.getTotalLength() again
138+
* isClosed: true iff the start and end points of the path are both visible
139+
* and are at the same point
136140
* }
137141
*
138142
* Works by starting from either end and repeatedly finding the distance from
@@ -147,17 +151,24 @@ exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
147151
var top = bounds.top;
148152
var bottom = bounds.bottom;
149153

154+
var pMin = 0;
155+
var pTotal = path.getTotalLength();
156+
var pMax = pTotal;
157+
158+
var pt0, ptTotal;
159+
150160
function getDistToPlot(len) {
151161
var pt = path.getPointAtLength(len);
162+
163+
// hold on to the start and end points for `closed`
164+
if(len === 0) pt0 = pt;
165+
else if(len === pTotal) ptTotal = pt;
166+
152167
var dx = (pt.x < left) ? left - pt.x : (pt.x > right ? pt.x - right : 0);
153168
var dy = (pt.y < top) ? top - pt.y : (pt.y > bottom ? pt.y - bottom : 0);
154169
return Math.sqrt(dx * dx + dy * dy);
155170
}
156171

157-
var pMin = 0;
158-
var pTotal = path.getTotalLength();
159-
var pMax = pTotal;
160-
161172
var distToPlot = getDistToPlot(pMin);
162173
while(distToPlot) {
163174
pMin += distToPlot + buffer;
@@ -172,5 +183,13 @@ exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
172183
distToPlot = getDistToPlot(pMax);
173184
}
174185

175-
return {min: pMin, max: pMax, total: pTotal};
186+
return {
187+
min: pMin,
188+
max: pMax,
189+
len: pMax - pMin,
190+
total: pTotal,
191+
isClosed: pMin === 0 && pMax === pTotal &&
192+
Math.abs(pt0.x - ptTotal.x) < 0.1 &&
193+
Math.abs(pt0.y - ptTotal.y) < 0.1
194+
};
176195
};

0 commit comments

Comments
 (0)