drawConnections method
Draws connection lines between particles within the specified distance
Algorithm Overview:
- Iterates through each grid cell and its particles
- Checks particles against others in the same cell
- Uses distance to determine line opacity (closer = more opaque)
- Draws lines with distance-based alpha blending
Mathematical Formulas:
- Distance: d = √(Δx² + Δy²) (handled by DistanceCalculator)
- Opacity: α = 255 * (1 - d/d_max) * fursOpacity where fursOpacity is a constant (currently 1)
Performance Characteristics: Time Complexity: O(n * k²) where: n = number of grid cells k = average particles per cell (typically small due to spatial partitioning)
Implementation
void drawConnections(Canvas canvas, Map<GridCell, List<int>> grid) {
// Tracks processed particle pairs to avoid duplicate drawing
final Set<int> processed = <int>{};
final int factor = isComplex ? 2 : 1;
final int adjustedParticleCountBase = particleCount ~/ factor;
// Process each grid cell
grid.forEach((_, particleIndices) {
// Compare each particle with others in the same cell
for (int i = 0; i < particleIndices.length; i++) {
final int pIndex = particleIndices[i];
final Particle p = particles[pIndex];
// Only check particles after current to avoid duplicate pairs
for (int j = i + 1; j < particleIndices.length; j++) {
final int otherIndex = particleIndices[j];
// Create unique pair key regardless of order
final int pairKey = pIndex * adjustedParticleCountBase + otherIndex;
// Skip if already processed
if (!processed.add(pairKey)) continue;
final Particle other = particles[otherIndex];
// Get distance (uses cached value if available)
final double distance = distanceCalculator.betweenParticles(p, other);
// Constant for opacity scaling (currently 1 = full effect)
const double fursOpacity = 1;
// Only connect if within maximum distance
if (distance < lineDistance) {
// Calculate opacity based on normalized distance (0 to 1)
// Then scale by fursOpacity and convert to 0-255 range
final int opacity =
((1 - distance / lineDistance) * fursOpacity * 255).toInt();
// Update paint with new alpha value
linePaint.color = lineColor.withAlpha(opacity.clamp(0, 255));
// Draw the connection line
canvas.drawLine(p.position, other.position, linePaint);
}
}
}
});
}