normalizeCurve method

List<Vec2D> normalizeCurve(
  1. List<Vec2D> curve,
  2. int numSegments
)

Implementation

List<Vec2D> normalizeCurve(List<Vec2D> curve, int numSegments) {
  List<Vec2D> points = <Vec2D>[];
  int curvePointCount = curve.length;
  List<double> distances = List<double>.filled(curvePointCount, 0.0);
  for (int i = 0; i < curvePointCount - 1; i++) {
    Vec2D p1 = curve[i];
    Vec2D p2 = curve[i + 1];
    distances[i + 1] = distances[i] + Vec2D.distance(p1, p2);
  }
  double totalDistance = distances.last;

  double segmentLength = totalDistance / numSegments;
  int pointIndex = 1;
  for (int i = 1; i <= numSegments; i++) {
    double distance = segmentLength * i;

    while (pointIndex < curvePointCount - 1 &&
        distances[pointIndex] < distance) {
      pointIndex++;
    }

    double d = distances[pointIndex];
    double lastCurveSegmentLength = d - distances[pointIndex - 1];
    double remainderOfDesired = d - distance;
    double ratio = remainderOfDesired / lastCurveSegmentLength;
    double iratio = 1.0 - ratio;

    Vec2D p1 = curve[pointIndex - 1];
    Vec2D p2 = curve[pointIndex];
    points.add(Vec2D.fromValues(
        p1[0] * ratio + p2[0] * iratio, p1[1] * ratio + p2[1] * iratio));
  }

  return points;
}