#FRACTAL EXTRUDER

bl_info = {
    "name": "FRACTAL EXTRUDER",
    "author": "Andrea Rastelli",
    "version": (0, 0, 0),
    "blender": (2, 79, 0),
    "location": "View3D > Tools > Mesh Tools",
    "description": " Lindenmayer system extrusion",
    "warning": "working in progress",
    "wiki_url": "",
    "category": "Mesh",
}

import math
import bpy
import bmesh
from mathutils import Vector, Matrix
from random import randrange

from bpy.props import (
        BoolProperty,
        EnumProperty,
        FloatProperty,
        StringProperty,
        IntProperty
        )


class fractal_extruder(bpy.types.Operator):
    bl_idname = "mesh.fractal_extruder"
    bl_label = "Fractal Extruder"
    bl_options = {'REGISTER', 'UNDO','PRESET'}
    
    fractal_ID = StringProperty(name="ID", default='fractal_obj')

    axiom = StringProperty(name="AXIOM", default='FFA')
    rules = StringProperty(name="RULES", default="A:[&SFFFA]////[&SFFFA]////[&SFFFA]")

    angle = FloatProperty(name="ANGLE", default=30.0)
    length = FloatProperty(name="LENGTH", default=1)
    scale = FloatProperty(name="SCALE", default=0.8)
    radius_scale = FloatProperty(name="RADIUS_SCALE", default=0.5)
    rand = IntProperty(name="RAND_ANGLE", default=0,min=0)
    rand_len = IntProperty(name="RAND_LEN", default=0,min=0)
    iterations = IntProperty(name="ITERATIONS", default=3)


    @classmethod
    def poll(cls, context):
        obj = context.active_object
        return (obj and obj.type == 'MESH' and context.mode == 'EDIT_MESH')

    def draw(self, context):
        layout = self.layout
        box = layout.box()
        box.label("fractal_extruder:")
        
        box.prop(self, "axiom")
        box.prop(self, "rules")
        box.prop(self, "angle")
        box.prop(self, "length")
        box.prop(self, "scale")
        box.prop(self, "radius_scale")
        box.prop(self, "rand")
        box.prop(self, "rand_len")
        box.prop(self, "iterations")
        
    def invoke(self, context, event):
        self.action(context)
        return {'FINISHED'}

    def execute(self, context):
        self.action(context)
        return {'FINISHED'}

    def action(self, context):
        save_global_undo = bpy.context.user_preferences.edit.use_global_undo
        bpy.context.user_preferences.edit.use_global_undo = False
        obj = bpy.context.active_object
        mesh = obj.data
        FRACTALEX(mesh,self.axiom, 
                self.rules, self.angle, self.length, 
                self.scale, self.radius_scale, 
                self.rand, self.rand_len, self.iterations)
        bpy.context.user_preferences.edit.use_global_undo = save_global_undo
        bpy.ops.object.editmode_toggle()
        bpy.ops.object.editmode_toggle()

