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