packCirclesInCircle function

List<Offset> packCirclesInCircle({
  1. required int count,
  2. required double containerRadius,
  3. required double bodyRadius,
})

在圆内从底部六边形密排 count 个圆,坐标以容器圆心为原点。

放不下时等比压缩间距;非正数量返回空列表,物体大于容器时放在原点。 例如 packCirclesInCircle(count: 3, containerRadius: 50, bodyRadius: 5)。

Implementation

List<Offset> packCirclesInCircle(
    {required int count,
    required double containerRadius,
    required double bodyRadius}) {
  if (count <= 0) return const [];
  final limit = math.max(0.0, containerRadius - bodyRadius);
  if (limit == 0 || bodyRadius <= 0) return List.filled(count, Offset.zero);
  final points = <Offset>[];
  var spacing = bodyRadius * kLuckyHalfDivisor;
  while (points.length < count) {
    points.clear();
    final rowHeight = spacing * math.sqrt(3) / kLuckyHalfDivisor;
    var row = 0;
    for (var y = limit; y >= -limit && points.length < count; y -= rowHeight) {
      final halfWidth = math.sqrt(math.max(0, limit * limit - y * y));
      final shift = row.isOdd ? spacing / kLuckyHalfDivisor : 0.0;
      for (var column = ((-halfWidth - shift) / spacing).ceil();
          column * spacing + shift <= halfWidth && points.length < count;
          column++) {
        points.add(Offset(column * spacing + shift, y));
      }
      row++;
    }
    if (points.length < count) {
      // 底部单点网格装不下时先尝试圆环和居中六角网格,再压缩间距。
      if (count > 1 && limit * math.sin(math.pi / count) >= bodyRadius) {
        return List.unmodifiable(List.generate(count, (i) {
          final angle = kLuckyHalfDivisor * math.pi * i / count;
          return Offset(limit * math.sin(angle), limit * math.cos(angle));
        }));
      }
      points.clear();
      final rows = (limit / rowHeight).floor();
      for (var row = rows; row >= -rows && points.length < count; row--) {
        final y = row * rowHeight;
        final halfWidth = math.sqrt(math.max(0, limit * limit - y * y));
        final shift = row.isOdd ? spacing / kLuckyHalfDivisor : 0.0;
        for (var col = ((-halfWidth - shift) / spacing).ceil();
            col * spacing + shift <= halfWidth && points.length < count;
            col++) {
          points.add(Offset(col * spacing + shift, y));
        }
      }
    }
    spacing *= _speedRange;
  }
  return List.unmodifiable(points);
}