RosettaCodeData/Task/Fractal-tree/Scilab/fractal-tree-1.scilab
2017-09-25 22:28:19 +02:00

80 lines
2.6 KiB
Text

trunk = 1; //trunk length
ratio = 0.8; //size ratio between two consecutive branches
depth = 9; //final number of branch levels
orign = 0; //origin of the tree (should be complex)
angle = 45*%pi/180; //angle between two branches [rad]
trunk_angle = 90*%pi/180; //angle between trunk and X-axis [rad]
right_angle = angle/2; //angles to the right or to the left
left_angle = 0.8*angle; //can be set independently or
//as function of 'angle'
//L-system definition:
//Alphabet: FBD[]+-
//F: go forward B: go backwards
//[: start new branch ]: end current branch
//+: branch to the right -: branch to the left
//D: double line (forward then backward)
//Axiom: D
//Rule: D -> F[+D-D]B
//L-system sentence generation
sentence = 'D'
rule = 'F[+D-D]B';
for i=1:depth
sentence = strsubst(sentence,'D',rule);
end
sentence = strsplit(sentence)';
//Empty tree
tree_size = 1.0...
+ length(find(sentence=='F'|sentence=='B'))...
+ 2 * length(find(sentence=='D'));
tree=zeros(tree_size,1);
//Drawing the tree
branch_level = 0;
curr_angle = trunk_angle;
curr_pos = 1;
for ind = 1:size(sentence,'c')
charac = sentence(ind);
select charac
case 'F' then //Draw line forward
tree(curr_pos+1) = tree(curr_pos)...
+ trunk * ratio^branch_level * exp(curr_angle*%i);
curr_pos = curr_pos + 1;
case 'B' then //Draw line backwards
tree(curr_pos+1) = tree(curr_pos)...
+ trunk * ratio^branch_level * exp((%pi+curr_angle)*%i);
curr_pos = curr_pos + 1;
case '[' then //New branch
branch_level = branch_level + 1;
case '+' then //Turn right
curr_angle = curr_angle - right_angle;
case '-' then //Turn left
curr_angle = curr_angle + right_angle + left_angle;
case ']' then //End of branch
branch_level = branch_level - 1;
curr_angle = curr_angle - left_angle;
case 'D' then //Double line
tree(curr_pos+1) = tree(curr_pos)...
+ trunk * ratio^branch_level * exp(curr_angle*%i);
tree(curr_pos+2) = tree(curr_pos+1)...
+ trunk * ratio^branch_level * exp((%pi+curr_angle)*%i);
curr_pos = curr_pos + 2;
end
end
scf(); clf();
xname('Fractal tree: '+string(depth)+' levels')
plot2d(real(tree),imag(tree),14);
set(gca(),'isoview','on');
set(gca(),'axes_visible',['off','off','off']);