1//////////////////////////////////////////////////////////////////////
   2// LibFile: shapes2d.scad
   3//   This file includes redefinitions of the core modules to
   4//   work with attachment, and functional forms of those modules
   5//   that produce paths.  You can create regular polygons
   6//   with optional rounded corners and alignment features not
   7//   available with circle().  The file also provides teardrop2d,
   8//   which is useful for 3D printable holes.  
   9//   Many of the commands have module forms that produce geometry and
  10//   function forms that produce a path. 
  11// Includes:
  12//   include <BOSL2/std.scad>
  13// FileGroup: Basic Modeling
  14// FileSummary: Attachable circles, squares, polygons, teardrop.  Can make geometry or paths.
  15// FileFootnotes: STD=Included in std.scad
  16//////////////////////////////////////////////////////////////////////
  17
  18use <builtins.scad>
  19
  20
  21// Section: 2D Primitives
  22
  23// Function&Module: square()
  24// Topics: Shapes (2D), Path Generators (2D)
  25// Usage: As a Module
  26//   square(size, [center], ...);
  27// Usage: With Attachments
  28//   square(size, [center], ...) [ATTACHMENTS];
  29// Usage: As a Function
  30//   path = square(size, [center], ...);
  31// See Also: rect()
  32// Description:
  33//   When called as the builtin module, creates a 2D square or rectangle of the given size.
  34//   When called as a function, returns a 2D path/list of points for a square/rectangle of the given size.
  35// Arguments:
  36//   size = The size of the square to create.  If given as a scalar, both X and Y will be the same size.
  37//   center = If given and true, overrides `anchor` to be `CENTER`.  If given and false, overrides `anchor` to be `FRONT+LEFT`.
  38//   ---
  39//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
  40//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
  41// Example(2D):
  42//   square(40);
  43// Example(2D): Centered
  44//   square([40,30], center=true);
  45// Example(2D): Called as Function
  46//   path = square([40,30], anchor=FRONT, spin=30);
  47//   stroke(path, closed=true);
  48//   move_copies(path) color("blue") circle(d=2,$fn=8);
  49function square(size=1, center, anchor, spin=0) =
  50    let(
  51        anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]),
  52        size = is_num(size)? [size,size] : point2d(size),
  53        path = [
  54            [ size.x,-size.y],
  55            [-size.x,-size.y],
  56            [-size.x, size.y],
  57            [ size.x, size.y]
  58        ] / 2
  59    ) reorient(anchor,spin, two_d=true, size=size, p=path);
  60
  61
  62module square(size=1, center, anchor, spin) {
  63    anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]);
  64    size = is_num(size)? [size,size] : point2d(size);
  65    attachable(anchor,spin, two_d=true, size=size) {
  66        _square(size, center=true);
  67        children();
  68    }
  69}
  70
  71
  72
  73// Function&Module: rect()
  74// Usage: As Module
  75//   rect(size, [rounding], [chamfer], ...) [ATTACHMENTS];
  76// Usage: As Function
  77//   path = rect(size, [rounding], [chamfer], ...);
  78// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
  79// See Also: square()
  80// Description:
  81//   When called as a module, creates a 2D rectangle of the given size, with optional rounding or chamfering.
  82//   When called as a function, returns a 2D path/list of points for a square/rectangle of the given size.
  83// Arguments:
  84//   size = The size of the rectangle to create.  If given as a scalar, both X and Y will be the same size.
  85//   ---
  86//   rounding = The rounding radius for the corners.  If negative, produces external roundover spikes on the X axis. If given as a list of four numbers, gives individual radii for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-]. Default: 0 (no rounding)
  87//   chamfer = The chamfer size for the corners.  If negative, produces external chamfer spikes on the X axis. If given as a list of four numbers, gives individual chamfers for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-].  Default: 0 (no chamfer)
  88//   atype = The type of anchoring to use with `anchor=`.  Valid opptions are "box" and "perim".  This lets you choose between putting anchors on the rounded or chamfered perimeter, or on the square bounding box of the shape. Default: "box"
  89//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
  90//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
  91// Anchor Types:
  92//   box = Anchor is with respect to the rectangular bounding box of the shape.
  93//   perim = Anchors are placed along the rounded or chamfered perimeter of the shape.
  94// Example(2D):
  95//   rect(40);
  96// Example(2D): Anchored
  97//   rect([40,30], anchor=FRONT);
  98// Example(2D): Spun
  99//   rect([40,30], anchor=FRONT, spin=30);
 100// Example(2D): Chamferred Rect
 101//   rect([40,30], chamfer=5);
 102// Example(2D): Rounded Rect
 103//   rect([40,30], rounding=5);
 104// Example(2D): Negative-Chamferred Rect
 105//   rect([40,30], chamfer=-5);
 106// Example(2D): Negative-Rounded Rect
 107//   rect([40,30], rounding=-5);
 108// Example(2D): Default "box" Anchors
 109//   color("red") rect([40,30]);
 110//   rect([40,30], rounding=10)
 111//       show_anchors();
 112// Example(2D): "perim" Anchors
 113//   rect([40,30], rounding=10, atype="perim")
 114//       show_anchors();
 115// Example(2D): Mixed Chamferring and Rounding
 116//   rect([40,30],rounding=[5,0,10,0],chamfer=[0,8,0,15],$fa=1,$fs=1);
 117// Example(2D): Called as Function
 118//   path = rect([40,30], chamfer=5, anchor=FRONT, spin=30);
 119//   stroke(path, closed=true);
 120//   move_copies(path) color("blue") circle(d=2,$fn=8);
 121module rect(size=1, rounding=0, atype="box", chamfer=0, anchor=CENTER, spin=0) {
 122    errchk = assert(in_list(atype, ["box", "perim"]));
 123    size = is_num(size)? [size,size] : point2d(size);
 124    if (rounding==0 && chamfer==0) {
 125        attachable(anchor, spin, two_d=true, size=size) {
 126            square(size, center=true);
 127            children();
 128        }
 129    } else {
 130        pts = rect(size=size, rounding=rounding, chamfer=chamfer);
 131        if (atype == "perim") {
 132            attachable(anchor, spin, two_d=true, path=pts) {
 133                polygon(pts);
 134                children();
 135            }
 136        } else {
 137            attachable(anchor, spin, two_d=true, size=size) {
 138                polygon(pts);
 139                children();
 140            }
 141        }
 142    }
 143}
 144
 145
 146
 147function rect(size=1, rounding=0, chamfer=0, atype="box", anchor=CENTER, spin=0) =
 148    assert(is_num(size)     || is_vector(size))
 149    assert(is_num(chamfer)  || len(chamfer)==4)
 150    assert(is_num(rounding) || len(rounding)==4)
 151    assert(in_list(atype, ["box", "perim"]))
 152    let(
 153        anchor=point2d(anchor),
 154        size = is_num(size)? [size,size] : point2d(size),
 155        complex = rounding!=0 || chamfer!=0
 156    )
 157    (rounding==0 && chamfer==0)? let(
 158        path = [
 159            [ size.x/2, -size.y/2],
 160            [-size.x/2, -size.y/2],
 161            [-size.x/2,  size.y/2],
 162            [ size.x/2,  size.y/2] 
 163        ]
 164    )
 165    rot(spin, p=move(-v_mul(anchor,size/2), p=path)) :
 166    let(
 167        chamfer = is_list(chamfer)? chamfer : [for (i=[0:3]) chamfer],
 168        rounding = is_list(rounding)? rounding : [for (i=[0:3]) rounding],
 169        quadorder = [3,2,1,0],
 170        quadpos = [[1,1],[-1,1],[-1,-1],[1,-1]],
 171        eps = 1e-9,
 172        insets = [for (i=[0:3]) abs(chamfer[i])>=eps? chamfer[i] : abs(rounding[i])>=eps? rounding[i] : 0],
 173        insets_x = max(insets[0]+insets[1],insets[2]+insets[3]),
 174        insets_y = max(insets[0]+insets[3],insets[1]+insets[2])
 175    )
 176    assert(insets_x <= size.x, "Requested roundings and/or chamfers exceed the rect width.")
 177    assert(insets_y <= size.y, "Requested roundings and/or chamfers exceed the rect height.")
 178    let(
 179        path = [
 180            for(i = [0:3])
 181            let(
 182                quad = quadorder[i],
 183                qinset = insets[quad],
 184                qpos = quadpos[quad],
 185                qchamf = chamfer[quad],
 186                qround = rounding[quad],
 187                cverts = quant(segs(abs(qinset)),4)/4,
 188                step = 90/cverts,
 189                cp = v_mul(size/2-[qinset,abs(qinset)], qpos),
 190                qpts = abs(qchamf) >= eps? [[0,abs(qinset)], [qinset,0]] :
 191                    abs(qround) >= eps? [for (j=[0:1:cverts]) let(a=90-j*step) v_mul(polar_to_xy(abs(qinset),a),[sign(qinset),1])] :
 192                    [[0,0]],
 193                qfpts = [for (p=qpts) v_mul(p,qpos)],
 194                qrpts = qpos.x*qpos.y < 0? reverse(qfpts) : qfpts
 195            )
 196            each move(cp, p=qrpts)
 197        ]
 198    ) complex && atype=="perim"?
 199        reorient(anchor,spin, two_d=true, path=path, p=path) :
 200        reorient(anchor,spin, two_d=true, size=size, p=path);
 201
 202
 203// Function&Module: circle()
 204// Topics: Shapes (2D), Path Generators (2D)
 205// Usage: As a Module
 206//   circle(r|d=, ...) [ATTACHMENTS];
 207//   circle(points=) [ATTACHMENTS];
 208//   circle(r|d=, corner=) [ATTACHMENTS];
 209// Usage: As a Function
 210//   path = circle(r|d=, ...);
 211//   path = circle(points=);
 212//   path = circle(r|d=, corner=);
 213// See Also: ellipse(), circle_2tangents(), circle_3points()
 214// Description:
 215//   When called as the builtin module, creates a 2D polygon that approximates a circle of the given size.
 216//   When called as a function, returns a 2D list of points (path) for a polygon that approximates a circle of the given size.
 217//   If `corner=` is given three 2D points, centers the circle so that it will be tangent to both segments of the path, on the inside corner.
 218//   If `points=` is given three 2D points, centers and sizes the circle so that it passes through all three points.
 219// Arguments:
 220//   r = The radius of the circle to create.
 221//   d = The diameter of the circle to create.
 222//   ---
 223//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 224//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 225// Example(2D): By Radius
 226//   circle(r=25);
 227// Example(2D): By Diameter
 228//   circle(d=50);
 229// Example(2D): Fit to Three Points
 230//   pts = [[50,25], [25,-25], [-10,0]];
 231//   circle(points=pts);
 232//   color("red") move_copies(pts) circle();
 233// Example(2D): Fit Tangent to Inside Corner of Two Segments
 234//   path = [[50,25], [-10,0], [25,-25]];
 235//   circle(corner=path, r=15);
 236//   color("red") stroke(path);
 237// Example(2D): Called as Function
 238//   path = circle(d=50, anchor=FRONT, spin=45);
 239//   stroke(path);
 240function circle(r, d, points, corner, anchor=CENTER, spin=0) =
 241    assert(is_undef(corner) || (is_path(corner,[2]) && len(corner) == 3))
 242    assert(is_undef(points) || is_undef(corner), "Cannot specify both points and corner.")
 243    let(
 244        data = is_def(points)?
 245                assert(is_path(points,[2]) && len(points) == 3)
 246                assert(is_undef(corner), "Cannot specify corner= when points= is given.")
 247                assert(is_undef(r) && is_undef(d), "Cannot specify r= or d= when points= is given.")
 248                let( c = circle_3points(points) )
 249                assert(!is_undef(c[0]), "Points cannot be collinear.")
 250                let( cp = c[0], r = c[1]  )
 251                [cp, r] :
 252            is_def(corner)?
 253                assert(is_path(corner,[2]) && len(corner) == 3)
 254                assert(is_undef(points), "Cannot specify points= when corner= is given.")
 255                let(
 256                    r = get_radius(r=r, d=d, dflt=1),
 257                    c = circle_2tangents(r=r, pt1=corner[0], pt2=corner[1], pt3=corner[2])
 258                )
 259                assert(c!=undef, "Corner path cannot be collinear.")
 260                let( cp = c[0] )
 261                [cp, r] :
 262            let(
 263                cp = [0, 0],
 264                r = get_radius(r=r, d=d, dflt=1)
 265            ) [cp, r],
 266        cp = data[0],
 267        r = data[1],
 268        sides = segs(r),
 269        path = [for (i=[0:1:sides-1]) let(a=360-i*360/sides) r*[cos(a),sin(a)]+cp]
 270    ) reorient(anchor,spin, two_d=true, r=r, p=path);
 271
 272module circle(r, d, points, corner, anchor=CENTER, spin=0) {
 273    if (is_path(points)) {
 274        c = circle_3points(points);
 275        check = assert(c!=undef && c[0] != undef, "Points must not be collinear.");
 276        cp = c[0];
 277        r = c[1];
 278        translate(cp) {
 279            attachable(anchor,spin, two_d=true, r=r) {
 280                _circle(r=r);
 281                children();
 282            }
 283        }
 284    } else if (is_path(corner)) {
 285        r = get_radius(r=r, d=d, dflt=1);
 286        c = circle_2tangents(r=r, pt1=corner[0], pt2=corner[1], pt3=corner[2]);
 287        check = assert(c != undef && c[0] != undef, "Points must not be collinear.");
 288        cp = c[0];
 289        translate(cp) {
 290            attachable(anchor,spin, two_d=true, r=r) {
 291                _circle(r=r);
 292                children();
 293            }
 294        }
 295    } else {
 296        r = get_radius(r=r, d=d, dflt=1);
 297        attachable(anchor,spin, two_d=true, r=r) {
 298            _circle(r=r);
 299            children();
 300        }
 301    }
 302}
 303
 304
 305
 306// Function&Module: ellipse()
 307// Usage: As a Module
 308//   ellipse(r|d=, [realign=], [circum=], [uniform=], ...) [ATTACHMENTS];
 309// Usage: As a Function
 310//   path = ellipse(r|d=, [realign=], [circum=], [uniform=], ...);
 311// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
 312// See Also: circle(), circle_2tangents(), circle_3points()
 313// Description:
 314//   When called as a module, creates a 2D polygon that approximates a circle or ellipse of the given size.
 315//   When called as a function, returns a 2D list of points (path) for a polygon that approximates a circle or ellipse of the given size.
 316//   By default the point list or shape is the same as the one you would get by scaling the output of {{circle()}}, but with this module your
 317//   attachments to the ellipse will retain their dimensions, whereas scaling a circle with attachments will also scale the attachments.
 318//   If you set `uniform` to true then you will get a polygon with congruent sides whose vertices lie on the ellipse.  The `circum` option
 319//   requests a polygon that circumscribes the requested ellipse (so the specified ellipse will fit into the resulting polygon).  Note that
 320//   you cannot gives `circum=true` and `uniform=true`.  
 321// Arguments:
 322//   r = Radius of the circle or pair of semiaxes of ellipse 
 323//   ---
 324//   d = Diameter of the circle or a pair giving the full X and Y axis lengths.  
 325//   realign = If false starts the approximate ellipse with a point on the X+ axis.  If true the midpoint of a side is on the X+ axis and the first point of the polygon is below the X+ axis.  This can result in a very different polygon when $fn is small.  Default: false
 326//   uniform = If true, the polygon that approximates the circle will have segments of equal length.  Only works if `circum=false`.  Default: false
 327//   circum = If true, the polygon that approximates the circle will be upsized slightly to circumscribe the theoretical circle.  If false, it inscribes the theoretical circle.  If this is true then `uniform` must be false.  Default: false
 328//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 329//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 330// Example(2D): By Radius
 331//   ellipse(r=25);
 332// Example(2D): By Diameter
 333//   ellipse(d=50);
 334// Example(2D): Anchoring
 335//   ellipse(d=50, anchor=FRONT);
 336// Example(2D): Spin
 337//   ellipse(d=50, anchor=FRONT, spin=45);
 338// Example(NORENDER): Called as Function
 339//   path = ellipse(d=50, anchor=FRONT, spin=45);
 340// Example(2D,NoAxes): Uniformly sampled hexagon at the top, regular non-uniform one at the bottom
 341//   r=[10,3];
 342//   ydistribute(7){
 343//     union(){
 344//       stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
 345//       stroke([ellipse(r=r, $fn=6)],width=0.1,color="red");
 346//     }
 347//     union(){
 348//       stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
 349//       stroke([ellipse(r=r, $fn=6,uniform=true)],width=0.1,color="red");
 350//     }
 351//   }
 352// Example(2D): The realigned hexagons are even more different
 353//   r=[10,3];
 354//   ydistribute(7){
 355//     union(){
 356//       stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
 357//       stroke([ellipse(r=r, $fn=6,realign=true)],width=0.1,color="red");
 358//     }
 359//     union(){
 360//       stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
 361//       stroke([ellipse(r=r, $fn=6,realign=true,uniform=true)],width=0.1,color="red");
 362//     }
 363//   }
 364// Example(2D): For odd $fn the result may not look very elliptical:
 365//    r=[10,3];
 366//    ydistribute(7){
 367//      union(){
 368//        stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
 369//        stroke([ellipse(r=r, $fn=5,realign=false)],width=0.1,color="red");
 370//      }
 371//      union(){
 372//        stroke([ellipse(r=r, $fn=100)],width=0.05,color="blue");
 373//        stroke([ellipse(r=r, $fn=5,realign=false,uniform=true)],width=0.1,color="red");
 374//      }
 375//    }
 376// Example(2D): The same ellipse, turned 90 deg, gives a very different result:
 377//   r=[3,10];
 378//   xdistribute(7){
 379//     union(){
 380//       stroke([ellipse(r=r, $fn=100)],width=0.1,color="blue");
 381//       stroke([ellipse(r=r, $fn=5,realign=false)],width=0.2,color="red");
 382//     }
 383//     union(){
 384//       stroke([ellipse(r=r, $fn=100)],width=0.1,color="blue");
 385//       stroke([ellipse(r=r, $fn=5,realign=false,uniform=true)],width=0.2,color="red");
 386//     }
 387//   }
 388module ellipse(r, d, realign=false, circum=false, uniform=false, anchor=CENTER, spin=0)
 389{
 390    r = force_list(get_radius(r=r, d=d, dflt=1),2);
 391    dummy = assert(is_vector(r,2) && all_positive(r), "Invalid radius or diameter for ellipse");
 392    sides = segs(max(r));
 393    sc = circum? (1 / cos(180/sides)) : 1;
 394    rx = r.x * sc;
 395    ry = r.y * sc;
 396    attachable(anchor,spin, two_d=true, r=[rx,ry]) {
 397        if (uniform) {
 398            check = assert(!circum, "Circum option not allowed when \"uniform\" is true");
 399            polygon(ellipse(r,realign=realign, circum=circum, uniform=true));
 400        }
 401        else if (rx < ry) {
 402            xscale(rx/ry) {
 403                zrot(realign? 180/sides : 0) {
 404                    circle(r=ry, $fn=sides);
 405                }
 406            }
 407        } else {
 408            yscale(ry/rx) {
 409                zrot(realign? 180/sides : 0) {
 410                    circle(r=rx, $fn=sides);
 411                }
 412            }
 413        }
 414        children();
 415    }
 416}
 417
 418
 419// Iterative refinement to produce an inscribed polygon
 420// in an ellipse whose side lengths are all equal
 421function _ellipse_refine(a,b,N, _theta=[]) =
 422   len(_theta)==0? _ellipse_refine(a,b,N,lerpn(0,360,N,endpoint=false))
 423   :
 424   let(
 425       pts = [for(t=_theta) [a*cos(t),b*sin(t)]],
 426       lenlist= path_segment_lengths(pts,closed=true),
 427       meanlen = mean(lenlist),
 428       error = lenlist/meanlen
 429   )
 430   all_equal(error,EPSILON) ? pts
 431   :
 432   let(
 433        dtheta = [each deltas(_theta),
 434                  360-last(_theta)],
 435        newdtheta = [for(i=idx(dtheta)) dtheta[i]/error[i]],
 436        adjusted = [0,each cumsum(list_head(newdtheta / sum(newdtheta) * 360))]
 437   )
 438   _ellipse_refine(a,b,N,adjusted);
 439
 440
 441
 442
 443function _ellipse_refine_realign(a,b,N, _theta=[],i=0) =
 444   len(_theta)==0?
 445         _ellipse_refine_realign(a,b,N, count(N-1,180/N,360/N))
 446   :
 447   let(
 448       pts = [for(t=_theta) [a*cos(t),b*sin(t)],
 449              [a*cos(_theta[0]), -b*sin(_theta[0])]],
 450       lenlist= path_segment_lengths(pts,closed=true),
 451       meanlen = mean(lenlist),
 452       error = lenlist/meanlen
 453   )
 454   all_equal(error,EPSILON) ? pts
 455   :
 456   let(
 457        dtheta = [each deltas(_theta),
 458                  360-last(_theta)-_theta[0],
 459                  2*_theta[0]],
 460        newdtheta = [for(i=idx(dtheta)) dtheta[i]/error[i]],
 461        normdtheta = newdtheta / sum(newdtheta) * 360,
 462        adjusted = cumsum([last(normdtheta)/2, each list_head(normdtheta, -3)])
 463   )
 464   _ellipse_refine_realign(a,b,N,adjusted, i+1);
 465
 466
 467
 468function ellipse(r, d, realign=false, circum=false, uniform=false, anchor=CENTER, spin=0) =
 469    let(
 470        r = force_list(get_radius(r=r, d=d, dflt=1),2),
 471        sides = segs(max(r))
 472    )
 473    uniform ? assert(!circum, "Circum option not allowed when \"uniform\" is true")
 474                 reorient(anchor,spin,two_d=true,r=[r.x,r.y],
 475                          p=realign ? reverse(_ellipse_refine_realign(r.x,r.y,sides))
 476                                    : reverse_polygon(_ellipse_refine(r.x,r.y,sides)))
 477    :
 478    let(
 479        offset = realign? 180/sides : 0,
 480        sc = circum? (1 / cos(180/sides)) : 1,
 481        rx = r.x * sc,
 482        ry = r.y * sc,
 483        pts = [for (i=[0:1:sides-1]) let(a=360-offset-i*360/sides) [rx*cos(a), ry*sin(a)]]
 484    ) reorient(anchor,spin, two_d=true, r=[rx,ry], p=pts);
 485
 486
 487// Section: Polygons
 488
 489// Function&Module: regular_ngon()
 490// Usage:
 491//   regular_ngon(n, r|d=|or=|od=, [realign=]) [ATTACHMENTS];
 492//   regular_ngon(n, ir=|id=, [realign=]) [ATTACHMENTS];
 493//   regular_ngon(n, side=, [realign=]) [ATTACHMENTS];
 494// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
 495// See Also: circle(), pentagon(), hexagon(), octagon(), ellipse(), star()
 496// Description:
 497//   When called as a function, returns a 2D path for a regular N-sided polygon.
 498//   When called as a module, creates a 2D regular N-sided polygon.
 499// Arguments:
 500//   n = The number of sides.
 501//   r/or = Outside radius, at points.
 502//   ---
 503//   d/od = Outside diameter, at points.
 504//   ir = Inside radius, at center of sides.
 505//   id = Inside diameter, at center of sides.
 506//   side = Length of each side.
 507//   rounding = Radius of rounding for the tips of the polygon.  Default: 0 (no rounding)
 508//   realign = If false, vertex 0 will lie on the X+ axis.  If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis.    Default: false
 509//   align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction.  This occurs before spin.
 510//   align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction.  This occurs before spin.
 511//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 512//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 513// Extra Anchors:
 514//   "tip0", "tip1", etc. = Each tip has an anchor, pointing outwards.
 515//   "side0", "side1", etc. = The center of each side has an anchor, pointing outwards.
 516// Example(2D): by Outer Size
 517//   regular_ngon(n=5, or=30);
 518//   regular_ngon(n=5, od=60);
 519// Example(2D): by Inner Size
 520//   regular_ngon(n=5, ir=30);
 521//   regular_ngon(n=5, id=60);
 522// Example(2D): by Side Length
 523//   regular_ngon(n=8, side=20);
 524// Example(2D): Realigned
 525//   regular_ngon(n=8, side=20, realign=true);
 526// Example(2D): Alignment by Tip
 527//   regular_ngon(n=5, r=30, align_tip=BACK+RIGHT)
 528//       attach("tip0", FWD) color("blue")
 529//           stroke([[0,0],[0,7]], endcap2="arrow2");
 530// Example(2D): Alignment by Side
 531//   regular_ngon(n=5, r=30, align_side=BACK+RIGHT)
 532//       attach("side0", FWD) color("blue")
 533//           stroke([[0,0],[0,7]], endcap2="arrow2");
 534// Example(2D): Rounded
 535//   regular_ngon(n=5, od=100, rounding=20, $fn=20);
 536// Example(2D): Called as Function
 537//   stroke(closed=true, regular_ngon(n=6, or=30));
 538function regular_ngon(n=6, r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0, _mat, _anchs) =
 539    assert(is_int(n) && n>=3)
 540    assert(is_undef(align_tip) || is_vector(align_tip))
 541    assert(is_undef(align_side) || is_vector(align_side))
 542    assert(is_undef(align_tip) || is_undef(align_side), "Can only specify one of align_tip and align-side")
 543    let(
 544        sc = 1/cos(180/n),
 545        ir = is_finite(ir)? ir*sc : undef,
 546        id = is_finite(id)? id*sc : undef,
 547        side = is_finite(side)? side/2/sin(180/n) : undef,
 548        r = get_radius(r1=ir, r2=or, r=r, d1=id, d2=od, d=d, dflt=side)
 549    )
 550    assert(!is_undef(r), "regular_ngon(): need to specify one of r, d, or, od, ir, id, side.")
 551    assert(all_positive([r]), "polygon size must be a positive value")
 552    let(
 553        inset = opp_ang_to_hyp(rounding, (180-360/n)/2),
 554        mat = !is_undef(_mat) ? _mat :
 555            ( realign? zrot(-180/n) : ident(4)) * (
 556                !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
 557                !is_undef(align_side)? rot(from=RIGHT, to=point2d(align_side)) * zrot(180/n) :
 558                1
 559            ),
 560        path4 = rounding==0? ellipse(r=r, $fn=n) : (
 561            let(
 562                steps = floor(segs(r)/n),
 563                step = 360/n/steps,
 564                path2 = [
 565                    for (i = [0:1:n-1]) let(
 566                        a = 360 - i*360/n,
 567                        p = polar_to_xy(r-inset, a)
 568                    )
 569                    each arc(n=steps, cp=p, r=rounding, start=a+180/n, angle=-360/n)
 570                ],
 571                maxx_idx = max_index(column(path2,0)),
 572                path3 = list_rotate(path2,maxx_idx)
 573            ) path3
 574        ),
 575        path = apply(mat, path4),
 576        anchors = !is_undef(_anchs) ? _anchs :
 577            !is_string(anchor)? [] : [
 578            for (i = [0:1:n-1]) let(
 579                a1 = 360 - i*360/n,
 580                a2 = a1 - 360/n,
 581                p1 = apply(mat, polar_to_xy(r,a1)),
 582                p2 = apply(mat, polar_to_xy(r,a2)),
 583                tipp = apply(mat, polar_to_xy(r-inset+rounding,a1)),
 584                pos = (p1+p2)/2
 585            ) each [
 586                named_anchor(str("tip",i), tipp, unit(tipp,BACK), 0),
 587                named_anchor(str("side",i), pos, unit(pos,BACK), 0),
 588            ]
 589        ]
 590    ) reorient(anchor,spin, two_d=true, path=path, extent=false, p=path, anchors=anchors);
 591
 592
 593module regular_ngon(n=6, r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) {
 594    sc = 1/cos(180/n);
 595    ir = is_finite(ir)? ir*sc : undef;
 596    id = is_finite(id)? id*sc : undef;
 597    side = is_finite(side)? side/2/sin(180/n) : undef;
 598    r = get_radius(r1=ir, r2=or, r=r, d1=id, d2=od, d=d, dflt=side);
 599    check = assert(!is_undef(r), "regular_ngon(): need to specify one of r, d, or, od, ir, id, side.")
 600            assert(all_positive([r]), "polygon size must be a positive value");
 601    mat = ( realign? zrot(-180/n) : ident(4) ) * (
 602            !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
 603            !is_undef(align_side)? rot(from=RIGHT, to=point2d(align_side)) * zrot(180/n) :
 604            1
 605        );
 606    inset = opp_ang_to_hyp(rounding, (180-360/n)/2);
 607    anchors = [
 608        for (i = [0:1:n-1]) let(
 609            a1 = 360 - i*360/n,
 610            a2 = a1 - 360/n,
 611            p1 = apply(mat, polar_to_xy(r,a1)),
 612            p2 = apply(mat, polar_to_xy(r,a2)),
 613            tipp = apply(mat, polar_to_xy(r-inset+rounding,a1)),
 614            pos = (p1+p2)/2
 615        ) each [
 616            named_anchor(str("tip",i), tipp, unit(tipp,BACK), 0),
 617            named_anchor(str("side",i), pos, unit(pos,BACK), 0),
 618        ]
 619    ];
 620    path = regular_ngon(n=n, r=r, rounding=rounding, _mat=mat, _anchs=anchors);
 621    attachable(anchor,spin, two_d=true, path=path, extent=false, anchors=anchors) {
 622        polygon(path);
 623        children();
 624    }
 625}
 626
 627
 628// Function&Module: pentagon()
 629// Usage:
 630//   pentagon(or|od=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
 631//   pentagon(ir=|id=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
 632//   pentagon(side=, [realign=], [align_tip=|align_side=]) [ATTACHMENTS];
 633// Usage: as function
 634//   path = pentagon(...);
 635// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
 636// See Also: circle(), regular_ngon(), hexagon(), octagon(), ellipse(), star()
 637// Description:
 638//   When called as a function, returns a 2D path for a regular pentagon.
 639//   When called as a module, creates a 2D regular pentagon.
 640// Arguments:
 641//   r/or = Outside radius, at points.
 642//   ---
 643//   d/od = Outside diameter, at points.
 644//   ir = Inside radius, at center of sides.
 645//   id = Inside diameter, at center of sides.
 646//   side = Length of each side.
 647//   rounding = Radius of rounding for the tips of the polygon.  Default: 0 (no rounding)
 648//   realign = If false, vertex 0 will lie on the X+ axis.  If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis.    Default: false
 649//   align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction.  This occurs before spin.
 650//   align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction.  This occurs before spin.
 651//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 652//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 653// Extra Anchors:
 654//   "tip0" ... "tip4" = Each tip has an anchor, pointing outwards.
 655//   "side0" ... "side4" = The center of each side has an anchor, pointing outwards.
 656// Example(2D): by Outer Size
 657//   pentagon(or=30);
 658//   pentagon(od=60);
 659// Example(2D): by Inner Size
 660//   pentagon(ir=30);
 661//   pentagon(id=60);
 662// Example(2D): by Side Length
 663//   pentagon(side=20);
 664// Example(2D): Realigned
 665//   pentagon(side=20, realign=true);
 666// Example(2D): Alignment by Tip
 667//   pentagon(r=30, align_tip=BACK+RIGHT)
 668//       attach("tip0", FWD) color("blue")
 669//           stroke([[0,0],[0,7]], endcap2="arrow2");
 670// Example(2D): Alignment by Side
 671//   pentagon(r=30, align_side=BACK+RIGHT)
 672//       attach("side0", FWD) color("blue")
 673//           stroke([[0,0],[0,7]], endcap2="arrow2");
 674// Example(2D): Rounded
 675//   pentagon(od=100, rounding=20, $fn=20);
 676// Example(2D): Called as Function
 677//   stroke(closed=true, pentagon(or=30));
 678function pentagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
 679    regular_ngon(n=5, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin);
 680
 681
 682module pentagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
 683    regular_ngon(n=5, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin) children();
 684
 685
 686// Function&Module: hexagon()
 687// Usage: As Module
 688//   hexagon(r/or, [realign=], <align_tip=|align_side=>, [rounding=], ...) [ATTACHMENTS];
 689//   hexagon(d=/od=, ...) [ATTACHMENTS];
 690//   hexagon(ir=/id=, ...) [ATTACHMENTS];
 691//   hexagon(side=, ...) [ATTACHMENTS];
 692// Usage: As Function
 693//   path = hexagon(...);
 694// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
 695// See Also: circle(), regular_ngon(), pentagon(), octagon(), ellipse(), star()
 696// Description:
 697//   When called as a function, returns a 2D path for a regular hexagon.
 698//   When called as a module, creates a 2D regular hexagon.
 699// Arguments:
 700//   r/or = Outside radius, at points.
 701//   ---
 702//   d/od = Outside diameter, at points.
 703//   ir = Inside radius, at center of sides.
 704//   id = Inside diameter, at center of sides.
 705//   side = Length of each side.
 706//   rounding = Radius of rounding for the tips of the polygon.  Default: 0 (no rounding)
 707//   realign = If false, vertex 0 will lie on the X+ axis.  If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis.    Default: false
 708//   align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction.  This occurs before spin.
 709//   align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction.  This occurs before spin.
 710//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 711//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 712// Extra Anchors:
 713//   "tip0" ... "tip5" = Each tip has an anchor, pointing outwards.
 714//   "side0" ... "side5" = The center of each side has an anchor, pointing outwards.
 715// Example(2D): by Outer Size
 716//   hexagon(or=30);
 717//   hexagon(od=60);
 718// Example(2D): by Inner Size
 719//   hexagon(ir=30);
 720//   hexagon(id=60);
 721// Example(2D): by Side Length
 722//   hexagon(side=20);
 723// Example(2D): Realigned
 724//   hexagon(side=20, realign=true);
 725// Example(2D): Alignment by Tip
 726//   hexagon(r=30, align_tip=BACK+RIGHT)
 727//       attach("tip0", FWD) color("blue")
 728//           stroke([[0,0],[0,7]], endcap2="arrow2");
 729// Example(2D): Alignment by Side
 730//   hexagon(r=30, align_side=BACK+RIGHT)
 731//       attach("side0", FWD) color("blue")
 732//           stroke([[0,0],[0,7]], endcap2="arrow2");
 733// Example(2D): Rounded
 734//   hexagon(od=100, rounding=20, $fn=20);
 735// Example(2D): Called as Function
 736//   stroke(closed=true, hexagon(or=30));
 737function hexagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
 738    regular_ngon(n=6, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin);
 739
 740
 741module hexagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
 742    regular_ngon(n=6, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin) children();
 743
 744
 745// Function&Module: octagon()
 746// Usage: As Module
 747//   octagon(r/or, [realign=], [align_tip=|align_side=], [rounding=], ...) [ATTACHMENTS];
 748//   octagon(d=/od=, ...) [ATTACHMENTS];
 749//   octagon(ir=/id=, ...) [ATTACHMENTS];
 750//   octagon(side=, ...) [ATTACHMENTS];
 751// Usage: As Function
 752//   path = octagon(...);
 753// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
 754// See Also: circle(), regular_ngon(), pentagon(), hexagon(), ellipse(), star()
 755// Description:
 756//   When called as a function, returns a 2D path for a regular octagon.
 757//   When called as a module, creates a 2D regular octagon.
 758// Arguments:
 759//   r/or = Outside radius, at points.
 760//   d/od = Outside diameter, at points.
 761//   ir = Inside radius, at center of sides.
 762//   id = Inside diameter, at center of sides.
 763//   side = Length of each side.
 764//   rounding = Radius of rounding for the tips of the polygon.  Default: 0 (no rounding)
 765//   realign = If false, vertex 0 will lie on the X+ axis.  If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis.    Default: false
 766//   align_tip = If given as a 2D vector, rotates the whole shape so that the first vertex points in that direction.  This occurs before spin.
 767//   align_side = If given as a 2D vector, rotates the whole shape so that the normal of side0 points in that direction.  This occurs before spin.
 768//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 769//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 770// Extra Anchors:
 771//   "tip0" ... "tip7" = Each tip has an anchor, pointing outwards.
 772//   "side0" ... "side7" = The center of each side has an anchor, pointing outwards.
 773// Example(2D): by Outer Size
 774//   octagon(or=30);
 775//   octagon(od=60);
 776// Example(2D): by Inner Size
 777//   octagon(ir=30);
 778//   octagon(id=60);
 779// Example(2D): by Side Length
 780//   octagon(side=20);
 781// Example(2D): Realigned
 782//   octagon(side=20, realign=true);
 783// Example(2D): Alignment by Tip
 784//   octagon(r=30, align_tip=BACK+RIGHT)
 785//       attach("tip0", FWD) color("blue")
 786//           stroke([[0,0],[0,7]], endcap2="arrow2");
 787// Example(2D): Alignment by Side
 788//   octagon(r=30, align_side=BACK+RIGHT)
 789//       attach("side0", FWD) color("blue")
 790//           stroke([[0,0],[0,7]], endcap2="arrow2");
 791// Example(2D): Rounded
 792//   octagon(od=100, rounding=20, $fn=20);
 793// Example(2D): Called as Function
 794//   stroke(closed=true, octagon(or=30));
 795function octagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0) =
 796    regular_ngon(n=8, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin);
 797
 798
 799module octagon(r, d, or, od, ir, id, side, rounding=0, realign=false, align_tip, align_side, anchor=CENTER, spin=0)
 800    regular_ngon(n=8, r=r, d=d, or=or, od=od, ir=ir, id=id, side=side, rounding=rounding, realign=realign, align_tip=align_tip, align_side=align_side, anchor=anchor, spin=spin) children();
 801
 802
 803// Function&Module: right_triangle()
 804// Usage: As Module
 805//   right_triangle(size, [center], ...) [ATTACHMENTS];
 806// Usage: As Function
 807//   path = right_triangle(size, [center], ...);
 808// Description:
 809//   Creates a right triangle with the Hypotenuse in the X+Y+ quadrant.
 810// Arguments:
 811//   size = The width and length of the right triangle, given as a scalar or an XY vector.
 812//   center = If true, forces `anchor=CENTER`.  If false, forces `anchor=[-1,-1]`.  Default: undef (use `anchor=`)
 813//   ---
 814//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 815//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 816// Example(2D):
 817//   right_triangle([40,30]);
 818// Example(2D): With `center=true`
 819//   right_triangle([40,30], center=true);
 820// Example(2D): Anchors
 821//   right_triangle([40,30])
 822//       show_anchors();
 823function right_triangle(size=[1,1], center, anchor, spin=0) =
 824    let(
 825        size = is_num(size)? [size,size] : size,
 826        anchor = get_anchor(anchor, center, [-1,-1], [-1,-1])
 827    )
 828    assert(is_vector(size,2))
 829    assert(min(size)>0, "Must give positive size")
 830    let(
 831        path = [ [size.x/2,-size.y/2], [-size.x/2,-size.y/2], [-size.x/2,size.y/2] ]
 832    ) reorient(anchor,spin, two_d=true, size=[size.x,size.y], size2=0, shift=-size.x/2, p=path);
 833
 834module right_triangle(size=[1,1], center, anchor, spin=0) {
 835    size = is_num(size)? [size,size] : size;
 836    anchor = get_anchor(anchor, center, [-1,-1], [-1,-1]);
 837    check = assert(is_vector(size,2));
 838    path = right_triangle(size, center=true);
 839    attachable(anchor,spin, two_d=true, size=[size.x,size.y], size2=0, shift=-size.x/2) {
 840        polygon(path);
 841        children();
 842    }
 843}
 844
 845
 846// Function&Module: trapezoid()
 847// Usage: As Module
 848//   trapezoid(h, w1, w2, [shift=], [rounding=], [chamfer=], ...) [ATTACHMENTS];
 849//   trapezoid(h, w1, angle=, ...) [ATTACHMENTS];
 850//   trapezoid(h, w2, angle=, ...) [ATTACHMENTS];
 851//   trapezoid(w1, w2, angle=, ...) [ATTACHMENTS];
 852// Usage: As Function
 853//   path = trapezoid(...);
 854// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
 855// See Also: rect(), square()
 856// Description:
 857//   When called as a function, returns a 2D path for a trapezoid with parallel front and back sides.
 858//   When called as a module, creates a 2D trapezoid with parallel front and back sides.
 859// Arguments:
 860//   h = The Y axis height of the trapezoid.
 861//   w1 = The X axis width of the front end of the trapezoid.
 862//   w2 = The X axis width of the back end of the trapezoid.
 863//   ---
 864//   angle = If given in place of `h`, `w1`, or `w2`, then the missing value is calculated such that the right side has that angle away from the Y axis.
 865//   shift = Scalar value to shift the back of the trapezoid along the X axis by.  Default: 0
 866//   rounding = The rounding radius for the corners.  If given as a list of four numbers, gives individual radii for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-]. Default: 0 (no rounding)
 867//   chamfer = The Length of the chamfer faces at the corners.  If given as a list of four numbers, gives individual chamfers for each corner, in the order [X+Y+,X-Y+,X-Y-,X+Y-].  Default: 0 (no chamfer)
 868//   flip = If true, negative roundings and chamfers will point forward and back instead of left and right.  Default: `false`.
 869//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 870//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 871// Examples(2D):
 872//   trapezoid(h=30, w1=40, w2=20);
 873//   trapezoid(h=25, w1=20, w2=35);
 874//   trapezoid(h=20, w1=40, w2=0);
 875//   trapezoid(h=20, w1=30, angle=30);
 876//   trapezoid(h=20, w1=20, angle=-30);
 877//   trapezoid(h=20, w2=10, angle=30);
 878//   trapezoid(h=20, w2=30, angle=-30);
 879//   trapezoid(w1=30, w2=10, angle=30);
 880// Example(2D): Chamfered Trapezoid
 881//   trapezoid(h=30, w1=60, w2=40, chamfer=5);
 882// Example(2D): Negative Chamfered Trapezoid
 883//   trapezoid(h=30, w1=60, w2=40, chamfer=-5);
 884// Example(2D): Flipped Negative Chamfered Trapezoid
 885//   trapezoid(h=30, w1=60, w2=40, chamfer=-5, flip=true);
 886// Example(2D): Rounded Trapezoid
 887//   trapezoid(h=30, w1=60, w2=40, rounding=5);
 888// Example(2D): Negative Rounded Trapezoid
 889//   trapezoid(h=30, w1=60, w2=40, rounding=-5);
 890// Example(2D): Flipped Negative Rounded Trapezoid
 891//   trapezoid(h=30, w1=60, w2=40, rounding=-5, flip=true);
 892// Example(2D): Mixed Chamfering and Rounding
 893//   trapezoid(h=30, w1=60, w2=40, rounding=[5,0,-10,0],chamfer=[0,8,0,-15],$fa=1,$fs=1);
 894// Example(2D): Called as Function
 895//   stroke(closed=true, trapezoid(h=30, w1=40, w2=20));
 896function trapezoid(h, w1, w2, angle, shift=0, chamfer=0, rounding=0, flip=false, anchor=CENTER, spin=0) =
 897    assert(is_undef(h) || is_finite(h))
 898    assert(is_undef(w1) || is_finite(w1))
 899    assert(is_undef(w2) || is_finite(w2))
 900    assert(is_undef(angle) || is_finite(angle))
 901    assert(num_defined([h, w1, w2, angle]) == 3, "Must give exactly 3 of the arguments h, w1, w2, and angle.")
 902    assert(is_finite(shift))
 903    assert(is_finite(chamfer)  || is_vector(chamfer,4))
 904    assert(is_finite(rounding) || is_vector(rounding,4))
 905    let(
 906        simple = chamfer==0 && rounding==0,
 907        h  = !is_undef(h)?  h  : opp_ang_to_adj(abs(w2-w1)/2, abs(angle)),
 908        w1 = !is_undef(w1)? w1 : w2 + 2*(adj_ang_to_opp(h, angle) + shift),
 909        w2 = !is_undef(w2)? w2 : w1 - 2*(adj_ang_to_opp(h, angle) + shift),
 910        chamfs = is_num(chamfer)? [for (i=[0:3]) chamfer] :
 911            assert(len(chamfer)==4) chamfer,
 912        rounds = is_num(rounding)? [for (i=[0:3]) rounding] :
 913            assert(len(rounding)==4) rounding,
 914        srads = [for (i=[0:3]) rounds[i]? rounds[i] : chamfs[i]],
 915        rads = v_abs(srads)
 916    )
 917    assert(w1>=0 && w2>=0 && h>0, "Degenerate trapezoid geometry.")
 918    assert(w1+w2>0, "Degenerate trapezoid geometry.")
 919    let(
 920        base = [
 921            [ w2/2+shift, h/2],
 922            [-w2/2+shift, h/2],
 923            [-w1/2,-h/2],
 924            [ w1/2,-h/2],
 925        ],
 926        ang1 = v_theta(base[0]-base[3])-90,
 927        ang2 = v_theta(base[1]-base[2])-90,
 928        angs = [ang1, ang2, ang2, ang1],
 929        qdirs = [[1,1], [-1,1], [-1,-1], [1,-1]],
 930        hyps = [for (i=[0:3]) adj_ang_to_hyp(rads[i],angs[i])],
 931        offs = [
 932            for (i=[0:3]) let(
 933                xoff = adj_ang_to_opp(rads[i],angs[i]),
 934                a = [xoff, -rads[i]] * qdirs[i].y * (srads[i]<0 && flip? -1 : 1),
 935                b = a + [hyps[i] * qdirs[i].x * (srads[i]<0 && !flip? 1 : -1), 0]
 936            ) b
 937        ],
 938        cpath = [
 939            each (
 940                let(i = 0)
 941                rads[i] == 0? [base[i]] :
 942                srads[i] > 0? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[angs[i], 90], r=rads[i]) :
 943                flip? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[angs[i],-90], r=rads[i]) :
 944                arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[180+angs[i],90], r=rads[i])
 945            ),
 946            each (
 947                let(i = 1)
 948                rads[i] == 0? [base[i]] :
 949                srads[i] > 0? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[90,180+angs[i]], r=rads[i]) :
 950                flip? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[270,180+angs[i]], r=rads[i]) :
 951                arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[90,angs[i]], r=rads[i])
 952            ),
 953            each (
 954                let(i = 2)
 955                rads[i] == 0? [base[i]] :
 956                srads[i] > 0? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[180+angs[i],270], r=rads[i]) :
 957                flip? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[180+angs[i],90], r=rads[i]) :
 958                arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[angs[i],-90], r=rads[i])
 959            ),
 960            each (
 961                let(i = 3)
 962                rads[i] == 0? [base[i]] :
 963                srads[i] > 0? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[-90,angs[i]], r=rads[i]) :
 964                flip? arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[90,angs[i]], r=rads[i]) :
 965                arc(n=rounds[i]?undef:2, cp=base[i]+offs[i], angle=[270,180+angs[i]], r=rads[i])
 966            ),
 967        ],
 968        path = reverse(cpath)
 969    ) simple
 970      ? reorient(anchor,spin, two_d=true, size=[w1,h], size2=w2, shift=shift, p=path)
 971      : reorient(anchor,spin, two_d=true, path=path, p=path);
 972
 973
 974
 975module trapezoid(h, w1, w2, angle, shift=0, chamfer=0, rounding=0, flip=false, anchor=CENTER, spin=0) {
 976    path = trapezoid(h=h, w1=w1, w2=w2, angle=angle, shift=shift, chamfer=chamfer, rounding=rounding, flip=flip);
 977    union() {
 978        simple = chamfer==0 && rounding==0;
 979        h  = !is_undef(h)?  h  : opp_ang_to_adj(abs(w2-w1)/2, abs(angle));
 980        w1 = !is_undef(w1)? w1 : w2 + 2*(adj_ang_to_opp(h, angle) + shift);
 981        w2 = !is_undef(w2)? w2 : w1 - 2*(adj_ang_to_opp(h, angle) + shift);
 982        if (simple) {
 983            attachable(anchor,spin, two_d=true, size=[w1,h], size2=w2, shift=shift) {
 984                polygon(path);
 985                children();
 986            }
 987        } else {
 988            attachable(anchor,spin, two_d=true, path=path) {
 989                polygon(path);
 990                children();
 991            }
 992        }
 993    }
 994}
 995
 996
 997
 998// Function&Module: star()
 999// Usage: As Module