def FRACTALEX(mesh, axiom, rules, angle, length, scale, radius_scale, rand, rand_len,iterations):


    ############# USER VALUES ############# LSYSTEM RULES

    #axiom = 'FA'
    #rules = 'A:[&FFFA]////[&FFFA]////[&FFFA]'

    rules_dict={}
    rules=rules.split()
    for i in rules:
        i=i.split(':')
        rules_dict[i[0]] = i[1]

    #angle = 30.0

    up_axis = Vector((0,0,1))

    #length = 1
    #scale = 0.8
    #radius_scale = 0.5

    #iterations = 3


    ##############################LSYS DICT GENERATOR
    instructions = axiom

    def grow (axiom,rules):
        overwrite = ''\
    
        for i in axiom: #rewriting rules
            overwrite += rules.get(i,i)
        return overwrite


    while iterations != 0: 
        instructions = grow(instructions,rules_dict)
        iterations -=1

    print(instructions)

    ####################################### BLENDER CONSTRUCTOR
    
    obj = bpy.context.object
    me = obj.data

    root = bmesh.from_edit_mesh(me).select_history.active
    direction = root.normal
    wpos = root.calc_center_median()
    face_ID = "fractal_obj_%s" %root.index

    mesh = bpy.data.meshes.new("mesh")  # add a new mesh
    if not face_ID in bpy.data.objects:
        fractal_obj = bpy.data.objects.new(face_ID, mesh)  # add a new object using the mesh
        scene = bpy.context.scene
        scene.objects.link(fractal_obj)  # put the object into the scene (link)
        
    else:
        fractal_obj = bpy.data.objects[face_ID]
        fractal_obj.data = mesh
        scene = bpy.context.scene
        
    scene.objects.active = fractal_obj  # set as the active object in the scene
    #fractal_obj.select = False  # select object

    mesh = bpy.context.object.data
    bm = bmesh.new()
 
    turtlePos =  Matrix() #TURTLE INIT

    storePos = [] 
    storeLength = []
    

    ######################################## WIREFRAME GENERATOR
    for i in instructions:
        
        if not rand==0:  #RANDOM ANGLE
            r_angle= angle + randrange(-rand,+rand)
        
        else:
            r_angle=angle
            
        
        if not rand_len==0: #RANDOM LENGTH
            r_length= length + (randrange(-rand_len,+rand_len)/10)
        
        else:
            r_length=length           

    
        if i == 'S': #PROGRESSIVE SCALE ALONG 'S' INSTRUCTION
            length = length * scale

        elif i == 'F': # CREATE EDGE
        
            v1 = bm.verts.new( turtlePos.decompose()[0] ) 
      
            displace = turtlePos * ( up_axis  * r_length )
        
            v2 = bm.verts.new( displace ) 
        
            turtlePos[0][3]=displace[0]
            turtlePos[1][3]=displace[1]
            turtlePos[2][3]=displace[2]
        
            bm.edges.new((v1, v2))     

        elif i in '&^':#
            turtlePos *= Matrix.Rotation(math.radians(r_angle if i == '&' else -r_angle ), 4, 'X')
                                                        
        elif i in '+-':#
            turtlePos *= Matrix.Rotation(math.radians(r_angle if i == '+' else -r_angle), 4, 'Y')
        
        elif i in '|':#
            turtlePos *= Matrix.Rotation(math.radians(180.0), 4, 'Y')
        
        elif i in '\/':#
            turtlePos *= Matrix.Rotation(math.radians(r_angle if i == '\\' else -r_angle), 4, 'Z')
        
        elif i == '[': # START TRUNK
            storePos.append(turtlePos.copy())
            storeLength.append(length)
        
        elif i == ']': #CLOSE TRUNK
            turtlePos = storePos.pop()
            length = storeLength.pop()
        

    bm.to_mesh(mesh)
    bm.free()

    ################################################ SKIN GENERATOR

    storeLength=[] #overwrited to store skin radius
    
    if fractal_obj.modifiers:fractal_obj.modifiers.clear() #SKIN MODIFIER
    bpy.ops.object.modifier_add(type='SKIN')

    from math import sqrt
    radius = sqrt( root.calc_area() ) /2 #MATCH ROOT FACE AREA

    skin=fractal_obj.data.skin_vertices[0].data 
    j = 0

    for i in instructions: # ITERATE TREE TO SCALE VERTEX RADIUS 
    
        if i == 'S':
        
            radius *= radius_scale

        elif i == 'F':
            skin[j].radius= radius,radius
            skin[j+1].radius= radius,radius   
            j+=2
        
        elif i == '[':
             storeLength.append(radius)
        
        elif i == ']':
            radius= storeLength.pop()
             
   
    ############ ALIGN FRACTAL OBJ - REMOVE DOUBLES - RETURN TO INITIAL SELECTION 
    
    bpy.ops.object.editmode_toggle()
    obj.select = False
    fractal_obj.select = True
    bpy.context.scene.objects.active = fractal_obj
     
    bpy.context.object.rotation_mode = 'QUATERNION'
    bpy.context.object.rotation_quaternion = direction.to_track_quat('Z','Y')  
    bpy.context.object.rotation_mode = 'XYZ'
    bpy.context.object.location = wpos
    
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.select_all(action='TOGGLE')
    bpy.ops.mesh.remove_doubles(use_unselected=True,threshold=0.0001)
    bpy.ops.object.mode_set(mode='OBJECT')
    
    bpy.ops.object.editmode_toggle()
    
    obj.select = True
    fractal_obj.select = False    
    bpy.context.scene.objects.active = obj
    
    #######################################################################

def panel_func(self, context):
    self.layout.label(text="fractal_extruder:")
    self.layout.operator("mesh.fractal_extruder", text="fractal_extruder")


def register():
    bpy.utils.register_class(fractal_extruder)
    bpy.types.VIEW3D_PT_tools_meshedit.append(panel_func)


def unregister():
    bpy.utils.unregister_class(fractal_extruder)
    bpy.types.VIEW3D_PT_tools_meshedit.remove(panel_func)


if __name__ == "__main__":
    register()
