Skip to content
This repository has been archived by the owner on Dec 2, 2023. It is now read-only.

Commit

Permalink
perf: simplify long lists of points
Browse files Browse the repository at this point in the history
  • Loading branch information
adil192 committed Oct 28, 2023
1 parent d9defb8 commit 55ebb75
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/src/detect_shape.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,19 @@ import 'package:interactive_shape_recognition/src/shape.dart';
import 'package:interactive_shape_recognition/src/utils.dart';

/// Detects the shape of the given [points].
///
/// If [points] has more than [simplifyTo] points,
/// it will be simplified to [simplifyTo] points
/// to improve performance.
/// You can disable this by setting [simplifyTo] to `null`.
///
/// Returns a [DetectedShape] object with the detected shape
/// ([DetectedShape.shape]) and some other information.
DetectedShape detectShape(List<Offset> points) {
DetectedShape detectShape(List<Offset> points, {int? simplifyTo = 500}) {
if (simplifyTo != null && points.length > simplifyTo) {
points = simplify(points, simplifyTo);
}

final hull = convexHull(
points,
x: (Offset p) => p.dx,
Expand Down
20 changes: 20 additions & 0 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,26 @@ import 'dart:ui';

import 'package:area_polygon/area_polygon.dart';

List<Offset> simplify(List<Offset> points, int targetLength) {
if (points.length <= targetLength) {
return points;
}

final increment = points.length / targetLength;

final simplified = <Offset>[];
for (int i = 0; i < targetLength; i++) {
final index = (i * increment).round();
simplified.add(points[index]);
}

if (simplified.last != points.last) {
simplified.add(points.last);
}

return simplified;
}

double calcPerimeter(List<Offset> points) {
double perimeter = 0;
for (int i = 0; i < points.length - 1; i++) {
Expand Down

0 comments on commit 55ebb75

Please sign in to comment.