1000//   star(n, r/or, ir, [realign=], [align_tip=], [align_pit=], ...) [ATTACHMENTS];
1001//   star(n, r/or, step=, ...) [ATTACHMENTS];
1002// Usage: As Function
1003//   path = star(n, r/or, ir, [realign=], [align_tip=], [align_pit=], ...);
1004//   path = star(n, r/or, step=, ...);
1005// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1006// See Also: circle(), ellipse()
1007// Description:
1008//   When called as a function, returns the path needed to create a star polygon with N points.
1009//   When called as a module, creates a star polygon with N points.
1010// Arguments:
1011//   n = The number of stellate tips on the star.
1012//   r/or = The radius to the tips of the star.
1013//   ir = The radius to the inner corners of the star.
1014//   ---
1015//   d/od = The diameter to the tips of the star.
1016//   id = The diameter to the inner corners of the star.
1017//   step = Calculates the radius of the inner star corners by virtually drawing a straight line `step` tips around the star.  2 <= step < n/2
1018//   realign = If false, vertex 0 will lie on the X+ axis.  If true then the midpoint of the last edge will lie on the X+ axis, and vertex 0 will be below the X axis.    Default: false
1019//   align_tip = If given as a 2D vector, rotates the whole shape so that the first star tip points in that direction.  This occurs before spin.
1020//   align_pit = If given as a 2D vector, rotates the whole shape so that the first inner corner is pointed towards that direction.  This occurs before spin.
1021//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
1022//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1023//   atype = Choose "hull" or "intersect" anchor methods.  Default: "hull"
1024// Extra Anchors:
1025//   "tip0" ... "tip4" = Each tip has an anchor, pointing outwards.
1026//   "pit0" ... "pit4" = The inside corner between each tip has an anchor, pointing outwards.
1027//   "midpt0" ... "midpt4" = The center-point between each pair of tips has an anchor, pointing outwards.
1028// Examples(2D):
1029//   star(n=5, r=50, ir=25);
1030//   star(n=5, r=50, step=2);
1031//   star(n=7, r=50, step=2);
1032//   star(n=7, r=50, step=3);
1033// Example(2D): Realigned
1034//   star(n=7, r=50, step=3, realign=true);
1035// Example(2D): Alignment by Tip
1036//   star(n=5, ir=15, or=30, align_tip=BACK+RIGHT)
1037//       attach("tip0", FWD) color("blue")
1038//           stroke([[0,0],[0,7]], endcap2="arrow2");
1039// Example(2D): Alignment by Pit
1040//   star(n=5, ir=15, or=30, align_pit=BACK+RIGHT)
1041//       attach("pit0", FWD) color("blue")
1042//           stroke([[0,0],[0,7]], endcap2="arrow2");
1043// Example(2D): Called as Function
1044//   stroke(closed=true, star(n=5, r=50, ir=25));
1045function star(n, r, ir, d, or, od, id, step, realign=false, align_tip, align_pit, anchor=CENTER, spin=0, atype="hull", _mat, _anchs) =
1046    assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"")  
1047    assert(is_undef(align_tip) || is_vector(align_tip))
1048    assert(is_undef(align_pit) || is_vector(align_pit))
1049    assert(is_undef(align_tip) || is_undef(align_pit), "Can only specify one of align_tip and align_pit")
1050    assert(is_def(n), "Must specify number of points, n")
1051    let(
1052        r = get_radius(r1=or, d1=od, r=r, d=d),
1053        count = num_defined([ir,id,step]),
1054        stepOK = is_undef(step) || (step>1 && step<n/2)
1055    )
1056    assert(count==1, "Must specify exactly one of ir, id, step")
1057    assert(stepOK,  n==4 ? "Parameter 'step' not allowed for 4 point stars"
1058                  : n==5 || n==6 ? str("Parameter 'step' must be 2 for ",n," point stars")
1059                  : str("Parameter 'step' must be between 2 and ",floor(n/2-1/2)," for ",n," point stars"))
1060    let(
1061        mat = !is_undef(_mat) ? _mat :
1062            ( realign? zrot(-180/n) : ident(4) ) * (
1063                !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
1064                !is_undef(align_pit)? rot(from=RIGHT, to=point2d(align_pit)) * zrot(180/n) :
1065                1
1066            ),
1067        stepr = is_undef(step)? r : r*cos(180*step/n)/cos(180*(step-1)/n),
1068        ir = get_radius(r=ir, d=id, dflt=stepr),
1069        offset = realign? 180/n : 0,
1070        path1 = [for(i=[2*n:-1:1]) let(theta=180*i/n, radius=(i%2)?ir:r) radius*[cos(theta), sin(theta)]],
1071        path = apply(mat, path1),
1072        anchors = !is_undef(_anchs) ? _anchs :
1073            !is_string(anchor)? [] : [
1074            for (i = [0:1:n-1]) let(
1075                a1 = 360 - i*360/n,
1076                a2 = a1 - 180/n,
1077                a3 = a1 - 360/n,
1078                p1 = apply(mat, polar_to_xy(r,a1)),
1079                p2 = apply(mat, polar_to_xy(ir,a2)),
1080                p3 = apply(mat, polar_to_xy(r,a3)),
1081                pos = (p1+p3)/2
1082            ) each [
1083                named_anchor(str("tip",i), p1, unit(p1,BACK), 0),
1084                named_anchor(str("pit",i), p2, unit(p2,BACK), 0),
1085                named_anchor(str("midpt",i), pos, unit(pos,BACK), 0),
1086            ]
1087        ]
1088    ) reorient(anchor,spin, two_d=true, path=path, p=path, extent=atype=="hull", anchors=anchors);
1089
1090
1091module star(n, r, ir, d, or, od, id, step, realign=false, align_tip, align_pit, anchor=CENTER, spin=0, atype="hull") {
1092    checks =
1093        assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"")
1094        assert(is_undef(align_tip) || is_vector(align_tip))
1095        assert(is_undef(align_pit) || is_vector(align_pit))
1096        assert(is_undef(align_tip) || is_undef(align_pit), "Can only specify one of align_tip and align_pit");
1097    r = get_radius(r1=or, d1=od, r=r, d=d, dflt=undef);
1098    stepr = is_undef(step)? r : r*cos(180*step/n)/cos(180*(step-1)/n);
1099    ir = get_radius(r=ir, d=id, dflt=stepr);
1100    mat = ( realign? zrot(-180/n) : ident(4) ) * (
1101            !is_undef(align_tip)? rot(from=RIGHT, to=point2d(align_tip)) :
1102            !is_undef(align_pit)? rot(from=RIGHT, to=point2d(align_pit)) * zrot(180/n) :
1103            1
1104        );
1105    anchors = [
1106        for (i = [0:1:n-1]) let(
1107            a1 = 360 - i*360/n - (realign? 180/n : 0),
1108            a2 = a1 - 180/n,
1109            a3 = a1 - 360/n,
1110            p1 = apply(mat, polar_to_xy(r,a1)),
1111            p2 = apply(mat, polar_to_xy(ir,a2)),
1112            p3 = apply(mat, polar_to_xy(r,a3)),
1113            pos = (p1+p3)/2
1114        ) each [
1115            named_anchor(str("tip",i), p1, unit(p1,BACK), 0),
1116            named_anchor(str("pit",i), p2, unit(p2,BACK), 0),
1117            named_anchor(str("midpt",i), pos, unit(pos,BACK), 0),
1118        ]
1119    ];
1120    path = star(n=n, r=r, ir=ir, realign=realign, _mat=mat, _anchs=anchors);
1121    attachable(anchor,spin, two_d=true, path=path, extent=atype=="hull", anchors=anchors) {
1122        polygon(path);
1123        children();
1124    }
1125}
1126
1127
1128
1129/// Internal Function: _path_add_jitter()
1130/// Topics: Paths
1131/// See Also: jittered_poly()
1132/// Usage:
1133///   jpath = _path_add_jitter(path, [dist], [closed=]);
1134/// Description:
1135///   Adds tiny jitter offsets to collinear points in the given path so that they
1136///   are no longer collinear.  This is useful for preserving subdivision on long
1137///   straight segments, when making geometry with `polygon()`, for use with
1138///   `linear_exrtrude()` with a `twist()`.
1139/// Arguments:
1140///   path = The path to add jitter to.
1141///   dist = The amount to jitter points by.  Default: 1/512 (0.00195)
1142///   ---
1143///   closed = If true, treat path like a closed polygon.  Default: true
1144/// Example(3D):
1145///   d = 100; h = 75; quadsize = 5;
1146///   path = pentagon(d=d);
1147///   spath = subdivide_path(path, maxlen=quadsize, closed=true);
1148///   jpath = _path_add_jitter(spath, closed=true);
1149///   linear_extrude(height=h, twist=72, slices=h/quadsize)
1150///      polygon(jpath);
1151function _path_add_jitter(path, dist=1/512, closed=true) =
1152    assert(is_path(path))
1153    assert(is_finite(dist))
1154    assert(is_bool(closed))
1155    [
1156        path[0],
1157        for (i=idx(path,s=1,e=closed?-1:-2)) let(
1158            n = line_normal([path[i-1],path[i]])
1159        ) path[i] + n * (is_collinear(select(path,i-1,i+1))? (dist * ((i%2)*2-1)) : 0),
1160        if (!closed) last(path)
1161    ];
1162
1163
1164
1165// Module: jittered_poly()
1166// Topics: Extrusions
1167// See Also: subdivide_path()
1168// Usage:
1169//   jittered_poly(path, [dist]);
1170// Description:
1171//   Creates a 2D polygon shape from the given path in such a way that any extra
1172//   collinear points are not stripped out in the way that `polygon()` normally does.
1173//   This is useful for refining the mesh of a `linear_extrude()` with twist.
1174// Arguments:
1175//   path = The path to add jitter to.
1176//   dist = The amount to jitter points by.  Default: 1/512 (0.00195)
1177// Example:
1178//   d = 100; h = 75; quadsize = 5;
1179//   path = pentagon(d=d);
1180//   spath = subdivide_path(path, maxlen=quadsize, closed=true);
1181//   linear_extrude(height=h, twist=72, slices=h/quadsize)
1182//      jittered_poly(spath);
1183module jittered_poly(path, dist=1/512) {
1184    no_children($children);
1185    polygon(_path_add_jitter(path, dist, closed=true));
1186}
1187
1188
1189// Section: Curved 2D Shapes
1190
1191
1192// Function&Module: teardrop2d()
1193//
1194// Description:
1195//   Makes a 2D teardrop shape. Useful for extruding into 3D printable holes.  Uses "intersect" style anchoring.  
1196//   The cap_h parameter truncates the top of the teardrop.  If cap_h is taller than the untruncated form then
1197//   the result will be the full, untruncated shape.  The segments of the bottom section of the teardrop are
1198//   calculated to be the same as a circle or cylinder when rotated 90 degrees.  (Note that this agreement is poor when `$fn=6` or `$fn=7`.  
1199//   If `$fn` is a multiple of four then the teardrop will reach its extremes on all four axes.  The circum option
1200//   produces a teardrop that circumscribes the circle; in this case set `realign=true` to get a teardrop that meets its internal extremes
1201//   on the axes.  
1202//
1203// Usage: As Module
1204//   teardrop2d(r/d=, [ang], [cap_h]) [ATTACHMENTS];
1205// Usage: As Function
1206//   path = teardrop2d(r|d=, [ang], [cap_h]);
1207//
1208// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1209//
1210// See Also: teardrop(), onion()
1211//
1212// Arguments:
1213//   r = radius of circular part of teardrop.  (Default: 1)
1214//   ang = angle of hat walls from the Y axis.  (Default: 45 degrees)
1215//   cap_h = if given, height above center where the shape will be truncated.
1216//   ---
1217//   d = diameter of circular portion of bottom. (Use instead of r)
1218//   circum = if true, create a circumscribing teardrop.  Default: false
1219//   realign = if true, change whether bottom of teardrop is a point or a flat.  Default: false
1220//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
1221//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1222//
1223// Example(2D): Typical Shape
1224//   teardrop2d(r=30, ang=30);
1225// Example(2D): Crop Cap
1226//   teardrop2d(r=30, ang=30, cap_h=40);
1227// Example(2D): Close Crop
1228//   teardrop2d(r=30, ang=30, cap_h=20);
1229module teardrop2d(r, ang=45, cap_h, d, circum=false, realign=false, anchor=CENTER, spin=0)
1230{
1231    path = teardrop2d(r=r, d=d, ang=ang, circum=circum, realign=realign, cap_h=cap_h);
1232    attachable(anchor,spin, two_d=true, path=path, extent=false) {
1233        polygon(path);
1234        children();
1235    }
1236}
1237
1238// _extrapt = true causes the point to be duplicated so a teardrop with no cap
1239// has the same point count as one with a cap.  
1240
1241function teardrop2d(r, ang=45, cap_h, d, circum=false, realign=false, anchor=CENTER, spin=0, _extrapt=false) =
1242    let(
1243        r = get_radius(r=r, d=d, dflt=1),
1244        minheight = r*sin(ang),
1245        maxheight = r/sin(ang), //cos(90-ang),
1246        pointycap = is_undef(cap_h) || cap_h>=maxheight
1247    )
1248    assert(is_undef(cap_h) || cap_h>=minheight, str("cap_h cannot be less than ",minheight," but it is ",cap_h))
1249    let(
1250        cap = [
1251                pointycap? [0,maxheight] : [(maxheight-cap_h)*tan(ang), cap_h],
1252                r*[cos(ang),sin(ang)]
1253              ],
1254        fullcircle = ellipse(r=r, realign=realign, circum=circum,spin=90),        
1255        
1256        // Chose the point on the circle that is lower than the cap but also creates a segment bigger than
1257        // seglen/skipfactor so we don't have a teeny tiny segment at the end of the cap, except for the hexagoin
1258        // case which is treated specially
1259        skipfactor = len(fullcircle)==6 ? 15 : 3,
1260        path = !circum ?
1261                  let(seglen = norm(fullcircle[0]-fullcircle[1]))
1262                  [
1263                   each cap,
1264                   for (p=fullcircle)
1265                          if (
1266                               p.y<last(cap).y-EPSILON
1267                                 && norm([abs(p.x)-last(cap).x,p.y-last(cap.y)])>seglen/skipfactor
1268                             ) p,
1269                   xflip(cap[1]),
1270                   if (_extrapt || !pointycap) xflip(cap[0])
1271                  ]
1272             : let(
1273                   isect = [for(i=[0:1:len(fullcircle)/4])
1274                               let(p = line_intersection(cap, select(fullcircle,[i,i+1]), bounded1=RAY, bounded2=SEGMENT))
1275                               if (p) [i,p]
1276                           ],
1277                   i = last(isect)[0],
1278                   p = last(isect)[1],
1279                   ff=echo(isect)
1280               )
1281               [
1282                 cap[0],
1283                 p,
1284                 each select(fullcircle,i+1,-i-1-(realign?1:0)),
1285                 xflip(p),
1286                 if(_extrapt || !pointycap) xflip(cap[0])
1287               ]
1288    )
1289    reorient(anchor,spin, two_d=true, path=path, p=path, extent=false);
1290
1291
1292
1293// Function&Module: egg()
1294// Usage: As Module
1295//   egg(length, r1|d1=, r2|d2=, R|D=) [ATTACHMENTS];
1296// Usage: As Function
1297//   path = egg(length, r1|d1=, r2|d2=, R|D=);
1298// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1299// See Also: circle(), ellipse(), glued_circles()
1300// Description:
1301//   Constructs an egg-shaped object by connecting two circles with convex arcs that are tangent to the circles.
1302//   You specify the length of the egg, the radii of the two circles, and the desired arc radius.
1303//   Note that because the side radius, R, is often much larger than the end radii, you may get better
1304//   results using `$fs` and `$fa` to control the number of semgments rather than using `$fn`.
1305//   This shape may be useful for creating a cam.  
1306// Arguments:
1307//   length = length of the egg
1308//   r1 = radius of the left-hand circle
1309//   r2 = radius of the right-hand circle
1310//   R = radius of the joining arcs
1311//   ---
1312//   d1 = diameter of the left-hand circle
1313//   d2 = diameter of the right-hand circle
1314//   D = diameter of the joining arcs
1315// Extra Anchors:
1316//   "left" = center of the left circle
1317//   "right" = center of the right circle
1318// Example(2D,NoAxes): This first example shows how the egg is constructed from two circles and two joining arcs.
1319//   $fn=100;
1320//   color("red") stroke(egg(78,25,12, 60),closed=true);
1321//   stroke([left(14,circle(25)),
1322//           right(27,circle(12))]);
1323// Example(2D,Anim,VPD=250,VPR=[0,0,0]): Varying length between circles
1324//   r1 = 25; r2 = 12; R = 65;
1325//   length = floor(lookup($t, [[0,55], [0.5,90], [1,55]]));
1326//   egg(length,r1,r2,R,$fn=180);
1327//   color("black") text(str("length=",length), size=8, halign="center", valign="center");
1328// Example(2D,Anim,VPD=250,VPR=[0,0,0]): Varying tangent arc radius R
1329//   length = 78; r1 = 25; r2 = 12;
1330//   R = floor(lookup($t, [[0,45], [0.5,150], [1,45]]));
1331//   egg(length,r1,r2,R,$fn=180);
1332//   color("black") text(str("R=",R), size=8, halign="center", valign="center");
1333// Example(2D,Anim,VPD=250,VPR=[0,0,0]): Varying circle radius r2
1334//   length = 78; r1 = 25; R = 65;
1335//   r2 = floor(lookup($t, [[0,5], [0.5,30], [1,5]]));
1336//   egg(length,r1,r2,R,$fn=180);
1337//   color("black") text(str("r2=",r2), size=8, halign="center", valign="center");
1338function egg(length, r1, r2, R, d1, d2, D, anchor=CENTER, spin=0) =
1339    let(
1340        r1 = get_radius(r1=r1,d1=d1),
1341        r2 = get_radius(r1=r2,d1=d2),
1342        D = get_radius(r1=R, d1=D)
1343    )
1344    assert(length>0)
1345    assert(R>length/2, "Side radius R must be larger than length/2")
1346    assert(length>r1+r2, "Length must be longer than 2*(r1+r2)")
1347    assert(length>2*r2, "Length must be longer than 2*r2")
1348    assert(length>2*r1, "Length must be longer than 2*r1")  
1349    let(
1350        c1 = [-length/2+r1,0],
1351        c2 = [length/2-r2,0],
1352        Rmin = (r1+r2+norm(c1-c2))/2,
1353        Mlist = circle_circle_intersection(R-r1, c1, R-r2, c2),
1354        arcparms = reverse([for(M=Mlist) [M, c1+r1*unit(c1-M), c2+r2*unit(c2-M)]]),
1355        path = concat(
1356                      arc(r=r2, cp=c2, points=[[length/2,0],arcparms[0][2]],endpoint=false),
1357                      arc(r=R, cp=arcparms[0][0], points=select(arcparms[0],[2,1]),endpoint=false),
1358                      arc(r=r1, points=[arcparms[0][1], [-length/2,0], arcparms[1][1]],endpoint=false),
1359                      arc(r=R, cp=arcparms[1][0], points=select(arcparms[1],[1,2]),endpoint=false),
1360                      arc(r=r2, cp=c2, points=[arcparms[1][2], [length/2,0]],endpoint=false)
1361        ),
1362        anchors = [named_anchor("left", c1, BACK, 0),
1363                   named_anchor("right", c2, BACK, 0)]
1364    )
1365    reorient(anchor, spin, two_d=true, path=path, extent=true, p=path, anchors=anchors);
1366
1367module egg(length,r1,r2,R,d1,d2,D,anchor=CENTER, spin=0)
1368{
1369  path = egg(length,r1,r2,R,d1,d2,D);
1370  anchors = [named_anchor("left", [-length/2+r1,0], BACK, 0),
1371             named_anchor("right", [length/2-r2,0], BACK, 0)];
1372  attachable(anchor, spin, two_d=true, path=path, extent=true, anchors=anchors){
1373    polygon(path);
1374    children();
1375  }
1376}
1377
1378
1379
1380// Function&Module: glued_circles()
1381// Usage: As Module
1382//   glued_circles(r/d=, [spread], [tangent], ...) [ATTACHMENTS];
1383// Usage: As Function
1384//   path = glued_circles(r/d=, [spread], [tangent], ...);
1385// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1386// See Also: circle(), ellipse(), egg()
1387// Description:
1388//   When called as a function, returns a 2D path forming a shape of two circles joined by curved waist.
1389//   When called as a module, creates a 2D shape of two circles joined by curved waist.  Uses "hull" style anchoring.  
1390// Arguments:
1391//   r = The radius of the end circles.
1392//   spread = The distance between the centers of the end circles.  Default: 10
1393//   tangent = The angle in degrees of the tangent point for the joining arcs, measured away from the Y axis.  Default: 30
1394//   ---
1395//   d = The diameter of the end circles.
1396//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
1397//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1398// Examples(2D):
1399//   glued_circles(r=15, spread=40, tangent=45);
1400//   glued_circles(d=30, spread=30, tangent=30);
1401//   glued_circles(d=30, spread=30, tangent=15);
1402//   glued_circles(d=30, spread=30, tangent=-30);
1403// Example(2D): Called as Function
1404//   stroke(closed=true, glued_circles(r=15, spread=40, tangent=45));
1405function glued_circles(r, spread=10, tangent=30, d, anchor=CENTER, spin=0) =
1406    let(
1407        r = get_radius(r=r, d=d, dflt=10),
1408        r2 = (spread/2 / sin(tangent)) - r,
1409        cp1 = [spread/2, 0],
1410        cp2 = [0, (r+r2)*cos(tangent)],
1411        sa1 = 90-tangent,
1412        ea1 = 270+tangent,
1413        lobearc = ea1-sa1,
1414        lobesegs = ceil(segs(r)*lobearc/360),
1415        sa2 = 270-tangent,
1416        ea2 = 270+tangent,
1417        subarc = ea2-sa2,
1418        arcsegs = ceil(segs(r2)*abs(subarc)/360),
1419        // In the tangent zero case the inner curves are missing so we need to complete the two
1420        // outer curves.  In the other case the inner curves are present and endpoint=false
1421        // prevents point duplication.  
1422        path = tangent==0 ?
1423                    concat(arc(n=lobesegs+1, r=r, cp=-cp1, angle=[sa1,ea1]),
1424                           arc(n=lobesegs+1, r=r, cp=cp1, angle=[sa1+180,ea1+180]))
1425                :
1426                    concat(arc(n=lobesegs, r=r, cp=-cp1, angle=[sa1,ea1], endpoint=false),
1427                           [for(theta=lerpn(ea2+180,ea2-subarc+180,arcsegs,endpoint=false))  r2*[cos(theta),sin(theta)] - cp2],
1428                           arc(n=lobesegs, r=r, cp=cp1, angle=[sa1+180,ea1+180], endpoint=false),
1429                           [for(theta=lerpn(ea2,ea2-subarc,arcsegs,endpoint=false))  r2*[cos(theta),sin(theta)] + cp2]),
1430        maxx_idx = max_index(column(path,0)),
1431        path2 = reverse_polygon(list_rotate(path,maxx_idx))
1432    ) reorient(anchor,spin, two_d=true, path=path2, extent=true, p=path2);
1433
1434
1435module glued_circles(r, spread=10, tangent=30, d, anchor=CENTER, spin=0) {
1436    path = glued_circles(r=r, d=d, spread=spread, tangent=tangent);
1437    attachable(anchor,spin, two_d=true, path=path, extent=true) {
1438        polygon(path);
1439        children();
1440    }
1441}
1442
1443
1444
1445function _superformula(theta,m1,m2,n1,n2=1,n3=1,a=1,b=1) =
1446    pow(pow(abs(cos(m1*theta/4)/a),n2)+pow(abs(sin(m2*theta/4)/b),n3),-1/n1);
1447
1448// Function&Module: supershape()
1449// Usage: As Module
1450//   supershape([step],[n=], [m1=], [m2=], [n1=], [n2=], [n3=], [a=], [b=], [r=/d=]) [ATTACHMENTS];
1451// Usage: As Function
1452//   path = supershape([step], [n=], [m1=], [m2=], [n1=], [n2=], [n3=], [a=], [b=], [r=/d=]);
1453// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1454// See Also: circle(), ellipse()
1455// Description:
1456//   When called as a function, returns a 2D path for the outline of the [Superformula](https://en.wikipedia.org/wiki/Superformula) shape.
1457//   When called as a module, creates a 2D [Superformula](https://en.wikipedia.org/wiki/Superformula) shape.
1458//   Note that the "hull" type anchoring (the default) is more intuitive for concave star-like shapes, but the anchor points do not
1459//   necesarily lie on the line of the anchor vector, which can be confusing, especially for simpler, ellipse-like shapes.
1460//   Note that the default step angle of 0.5 is very fine and can be slow, but due to the complex curves of the supershape,
1461//   many points are often required to give a good result.  
1462// Arguments:
1463//   step = The angle step size for sampling the superformula shape.  Smaller steps are slower but more accurate.  Default: 0.5
1464//   ---
1465//   n = Produce n points as output.  Alternative to step.  Not to be confused with shape parameters n1 and n2.  
1466//   m1 = The m1 argument for the superformula. Default: 4.
1467//   m2 = The m2 argument for the superformula. Default: m1.
1468//   n1 = The n1 argument for the superformula. Default: 1.
1469//   n2 = The n2 argument for the superformula. Default: n1.
1470//   n3 = The n3 argument for the superformula. Default: n2.
1471//   a = The a argument for the superformula.  Default: 1.
1472//   b = The b argument for the superformula.  Default: a.
1473//   r = Radius of the shape.  Scale shape to fit in a circle of radius r.
1474//   d = Diameter of the shape.  Scale shape to fit in a circle of diameter d.
1475//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
1476//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1477//   atype = Select "hull" or "intersect" style anchoring.  Default: "hull". 
1478// Example(2D):
1479//   supershape(step=0.5,m1=16,m2=16,n1=0.5,n2=0.5,n3=16,r=50);
1480// Example(2D): Called as Function
1481//   stroke(closed=true, supershape(step=0.5,m1=16,m2=16,n1=0.5,n2=0.5,n3=16,d=100));
1482// Examples(2D,Med):
1483//   for(n=[2:5]) right(2.5*(n-2)) supershape(m1=4,m2=4,n1=n,a=1,b=2);  // Superellipses
1484//   m=[2,3,5,7]; for(i=[0:3]) right(2.5*i) supershape(.5,m1=m[i],n1=1);
1485//   m=[6,8,10,12]; for(i=[0:3]) right(2.7*i) supershape(.5,m1=m[i],n1=1,b=1.5);  // m should be even
1486//   m=[1,2,3,5]; for(i=[0:3]) fwd(1.5*i) supershape(m1=m[i],n1=0.4);
1487//   supershape(m1=5, n1=4, n2=1); right(2.5) supershape(m1=5, n1=40, n2=10);
1488//   m=[2,3,5,7]; for(i=[0:3]) right(2.5*i) supershape(m1=m[i], n1=60, n2=55, n3=30);
1489//   n=[0.5,0.2,0.1,0.02]; for(i=[0:3]) right(2.5*i) supershape(m1=5,n1=n[i], n2=1.7);
1490//   supershape(m1=2, n1=1, n2=4, n3=8);
1491//   supershape(m1=7, n1=2, n2=8, n3=4);
1492//   supershape(m1=7, n1=3, n2=4, n3=17);
1493//   supershape(m1=4, n1=1/2, n2=1/2, n3=4);
1494//   supershape(m1=4, n1=4.0,n2=16, n3=1.5, a=0.9, b=9);
1495//   for(i=[1:4]) right(3*i) supershape(m1=i, m2=3*i, n1=2);
1496//   m=[4,6,10]; for(i=[0:2]) right(i*5) supershape(m1=m[i], n1=12, n2=8, n3=5, a=2.7);
1497//   for(i=[-1.5:3:1.5]) right(i*1.5) supershape(m1=2,m2=10,n1=i,n2=1);
1498//   for(i=[1:3],j=[-1,1]) translate([3.5*i,1.5*j])supershape(m1=4,m2=6,n1=i*j,n2=1);
1499//   for(i=[1:3]) right(2.5*i)supershape(step=.5,m1=88, m2=64, n1=-i*i,n2=1,r=1);
1500// Examples:
1501//   linear_extrude(height=0.3, scale=0) supershape(step=1, m1=6, n1=0.4, n2=0, n3=6);
1502//   linear_extrude(height=5, scale=0) supershape(step=1, b=3, m1=6, n1=3.8, n2=16, n3=10);
1503function supershape(step=0.5, n, m1=4, m2, n1=1, n2, n3, a=1, b, r, d,anchor=CENTER, spin=0, atype="hull") =
1504    assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"")
1505    let(
1506        n = first_defined([n, ceil(360/step)]),
1507        angs = lerpn(360,0,n,endpoint=false),  
1508        r = get_radius(r=r, d=d, dflt=undef),
1509        m2 = is_def(m2) ? m2 : m1,
1510        n2 = is_def(n2) ? n2 : n1,
1511        n3 = is_def(n3) ? n3 : n2,
1512        b = is_def(b) ? b : a,
1513        // superformula returns r(theta), the point in polar coordinates
1514        rvals = [for (theta = angs) _superformula(theta=theta,m1=m1,m2=m2,n1=n1,n2=n2,n3=n3,a=a,b=b)],
1515        scale = is_def(r) ? r/max(rvals) : 1,
1516        path = [for (i=idx(angs)) scale*rvals[i]*[cos(angs[i]), sin(angs[i])]]
1517    ) reorient(anchor,spin, two_d=true, path=path, p=path, extent=atype=="hull");
1518
1519module supershape(step=0.5,n,m1=4,m2=undef,n1,n2=undef,n3=undef,a=1,b=undef, r=undef, d=undef, anchor=CENTER, spin=0, atype="hull") {
1520    check = assert(in_list(atype, _ANCHOR_TYPES), "Anchor type must be \"hull\" or \"intersect\"");
1521    path = supershape(step=step,n=n,m1=m1,m2=m2,n1=n1,n2=n2,n3=n3,a=a,b=b,r=r,d=d);
1522    attachable(anchor,spin,extent=atype=="hull", two_d=true, path=path) {
1523        polygon(path);
1524        children();
1525    }
1526}
1527
1528
1529// Function&Module: reuleaux_polygon()
1530// Usage: As Module
1531//   reuleaux_polygon(n, r|d=, ...) [ATTACHMENTS];
1532// Usage: As Function
1533//   path = reuleaux_polygon(n, r|d=, ...);
1534// Topics: Shapes (2D), Paths (2D), Path Generators, Attachable
1535// See Also: regular_ngon(), pentagon(), hexagon(), octagon()
1536// Description:
1537//   Creates a 2D Reuleaux Polygon; a constant width shape that is not circular.  Uses "intersect" type anchoring.  
1538// Arguments:
1539//   n = Number of "sides" to the Reuleaux Polygon.  Must be an odd positive number.  Default: 3
1540//   r = Radius of the shape.  Scale shape to fit in a circle of radius r.
1541//   ---
1542//   d = Diameter of the shape.  Scale shape to fit in a circle of diameter d.
1543//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
1544//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1545// Extra Anchors:
1546//   "tip0", "tip1", etc. = Each tip has an anchor, pointing outwards.
1547// Examples(2D):
1548//   reuleaux_polygon(n=3, r=50);
1549//   reuleaux_polygon(n=5, d=100);
1550// Examples(2D): Standard vector anchors are based on extents
1551//   reuleaux_polygon(n=3, d=50) show_anchors(custom=false);
1552// Examples(2D): Named anchors exist for the tips
1553//   reuleaux_polygon(n=3, d=50) show_anchors(std=false);
1554module reuleaux_polygon(n=3, r, d, anchor=CENTER, spin=0) {
1555    check = assert(n>=3 && (n%2)==1);
1556    r = get_radius(r=r, d=d, dflt=1);
1557    path = reuleaux_polygon(n=n, r=r);
1558    anchors = [
1559        for (i = [0:1:n-1]) let(
1560            ca = 360 - i * 360/n,
1561            cp = polar_to_xy(r, ca)
1562        ) named_anchor(str("tip",i), cp, unit(cp,BACK), 0),
1563    ];
1564    attachable(anchor,spin, two_d=true, path=path, extent=false, anchors=anchors) {
1565        polygon(path);
1566        children();
1567    }
1568}
1569
1570
1571function reuleaux_polygon(n=3, r, d, anchor=CENTER, spin=0) =
1572    assert(n>=3 && (n%2)==1)
1573    let(
1574        r = get_radius(r=r, d=d, dflt=1),
1575        ssegs = max(3,ceil(segs(r)/n)),
1576        slen = norm(polar_to_xy(r,0)-polar_to_xy(r,180-180/n)),
1577        path = [
1578            for (i = [0:1:n-1]) let(
1579                ca = 180 - (i+0.5) * 360/n,
1580                sa = ca + 180 + (90/n),
1581                ea = ca + 180 - (90/n),
1582                cp = polar_to_xy(r, ca)
1583            ) each arc(n=ssegs-1, r=slen, cp=cp, angle=[sa,ea], endpoint=false)
1584        ],
1585        anchors = [
1586            for (i = [0:1:n-1]) let(
1587                ca = 360 - i * 360/n,
1588                cp = polar_to_xy(r, ca)
1589            ) named_anchor(str("tip",i), cp, unit(cp,BACK), 0),
1590        ]
1591    ) reorient(anchor,spin, two_d=true, path=path, extent=false, anchors=anchors, p=path);
1592
1593
1594
1595// Section: Text
1596
1597// Module: text()
1598// Topics: Attachments, Text
1599// Usage:
1600//   text(text, [size], [font], ...);
1601// Description:
1602//   Creates a 3D text block that can be attached to other attachable objects.
1603//   You cannot attach children to text.
1604//   .
1605//   Historically fonts were specified by their "body size", the height of the metal body
1606//   on which the glyphs were cast.  This means the size was an upper bound on the size
1607//   of the font glyphs, not a direct measurement of their size.  In digital typesetting,
1608//   the metal body is replaced by an invisible box, the em square, whose side length is
1609//   defined to be the font's size.  The glyphs can be contained in that square, or they
1610//   can extend beyond it, depending on the choices made by the font designer.  As a
1611//   result, the meaning of font size varies between fonts: two fonts at the "same" size
1612//   can differ significantly in the actual size of their characters.  Typographers
1613//   customarily specify the size in the units of "points".  A point is 1/72 inch.  In
1614//   OpenSCAD, you specify the size in OpenSCAD units (often treated as millimeters for 3d
1615//   printing), so if you want points you will need to perform a suitable unit conversion.
1616//   In addition, the OpenSCAD font system has a bug: if you specify size=s you will
1617//   instead get a font whose size is s/0.72.  For many fonts this means the size of
1618//   capital letters will be approximately equal to s, because it is common for fonts to
1619//   use about 70% of their height for the ascenders in the font.  To get the customary
1620//   font size, you should multiply your desired size by 0.72.
1621//   .
1622//   To find the fonts that you have available in your OpenSCAD installation,
1623//   go to the Help menu and select "Font List".  
1624// Arguments:
1625//   text = Text to create.
1626//   size = The font will be created at this size divided by 0.72.   Default: 10
1627//   font = Font to use.  Default: "Liberation Sans"
1628//   ---
1629//   halign = If given, specifies the horizontal alignment of the text.  `"left"`, `"center"`, or `"right"`.  Overrides `anchor=`.
1630//   valign = If given, specifies the vertical alignment of the text.  `"top"`, `"center"`, `"baseline"` or `"bottom"`.  Overrides `anchor=`.
1631//   spacing = The relative spacing multiplier between characters.  Default: `1.0`
1632//   direction = The text direction.  `"ltr"` for left to right.  `"rtl"` for right to left. `"ttb"` for top to bottom. `"btt"` for bottom to top.  Default: `"ltr"`
1633//   language = The language the text is in.  Default: `"en"`
1634//   script = The script the text is in.  Default: `"latin"`
1635//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `"baseline"`
1636//   spin = Rotate this many degrees around the Z axis.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1637// See Also: attachable()
1638// Extra Anchors:
1639//   "baseline" = Anchors at the baseline of the text, at the start of the string.
1640//   str("baseline",VECTOR) = Anchors at the baseline of the text, modified by the X and Z components of the appended vector.
1641// Examples(2D):
1642//   text("Foobar", size=10);
1643//   text("Foobar", size=12, font="Helvetica");
1644//   text("Foobar", anchor=CENTER);
1645//   text("Foobar", anchor=str("baseline",CENTER));
1646// Example: Using line_copies() distributor
1647//   txt = "This is the string.";
1648//   line_copies(spacing=[10,-5],n=len(txt))
1649//       text(txt[$idx], size=10, anchor=CENTER);
1650// Example: Using arc_copies() distributor
1651//   txt = "This is the string";
1652//   arc_copies(r=50, n=len(txt), sa=0, ea=180)
1653//       text(select(txt,-1-$idx), size=10, anchor=str("baseline",CENTER), spin=-90);
1654module text(text, size=10, font="Helvetica", halign, valign, spacing=1.0, direction="ltr", language="en", script="latin", anchor="baseline", spin=0) {
1655    no_children($children);
1656    dummy1 =
1657        assert(is_undef(anchor) || is_vector(anchor) || is_string(anchor), str("Got: ",anchor))
1658        assert(is_undef(spin)   || is_vector(spin,3) || is_num(spin), str("Got: ",spin));
1659    anchor = default(anchor, CENTER);
1660    spin =   default(spin,   0);
1661    geom = attach_geom(size=[size,size],two_d=true);
1662    anch = !any([for (c=anchor) c=="["])? anchor :
1663        let(
1664            parts = str_split(str_split(str_split(anchor,"]")[0],"[")[1],","),
1665            vec = [for (p=parts) parse_float(str_strip(p," ",start=true))]
1666        ) vec;
1667    ha = halign!=undef? halign :
1668        anchor=="baseline"? "left" :
1669        anchor==anch && is_string(anchor)? "center" :
1670        anch.x<0? "left" :
1671        anch.x>0? "right" :
1672        "center";
1673    va = valign != undef? valign :
1674        starts_with(anchor,"baseline")? "baseline" :
1675        anchor==anch && is_string(anchor)? "center" :
1676        anch.y<0? "bottom" :
1677        anch.y>0? "top" :
1678        "center";
1679    base = anchor=="baseline"? CENTER :
1680        anchor==anch && is_string(anchor)? CENTER :
1681        anch.z<0? BOTTOM :
1682        anch.z>0? TOP :
1683        CENTER;
1684    m = _attach_transform(base,spin,undef,geom);
1685    multmatrix(m) {
1686        $parent_anchor = anchor;
1687        $parent_spin   = spin;
1688        $parent_orient = undef;
1689        $parent_geom   = geom;
1690        $parent_size   = _attach_geom_size(geom);
1691        $attach_to   = undef;
1692        if (_is_shown()){
1693            _color($color) {
1694                _text(
1695                    text=text, size=size, font=font,
1696                    halign=ha, valign=va, spacing=spacing,
1697                    direction=direction, language=language,
1698                    script=script
1699                );
1700            }
1701        }
1702    }
1703}
1704
1705
1706// Section: Rounding 2D shapes
1707
1708// Module: round2d()
1709// Usage:
1710//   round2d(r) [ATTACHMENTS];
1711//   round2d(or=) [ATTACHMENTS];
1712//   round2d(ir=) [ATTACHMENTS];
1713//   round2d(or=, ir=) [ATTACHMENTS];
1714// Description:
1715//   Rounds arbitrary 2D objects.  Giving `r` rounds all concave and convex corners.  Giving just `ir`
1716//   rounds just concave corners.  Giving just `or` rounds convex corners.  Giving both `ir` and `or`
1717//   can let you round to different radii for concave and convex corners.  The 2D object must not have
1718//   any parts narrower than twice the `or` radius.  Such parts will disappear.
1719// Arguments:
1720//   r = Radius to round all concave and convex corners to.
1721//   ---
1722//   or = Radius to round only outside (convex) corners to.  Use instead of `r`.
1723//   ir = Radius to round only inside (concave) corners to.  Use instead of `r`.
1724// Examples(2D):
1725//   round2d(r=10) {square([40,100], center=true); square([100,40], center=true);}
1726//   round2d(or=10) {square([40,100], center=true); square([100,40], center=true);}
1727//   round2d(ir=10) {square([40,100], center=true); square([100,40], center=true);}
1728//   round2d(or=16,ir=8) {square([40,100], center=true); square([100,40], center=true);}
1729module round2d(r, or, ir)
1730{
1731    or = get_radius(r1=or, r=r, dflt=0);
1732    ir = get_radius(r1=ir, r=r, dflt=0);
1733    offset(or) offset(-ir-or) offset(delta=ir,chamfer=true) children();
1734}
1735
1736
1737// Module: shell2d()
1738// Usage:
1739//   shell2d(thickness, [or], [ir])
1740// Description:
1741//   Creates a hollow shell from 2D children, with optional rounding.
1742// Arguments:
1743//   thickness = Thickness of the shell.  Positive to expand outward, negative to shrink inward, or a two-element list to do both.
1744//   or = Radius to round corners on the outside of the shell.  If given a list of 2 radii, [CONVEX,CONCAVE], specifies the radii for convex and concave corners separately.  Default: 0 (no outside rounding)
1745//   ir = Radius to round corners on the inside of the shell.  If given a list of 2 radii, [CONVEX,CONCAVE], specifies the radii for convex and concave corners separately.  Default: 0 (no inside rounding)
1746// Examples(2D):
1747//   shell2d(10) {square([40,100], center=true); square([100,40], center=true);}
1748//   shell2d(-10) {square([40,100], center=true); square([100,40], center=true);}
1749//   shell2d([-10,10]) {square([40,100], center=true); square([100,40], center=true);}
1750//   shell2d(10,or=10) {square([40,100], center=true); square([100,40], center=true);}
1751//   shell2d(10,ir=10) {square([40,100], center=true); square([100,40], center=true);}
1752//   shell2d(10,or=[10,0]) {square([40,100], center=true); square([100,40], center=true);}
1753//   shell2d(10,or=[0,10]) {square([40,100], center=true); square([100,40], center=true);}
1754//   shell2d(10,ir=[10,0]) {square([40,100], center=true); square([100,40], center=true);}
1755//   shell2d(10,ir=[0,10]) {square([40,100], center=true); square([100,40], center=true);}
1756//   shell2d(8,or=[16,8],ir=[16,8]) {square([40,100], center=true); square([100,40], center=true);}
1757module shell2d(thickness, or=0, ir=0)
1758{
1759    thickness = is_num(thickness)? (
1760        thickness<0? [thickness,0] : [0,thickness]
1761    ) : (thickness[0]>thickness[1])? (
1762        [thickness[1],thickness[0]]
1763    ) : thickness;
1764    orad = is_finite(or)? [or,or] : or;
1765    irad = is_finite(ir)? [ir,ir] : ir;
1766    difference() {
1767        round2d(or=orad[0],ir=orad[1])
1768            offset(delta=thickness[1])
1769                children();
1770        round2d(or=irad[1],ir=irad[0])
1771            offset(delta=thickness[0])
1772                children();
1773    }
1774}
1775
1776
1777// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap