RosettaCodeData/Task/Pythagoras-tree/Scilab/pythagoras-tree-1.scilab
2023-07-01 13:44:08 -04:00

92 lines
3 KiB
Text

side = 1; //side length of the square
depth = 8; //final number of branch levels
//L-system definition:
//Alphabet: UTDB+-[]
//U: go upwards T: top of the square
//D: go downwards B: bottom of the square
//[: start new branch ]: end current branch
//+: branch to the right -: branch to the left
//Axiom: UTDB
//Rule: T -> [+UTD-UTD]
//L-system sentence generation
sentence = 'UTDB'
rule = '[+UTD-UTD]';
for i=1:depth
sentence = strsubst(sentence,'T',rule);
end
sentence = strsplit(sentence)';
//Empty tree
tree_size = 1.0...
+ length(find(sentence == "U" | sentence == "T" |...
sentence == "D" | sentence == "B"))...
+ 2 * length(find(sentence == "]" | sentence == "-" |...
sentence == "+"));
tree=zeros(tree_size,1);
//Vectorial operation to calculate a new point in the tree
deff('z = new_point(origin,rho,theta)',...
'z = origin + rho * exp(%i*theta)');
//Drawing the tree
curr_angle = %pi/2;
curr_pos = 1;
ratio = 1/sqrt(2);
for ind = 1:size(sentence,'c')
charac = sentence(ind);
select charac
case 'U' then //Draw line upwards
tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle);
curr_pos = curr_pos + 1;
case 'T' then //Draw top of the square
curr_angle = curr_angle - %pi/2;
tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle);
curr_pos = curr_pos + 1;
case 'D' then //Draw line downwards
curr_angle = curr_angle - %pi/2;
tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle);
curr_pos = curr_pos + 1;
case 'B' then //Draw the bottom
curr_angle = curr_angle - %pi/2;
tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle);
curr_pos = curr_pos + 1;
case '[' then //Start branch
side = side * ratio;
case '+' then //Start going to the left
curr_angle = curr_angle - %pi/4;
// tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle);
// tree(curr_pos+2) = new_point(tree(curr_pos+1),side,%pi+curr_angle);
// curr_pos = curr_pos + 2;
curr_angle = curr_angle + %pi/2;
case '-' then //Start going to the left
// tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle);
// tree(curr_pos+2) = new_point(tree(curr_pos+1),side,%pi+curr_angle);
// curr_pos = curr_pos + 2;
curr_angle = curr_angle + %pi/2;
case ']' then
side = side / ratio;
curr_angle = curr_angle - %pi/4;
// tree(curr_pos+1) = new_point(tree(curr_pos),side,curr_angle);
// tree(curr_pos+2) = new_point(tree(curr_pos+1),side,%pi+curr_angle);
// curr_pos = curr_pos + 2;
curr_angle = curr_angle + %pi;
else
error('L-system sentence error');
end
end
scf(); clf();
xname('Pythagoras tree: '+string(depth)+' levels')
plot2d(real(tree),imag(tree),14);
set(gca(),'isoview','on');
set(gca(),'axes_visible',['off','off','off']);