# 2D 碎形／Sierpinski 三角形

March 13, 2022

## 從三角形開始

``````use <turtle/t2d.scad>

module triangle(t, leng, width) {
module line(t1, t2, width) {
polyline_join([t2d(t1, "point"), t2d(t2, "point")])
circle(width / 2);
}

commands = [["forward", leng], ["turn", 120]];
t1 = t2d(t, commands);
line(t, t1, width);

t2 = t2d(t1, commands);
line(t1, t2, width);

t3 = t2d(t2, commands);
line(t2, t3, width);
}

leng = 100;
width = 1;

t = t2d();
triangle(t, leng, width);
``````

## 三個相疊的三角形

``````use <turtle/t2d.scad>

module triangle(t, leng, width) {
module line(t1, t2, width) {
polyline_join([t2d(t1, "point"), t2d(t2, "point")])
circle(width / 2);
}

commands = [["forward", leng], ["turn", 120]];
t1 = t2d(t, commands);
line(t, t1, width);

t2 = t2d(t1, commands);
line(t1, t2, width);

t3 = t2d(t2, commands);
line(t2, t3, width);
}

leng = 100;
width = 1;

t = t2d();
triangle(t, leng, width);

t2 = t2d(t, "forward", leng = leng);
triangle(t2, leng, width);

t3 = t2d(t, [["turn", 60], ["forward", leng], ["turn", -60]]);
triangle(t3, leng, width);
``````

## 遞迴的三個三角形

``````module three_triangles(t, leng, width) {
half_leng = leng / 2;

triangle(t, half_leng, width);

t2 = t2d(t, "forward", leng = half_leng);
triangle(t2, half_leng, width);

t3 = t2d(t, [["turn", 60], ["forward", half_leng], ["turn", -60]]);
triangle(t3, half_leng, width);
}
``````

``````module sierpinski_triangle(t, leng, width) {
if(leng > width * 7) {
half_leng = leng / 2;

sierpinski_triangle(t, half_leng, width);

t2 = t2d(t, "forward", leng = half_leng);
sierpinski_triangle(t2, half_leng, width);

t3 = t2d(t, [["turn", 60], ["forward", half_leng], ["turn", -60]]);
sierpinski_triangle(t3, half_leng, width);
}
else {
// 遞迴終止，繪製三個小三角形
three_triangles(t, leng, width);
}
}
``````

``````use <turtle/t2d.scad>

leng = 100;
width = 1;

module triangle(t, leng, width) {
module line(t1, t2, width) {
polyline_join([t2d(t1, "point"), t2d(t2, "point")])
circle(width / 2);
}

commands = [["forward", leng], ["turn", 120]];
t1 = t2d(t, commands);
line(t, t1, width);

t2 = t2d(t1, commands);
line(t1, t2, width);

t3 = t2d(t2, commands);
line(t2, t3, width);
}

module three_triangles(t, leng, width) {
half_leng = leng / 2;

triangle(t, half_leng, width);

t2 = t2d(t, "forward", leng = half_leng);
triangle(t2, half_leng, width);

t3 = t2d(t, [["turn", 60], ["forward", half_leng], ["turn", -60]]);
triangle(t3, half_leng, width);
}

module sierpinski_triangle(t, leng, width) {
if(leng > width * 7) {
half_leng = leng / 2;

sierpinski_triangle(t, half_leng, width);

t2 = t2d(t, "forward", leng = half_leng);
sierpinski_triangle(t2, half_leng, width);

t3 = t2d(t, [["turn", 60], ["forward", half_leng], ["turn", -60]]);
sierpinski_triangle(t3, half_leng, width);
}
else {
three_triangles(t, leng, width);
}
}

sierpinski_triangle(t2d(), leng, width);
``````