 # slow generating of L-System trees

Hi all

Coding recursive trees is a bit complex in blender since bpy seems not having something like push and pop matrix.
Anyway, here is my code and it works to generate a small number of trees:

import bpy
import mathutils
import random
from mathutils import Vector
import math

dpth = 27
scale = 0.7

def branch(lv, rotz, rotx, r, d, loc):
if lv < 7:
bpy.context.scene.cursor_location = loc
cyl = bpy.context.object
#rotate based on previous rotation
ang1 = math.atan(rotz/rotz)
bpy.ops.transform.rotate(value = ang1, constraint_axis = (False, True, False))
if rotz != 0:
ang2 = math.atan(rotz/rotz)
if ang2 > 3.1416/2:
ang2 = 3.1416- ang2
bpy.ops.transform.rotate(value = ang2, constraint_axis = (False, False, True))
#rotate randomly
if lv != 0:
theAxis = rotx
bpy.ops.transform.rotate(value = random.uniform(-0.7, 0.7), axis = rotx)
theAxis = rotz
bpy.ops.transform.rotate(value = random.uniform(0, 3.1416), axis = theAxis)
#move up half depth in local coordinates
vec = mathutils.Vector((0, 0, d/2))
inv = cyl.matrix_world.copy()
vec_rot = mathutils.Vector((inv*d/2, inv*d/2, invd/2))
cyl.location = cyl.location + vec_rot
#get the next generation position
next_loc = cyl.location + vec_rot
prev_rot = vec_rot
2
prev_rotX = mathutils.Vector((inv, inv, inv))
#set 3d cursor location

``````	#start new branch
branch(lv+1, prev_rot, prev_rotX, r*scale, d*scale, next_loc)
#get another generation position
branch(lv+1, prev_rot, prev_rotX, r*scale, d*scale, next_loc-vec_rot*0.6)
if lv == 0:
branch(lv+1, prev_rot, prev_rotX, r*scale, d*scale, next_loc-vec_rot*0.4)
branch(lv+1, prev_rot, prev_rotX, r*scale, d*scale, next_loc-vec_rot*0.8)
``````

for i in range(0, 5):
branch(0, mathutils.Vector((0, 0, 1)), mathutils.Vector((1, 0, 0)), rad, dpth, mathutils.Vector((random.randint(-50, 50), random.randint(-50, 50), 0)))

My problem now is that, if I increase the times of iteration in the for loop in the end, the time to generate will increase drastically.
For example, generating five trees takes 30 seconds, ten trees takes 90 seconds, and twenty trees takes 8 minutes.
This doesn’t really make sense because each tree is not related to each other.
Any one have any idea?