Skip to content

Commit

Permalink
fix(Geometry): prevent rounding errors in simplify() of Polyline (#2371)
Browse files Browse the repository at this point in the history
  • Loading branch information
kumilingus authored Oct 19, 2023
1 parent 4684a9a commit 70a8631
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
2 changes: 1 addition & 1 deletion docs/src/geometry/api/g/Polyline/prototype/simplify.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

<p>This function modifies the original polyline and returns self. If the polyline has fewer than 3 points, the polyline is not modified.</p>

<p>By default, a point is considered non-essential only if it lies directly on the connection line between the previous and the following point. You can specify a tolerance range by providing a <code>threshold</code> value within the <code>opt</code> object. Polyline points that are closer to the connection line than this value (inclusive) are removed; points that are farther from the connection line (exclusive) are kept.</p>
<p>By default, a point is considered non-essential only if it lies directly on the connection line between the previous and the following point. You can specify a tolerance range by providing a <code>threshold</code> value within the <code>opt</code> object (the default is <code>1e-10</code>). Polyline points that are closer to the connection line than this value (inclusive) are removed; points that are farther from the connection line (exclusive) are kept.</p>
5 changes: 4 additions & 1 deletion src/g/polyline.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,10 @@ Polyline.prototype = {
if (points.length < 3) return this; // we need at least 3 points

// TODO: we may also accept startIndex and endIndex to specify where to start and end simplification
const threshold = opt.threshold || 0; // = max distance of middle point from chord to be simplified

// Due to the nature of the algorithm, we do not use 0 as the default value for `threshold`
// because of the rounding errors that can occur when comparing distances.
const threshold = opt.threshold || 1e-10; // = max distance of middle point from chord to be simplified

// start at the beginning of the polyline and go forward
let currentIndex = 0;
Expand Down
2 changes: 2 additions & 0 deletions test/geometry/polyline.js
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,8 @@ QUnit.module('polyline', function() {
assert.equal((new g.Polyline(['10 0'])).simplify().serialize(), '10,0');
assert.equal((new g.Polyline('10,0')).simplify().serialize(), '10,0');

assert.equal((new g.Polyline(['210 740', '250 740', '570 740'])).simplify().serialize(), '210,740 570,740');

assert.equal((new g.Polyline()).simplify().serialize(), '');
});

Expand Down

0 comments on commit 70a8631

Please sign in to comment.