tree function
Branching lightning path from (x0, y0) to (x1, y1).
Implementation
List<BoltBranch> tree(
Rng r,
double x0,
double y0,
double x1,
double y1, [
double jag = 0.3,
double forks = 0.4,
double w = 1.0,
int depth = 0,
]) {
final out = <BoltBranch>[];
final l = math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
var pts = <(double, double)>[(x0, y0), (x1, y1)];
var off = l * jag;
while (pts.length < 2.0 + l / 3.0) {
final nxt = <(double, double)>[pts[0]];
for (var i = 0; i < pts.length - 1; i++) {
final (ax, ay) = pts[i];
final (bx, by) = pts[i + 1];
final segLen = math.sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
final len = segLen == 0.0 ? 1.0 : segLen;
final o = r.range(-off, off);
nxt.add((
(ax + bx) / 2.0 + (-(by - ay) / len) * o,
(ay + by) / 2.0 + ((bx - ax) / len) * o,
));
nxt.add((bx, by));
}
pts = nxt;
off *= 0.52;
}
out.add(BoltBranch(pts, w, depth));
if (depth < 2) {
for (var i = 2; i < pts.length - 3; i++) {
if (r.chance(forks / (1 + depth) / math.max(4.0, pts.length / 6.0))) {
final (ax, ay) = pts[i];
final (bx, by) = pts[math.min(pts.length - 1, i + 3)];
final a = math.atan2(by - ay, bx - ax) + r.sign() * r.range(0.35, 0.95);
final fl = (l - (i / pts.length) * l) * r.range(0.25, 0.55);
out.addAll(
tree(
r,
ax,
ay,
ax + math.cos(a) * fl,
ay + math.sin(a) * fl,
jag * 1.1,
forks,
w * 0.55,
depth + 1,
),
);
}
}
}
return out;
}