[OpenSCAD] Barnsley Fern recursive

Ronaldo rcmpersiano at gmail.com
Wed Sep 12 13:54:46 EDT 2018


doug.moen wrote
> The only language feature that supports this kind of iteration, without
> using recursion,
> is the C-style for loop, which is only available in list comprehensions,
> not in modules.
> For this, you need a development snapshot with the "C-style for" option
> enabled
> in Preferences.

You are right, Doug, and the following code takes that path. The nested for
in the module BarnsleyFern was needed to circumvent the OpenSCAD for limit
of at most 9999 elements. Anyway, this code is valid to at most 9999x9999
iterations.

m1 = [[0,0],[0,0.16]];
c1 = [0,0];
m2 = [[0.85,0.04],[-0.04,0.85]];
c2 = [0, 1.6];
m3 = [[0.2,-0.26],[0.23,0.22]];
c3 = [0, 1.6];
m4 = [[-0.15,0.28],[0.26,0.24]];
c4 = [0, 0.44];

function f1(p) = m1 * p + c1;
function f2(p) = m2 * p + c2;
function f3(p) = m3 * p + c3;
function f4(p) = m4 * p + c4;

module dot(p) translate(100 * p) square();

module BarnsleyFern(index) {
  q = BarnsleyFern([0,0],index); 
  echo(len=len(q));
  for(i=[0:9999:len(q)-1]) {
    r = len(q)-i; 
    for(j=[0:min(r,9999)-1])
      dot(q[i+j]);
  }
}
  
function BarnsleyFern(p,index) =
  [ for(i=0, q=p; i<index; i=i+1,
      r =  rands(0,1,1)[0],
      q = 
        r <= 0.01 ?
          f1(q) :
        r > 0.01 && r <=0.86?
          f2(q) :
        r > 0.86 && r <=0.93?
          f3(q) :
          f4(q) )
      q ];


BarnsleyFern(200000); 

The code generated the following image in 25sec:

<http://forum.openscad.org/file/t1275/BarnsleyFern_200000.png> 

That is a detail look:

<http://forum.openscad.org/file/t1275/BarnsleyFern_200000_detail.png> 




--
Sent from: http://forum.openscad.org/



More information about the Discuss mailing list