HowTo:Use for loop over traditional while loop
Loops
Traditionally in POV-Ray the #while
directive has been the way to implement loops. In 3.7 a new #for
directive was added that makes coding counting loops much simpler.
Nested Loops
Loops can of course be nested. This capability is often used to lay out very large numbers of objects using an economical amount of code.
First, here's a very simple, complete scene file containing a nested #while
loop with which you can play:
#include "colors.inc"
#include "woods.inc"
camera {location <-1.5,0.9,-0.08> look_at <0,0.7,0.5>}
light_source {<-20,75,-100> White}
background {LightBlue}
plane {y,0 pigment {color GreenYellow}
#declare RandomSeed = seed(1);
#declare XCount=0;
#while (XCount < 200)
#declare ZCount=0;
#while (ZCount < 200)
box {<-0.05,0,-0.05><0.05,1,0.05>
rotate <3*rand(RandomSeed),5*rand(RandomSeed),3*rand(RandomSeed)>
texture {T_Wood1 translate <rand(RandomSeed),ZCount,rand(RandomSeed)> rotate x*90 scale 0.07}
translate <XCount,0,ZCount>
}
#declare ZCount=ZCount+1;
#end
#declare XCount=XCount+1;
#end
Here's the same looping accomplished with the new #for
loop directive:
#include "colors.inc"
#include "woods.inc"
camera {location <-1.5,0.9,-0.08> look_at <0,0.7,0.5>}
light_source {<-20,75,-100> White}
background {LightBlue}
plane {y,0 pigment {color GreenYellow}
#declare RandomSeed = seed(1);
#for (XCount,0,199)
#for (ZCount,0,199)
box {<-0.05,0,-0.05><0.05,1,0.05>
rotate <3*rand(RandomSeed),5*rand(RandomSeed),3*rand(RandomSeed)>
texture {T_Wood1 translate <rand(RandomSeed),ZCount,rand(RandomSeed)> rotate x*90 scale 0.07}
translate <XCount,0,ZCount>
}
#end
#end
These example uses 2 nested loops. Each nested loop has its own control variable. It starts with both XCount and YCount equal to zero. With XCount at zero, YCount loops from 0 to 199, then XCount is incremented to 1, YCount is reset to zero and the second loop repeats.
This example also introduces a degree of randomness in each iteration using the POV-Ray seed and rand functions. When generating a large number of objects using loops you'll find that a little randomness goes a long way. This example generates 40,000 wooden posts, each with a little bit of a wobble and each with a slightly different wood texture pattern. It should take about 10 or 20 seconds to render