1//////////////////////////////////////////////////////////////////////
2// LibFile: distributors.scad
3// Functions and modules to distribute children or copies of children onto
4// a line, a grid, or an arbitrary path. The $idx mechanism means that
5// the "copies" of children can vary. Also includes shortcuts for mirroring.
6// Includes:
7// include <BOSL2/std.scad>
8// FileGroup: Basic Modeling
9// FileSummary: Copy or distribute objects onto a line, grid, or path. Mirror shortcuts.
10// FileFootnotes: STD=Included in std.scad
11//////////////////////////////////////////////////////////////////////
12
13// Section: Adaptive Children Using `$` Variables
14// The distributor methods create multiple copies of their children and place them in various ways. While many models
15// require multiple identical copies of an object, this framework is more powerful than
16// might be immediately obvious because of `$` variables. The distributors set `$` variables that the children can use to change their
17// behavior from one child to the next within a single distributor invocation. This means the copies need not be identical.
18// The {{xcopies()}} module sets `$idx` to the index number of the copy, and in the examples below we use `$idx`, but the various
19// distributors offer a variety of `$` variables that you can use in your children. Check the "Side Effects" section for each module
20// to learn what variables that module provides.
21// .
22// Two gotchas may lead to models that don't behave as expected. While `if` statements work to control modules, you cannot
23// use them to make variable assignments in your child object. If you write a statement like
24// ```
25// if (condition) { c="red";}
26// else {c="green";}
27// ```
28// then the `c` variable is set only in the scope of the `if` and `else` clauses and is not available later on when you actually
29// try to use it. Instead you must use the ternary operator and write:
30// ```
31// c = condition ? "red" : "green";
32// ```
33// The second complication is
34// that in OpenSCAD version 2021.01 and earlier, assignments in children were executed before their parent. This means
35// that `$` variables like `$idx` are not available in assignments because the parent hasn't run to set them, so if you use them
36// you will get a warning about an unknown variable.
37// Two workarounds exist, neither of which are needed in newer versions of OpenSCAD. The workarounds solve the problem because
38// **modules** execute after their parent, so the `$` variables **are** available in modules. You can put your assignments
39// in a `let()` module, or you can wrap your child in a `union()`. Both methods appear below.
40// Figure(2D,NoScales): This example shows how we can use `$idx` to produce **different** geometry at each index.
41// xcopies(n=10, spacing=10)
42// text(str($idx));
43// Continues:
44// ```
45// xcopies(n=10, spacing=10)
46// text(str($idx));
47// ```
48// Figure(2D,NoScales): Here the children are sometimes squares and sometimes circles as determined by the conditional `if` module. This use of `if` is OK because no variables are assigned.
49// xcopies(n=4, spacing=10)
50// if($idx%2==0) circle(r=3,$fn=16);
51// else rect(6);
52// Continues:
53// ```
54// xcopies(n=4, spacing=10)
55// if($idx%2==0) circle(r=3,$fn=16);
56// else rect(6);
57// ```
58// Figure(2D,NoScales): Suppose we would like to color odd and even index copies differently. In this example we compute the color for a given child from `$idx` using the ternary operator. The `let()` module is a module that sets variables and makes them available to its children. Note that multiple assignments in `let()` are separated by commas, not semicolons.
59// xcopies(n=6, spacing=10){
60// let(c = $idx % 2 == 0 ? "red" : "green")
61// color(c) rect(6);
62// }
63// Continues:
64// ```
65// xcopies(n=6, spacing=10){
66// let(c = $idx % 2 == 0 ? "red" : "green")
67// color(c) rect(6);
68// }
69// ```
70// Figure(2D,NoScales): This example shows how you can change the position of children adaptively. If you want to avoid repeating your code for each case, this requires storing a transformation matrix in a variable and then applying it using `multmatrix()`. We wrap our code in `union()` to ensure that it works in OpenSCAD 2021.01.
71// xcopies(n=5,spacing=10)
72// union()
73// {
74// shiftback = $idx%2==0 ? back(10) : IDENT;
75// spin = zrot(180*$idx/4);
76// multmatrix(shiftback*spin) stroke([[-4,0],[4,0]],endcap2="arrow2",width=3/4, color="red");
77// }
78// Continues:
79// ```
80// xcopies(n=5,spacing=10)
81// union()
82// {
83// shiftback = $idx%2==0 ? back(10) : IDENT;
84// spin = zrot(180*$idx/4);
85// multmatrix(shiftback*spin) stroke([[-4,0],[4,0]],endcap2="arrow2",width=3/4,color="red");
86// }
87// ```
88
89
90//////////////////////////////////////////////////////////////////////
91// Section: Translating copies of all the children
92//////////////////////////////////////////////////////////////////////
93
94// Function&Module: move_copies()
95// Synopsis: Translates copies of all children.
96// SynTags: MatList, Trans
97// Topics: Transformations, Distributors, Translation, Copiers
98// See Also: xcopies(), ycopies(), zcopies(), line_copies(), grid_copies(), rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies()
99//
100// Usage:
101// move_copies(a) CHILDREN;
102// Usage: As a function to translate points, VNF, or Bezier patches
103// copies = move_copies(a, p=);
104// Usage: Get Translation Matrices
105// mats = move_copies(a);
106// Description:
107// When called as a module, translates copies of all children to each given translation offset.
108// When called as a function, with no `p=` argument, returns a list of transformation matrices, one for each copy.
109// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
110//
111// Arguments:
112// a = Array of XYZ offset vectors. Default `[[0,0,0]]`
113// ---
114// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
115//
116// Side Effects:
117// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
118// `$idx` is set to the index number of each child being copied.
119//
120//
121// Example:
122// #sphere(r=10);
123// move_copies([[-25,-25,0], [25,-25,0], [0,0,50], [0,25,0]]) sphere(r=10);
124module move_copies(a=[[0,0,0]])
125{
126 req_children($children);
127 assert(is_list(a));
128 for ($idx = idx(a)) {
129 $pos = a[$idx];
130 assert(is_vector($pos),"move_copies offsets should be a 2d or 3d vector.");
131 translate($pos) children();
132 }
133}
134
135function move_copies(a=[[0,0,0]],p=_NO_ARG) =
136 assert(is_list(a))
137 let(
138 mats = [
139 for (pos = a)
140 assert(is_vector(pos),"move_copies offsets should be a 2d or 3d vector.")
141 translate(pos)
142 ]
143 )
144 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
145
146
147// Function&Module: xcopies()
148// Synopsis: Places copies of children along the X axis.
149// SynTags: MatList, Trans
150// Topics: Transformations, Distributors, Translation, Copiers
151// See Also: move_copies(), ycopies(), zcopies(), line_copies(), grid_copies(), rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies()
152//
153// Usage:
154// xcopies(spacing, [n], [sp=]) CHILDREN;
155// xcopies(l=, [n=], [sp=]) CHILDREN;
156// xcopies(LIST) CHILDREN;
157// Usage: As a function to translate points, VNF, or Bezier patches
158// copies = xcopies(spacing, [n], [sp=], p=);
159// copies = xcopies(l=, [n=], [sp=], p=);
160// copies = xcopies(LIST, p=);
161// Usage: Get Translation Matrices
162// mats = xcopies(spacing, [n], [sp=]);
163// mats = xcopies(l=, [n=], [sp=]);
164// mats = xcopies(LIST);
165// Description:
166// When called as a module, places `n` copies of the children along a line on the X axis.
167// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
168// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
169//
170// Arguments:
171// spacing = Given a scalar, specifies a uniform spacing between copies. Given a list of scalars, each one gives a specific position along the line. (Default: 1.0)
172// n = Number of copies to place. (Default: 2)
173// ---
174// l = If given, the length to place copies over.
175// sp = If given as a point, copies will be placed on a line to the right of starting position `sp`. If given as a scalar, copies will be placed on a line segment to the right of starting position `[sp,0,0]`. If not given, copies will be placed along a line segment that is centered at [0,0,0].
176// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
177//
178// Side Effects:
179// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
180// `$idx` is set to the index number of each child being copied.
181//
182// Examples:
183// xcopies(20) sphere(3);
184// xcopies(20, n=3) sphere(3);
185// xcopies(spacing=15, l=50) sphere(3);
186// xcopies(n=4, l=30, sp=[0,10,0]) sphere(3);
187// Example:
188// xcopies(10, n=3) {
189// cube(size=[1,3,1],center=true);
190// cube(size=[3,1,1],center=true);
191// }
192// Example:
193// xcopies([1,2,3,5,7]) sphere(d=1);
194module xcopies(spacing, n, l, sp)
195{
196 assert(is_undef(n) || num_defined([l,spacing])==1, "When n is given must give exactly one of spacing or l")
197 assert(is_def(n) || num_defined([l,spacing])>=1, "When n is not given must give at least one of spacing or l")
198 req_children($children);
199 dir = RIGHT;
200 sp = is_finite(sp)? (sp*dir) : sp;
201 if (is_vector(spacing)) {
202 translate(default(sp,[0,0,0])) {
203 for (i = idx(spacing)) {
204 $idx = i;
205 $pos = spacing[i]*dir;
206 translate($pos) children();
207 }
208 }
209 } else {
210 line_copies(
211 l=u_mul(l,dir),
212 spacing=u_mul(spacing,dir),
213 n=n, p1=sp
214 ) children();
215 }
216}
217
218
219function xcopies(spacing, n, l, sp, p=_NO_ARG) =
220 assert(is_undef(n) || num_defined([l,spacing])==1, "When n is given must give exactly one of spacing or l")
221 assert(is_def(n) || num_defined([l,spacing])>=1, "When n is not given must give at least one of spacing or l")
222 let(
223 dir = RIGHT,
224 sp = is_finite(sp)? (sp*dir) : sp,
225 mats = is_vector(spacing)
226 ? let(sp = default(sp,[0,0,0])) [for (n = spacing) translate(sp + n*dir)]
227 : line_copies(l=u_mul(l,dir), spacing=u_mul(spacing,dir), n=n, p1=sp)
228 )
229 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
230
231
232// Function&Module: ycopies()
233// Synopsis: Places copies of children along the Y axis.
234// SynTags: MatList, Trans
235// Topics: Transformations, Distributors, Translation, Copiers
236// See Also: move_copies(), xcopies(), zcopies(), line_copies(), grid_copies(), rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies()
237//
238// Usage:
239// ycopies(spacing, [n], [sp=]) CHILDREN;
240// ycopies(l=, [n=], [sp=]) CHILDREN;
241// ycopies(LIST) CHILDREN;
242// Usage: As a function to translate points, VNF, or Bezier patches
243// copies = ycopies(spacing, [n], [sp=], p=);
244// copies = ycopies(l=, [n=], [sp=], p=);
245// copies = ycopies(LIST, p=);
246// Usage: Get Translation Matrices
247// mats = ycopies(spacing, [n], [sp=]);
248// mats = ycopies(l=, [n=], [sp=]);
249// mats = ycopies(LIST);
250// Description:
251// When called as a module, places `n` copies of the children along a line on the Y axis.
252// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
253// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
254//
255// Arguments:
256// spacing = Given a scalar, specifies a uniform spacing between copies. Given a list of scalars, each one gives a specific position along the line. (Default: 1.0)
257// n = Number of copies to place on the line. (Default: 2)
258// ---
259// l = If given, the length to place copies over.
260// sp = If given as a point, copies will be place on a line back from starting position `sp`. If given as a scalar, copies will be placed on a line back from starting position `[0,sp,0]`. If not given, copies will be placed along a line that is centered at [0,0,0].
261// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
262//
263// Side Effects:
264// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
265// `$idx` is set to the index number of each child being copied.
266//
267// Examples:
268// ycopies(20) sphere(3);
269// ycopies(20, n=3) sphere(3);
270// ycopies(spacing=15, l=50) sphere(3);
271// ycopies(n=4, l=30, sp=[10,0,0]) sphere(3);
272// Example:
273// ycopies(10, n=3) {
274// cube(size=[1,3,1],center=true);
275// cube(size=[3,1,1],center=true);
276// }
277// Example:
278// ycopies([1,2,3,5,7]) sphere(d=1);
279module ycopies(spacing, n, l, sp)
280{
281 assert(is_undef(n) || num_defined([l,spacing])==1, "When n is given must give exactly one of spacing or l")
282 assert(is_def(n) || num_defined([l,spacing])>=1, "When n is not given must give at least one of spacing or l")
283 req_children($children);
284 dir = BACK;
285 sp = is_finite(sp)? (sp*dir) : sp;
286 if (is_vector(spacing)) {
287 translate(default(sp,[0,0,0])) {
288 for (i = idx(spacing)) {
289 $idx = i;
290 $pos = spacing[i]*dir;
291 translate($pos) children();
292 }
293 }
294 } else {
295 line_copies(
296 l=u_mul(l,dir),
297 spacing=u_mul(spacing,dir),
298 n=n, p1=sp
299 ) children();
300 }
301}
302
303
304function ycopies(spacing, n, l, sp, p=_NO_ARG) =
305 assert(is_undef(n) || num_defined([l,spacing])==1, "When n is given must give exactly one of spacing or l")
306 assert(is_def(n) || num_defined([l,spacing])>=1, "When n is not given must give at least one of spacing or l")
307 let(
308 dir = BACK,
309 sp = is_finite(sp)? (sp*dir) : sp,
310 mats = is_vector(spacing)
311 ? let(sp = default(sp,[0,0,0])) [for (n = spacing) translate(sp + n*dir)]
312 : line_copies(l=u_mul(l,dir), spacing=u_mul(spacing,dir), n=n, p1=sp)
313 )
314 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
315
316
317// Function&Module: zcopies()
318// Synopsis: Places copies of children along the Z axis.
319// SynTags: MatList, Trans
320// Topics: Transformations, Distributors, Translation, Copiers
321// See Also: move_copies(), xcopies(), ycopies(), line_copies(), grid_copies(), rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies()
322//
323// Usage:
324// zcopies(spacing, [n], [sp=]) CHILDREN;
325// zcopies(l=, [n=], [sp=]) CHILDREN;
326// zcopies(LIST) CHILDREN;
327// Usage: As a function to translate points, VNF, or Bezier patches
328// copies = zcopies(spacing, [n], [sp=], p=);
329// copies = zcopies(l=, [n=], [sp=], p=);
330// copies = zcopies(LIST, p=);
331// Usage: Get Translation Matrices
332// mats = zcopies(spacing, [n], [sp=]);
333// mats = zcopies(l=, [n=], [sp=]);
334// mats = zcopies(LIST);
335// Description:
336// When called as a module, places `n` copies of the children along a line on the Z axis.
337// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
338// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
339//
340// Arguments:
341// spacing = Given a scalar, specifies a uniform spacing between copies. Given a list of scalars, each one gives a specific position along the line. (Default: 1.0)
342// n = Number of copies to place. (Default: 2)
343// ---
344// l = If given, the length to place copies over.
345// sp = If given as a point, copies will be placed on a line up from starting position `sp`. If given as a scalar, copies will be placed on a line up from starting position `[0,0,sp]`. If not given, copies will be placed on a line that is centered at [0,0,0].
346// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
347//
348// Side Effects:
349// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
350// `$idx` is set to the index number of each child being copied.
351//
352// Examples:
353// zcopies(20) sphere(3);
354// zcopies(20, n=3) sphere(3);
355// zcopies(spacing=15, l=50) sphere(3);
356// zcopies(n=4, l=30, sp=[10,0,0]) sphere(3);
357// Example:
358// zcopies(10, n=3) {
359// cube(size=[1,3,1],center=true);
360// cube(size=[3,1,1],center=true);
361// }
362// Example: Cubic sphere packing
363// s = 20;
364// s2 = s * sin(45);
365// zcopies(s2,n=8)
366// grid_copies([s2,s2],n=8,stagger=($idx%2)? true : "alt")
367// sphere(d=s);
368// Example: Hexagonal sphere packing
369// s = 20;
370// xyr = adj_ang_to_hyp(s/2,30);
371// h = hyp_adj_to_opp(s,xyr);
372// zcopies(h,n=8)
373// back(($idx%2)*xyr*cos(60))
374// grid_copies(s,n=[12,7],stagger=($idx%2)? "alt" : true)
375// sphere(d=s);
376// Example:
377// zcopies([1,2,3,5,7]) sphere(d=1);
378module zcopies(spacing, n, l, sp)
379{
380 assert(is_undef(n) || num_defined([l,spacing])==1, "When n is given must give exactly one of spacing or l")
381 assert(is_def(n) || num_defined([l,spacing])>=1, "When n is not given must give at least one of spacing or l")
382 req_children($children);
383 dir = UP;
384 sp = is_finite(sp)? (sp*dir) : sp;
385 if (is_vector(spacing)) {
386 translate(default(sp,[0,0,0])) {
387 for (i = idx(spacing)) {
388 $idx = i;
389 $pos = spacing[i]*dir;
390 translate($pos) children();
391 }
392 }
393 } else {
394 line_copies(
395 l=u_mul(l,dir),
396 spacing=u_mul(spacing,dir),
397 n=n, p1=sp
398 ) children();
399 }
400}
401
402
403function zcopies(spacing, n, l, sp, p=_NO_ARG) =
404 assert(is_undef(n) || num_defined([l,spacing])==1, "When n is given must give exactly one of spacing or l")
405 assert(is_def(n) || num_defined([l,spacing])>=1, "When n is not given must give at least one of spacing or l")
406 let(
407 dir = UP,
408 sp = is_finite(sp)? (sp*dir) : sp,
409 mats = is_vector(spacing)
410 ? let(sp = default(sp,[0,0,0])) [for (n = spacing) translate(sp + n*dir)]
411 : line_copies(l=u_mul(l,dir), spacing=u_mul(spacing,dir), n=n, p1=sp)
412 )
413 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
414
415
416
417// Function&Module: line_copies()
418// Synopsis: Places copies of children along an arbitrary line.
419// SynTags: MatList, Trans
420// Topics: Transformations, Distributors, Translation, Copiers
421// See Also: move_copies(), xcopies(), ycopies(), zcopies(), rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies()
422//
423// Usage: Place `n` copies at a given spacing along the line
424// line_copies(spacing, [n], [p1=]) CHILDREN;
425// Usage: Place as many copies as will fit at a given spacing
426// line_copies(spacing, [l=], [p1=]) CHILDREN;
427// Usage: Place `n` copies along the length of the line
428// line_copies([n=], [l=], [p1=]) CHILDREN;
429// Usage: Place `n` copies along the line from `p1` to `p2`
430// line_copies([n=], [p1=], [p2=]) CHILDREN;
431// Usage: Place copies at the given spacing, centered along the line from `p1` to `p2`
432// line_copies([spacing], [p1=], [p2=]) CHILDREN;
433// Usage: As a function to translate points, VNF, or Bezier patches
434// copies = line_copies([spacing], [n], [p1=], p=);
435// copies = line_copies([spacing], [l=], [p1=], p=);
436// copies = line_copies([n=], [l=], [p1=], p=);
437// copies = line_copies([n=], [p1=], [p2=], p=);
438// copies = line_copies([spacing], [p1=], [p2=], p=);
439// Usage: Get Translation Matrices
440// mats = line_copies([spacing], [n], [p1=]);
441// mats = line_copies([spacing], [l=], [p1=]);
442// mats = line_copies([n=], [l=], [p1=]);
443// mats = line_copies([n=], [p1=], [p2=]);
444// mats = line_copies([spacing], [p1=], [p2=]);
445// Description:
446// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
447// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
448// When called as a module, copies `children()` at one or more evenly spaced positions along a line.
449// By default, the line will be centered at the origin, unless the starting point `p1` is given.
450// The line will be pointed towards `RIGHT` (X+) unless otherwise given as a vector in `l`,
451// `spacing`, or `p1`/`p2`. The psotion of the copies is specified in one of several ways:
452// .
453// If You Know... | Then Use Something Like...
454// -------------------------------- | --------------------------------
455// Spacing distance, Count | `line_copies(spacing=10, n=5) ...` or `line_copies(10, n=5) ...`
456// Spacing vector, Count | `line_copies(spacing=[10,5], n=5) ...` or `line_copies([10,5], n=5) ...`
457// Spacing distance, Line length | `line_copies(spacing=10, l=50) ...` or `line_copies(10, l=50) ...`
458// Spacing distance, Line vector | `line_copies(spacing=10, l=[50,30]) ...` or `line_copies(10, l=[50,30]) ...`
459// Spacing vector, Line length | `line_copies(spacing=[10,5], l=50) ...` or `line_copies([10,5], l=50) ...`
460// Line length, Count | `line_copies(l=50, n=5) ...`
461// Line vector, Count | `line_copies(l=[50,40], n=5) ...`
462// Line endpoints, Count | `line_copies(p1=[10,10], p2=[60,-10], n=5) ...`
463// Line endpoints, Spacing distance | `line_copies(p1=[10,10], p2=[60,-10], spacing=10) ...`
464//
465// Arguments:
466// spacing = Either the scalar spacing distance along the X+ direction, or the vector giving both the direction and spacing distance between each set of copies.
467// n = Number of copies to distribute along the line. (Default: 2)
468// ---
469// l = Either the scalar length of the line, or a vector giving both the direction and length of the line.
470// p1 = If given, specifies the starting point of the line.
471// p2 = If given with `p1`, specifies the ending point of line, and indirectly calculates the line length.
472// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
473//
474// Side Effects:
475// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
476// `$idx` is set to the index number of each child being copied.
477//
478// Examples:
479// line_copies(10) sphere(d=1.5);
480// line_copies(10, n=5) sphere(d=3);
481// line_copies([10,5], n=5) sphere(d=3);
482// line_copies(spacing=10, n=6) sphere(d=3);
483// line_copies(spacing=[10,5], n=6) sphere(d=3);
484// line_copies(spacing=10, l=50) sphere(d=3);
485// line_copies(spacing=10, l=[50,30]) sphere(d=3);
486// line_copies(spacing=[10,5], l=50) sphere(d=3);
487// line_copies(l=50, n=4) sphere(d=3);
488// line_copies(l=[50,-30], n=4) sphere(d=3);
489// Example(FlatSpin,VPD=133):
490// line_copies(p1=[0,0,0], p2=[5,5,20], n=6) cuboid([3,2,1]);
491// Example(FlatSpin,VPD=133):
492// line_copies(p1=[0,0,0], p2=[5,5,20], spacing=6) cuboid([3,2,1]);
493// Example: All children are copied to each position
494// line_copies(l=20, n=3) {
495// cube(size=[1,3,1],center=true);
496// cube(size=[3,1,1],center=true);
497// }
498// Example(2D): The functional form of line_copies() returns a list of transform matrices.
499// mats = line_copies([10,5],n=5);
500// for (m = mats) multmatrix(m) circle(d=3);
501// Example(2D): The functional form of line_copies() returns a list of points if given a point.
502// pts = line_copies([10,5],n=5,p=[0,0,0]);
503// move_copies(pts) circle(d=3);
504
505module line_of(spacing, n, l, p1, p2) {
506 deprecate("line_copies");
507 line_copies(spacing, n, l, p1, p2) children();
508}
509
510module line_copies(spacing, n, l, p1, p2)
511{
512 req_children($children);
513 pts = line_copies(spacing=spacing, n=n, l=l, p1=p1, p2=p2, p=[0,0,0]);
514 for (i=idx(pts)) {
515 $idx = i;
516 $pos = pts[i];
517 translate($pos) children();
518 }
519}
520
521function line_copies(spacing, n, l, p1, p2, p=_NO_ARG) =
522 assert(is_undef(spacing) || is_finite(spacing) || is_vector(spacing))
523 assert(is_undef(n) || is_finite(n))
524 assert(is_undef(l) || is_finite(l) || is_vector(l))
525 assert(is_undef(p1) || is_vector(p1))
526 assert(is_undef(p2) || is_vector(p2))
527 assert(is_undef(p2) || is_def(p1), "If p2 is given must also give p1")
528 assert(is_undef(p2) || is_undef(l), "Cannot give both p2 and l")
529 assert(is_undef(n) || num_defined([l,spacing,p2])==1,"If n is given then must give exactly one of 'l', 'spacing', or the 'p1'/'p2' pair")
530 assert(is_def(n) || num_defined([l,spacing,p2])>=1,"If n is given then must give at least one of 'l', 'spacing', or the 'p1'/'p2' pair")
531 let(
532 ll = is_def(l)? scalar_vec3(l, 0)
533 : is_def(spacing) && is_def(n)? (n-1) * scalar_vec3(spacing, 0)
534 : is_def(p1) && is_def(p2)? point3d(p2-p1)
535 : undef,
536 cnt = is_def(n)? n
537 : is_def(spacing) && is_def(ll) ? floor(norm(ll) / norm(scalar_vec3(spacing, 0)) + 1.000001)
538 : 2,
539 spc = cnt<=1? [0,0,0]
540 : is_undef(spacing) && is_def(ll)? ll/(cnt-1)
541 : is_num(spacing) && is_def(ll)? (ll/(cnt-1))
542 : scalar_vec3(spacing, 0)
543 )
544 assert(!is_undef(cnt), "Need two of `spacing`, 'l', 'n', or `p1`/`p2` arguments in `line_copies()`.")
545 let( spos = !is_undef(p1)? point3d(p1) : -(cnt-1)/2 * spc )
546 [for (i=[0:1:cnt-1]) translate(i * spc + spos, p=p)];
547
548
549
550// Function&Module: grid_copies()
551// Synopsis: Places copies of children in an [X,Y] grid.
552// SynTags: MatList, Trans
553// Topics: Transformations, Distributors, Translation, Copiers
554// See Also: move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies()
555//
556// Usage:
557// grid_copies(spacing, size=, [stagger=], [scale=], [inside=]) CHILDREN;
558// grid_copies(n=, size=, [stagger=], [scale=], [inside=]) CHILDREN;
559// grid_copies(spacing, [n], [stagger=], [scale=], [inside=]) CHILDREN;
560// grid_copies(n=, inside=, [stagger], [scale]) CHILDREN;
561// Usage: As a function to translate points, VNF, or Bezier patches
562// copies = grid_copies(spacing, size=, [stagger=], [scale=], [inside=], p=);
563// copies = grid_copies(n=, size=, [stagger=], [scale=], [inside=], p=);
564// copies = grid_copies(spacing, [n], [stagger=], [scale=], [inside=], p=);
565// copies = grid_copies(n=, inside=, [stagger], [scale], p=);
566// Usage: Get Translation Matrices
567// mats = grid_copies(spacing, size=, [stagger=], [scale=], [inside=]);
568// mats = grid_copies(n=, size=, [stagger=], [scale=], [inside=]);
569// mats = grid_copies(spacing, [n], [stagger=], [scale=], [inside=]);
570// mats = grid_copies(n=, inside=, [stagger], [scale]);
571// Description:
572// When called as a module, makes a square or hexagonal grid of copies of children, with an optional masking polygon or region.
573// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
574// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
575//
576// Arguments:
577// spacing = Distance between copies in [X,Y] or scalar distance.
578// n = How many columns and rows of copies to make. Can be given as `[COLS,ROWS]`, or just as a scalar that specifies both. If staggered, count both staggered and unstaggered columns and rows. Default: 2 (3 if staggered)
579// size = The [X,Y] size to spread the copies over.
580// ---
581// stagger = If true, make a staggered (hexagonal) grid. If false, make square grid. If `"alt"`, makes alternate staggered pattern. Default: false
582// inside = If given a list of polygon points, or a region, only creates copies whose center would be inside the polygon or region. Polygon can be concave and/or self crossing.
583// nonzero = If inside is set to a polygon with self-crossings then use the nonzero method for deciding if points are in the polygon. Default: false
584// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
585//
586// Side Effects:
587// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
588// `$col` is set to the integer column number for each child.
589// `$row` is set to the integer row number for each child.
590//
591// Examples:
592// grid_copies(size=50, spacing=10) cylinder(d=10, h=1);
593// grid_copies(size=50, spacing=[10,15]) cylinder(d=10, h=1);
594// grid_copies(spacing=10, n=[13,7], stagger=true) cylinder(d=6, h=5);
595// grid_copies(spacing=10, n=[13,7], stagger="alt") cylinder(d=6, h=5);
596// grid_copies(size=50, n=11, stagger=true) cylinder(d=5, h=1);
597//
598// Example:
599// poly = [[-25,-25], [25,25], [-25,25], [25,-25]];
600// grid_copies(spacing=5, stagger=true, inside=poly)
601// zrot(180/6) cylinder(d=5, h=1, $fn=6);
602// %polygon(poly);
603//
604// Example: Using `$row` and `$col`
605// grid_copies(spacing=8, n=8)
606// color(($row+$col)%2?"black":"red")
607// cube([8,8,0.01], center=false);
608//
609// Example: Makes a grid of hexagon pillars whose tops are all angled to reflect light at [0,0,50], if they were shiny.
610// hexregion = circle(r=50.01,$fn=6);
611// grid_copies(spacing=10, stagger=true, inside=hexregion)
612// union() { // Needed for OpenSCAD 2021.01 as noted above
613// ref_v = (unit([0,0,50]-point3d($pos)) + UP)/2;
614// half_of(v=-ref_v, cp=[0,0,5])
615// zrot(180/6)
616// cylinder(h=20, d=10/cos(180/6)+0.01, $fn=6);
617// }
618
619module grid2d(spacing, n, size, stagger=false, inside=undef, nonzero)
620{
621 deprecate("grid_copies");
622 grid_copies(spacing, n, size, stagger, inside, nonzero) children();
623}
624
625module grid_copies(spacing, n, size, stagger=false, inside=undef, nonzero)
626{
627 req_children($children);
628 dummy = assert(in_list(stagger, [false, true, "alt"]));
629 bounds = is_undef(inside)? undef :
630 is_path(inside)? pointlist_bounds(inside) :
631 assert(is_region(inside))
632 pointlist_bounds(flatten(inside));
633 nonzero = is_path(inside) ? default(nonzero,false)
634 : assert(is_undef(nonzero), "nonzero only allowed if inside is a polygon")
635 false;
636 size = is_num(size)? [size, size] :
637 is_vector(size)? assert(len(size)==2) size :
638 bounds!=undef? [
639 for (i=[0:1]) 2*max(abs(bounds[0][i]),bounds[1][i])
640 ] : undef;
641 spacing = is_num(spacing)? (
642 stagger!=false? polar_to_xy(spacing,60) :
643 [spacing,spacing]
644 ) :
645 is_vector(spacing)? assert(len(spacing)==2) spacing :
646 size!=undef? (
647 is_num(n)? v_div(size,(n-1)*[1,1]) :
648 is_vector(n)? assert(len(n)==2) v_div(size,n-[1,1]) :
649 v_div(size,(stagger==false? [1,1] : [2,2]))
650 ) :
651 undef;
652 n = is_num(n)? [n,n] :
653 is_vector(n)? assert(len(n)==2) n :
654 size!=undef && spacing!=undef? v_floor(v_div(size,spacing))+[1,1] :
655 [2,2];
656 offset = v_mul(spacing, n-[1,1])/2;
657 if (stagger == false) {
658 for (row = [0:1:n.y-1]) {
659 for (col = [0:1:n.x-1]) {
660 pos = v_mul([col,row],spacing) - offset;
661 if (
662 is_undef(inside) ||
663 (is_path(inside) && point_in_polygon(pos, inside, nonzero=nonzero)>=0) ||
664 (is_region(inside) && point_in_region(pos, inside)>=0)
665 ) {
666 $col = col;
667 $row = row;
668 $pos = pos;
669 translate(pos) children();
670 }
671 }
672 }
673 } else {
674 // stagger == true or stagger == "alt"
675 staggermod = (stagger == "alt")? 1 : 0;
676 cols1 = ceil(n.x/2);
677 cols2 = n.x - cols1;
678 for (row = [0:1:n.y-1]) {
679 rowcols = ((row%2) == staggermod)? cols1 : cols2;
680 if (rowcols > 0) {
681 for (col = [0:1:rowcols-1]) {
682 rowdx = (row%2 != staggermod)? spacing.x : 0;
683 pos = v_mul([2*col,row],spacing) + [rowdx,0] - offset;
684 if (
685 is_undef(inside) ||
686 (is_path(inside) && point_in_polygon(pos, inside, nonzero=nonzero)>=0) ||
687 (is_region(inside) && point_in_region(pos, inside)>=0)
688 ) {
689 $col = col * 2 + ((row%2!=staggermod)? 1 : 0);
690 $row = row;
691 $pos = pos;
692 translate(pos) children();
693 }
694 }
695 }
696 }
697 }
698}
699
700
701function grid_copies(spacing, n, size, stagger=false, inside=undef, nonzero, p=_NO_ARG) =
702 let(
703 dummy = assert(in_list(stagger, [false, true, "alt"])),
704 bounds = is_undef(inside)? undef :
705 is_path(inside)? pointlist_bounds(inside) :
706 assert(is_region(inside))
707 pointlist_bounds(flatten(inside)),
708 nonzero = is_path(inside) ? default(nonzero,false)
709 : assert(is_undef(nonzero), "nonzero only allowed if inside is a polygon")
710 false,
711 size = is_num(size)? [size, size] :
712 is_vector(size)? assert(len(size)==2) size :
713 bounds!=undef? [
714 for (i=[0:1]) 2*max(abs(bounds[0][i]),bounds[1][i])
715 ] : undef,
716 spacing = is_num(spacing)? (
717 stagger!=false? polar_to_xy(spacing,60) :
718 [spacing,spacing]
719 ) :
720 is_vector(spacing)? assert(len(spacing)==2) spacing :
721 size!=undef? (
722 is_num(n)? v_div(size,(n-1)*[1,1]) :
723 is_vector(n)? assert(len(n)==2) v_div(size,n-[1,1]) :
724 v_div(size,(stagger==false? [1,1] : [2,2]))
725 ) :
726 undef,
727 n = is_num(n)? [n,n] :
728 is_vector(n)? assert(len(n)==2) n :
729 size!=undef && spacing!=undef? v_floor(v_div(size,spacing))+[1,1] :
730 [2,2],
731 offset = v_mul(spacing, n-[1,1])/2,
732 mats = stagger == false
733 ? [
734 for (row = [0:1:n.y-1], col = [0:1:n.x-1])
735 let( pos = v_mul([col,row],spacing) - offset )
736 if (
737 is_undef(inside) ||
738 (is_path(inside) && point_in_polygon(pos, inside, nonzero=nonzero)>=0) ||
739 (is_region(inside) && point_in_region(pos, inside)>=0)
740 )
741 translate(pos)
742 ]
743 : // stagger == true or stagger == "alt"
744 let(
745 staggermod = (stagger == "alt")? 1 : 0,
746 cols1 = ceil(n.x/2),
747 cols2 = n.x - cols1
748 )
749 [
750 for (row = [0:1:n.y-1])
751 let( rowcols = ((row%2) == staggermod)? cols1 : cols2 )
752 if (rowcols > 0)
753 for (col = [0:1:rowcols-1])
754 let(
755 rowdx = (row%2 != staggermod)? spacing.x : 0,
756 pos = v_mul([2*col,row],spacing) + [rowdx,0] - offset
757 )
758 if (
759 is_undef(inside) ||
760 (is_path(inside) && point_in_polygon(pos, inside, nonzero=nonzero)>=0) ||
761 (is_region(inside) && point_in_region(pos, inside)>=0)
762 )
763 translate(pos)
764 ]
765 )
766 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
767
768
769//////////////////////////////////////////////////////////////////////
770// Section: Rotating copies of all children
771//////////////////////////////////////////////////////////////////////
772
773// Function&Module: rot_copies()
774// Synopsis: Rotates copies of children.
775// SynTags: MatList, Trans
776// Topics: Transformations, Distributors, Rotation, Copiers
777// See Also: rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
778//
779// Usage:
780// rot_copies(rots, [cp=], [sa=], [delta=], [subrot=]) CHILDREN;
781// rot_copies(rots, v, [cp=], [sa=], [delta=], [subrot=]) CHILDREN;
782// rot_copies(n=, [v=], [cp=], [sa=], [delta=], [subrot=]) CHILDREN;
783// Usage: As a function to translate points, VNF, or Bezier patches
784// copies = rot_copies(rots, [cp=], [sa=], [delta=], [subrot=], p=);
785// copies = rot_copies(rots, v, [cp=], [sa=], [delta=], [subrot=], p=);
786// copies = rot_copies(n=, [v=], [cp=], [sa=], [delta=], [subrot=], p=);
787// Usage: Get Translation Matrices
788// mats = rot_copies(rots, [cp=], [sa=], [delta=], [subrot=]);
789// mats = rot_copies(rots, v, [cp=], [sa=], [delta=], [subrot=]);
790// mats = rot_copies(n=, [v=], [cp=], [sa=], [delta=], [subrot=]);
791// Description:
792// When called as a module:
793// - Given a list of [X,Y,Z] rotation angles in `rots`, rotates copies of the children to each of those angles, regardless of axis of rotation.
794// - Given a list of scalar angles in `rots`, rotates copies of the children to each of those angles around the axis of rotation.
795// - If given a vector `v`, that becomes the axis of rotation. Default axis of rotation is UP.
796// - If given a count `n`, makes that many copies, rotated evenly around the axis.
797// - If given an offset `delta`, translates each child by that amount before rotating them into place. This makes rings.
798// - If given a centerpoint `cp`, centers the ring around that centerpoint.
799// - If `subrot` is true, each child will be rotated in place to keep the same size towards the center when making rings.
800// - The first (unrotated) copy will be placed at the relative starting angle `sa`.
801// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
802// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
803//
804// Arguments:
805// rots = A list of [X,Y,Z] rotation angles in degrees. If `v` is given, this will be a list of scalar angles in degrees to rotate around `v`.
806// v = If given, this is the vector of the axis to rotate around.
807// cp = Centerpoint to rotate around. Default: `[0,0,0]`
808// ---
809// n = Optional number of evenly distributed copies, rotated around the axis.
810// sa = Starting angle, in degrees. For use with `n`. Angle is in degrees counter-clockwise. Default: 0
811// delta = [X,Y,Z] amount to move away from cp before rotating. Makes rings of copies. Default: `[0,0,0]`
812// subrot = If false, don't sub-rotate children as they are copied around the ring. Only makes sense when used with `delta`. Default: `true`
813// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
814//
815// Side Effects:
816// `$ang` is set to the rotation angle (or XYZ rotation triplet) of each child copy, and can be used to modify each child individually.
817// `$idx` is set to the index value of each child copy.
818// `$axis` is set to the axis to rotate around, if `rots` was given as a list of angles instead of a list of [X,Y,Z] rotation angles.
819//
820//
821// Example:
822// #cylinder(h=20, r1=5, r2=0);
823// rot_copies([[45,0,0],[0,45,90],[90,-45,270]]) cylinder(h=20, r1=5, r2=0);
824//
825// Example:
826// rot_copies([45, 90, 135], v=DOWN+BACK)
827// yrot(90) cylinder(h=20, r1=5, r2=0);
828// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
829//
830// Example:
831// rot_copies(n=6, v=DOWN+BACK)
832// yrot(90) cylinder(h=20, r1=5, r2=0);
833// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
834//
835// Example:
836// rot_copies(n=6, v=DOWN+BACK, delta=[10,0,0])
837// yrot(90) cylinder(h=20, r1=5, r2=0);
838// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
839//
840// Example:
841// rot_copies(n=6, v=UP+FWD, delta=[10,0,0], sa=45)
842// yrot(90) cylinder(h=20, r1=5, r2=0);
843// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
844//
845// Example:
846// rot_copies(n=6, v=DOWN+BACK, delta=[20,0,0], subrot=false)
847// yrot(90) cylinder(h=20, r1=5, r2=0);
848// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
849module rot_copies(rots=[], v, cp=[0,0,0], n, sa=0, offset=0, delta=[0,0,0], subrot=true)
850{
851 req_children($children);
852 sang = sa + offset;
853 angs = !is_undef(n)?
854 (n<=0? [] : [for (i=[0:1:n-1]) i/n*360+sang]) :
855 rots==[]? [] :
856 assert(!is_string(rots), "Argument rots must be an angle, a list of angles, or a range of angles.")
857 assert(!is_undef(rots[0]), "Argument rots must be an angle, a list of angles, or a range of angles.")
858 [for (a=rots) a];
859 for ($idx = idx(angs)) {
860 $ang = angs[$idx];
861 $axis = v;
862 translate(cp) {
863 rotate(a=$ang, v=v) {
864 translate(delta) {
865 rot(a=(subrot? sang : $ang), v=v, reverse=true) {
866 translate(-cp) {
867 children();
868 }
869 }
870 }
871 }
872 }
873 }
874}
875
876
877function rot_copies(rots=[], v, cp=[0,0,0], n, sa=0, offset=0, delta=[0,0,0], subrot=true, p=_NO_ARG) =
878 let(
879 sang = sa + offset,
880 angs = !is_undef(n)?
881 (n<=0? [] : [for (i=[0:1:n-1]) i/n*360+sang]) :
882 rots==[]? [] :
883 assert(!is_string(rots), "Argument rots must be an angle, a list of angles, or a range of angles.")
884 assert(!is_undef(rots[0]), "Argument rots must be an angle, a list of angles, or a range of angles.")
885 [for (a=rots) a],
886 mats = [
887 for (ang = angs)
888 translate(cp) *
889 rot(a=ang, v=v) *
890 translate(delta) *
891 rot(a=(subrot? sang : ang), v=v, reverse=true) *
892 translate(-cp)
893 ]
894 )
895 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
896
897
898// Function&Module: xrot_copies()
899// Synopsis: Rotates copies of children around the X axis.
900// SynTags: MatList, Trans
901// Topics: Transformations, Distributors, Rotation, Copiers
902// See Also: rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
903//
904// Usage:
905// xrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=]) CHILDREN;
906// xrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=]) CHILDREN;
907// Usage: As a function to translate points, VNF, or Bezier patches
908// copies = xrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=], p=);
909// copies = xrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=], p=);
910// Usage: Get Translation Matrices
911// mats = xrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=]);
912// mats = xrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=]);
913// Description:
914// When called as a module:
915// - Given an array of angles, rotates copies of the children to each of those angles around the X axis.
916// - If given a count `n`, makes that many copies, rotated evenly around the X axis.
917// - If given a radius `r` (or diameter `d`), distributes children around a ring of that size around the X axis.
918// - If given a centerpoint `cp`, centers the rotation around that centerpoint.
919// - If `subrot` is true, each child will be rotated in place to keep the same size towards the center when making rings.
920// - The first (unrotated) copy will be placed at the relative starting angle `sa`.
921// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
922// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
923//
924// Arguments:
925// rots = Optional array of rotation angles, in degrees, to make copies at.
926// cp = Centerpoint to rotate around.
927// ---
928// n = Optional number of evenly distributed copies to be rotated around the ring.
929// sa = Starting angle, in degrees. For use with `n`. Angle is in degrees counter-clockwise from Y+, when facing the origin from X+. First unrotated copy is placed at that angle.
930// r = If given, makes a ring of child copies around the X axis, at the given radius. Default: 0
931// d = If given, makes a ring of child copies around the X axis, at the given diameter.
932// subrot = If false, don't sub-rotate children as they are copied around the ring.
933// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
934//
935// Side Effects:
936// `$idx` is set to the index value of each child copy.
937// `$ang` is set to the rotation angle of each child copy, and can be used to modify each child individually.
938// `$axis` is set to the axis vector rotated around.
939//
940//
941// Example:
942// xrot_copies([180, 270, 315])
943// cylinder(h=20, r1=5, r2=0);
944// color("red",0.333) cylinder(h=20, r1=5, r2=0);
945//
946// Example:
947// xrot_copies(n=6)
948// cylinder(h=20, r1=5, r2=0);
949// color("red",0.333) cylinder(h=20, r1=5, r2=0);
950//
951// Example:
952// xrot_copies(n=6, r=10)
953// xrot(-90) cylinder(h=20, r1=5, r2=0);
954// color("red",0.333) xrot(-90) cylinder(h=20, r1=5, r2=0);
955//
956// Example:
957// xrot_copies(n=6, r=10, sa=45)
958// xrot(-90) cylinder(h=20, r1=5, r2=0);
959// color("red",0.333) xrot(-90) cylinder(h=20, r1=5, r2=0);
960//
961// Example:
962// xrot_copies(n=6, r=20, subrot=false)
963// xrot(-90) cylinder(h=20, r1=5, r2=0, center=true);
964// color("red",0.333) xrot(-90) cylinder(h=20, r1=5, r2=0, center=true);
965module xrot_copies(rots=[], cp=[0,0,0], n, sa=0, r, d, subrot=true)
966{
967 req_children($children);
968 r = get_radius(r=r, d=d, dflt=0);
969 rot_copies(rots=rots, v=RIGHT, cp=cp, n=n, sa=sa, delta=[0, r, 0], subrot=subrot) children();
970}
971
972
973function xrot_copies(rots=[], cp=[0,0,0], n, sa=0, r, d, subrot=true, p=_NO_ARG) =
974 let( r = get_radius(r=r, d=d, dflt=0) )
975 rot_copies(rots=rots, v=RIGHT, cp=cp, n=n, sa=sa, delta=[0, r, 0], subrot=subrot, p=p);
976
977
978// Function&Module: yrot_copies()
979// Synopsis: Rotates copies of children around the Y axis.
980// SynTags: MatList, Trans
981// Topics: Transformations, Distributors, Rotation, Copiers
982// See Also: rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
983//
984// Usage:
985// yrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=]) CHILDREN;
986// yrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=]) CHILDREN;
987// Usage: As a function to translate points, VNF, or Bezier patches
988// copies = yrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=], p=);
989// copies = yrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=], p=);
990// Usage: Get Translation Matrices
991// mats = yrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=]);
992// mats = yrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=]);
993// Description:
994// When called as a module:
995// - Given an array of angles, rotates copies of the children to each of those angles around the Y axis.
996// - If given a count `n`, makes that many copies, rotated evenly around the Y axis.
997// - If given a radius `r` (or diameter `d`), distributes children around a ring of that size around the Y axis.
998// - If given a centerpoint `cp`, centers the rotation around that centerpoint.
999// - If `subrot` is true, each child will be rotated in place to keep the same size towards the center when making rings.
1000// - The first (unrotated) copy will be placed at the relative starting angle `sa`.
1001// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1002// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1003//
1004// Arguments:
1005// rots = Optional array of rotation angles, in degrees, to make copies at.
1006// cp = Centerpoint to rotate around.
1007// ---
1008// n = Optional number of evenly distributed copies to be rotated around the ring.
1009// sa = Starting angle, in degrees. For use with `n`. Angle is in degrees counter-clockwise from X-, when facing the origin from Y+.
1010// r = If given, makes a ring of child copies around the Y axis, at the given radius. Default: 0
1011// d = If given, makes a ring of child copies around the Y axis, at the given diameter.
1012// subrot = If false, don't sub-rotate children as they are copied around the ring.
1013// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1014//
1015// Side Effects:
1016// `$idx` is set to the index value of each child copy.
1017// `$ang` is set to the rotation angle of each child copy, and can be used to modify each child individually.
1018// `$axis` is set to the axis vector rotated around.
1019//
1020//
1021// Example:
1022// yrot_copies([180, 270, 315])
1023// cylinder(h=20, r1=5, r2=0);
1024// color("red",0.333) cylinder(h=20, r1=5, r2=0);
1025//
1026// Example:
1027// yrot_copies(n=6)
1028// cylinder(h=20, r1=5, r2=0);
1029// color("red",0.333) cylinder(h=20, r1=5, r2=0);
1030//
1031// Example:
1032// yrot_copies(n=6, r=10)
1033// yrot(-90) cylinder(h=20, r1=5, r2=0);
1034// color("red",0.333) yrot(-90) cylinder(h=20, r1=5, r2=0);
1035//
1036// Example:
1037// yrot_copies(n=6, r=10, sa=45)
1038// yrot(-90) cylinder(h=20, r1=5, r2=0);
1039// color("red",0.333) yrot(-90) cylinder(h=20, r1=5, r2=0);
1040//
1041// Example:
1042// yrot_copies(n=6, r=20, subrot=false)
1043// yrot(-90) cylinder(h=20, r1=5, r2=0, center=true);
1044// color("red",0.333) yrot(-90) cylinder(h=20, r1=5, r2=0, center=true);
1045module yrot_copies(rots=[], cp=[0,0,0], n, sa=0, r, d, subrot=true)
1046{
1047 req_children($children);
1048 r = get_radius(r=r, d=d, dflt=0);
1049 rot_copies(rots=rots, v=BACK, cp=cp, n=n, sa=sa, delta=[-r, 0, 0], subrot=subrot) children();
1050}
1051
1052
1053function yrot_copies(rots=[], cp=[0,0,0], n, sa=0, r, d, subrot=true, p=_NO_ARG) =
1054 let( r = get_radius(r=r, d=d, dflt=0) )
1055 rot_copies(rots=rots, v=BACK, cp=cp, n=n, sa=sa, delta=[-r, 0, 0], subrot=subrot, p=p);
1056
1057
1058// Function&Module: zrot_copies()
1059// Synopsis: Rotates copies of children around the Z axis.
1060// SynTags: MatList, Trans
1061// Topics: Transformations, Distributors, Rotation, Copiers
1062// See Also: rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), sphere_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
1063//
1064// Usage:
1065// zrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=]) CHILDREN;
1066// zrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=]) CHILDREN;
1067// Usage: As a function to translate points, VNF, or Bezier patches
1068// copies = zrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=], p=);
1069// copies = zrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=], p=);
1070// Usage: Get Translation Matrices
1071// mats = zrot_copies(rots, [cp], [r=|d=], [sa=], [subrot=]);
1072// mats = zrot_copies(n=, [cp=], [r=|d=], [sa=], [subrot=]);
1073//
1074// Description:
1075// When called as a module:
1076// - Given an array of angles, rotates copies of the children to each of those angles around the Z axis.
1077// - If given a count `n`, makes that many copies, rotated evenly around the Z axis.
1078// - If given a radius `r` (or diameter `d`), distributes children around a ring of that size around the Z axis.
1079// - If given a centerpoint `cp`, centers the rotation around that centerpoint.
1080// - If `subrot` is true, each child will be rotated in place to keep the same size towards the center when making rings.
1081// - The first (unrotated) copy will be placed at the relative starting angle `sa`.
1082// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1083// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1084//
1085// Arguments:
1086// rots = Optional array of rotation angles, in degrees, to make copies at.
1087// cp = Centerpoint to rotate around. Default: [0,0,0]
1088// ---
1089// n = Optional number of evenly distributed copies to be rotated around the ring.
1090// sa = Starting angle, in degrees. For use with `n`. Angle is in degrees counter-clockwise from X+, when facing the origin from Z+. Default: 0
1091// r = If given, makes a ring of child copies around the Z axis, at the given radius. Default: 0
1092// d = If given, makes a ring of child copies around the Z axis, at the given diameter.
1093// subrot = If false, don't sub-rotate children as they are copied around the ring. Default: true
1094// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1095//
1096// Side Effects:
1097// `$idx` is set to the index value of each child copy.
1098// `$ang` is set to the rotation angle of each child copy, and can be used to modify each child individually.
1099// `$axis` is set to the axis vector rotated around.
1100//
1101//
1102// Example:
1103// zrot_copies([180, 270, 315])
1104// yrot(90) cylinder(h=20, r1=5, r2=0);
1105// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
1106//
1107// Example:
1108// zrot_copies(n=6)
1109// yrot(90) cylinder(h=20, r1=5, r2=0);
1110// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
1111//
1112// Example:
1113// zrot_copies(n=6, r=10)
1114// yrot(90) cylinder(h=20, r1=5, r2=0);
1115// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0);
1116//
1117// Example:
1118// zrot_copies(n=6, r=20, sa=45)
1119// yrot(90) cylinder(h=20, r1=5, r2=0, center=true);
1120// color("red",0.333) yrot(90) cylinder(h=20, r1=5, r2=0, center=true);
1121//
1122// Example:
1123// zrot_copies(n=6, r=20, subrot=false)
1124// yrot(-90) cylinder(h=20, r1=5, r2=0, center=true);
1125// color("red",0.333) yrot(-90) cylinder(h=20, r1=5, r2=0, center=true);
1126module zrot_copies(rots=[], cp=[0,0,0], n, sa=0, r, d, subrot=true)
1127{
1128 r = get_radius(r=r, d=d, dflt=0);
1129 rot_copies(rots=rots, v=UP, cp=cp, n=n, sa=sa, delta=[r, 0, 0], subrot=subrot) children();
1130}
1131
1132
1133function zrot_copies(rots=[], cp=[0,0,0], n, sa=0, r, d, subrot=true, p=_NO_ARG) =
1134 let( r = get_radius(r=r, d=d, dflt=0) )
1135 rot_copies(rots=rots, v=UP, cp=cp, n=n, sa=sa, delta=[r, 0, 0], subrot=subrot, p=p);
1136
1137
1138// Function&Module: arc_copies()
1139// Synopsis: Distributes duplicates of children along an arc.
1140// SynTags: MatList, Trans
1141// Topics: Transformations, Distributors, Rotation, Copiers
1142// See Also: rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), sphere_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
1143//
1144// Usage:
1145// arc_copies(n, r|d=, [sa=], [ea=], [rot=]) CHILDREN;
1146// arc_copies(n, rx=|dx=, ry=|dy=, [sa=], [ea=], [rot=]) CHILDREN;
1147// Usage: As a function to translate points, VNF, or Bezier patches
1148// copies = arc_copies(n, r|d=, [sa=], [ea=], [rot=], p=);
1149// copies = arc_copies(n, rx=|dx=, ry=|dy=, [sa=], [ea=], [rot=], p=);
1150// Usage: Get Translation Matrices
1151// mats = arc_copies(n, r|d=, [sa=], [ea=], [rot=]);
1152// mats = arc_copies(n, rx=|dx=, ry=|dy=, [sa=], [ea=], [rot=]);
1153//
1154//
1155// Description:
1156// When called as a module, evenly distributes n duplicate children around an ovoid arc on the XY plane.
1157// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1158// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1159//
1160// Arguments:
1161// n = number of copies to distribute around the circle. (Default: 6)
1162// r = radius of circle (Default: 1)
1163// ---
1164// rx = radius of ellipse on X axis. Used instead of r.
1165// ry = radius of ellipse on Y axis. Used instead of r.
1166// d = diameter of circle. (Default: 2)
1167// dx = diameter of ellipse on X axis. Used instead of d.
1168// dy = diameter of ellipse on Y axis. Used instead of d.
1169// rot = whether to rotate the copied children. (Default: true)
1170// sa = starting angle. (Default: 0.0)
1171// ea = ending angle. Will distribute copies CCW from sa to ea. (Default: 360.0)
1172// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1173//
1174// Side Effects:
1175// `$ang` is set to the rotation angle of each child copy, and can be used to modify each child individually.
1176// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
1177// `$idx` is set to the index value of each child copy.
1178//
1179//
1180// Example:
1181// #cube(size=[10,3,3],center=true);
1182// arc_copies(d=40, n=5) cube(size=[10,3,3],center=true);
1183//
1184// Example:
1185// #cube(size=[10,3,3],center=true);
1186// arc_copies(d=40, n=5, sa=45, ea=225) cube(size=[10,3,3],center=true);
1187//
1188// Example:
1189// #cube(size=[10,3,3],center=true);
1190// arc_copies(r=15, n=8, rot=false) cube(size=[10,3,3],center=true);
1191//
1192// Example:
1193// #cube(size=[10,3,3],center=true);
1194// arc_copies(rx=20, ry=10, n=8) cube(size=[10,3,3],center=true);
1195// Example(2D): Using `$idx` to alternate shapes
1196// arc_copies(r=50, n=19, sa=0, ea=180)
1197// if ($idx % 2 == 0) rect(6);
1198// else circle(d=6);
1199
1200module arc_of(n=6,r,rx,ry,d,dx,dy,sa=0,ea=360,rot=true){
1201 deprecate("arc_copies");
1202 arc_copies(n,r,rx,ry,d,dx,dy,sa,ea,rot) children();
1203}
1204
1205
1206module arc_copies(
1207 n=6,
1208 r=undef,
1209 rx=undef, ry=undef,
1210 d=undef, dx=undef, dy=undef,
1211 sa=0, ea=360,
1212 rot=true
1213) {
1214 req_children($children);
1215 rx = get_radius(r1=rx, r=r, d1=dx, d=d, dflt=1);
1216 ry = get_radius(r1=ry, r=r, d1=dy, d=d, dflt=1);
1217 sa = posmod(sa, 360);
1218 ea = posmod(ea, 360);
1219 n = (abs(ea-sa)<0.01)?(n+1):n;
1220 delt = (((ea<=sa)?360.0:0)+ea-sa)/(n-1);
1221 for ($idx = [0:1:n-1]) {
1222 $ang = sa + ($idx * delt);
1223 $pos =[rx*cos($ang), ry*sin($ang), 0];
1224 translate($pos) {
1225 zrot(rot? atan2(ry*sin($ang), rx*cos($ang)) : 0) {
1226 children();
1227 }
1228 }
1229 }
1230}
1231
1232
1233function arc_copies(
1234 n=6,
1235 r=undef,
1236 rx=undef, ry=undef,
1237 d=undef, dx=undef, dy=undef,
1238 sa=0, ea=360,
1239 rot=true,
1240 p=_NO_ARG
1241) =
1242 let(
1243 rx = get_radius(r1=rx, r=r, d1=dx, d=d, dflt=1),
1244 ry = get_radius(r1=ry, r=r, d1=dy, d=d, dflt=1),
1245 sa = posmod(sa, 360),
1246 ea = posmod(ea, 360),
1247 n = (abs(ea-sa)<0.01)?(n+1):n,
1248 delt = (((ea<=sa)?360.0:0)+ea-sa)/(n-1),
1249 mats = [
1250 for (i = [0:1:n-1])
1251 let(
1252 ang = sa + (i * delt),
1253 pos =[rx*cos(ang), ry*sin(ang), 0],
1254 ang2 = rot? atan2(ry*sin(ang), rx*cos(ang)) : 0
1255 )
1256 translate(pos) * zrot(ang2)
1257 ]
1258 )
1259 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
1260
1261
1262
1263// Function&Module: sphere_copies()
1264// Synopsis: Distributes copies of children over the surface of a sphere.
1265// SynTags: MatList, Trans
1266// Topics: Transformations, Distributors, Rotation, Copiers
1267// See Also: rot_copies(), xrot_copies(), yrot_copies(), zrot_copies(), arc_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
1268//
1269// Usage:
1270// sphere_copies(n, r|d=, [cone_ang=], [scale=], [perp=]) CHILDREN;
1271// Usage: As a function to translate points, VNF, or Bezier patches
1272// copies = sphere_copies(n, r|d=, [cone_ang=], [scale=], [perp=], p=);
1273// Usage: Get Translation Matrices
1274// mats = sphere_copies(n, r|d=, [cone_ang=], [scale=], [perp=]);
1275//
1276// Description:
1277// When called as a module, spreads children semi-evenly over the surface of a sphere or ellipsoid.
1278// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1279// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1280//
1281// Arguments:
1282// n = How many copies to evenly spread over the surface.
1283// r = Radius of the sphere to distribute over
1284// ---
1285// d = Diameter of the sphere to distribute over
1286// cone_ang = Angle of the cone, in degrees, to limit how much of the sphere gets covered. For full sphere coverage, use 180. Measured pre-scaling. Default: 180
1287// scale = The [X,Y,Z] scaling factors to reshape the sphere being covered.
1288// perp = If true, rotate children to be perpendicular to the sphere surface. Default: true
1289// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1290//
1291// Side Effects:
1292// `$pos` is set to the relative post-scaled centerpoint of each child copy, and can be used to modify each child individually.
1293// `$theta` is set to the theta angle of the child from the center of the sphere.
1294// `$phi` is set to the pre-scaled phi angle of the child from the center of the sphere.
1295// `$rad` is set to the pre-scaled radial distance of the child from the center of the sphere.
1296// `$idx` is set to the index number of each child being copied.
1297//
1298//
1299// Example:
1300// sphere_copies(n=250, d=100, cone_ang=45, scale=[3,3,1])
1301// cylinder(d=10, h=10, center=false);
1302//
1303// Example:
1304// sphere_copies(n=500, d=100, cone_ang=180)
1305// color(unit(point3d(v_abs($pos))))
1306// cylinder(d=8, h=10, center=false);
1307
1308module ovoid_spread(n=100, r=undef, d=undef, cone_ang=90, scale=[1,1,1], perp=true)
1309{
1310 deprecate("sphere_copies");
1311 sphere_copies(n,r,d,cone_ang,scale,perp) children();
1312}
1313
1314
1315module sphere_copies(n=100, r=undef, d=undef, cone_ang=90, scale=[1,1,1], perp=true)
1316{
1317 req_children($children);
1318 r = get_radius(r=r, d=d, dflt=50);
1319 cnt = ceil(n / (cone_ang/180));
1320
1321 // Calculate an array of [theta,phi] angles for `n` number of
1322 // points, almost evenly spaced across the surface of a sphere.
1323 // This approximation is based on the golden spiral method.
1324 theta_phis = [for (x=[0:1:n-1]) [180*(1+sqrt(5))*(x+0.5)%360, acos(1-2*(x+0.5)/cnt)]];
1325
1326 for ($idx = idx(theta_phis)) {
1327 tp = theta_phis[$idx];
1328 xyz = spherical_to_xyz(r, tp[0], tp[1]);
1329 $pos = v_mul(xyz,point3d(scale,1));
1330 $theta = tp[0];
1331 $phi = tp[1];
1332 $rad = r;
1333 translate($pos) {
1334 if (perp) {
1335 rot(from=UP, to=xyz) children();
1336 } else {
1337 children();
1338 }
1339 }
1340 }
1341}
1342
1343
1344function sphere_copies(n=100, r=undef, d=undef, cone_ang=90, scale=[1,1,1], perp=true, p=_NO_ARG) =
1345 let(
1346 r = get_radius(r=r, d=d, dflt=50),
1347 cnt = ceil(n / (cone_ang/180)),
1348
1349 // Calculate an array of [theta,phi] angles for `n` number of
1350 // points, almost evenly spaced across the surface of a sphere.
1351 // This approximation is based on the golden spiral method.
1352 theta_phis = [for (x=[0:1:n-1]) [180*(1+sqrt(5))*(x+0.5)%360, acos(1-2*(x+0.5)/cnt)]],
1353
1354 mats = [
1355 for (tp = theta_phis)
1356 let(
1357 xyz = spherical_to_xyz(r, tp[0], tp[1]),
1358 pos = v_mul(xyz,point3d(scale,1))
1359 )
1360 translate(pos) *
1361 (perp? rot(from=UP, to=xyz) : ident(4))
1362 ]
1363 )
1364 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
1365
1366
1367
1368// Section: Placing copies of all children on a path
1369
1370
1371// Function&Module: path_copies()
1372// Synopsis: Uniformly distributes copies of children along a path.
1373// SynTags: MatList, Trans
1374// Topics: Transformations, Distributors, Copiers
1375// See Also: line_copies(), move_copies(), xcopies(), ycopies(), zcopies(), grid_copies(), xflip_copy(), yflip_copy(), zflip_copy(), mirror_copy()
1376//
1377// Usage: Uniformly distribute copies
1378// path_copies(path, [n], [spacing], [sp], [rotate_children], [closed=]) CHILDREN;
1379// Usage: Place copies at specified locations
1380// path_copies(path, dist=, [rotate_children=], [closed=]) CHILDREN;
1381// Usage: As a function to translate points, VNF, or Bezier patches
1382// copies = path_copies(path, [n], [spacing], [sp], [rotate_children], [closed=], p=);
1383// copies = path_copies(path, dist=, [rotate_children=], [closed=], p=);
1384// Usage: Get Translation Matrices
1385// mats = path_copies(path, [n], [spacing], [sp], [rotate_children], [closed=]);
1386// mats = path_copies(path, dist=, [rotate_children=], [closed=]);
1387//
1388// Description:
1389// When called as a module:
1390// - Place copies all of the children at points along the path based on path length. You can specify `dist` as
1391// - a scalar or distance list and the children will be placed at the specified distances from the start of the path. Otherwise the children are
1392// - placed at uniformly spaced points along the path. If you specify `n` but not `spacing` then `n` copies will be placed
1393// - with one at path[0] if `closed` is true, or spanning the entire path from start to end if `closed` is false.
1394// - If you specify `spacing` but not `n` then copies will spread out starting from one set at path[0] for `closed=true` or at the path center for open paths.
1395// - If you specify `sp` then the copies will start at distance `sp` from the start of the path.
1396// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1397// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1398//
1399// Arguments:
1400// path = path or 1-region where children are placed
1401// n = number of copies
1402// spacing = space between copies
1403// sp = if given, copies will start distance sp from the path start and spread beyond that point
1404// rotate_children = if true, rotate children to line up with curve normal. Default: true
1405// ---
1406// dist = Specify a list of distances to determine placement of children.
1407// closed = If true treat path as a closed curve. Default: false
1408// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1409//
1410// Side Effects:
1411// `$pos` is set to the center of each copy
1412// `$idx` is set to the index number of each copy. In the case of closed paths the first copy is at `path[0]` unless you give `sp`.
1413// `$dir` is set to the direction vector of the path at the point where the copy is placed.
1414// `$normal` is set to the direction of the normal vector to the path direction that is coplanar with the path at this point
1415//
1416//
1417// Example(2D):
1418// spiral = [for(theta=[0:360*8]) theta * [cos(theta), sin(theta)]]/100;
1419// stroke(spiral,width=.25);
1420// color("red") path_copies(spiral, n=100) circle(r=1);
1421// Example(2D):
1422// circle = regular_ngon(n=64, or=10);
1423// stroke(circle,width=1,closed=true);
1424// color("green") path_copies(circle, n=7, closed=true) circle(r=1+$idx/3);
1425// Example(2D):
1426// heptagon = regular_ngon(n=7, or=10);
1427// stroke(heptagon, width=1, closed=true);
1428// color("purple") path_copies(heptagon, n=9, closed=true) rect([0.5,3],anchor=FRONT);
1429// Example(2D): Direction at the corners is the average of the two adjacent edges
1430// heptagon = regular_ngon(n=7, or=10);
1431// stroke(heptagon, width=1, closed=true);
1432// color("purple") path_copies(heptagon, n=7, closed=true) rect([0.5,3],anchor=FRONT);
1433// Example(2D): Don't rotate the children
1434// heptagon = regular_ngon(n=7, or=10);
1435// stroke(heptagon, width=1, closed=true);
1436// color("red") path_copies(heptagon, n=9, closed=true, rotate_children=false) rect([0.5,3],anchor=FRONT);
1437// Example(2D): Open path, specify `n`
1438// sinwav = [for(theta=[0:360]) 5*[theta/180, sin(theta)]];
1439// stroke(sinwav,width=.1);
1440// color("red") path_copies(sinwav, n=5) rect([.2,1.5],anchor=FRONT);
1441// Example(2D): Open path, specify `n` and `spacing`
1442// sinwav = [for(theta=[0:360]) 5*[theta/180, sin(theta)]];
1443// stroke(sinwav,width=.1);
1444// color("red") path_copies(sinwav, n=5, spacing=1) rect([.2,1.5],anchor=FRONT);
1445// Example(2D): Closed path, specify `n` and `spacing`, copies centered around circle[0]
1446// circle = regular_ngon(n=64,or=10);
1447// stroke(circle,width=.1,closed=true);
1448// color("red") path_copies(circle, n=10, spacing=1, closed=true) rect([.2,1.5],anchor=FRONT);
1449// Example(2D): Open path, specify `spacing`
1450// sinwav = [for(theta=[0:360]) 5*[theta/180, sin(theta)]];
1451// stroke(sinwav,width=.1);
1452// color("red") path_copies(sinwav, spacing=5) rect([.2,1.5],anchor=FRONT);
1453// Example(2D): Open path, specify `sp`
1454// sinwav = [for(theta=[0:360]) 5*[theta/180, sin(theta)]];
1455// stroke(sinwav,width=.1);
1456// color("red") path_copies(sinwav, n=5, sp=18) rect([.2,1.5],anchor=FRONT);
1457// Example(2D): Open path, specify `dist`
1458// sinwav = [for(theta=[0:360]) 5*[theta/180, sin(theta)]];
1459// stroke(sinwav,width=.1);
1460// color("red") path_copies(sinwav, dist=[1,4,9,16]) rect([.2,1.5],anchor=FRONT);
1461// Example(2D):
1462// wedge = arc(angle=[0,100], r=10, $fn=64);
1463// difference(){
1464// polygon(concat([[0,0]],wedge));
1465// path_copies(wedge,n=5,spacing=3) fwd(.1) rect([1,4],anchor=FRONT);
1466// }
1467// Example(Spin,VPD=115): 3d example, with children rotated into the plane of the path
1468// tilted_circle = lift_plane([[0,0,0], [5,0,5], [0,2,3]],regular_ngon(n=64, or=12));
1469// path_sweep(regular_ngon(n=16,or=.1),tilted_circle);
1470// path_copies(tilted_circle, n=15,closed=true) {
1471// color("blue") cyl(h=3,r=.2, anchor=BOTTOM); // z-aligned cylinder
1472// color("red") xcyl(h=10,r=.2, anchor=FRONT+LEFT); // x-aligned cylinder
1473// }
1474// Example(Spin,VPD=115): 3d example, with rotate_children set to false
1475// tilted_circle = lift_plane([[0,0,0], [5,0,5], [0,2,3]], regular_ngon(n=64, or=12));
1476// path_sweep(regular_ngon(n=16,or=.1),tilted_circle);
1477// path_copies(tilted_circle, n=25,rotate_children=false,closed=true) {
1478// color("blue") cyl(h=3,r=.2, anchor=BOTTOM); // z-aligned cylinder
1479// color("red") xcyl(h=10,r=.2, anchor=FRONT+LEFT); // x-aligned cylinder
1480// }
1481
1482module path_spread(path, n, spacing, sp=undef, rotate_children=true, dist, closed){
1483 deprecate("path_copes");
1484 path_copies(path,n,spacing,sp,dist,rotate_children,dist, closed) children();
1485}
1486
1487
1488module path_copies(path, n, spacing, sp=undef, dist, rotate_children=true, dist, closed)
1489{
1490 req_children($children);
1491 is_1reg = is_1region(path);
1492 path = is_1reg ? path[0] : path;
1493 closed = default(closed, is_1reg);
1494 length = path_length(path,closed);
1495 distind = is_def(dist) ? sortidx(dist) : undef;
1496 distances =
1497 is_def(dist) ? assert(is_undef(n) && is_undef(spacing) && is_undef(sp), "Can't use n, spacing or undef with dist")
1498 select(dist,distind)
1499 : is_def(sp)? ( // Start point given
1500 is_def(n) && is_def(spacing)? count(n,sp,spacing) :
1501 is_def(n)? lerpn(sp, length, n) :
1502 list([sp:spacing:length])
1503 )
1504 : is_def(n) && is_undef(spacing)? lerpn(0,length,n,!closed) // N alone given
1505 : ( // No start point and spacing is given, N maybe given
1506 let(
1507 n = is_def(n)? n : floor(length/spacing)+(closed?0:1),
1508 ptlist = count(n,0,spacing),
1509 listcenter = mean(ptlist)
1510 ) closed?
1511 sort([for(entry=ptlist) posmod(entry-listcenter,length)]) :
1512 [for(entry=ptlist) entry + length/2-listcenter ]
1513 );
1514 distOK = min(distances)>=0 && max(distances)<=length;
1515 dummy = assert(distOK,"Cannot fit all of the copies");
1516 cutlist = path_cut_points(path, distances, closed, direction=true);
1517 planar = len(path[0])==2;
1518 for(i=[0:1:len(cutlist)-1]) {
1519 $pos = cutlist[i][0];
1520 $idx = is_def(dist) ? distind[i] : i;
1521 $dir = rotate_children ? (planar?[1,0]:[1,0,0]) : cutlist[i][2];
1522 $normal = rotate_children? (planar?[0,1]:[0,0,1]) : cutlist[i][3];
1523 translate($pos) {
1524 if (rotate_children) {
1525 if(planar) {
1526 rot(from=[0,1],to=cutlist[i][3]) children();
1527 } else {
1528 frame_map(x=cutlist[i][2], z=cutlist[i][3])
1529 children();
1530 }
1531 } else {
1532 children();
1533 }
1534 }
1535 }
1536}
1537
1538
1539function path_copies(path, n, spacing, sp=undef, dist, rotate_children=true, dist, closed, p=_NO_ARG) =
1540 let(
1541 is_1reg = is_1region(path),
1542 path = is_1reg ? path[0] : path,
1543 closed = default(closed, is_1reg),
1544 length = path_length(path,closed),
1545 distind = is_def(dist) ? sortidx(dist) : undef,
1546 distances =
1547 is_def(dist) ? assert(is_undef(n) && is_undef(spacing) && is_undef(sp), "Can't use n, spacing or undef with dist")
1548 select(dist,distind)
1549 : is_def(sp)? ( // Start point given
1550 is_def(n) && is_def(spacing)? count(n,sp,spacing) :
1551 is_def(n)? lerpn(sp, length, n) :
1552 list([sp:spacing:length])
1553 )
1554 : is_def(n) && is_undef(spacing)? lerpn(0,length,n,!closed) // N alone given
1555 : ( // No start point and spacing is given, N maybe given
1556 let(
1557 n = is_def(n)? n : floor(length/spacing)+(closed?0:1),
1558 ptlist = count(n,0,spacing),
1559 listcenter = mean(ptlist)
1560 ) closed?
1561 sort([for(entry=ptlist) posmod(entry-listcenter,length)]) :
1562 [for(entry=ptlist) entry + length/2-listcenter ]
1563 ),
1564 distOK = min(distances)>=0 && max(distances)<=length,
1565 dummy = assert(distOK,"Cannot fit all of the copies"),
1566 cutlist = path_cut_points(path, distances, closed, direction=true),
1567 planar = len(path[0])==2,
1568 mats = [
1569 for(i=[0:1:len(cutlist)-1])
1570 translate(cutlist[i][0]) * (
1571 !rotate_children? ident(4) :
1572 planar? rot(from=[0,1],to=cutlist[i][3]) :
1573 frame_map(x=cutlist[i][2], z=cutlist[i][3])
1574 )
1575 ]
1576 )
1577 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
1578
1579
1580
1581//////////////////////////////////////////////////////////////////////
1582// Section: Making a copy of all children with reflection
1583//////////////////////////////////////////////////////////////////////
1584
1585// Function&Module: xflip_copy()
1586// Synopsis: Makes a copy of children mirrored across the X axis.
1587// SynTags: MatList, Trans
1588// Topics: Transformations, Distributors, Translation, Copiers
1589// See Also: yflip_copy(), zflip_copy(), mirror_copy(), path_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
1590//
1591// Usage:
1592// xflip_copy([offset], [x]) CHILDREN;
1593// Usage: As a function to translate points, VNF, or Bezier patches
1594// copies = xflip_copy([offset], [x], p=);
1595// Usage: Get Translation Matrices
1596// mats = xflip_copy([offset], [x]);
1597//
1598// Description:
1599// When called as a module, makes a copy of the children, mirrored across the X axis.
1600// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1601// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1602//
1603// Arguments:
1604// offset = Distance to offset children right, before copying.
1605// x = The X coordinate of the mirroring plane. Default: 0
1606// ---
1607// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1608//
1609// Side Effects:
1610// `$orig` is true for the original instance of children. False for the copy.
1611// `$idx` is set to the index value of each copy.
1612//
1613//
1614// Example:
1615// xflip_copy() yrot(90) cylinder(h=20, r1=4, r2=0);
1616// color("blue",0.25) cube([0.01,15,15], center=true);
1617//
1618// Example:
1619// xflip_copy(offset=5) yrot(90) cylinder(h=20, r1=4, r2=0);
1620// color("blue",0.25) cube([0.01,15,15], center=true);
1621//
1622// Example:
1623// xflip_copy(x=-5) yrot(90) cylinder(h=20, r1=4, r2=0);
1624// color("blue",0.25) left(5) cube([0.01,15,15], center=true);
1625module xflip_copy(offset=0, x=0)
1626{
1627 req_children($children);
1628 mirror_copy(v=[1,0,0], offset=offset, cp=[x,0,0]) children();
1629}
1630
1631
1632function xflip_copy(offset=0, x=0, p=_NO_ARG) =
1633 mirror_copy(v=[1,0,0], offset=offset, cp=[x,0,0], p=p);
1634
1635
1636// Function&Module: yflip_copy()
1637// Synopsis: Makes a copy of children mirrored across the Y axis.
1638// SynTags: MatList, Trans
1639// Topics: Transformations, Distributors, Translation, Copiers
1640// See Also: xflip_copy(), zflip_copy(), mirror_copy(), path_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
1641//
1642// Usage:
1643// yflip_copy([offset], [y]) CHILDREN;
1644// Usage: As a function to translate points, VNF, or Bezier patches
1645// copies = yflip_copy([offset], [y], p=);
1646// Usage: Get Translation Matrices
1647// mats = yflip_copy([offset], [y]);
1648//
1649// Description:
1650// When called as a module, makes a copy of the children, mirrored across the Y axis.
1651// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1652// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1653//
1654// Arguments:
1655// offset = Distance to offset children back, before copying.
1656// y = The Y coordinate of the mirroring plane. Default: 0
1657// ---
1658// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1659//
1660// Side Effects:
1661// `$orig` is true for the original instance of children. False for the copy.
1662// `$idx` is set to the index value of each copy.
1663//
1664//
1665// Example:
1666// yflip_copy() xrot(-90) cylinder(h=20, r1=4, r2=0);
1667// color("blue",0.25) cube([15,0.01,15], center=true);
1668//
1669// Example:
1670// yflip_copy(offset=5) xrot(-90) cylinder(h=20, r1=4, r2=0);
1671// color("blue",0.25) cube([15,0.01,15], center=true);
1672//
1673// Example:
1674// yflip_copy(y=-5) xrot(-90) cylinder(h=20, r1=4, r2=0);
1675// color("blue",0.25) fwd(5) cube([15,0.01,15], center=true);
1676module yflip_copy(offset=0, y=0)
1677{
1678 req_children($children);
1679 mirror_copy(v=[0,1,0], offset=offset, cp=[0,y,0]) children();
1680}
1681
1682
1683function yflip_copy(offset=0, y=0, p=_NO_ARG) =
1684 mirror_copy(v=[0,1,0], offset=offset, cp=[0,y,0], p=p);
1685
1686
1687// Function&Module: zflip_copy()
1688// Synopsis: Makes a copy of children mirrored across the Z axis.
1689// SynTags: MatList, Trans
1690// Topics: Transformations, Distributors, Translation, Copiers
1691// See Also: xflip_copy(), yflip_copy(), mirror_copy(), path_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
1692//
1693// Usage:
1694// zflip_copy([offset], [z]) CHILDREN;
1695// Usage: As a function to translate points, VNF, or Bezier patches
1696// copies = zflip_copy([offset], [z], p=);
1697// Usage: Get Translation Matrices
1698// mats = zflip_copy([offset], [z]);
1699//
1700// Description:
1701// When called as a module, makes a copy of the children, mirrored across the Z axis.
1702// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1703// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1704//
1705// Arguments:
1706// offset = Distance to offset children up, before copying.
1707// z = The Z coordinate of the mirroring plane. Default: 0
1708// ---
1709// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1710//
1711// Side Effects:
1712// `$orig` is true for the original instance of children. False for the copy.
1713// `$idx` is set to the index value of each copy.
1714//
1715//
1716// Example:
1717// zflip_copy() cylinder(h=20, r1=4, r2=0);
1718// color("blue",0.25) cube([15,15,0.01], center=true);
1719//
1720// Example:
1721// zflip_copy(offset=5) cylinder(h=20, r1=4, r2=0);
1722// color("blue",0.25) cube([15,15,0.01], center=true);
1723//
1724// Example:
1725// zflip_copy(z=-5) cylinder(h=20, r1=4, r2=0);
1726// color("blue",0.25) down(5) cube([15,15,0.01], center=true);
1727module zflip_copy(offset=0, z=0)
1728{
1729 req_children($children);
1730 mirror_copy(v=[0,0,1], offset=offset, cp=[0,0,z]) children();
1731}
1732
1733
1734function zflip_copy(offset=0, z=0, p=_NO_ARG) =
1735 mirror_copy(v=[0,0,1], offset=offset, cp=[0,0,z], p=p);
1736
1737
1738// Function&Module: mirror_copy()
1739// Synopsis: Makes a copy of children mirrored across a given plane.
1740// SynTags: MatList, Trans
1741// Topics: Transformations, Distributors, Translation, Copiers
1742// See Also: xflip_copy(), yflip_copy(), zflip_copy(), path_copies(), move_copies(), xcopies(), ycopies(), zcopies(), line_copies(), grid_copies()
1743//
1744// Usage:
1745// mirror_copy(v, [cp], [offset]) CHILDREN;
1746// Usage: As a function to translate points, VNF, or Bezier patches
1747// copies = mirror_copy(v, [cp], [offset], p=);
1748// Usage: Get Translation Matrices
1749// mats = mirror_copy(v, [cp], [offset]);
1750//
1751// Description:
1752// When called as a module, makes a copy of the children, mirrored across the given plane.
1753// When called as a function, *without* a `p=` argument, returns a list of transformation matrices, one for each copy.
1754// When called as a function, *with* a `p=` argument, returns a list of transformed copies of `p=`.
1755//
1756// Arguments:
1757// v = The normal vector of the plane to mirror across.
1758// offset = distance to offset away from the plane.
1759// cp = A point that lies on the mirroring plane.
1760// ---
1761// p = Either a point, pointlist, VNF or Bezier patch to be translated when used as a function.
1762//
1763// Side Effects:
1764// `$orig` is true for the original instance of children. False for the copy.
1765// `$idx` is set to the index value of each copy.
1766//
1767//
1768// Example:
1769// mirror_copy([1,-1,0]) zrot(-45) yrot(90) cylinder(d1=10, d2=0, h=20);
1770// color("blue",0.25) zrot(-45) cube([0.01,15,15], center=true);
1771//
1772// Example:
1773// mirror_copy([1,1,0], offset=5) rot(a=90,v=[-1,1,0]) cylinder(d1=10, d2=0, h=20);
1774// color("blue",0.25) zrot(45) cube([0.01,15,15], center=true);
1775//
1776// Example:
1777// mirror_copy(UP+BACK, cp=[0,-5,-5]) rot(from=UP, to=BACK+UP) cylinder(d1=10, d2=0, h=20);
1778// color("blue",0.25) translate([0,-5,-5]) rot(from=UP, to=BACK+UP) cube([15,15,0.01], center=true);
1779module mirror_copy(v=[0,0,1], offset=0, cp)
1780{
1781 req_children($children);
1782 cp = is_vector(v,4)? plane_normal(v) * v[3] :
1783 is_vector(cp)? cp :
1784 is_num(cp)? cp*unit(v) :
1785 [0,0,0];
1786 nv = is_vector(v,4)? plane_normal(v) : unit(v);
1787 off = nv*offset;
1788 if (cp == [0,0,0]) {
1789 translate(off) {
1790 $orig = true;
1791 $idx = 0;
1792 children();
1793 }
1794 mirror(nv) translate(off) {
1795 $orig = false;
1796 $idx = 1;
1797 children();
1798 }
1799 } else {
1800 translate(off) children();
1801 translate(cp) mirror(nv) translate(-cp) translate(off) children();
1802 }
1803}
1804
1805
1806function mirror_copy(v=[0,0,1], offset=0, cp, p=_NO_ARG) =
1807 let(
1808 cp = is_vector(v,4)? plane_normal(v) * v[3] :
1809 is_vector(cp)? cp :
1810 is_num(cp)? cp*unit(v) :
1811 [0,0,0],
1812 nv = is_vector(v,4)? plane_normal(v) : unit(v),
1813 off = nv*offset,
1814 mats = [
1815 translate(off),
1816 translate(cp) *
1817 mirror(nv) *
1818 translate(-cp) *
1819 translate(off)
1820 ]
1821 )
1822 p==_NO_ARG? mats : [for (m = mats) apply(m, p)];
1823
1824
1825
1826////////////////////
1827// Section: Distributing children individually along a line
1828///////////////////
1829// Module: xdistribute()
1830// Synopsis: Distributes each child, individually, out along the X axis.
1831// SynTags: Trans
1832// See Also: xdistribute(), ydistribute(), zdistribute(), distribute()
1833//
1834// Usage:
1835// xdistribute(spacing, [sizes]) CHILDREN;
1836// xdistribute(l=, [sizes=]) CHILDREN;
1837//
1838//
1839// Description:
1840// Spreads out the children individually along the X axis.
1841// Every child is placed at a different position, in order.
1842// This is useful for laying out groups of disparate objects
1843// where you only really care about the spacing between them.
1844//
1845// Arguments:
1846// spacing = spacing between each child. (Default: 10.0)
1847// sizes = Array containing how much space each child will need.
1848// l = Length to distribute copies along.
1849//
1850// Side Effects:
1851// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
1852// `$idx` is set to the index number of each child being copied.
1853//
1854// Example:
1855// xdistribute(sizes=[100, 10, 30], spacing=40) {
1856// sphere(r=50);
1857// cube([10,20,30], center=true);
1858// cylinder(d=30, h=50, center=true);
1859// }
1860module xdistribute(spacing=10, sizes=undef, l=undef)
1861{
1862 req_children($children);
1863 dir = RIGHT;
1864 gaps = ($children < 2)? [0] :
1865 !is_undef(sizes)? [for (i=[0:1:$children-2]) sizes[i]/2 + sizes[i+1]/2] :
1866 [for (i=[0:1:$children-2]) 0];
1867 spc = !is_undef(l)? ((l - sum(gaps)) / ($children-1)) : default(spacing, 10);
1868 gaps2 = [for (gap = gaps) gap+spc];
1869 spos = dir * -sum(gaps2)/2;
1870 spacings = cumsum([0, each gaps2]);
1871 for (i=[0:1:$children-1]) {
1872 $pos = spos + spacings[i] * dir;
1873 $idx = i;
1874 translate($pos) children(i);
1875 }
1876}
1877
1878
1879// Module: ydistribute()
1880// Synopsis: Distributes each child, individually, out along the Y axis.
1881// SynTags: Trans
1882// See Also: xdistribute(), ydistribute(), zdistribute(), distribute()
1883//
1884// Usage:
1885// ydistribute(spacing, [sizes]) CHILDREN;
1886// ydistribute(l=, [sizes=]) CHILDREN;
1887//
1888// Description:
1889// Spreads out the children individually along the Y axis.
1890// Every child is placed at a different position, in order.
1891// This is useful for laying out groups of disparate objects
1892// where you only really care about the spacing between them.
1893//
1894// Arguments:
1895// spacing = spacing between each child. (Default: 10.0)
1896// sizes = Array containing how much space each child will need.
1897// l = Length to distribute copies along.
1898//
1899// Side Effects:
1900// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
1901// `$idx` is set to the index number of each child being copied.
1902//
1903// Example:
1904// ydistribute(sizes=[30, 20, 100], spacing=40) {
1905// cylinder(d=30, h=50, center=true);
1906// cube([10,20,30], center=true);
1907// sphere(r=50);
1908// }
1909module ydistribute(spacing=10, sizes=undef, l=undef)
1910{
1911 req_children($children);
1912 dir = BACK;
1913 gaps = ($children < 2)? [0] :
1914 !is_undef(sizes)? [for (i=[0:1:$children-2]) sizes[i]/2 + sizes[i+1]/2] :
1915 [for (i=[0:1:$children-2]) 0];
1916 spc = !is_undef(l)? ((l - sum(gaps)) / ($children-1)) : default(spacing, 10);
1917 gaps2 = [for (gap = gaps) gap+spc];
1918 spos = dir * -sum(gaps2)/2;
1919 spacings = cumsum([0, each gaps2]);
1920 for (i=[0:1:$children-1]) {
1921 $pos = spos + spacings[i] * dir;
1922 $idx = i;
1923 translate($pos) children(i);
1924 }
1925}
1926
1927
1928// Module: zdistribute()
1929// Synopsis: Distributes each child, individually, out along the Z axis.
1930// SynTags: Trans
1931// See Also: xdistribute(), ydistribute(), zdistribute(), distribute()
1932//
1933// Usage:
1934// zdistribute(spacing, [sizes]) CHILDREN;
1935// zdistribute(l=, [sizes=]) CHILDREN;
1936//
1937// Description:
1938// Spreads out each individual child along the Z axis.
1939// Every child is placed at a different position, in order.
1940// This is useful for laying out groups of disparate objects
1941// where you only really care about the spacing between them.
1942//
1943// Arguments:
1944// spacing = spacing between each child. (Default: 10.0)
1945// sizes = Array containing how much space each child will need.
1946// l = Length to distribute copies along.
1947//
1948// Side Effects:
1949// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
1950// `$idx` is set to the index number of each child being copied.
1951//
1952// Example:
1953// zdistribute(sizes=[30, 20, 100], spacing=40) {
1954// cylinder(d=30, h=50, center=true);
1955// cube([10,20,30], center=true);
1956// sphere(r=50);
1957// }
1958module zdistribute(spacing=10, sizes=undef, l=undef)
1959{
1960 req_children($children);
1961 dir = UP;
1962 gaps = ($children < 2)? [0] :
1963 !is_undef(sizes)? [for (i=[0:1:$children-2]) sizes[i]/2 + sizes[i+1]/2] :
1964 [for (i=[0:1:$children-2]) 0];
1965 spc = !is_undef(l)? ((l - sum(gaps)) / ($children-1)) : default(spacing, 10);
1966 gaps2 = [for (gap = gaps) gap+spc];
1967 spos = dir * -sum(gaps2)/2;
1968 spacings = cumsum([0, each gaps2]);
1969 for (i=[0:1:$children-1]) {
1970 $pos = spos + spacings[i] * dir;
1971 $idx = i;
1972 translate($pos) children(i);
1973 }
1974}
1975
1976
1977
1978// Module: distribute()
1979// Synopsis: Distributes each child, individually, out along an arbitrary line.
1980// SynTags: Trans
1981// See Also: xdistribute(), ydistribute(), zdistribute(), distribute()
1982//
1983// Usage:
1984// distribute(spacing, sizes, dir) CHILDREN;
1985// distribute(l=, [sizes=], [dir=]) CHILDREN;
1986//
1987// Description:
1988// Spreads out the children individually along the direction `dir`.
1989// Every child is placed at a different position, in order.
1990// This is useful for laying out groups of disparate objects
1991// where you only really care about the spacing between them.
1992//
1993// Arguments:
1994// spacing = Spacing to add between each child. (Default: 10.0)
1995// sizes = Array containing how much space each child will need.
1996// dir = Vector direction to distribute copies along. Default: RIGHT
1997// l = Length to distribute copies along.
1998//
1999// Side Effects:
2000// `$pos` is set to the relative centerpoint of each child copy, and can be used to modify each child individually.
2001// `$idx` is set to the index number of each child being copied.
2002//
2003// Example:
2004// distribute(sizes=[100, 30, 50], dir=UP) {
2005// sphere(r=50);
2006// cube([10,20,30], center=true);
2007// cylinder(d=30, h=50, center=true);
2008// }
2009module distribute(spacing=undef, sizes=undef, dir=RIGHT, l=undef)
2010{
2011 req_children($children);
2012 gaps = ($children < 2)? [0] :
2013 !is_undef(sizes)? [for (i=[0:1:$children-2]) sizes[i]/2 + sizes[i+1]/2] :
2014 [for (i=[0:1:$children-2]) 0];
2015 spc = !is_undef(l)? ((l - sum(gaps)) / ($children-1)) : default(spacing, 10);
2016 gaps2 = [for (gap = gaps) gap+spc];
2017 spos = dir * -sum(gaps2)/2;
2018 spacings = cumsum([0, each gaps2]);
2019 for (i=[0:1:$children-1]) {
2020 $pos = spos + spacings[i] * dir;
2021 $idx = i;
2022 translate($pos) children(i);
2023 }
2024}
2025
2026
2027
2028// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap