#!bpy
 
import bpy
import random
 
"""
Generate  a fir tree
"""

MATERIAL_TREE = bpy.data.materials.new('material tree')
MATERIAL_TRUNK = bpy.data.materials.new('material trunk')
 
def create_tree(x=0, y=0, parts=6):
    size=parts
    z = 2
    color = random.random() /20
    for i  in range(size):        
        bpy.ops.mesh.primitive_cone_add(radius1=size, 
                                        radius2=0, 
                                        depth=2,
                                        view_align=False, 
                                        enter_editmode=False, 
                                        location=(x*2, y*2, z))
        obj = bpy.context.object
        bpy.context.scene.objects.active
        setColor(obj, MATERIAL_TREE, (color, 0.07, color))    
        
        z += 1.5
        size -= 1
        bpy.ops.mesh.primitive_cone_add(radius1=1, 
                                        radius2=1, 
                                        depth=2,
                                        view_align=False, 
                                        enter_editmode=False, 
                                        location=(x*2, y*2, 0))
        obj = bpy.context.object
        bpy.context.scene.objects.active
        setColor(obj, MATERIAL_TRUNK, (0.2, 0.08, 0.009))

        
def setColor(obj, material, color):
    material.diffuse_color = color
    material.specular_hardness = 200
    obj.data.materials.append(material)
    
if __name__ == '__main__':
    bpy.ops.object.select_by_type(type='MESH')
    bpy.ops.object.delete()
    for ob in bpy.context.selected_editable_objects:
        ob.active_material_index = 0
        for i in range(len(ob.material_slots)):
            bpy.ops.object.material_slot_remove({'object': ob})
    
    for i in range(1,10):
        x = random.randint(0,20)
        y = random.randint(0,20)
        parts = random.randint(4,7)
        create_tree(x, y, parts)