OpenSCAD User Manual/Modules

出典: フリー教科書『ウィキブックス(Wikibooks)』
ナビゲーションに移動 検索に移動

モジュール(他の言語でのマクロ、関数にあたる)は処理の再利用を容易にする。

module hole(distance, rot, size) {
    rotate(a = rot, v = [1, 0, 0]) {
        translate([0, distance, 0]) {
            cylinder(r = size, h = 100, center = true);
        }
    }
}

この例では、引数 distance、rot、size を設定して呼び出すことにより、このような描画を複数繰り返す場合のプログラムの行数を節約し、 プログラムの可動性を上げる。

呼び出しは、次の例のようにC言語の関数呼び出しに似た方法で、値または数式を渡して行なう。

hole(0, 90, 10);

children[編集]

The child nodes of the module instantiation can be accessed using the children() statement within the module. The number of module children can be accessed using the $children variable.

Parameters

empty
select all the children
index
integer. select one child, at index value. Index start at 0 and should be less than or equal to $children-1.
vector
vector of integer. select children with index in vector. Index should be between 0 and $children-1.
range
[<start>:<end>] or [<start>:<increment>:<end>]. select children between <start> to <end>, incremented by <increment> (default 1).

Deprecated child() module

Up to release 2013.06 the now deprecated child() module was used instead. This can be translated to the new children() according to the table:

up to 2013.06 2014.03 and later
child() children(0)
child(x) children(x)
for (a = [0:$children-1]) child(a) children([0:$children-1])

Examples

Transfer all children to another module:

 // rotate to other center point:
 module rz(angle, center=undef) {
   translate(center)
      rotate(angle)
         translate(-center)
            children();
 }

 rz(15, [10,0]) sphere(30);

Use the first child, multiple time:

 module lineup(num, space) {
   for (i = [0 : num-1])
     translate([ space*i, 0, 0 ]) children(0);
 }
 
 lineup(5, 65) sphere(30);

If you need to make your module iterate over all children you will need to make use of the $children variable, e.g.:

 module elongate() {
   for (i = [0 : $children-1])
     scale([10 , 1, 1 ]) children(i);
 }
 
 elongate() { sphere(30); cube([10,10,10]); cylinder(r=10,h=50); }

arguments[編集]

One can specify default values for the arguments:

 module house(roof="flat",paint=[1,0,0]){
   color(paint)
   if(roof=="flat"){
     translate([0,-1,0])
     cube();
   } else if(roof=="pitched"){
     rotate([90,0,0])
     linear_extrude(height=1)
     polygon(points=[[0,0],[0,1],[0.5,1.5],[1,1],[1,0]],paths=[ [0,1,2,3,4] ]);
   } else if(roof=="domical"){
     translate([0,-1,0])
     union(){
       translate([0.5,0.5,1]) sphere(r=0.5,$fn=20);
       cube();	
     }
   }
 }

And then use one of the following ways to supply the arguments

 union(){
   house();
   translate([2,0,0]) house("pitched");
   translate([4,0,0]) house("domical",[0,1,0]);
   translate([6,0,0]) house(roof="pitched",paint=[0,0,1]);
   translate([8,0,0]) house(paint=[0,0,0],roof="pitched");
   translate([10,0,0]) house(roof="domical");
   translate([12,0,0]) house(paint=[0,0.5,0.5]);
 }