# lsystem.py
# One of 7 python scripts that implement a simple L system. 
# Useage from a terminal:
#    $ python PATH_TO_PYTHON_DIR/lsystem.py "PATH_TO_SCRIPT_DIR/script.dat"
#
# The information in the script.dat file determines what type of graphics
# are generated by the L system. The other python scripts are,
# lscriptreader.py - reads a script.dat file and produces a database.
# lgenerator.py - uses the database to generate a long L string.
# lmel.py - uses the L string to generate a .mel script for Maya.
# lrib - uses the L string to generate a .rib file for RenderMan.
# mayaport.py - uses a socket to tell Maya to source a .mel script.
# A mel script, LMelProcs.mel, is also part of the L system. See lmel.py
# for more information.
#
# Malcolm Kesson
# 18 Jan 2012, 26 Jan 2012
  
import lscriptreader
import lgenerator
import lmel, mayasocket
import lrib
import os, sys
  
def main():
    args = sys.argv[1:]
    script_path = args[0]    # full path to the dat file
    run(script_path)
  
def run(script_path):
    # Read the data from the L script file and 
    # transfer it to the database (dictionary).
    text = lscriptreader.read(script_path)
    database = lscriptreader.parse(text, lscriptreader.defaults)
    
    # Extract some basic information that will control
    # how the L string is generated and interpreted.
    port = database['port']
    display = database['display'].lower()
    title = database['title']
    
    # Generate the L string.
    lstr = lgenerator.write_lstring(database)
  
    # Prepare the path to the output file. The appropriate
    # file extension will be added later.
    directory = os.path.dirname(script_path)    
    outpath = os.path.join(directory, title)
    if display == 'mel':
        outpath += '.mel'
        print outpath
        lmel.render(lstr, outpath, database)
        if port > 1024:
            mayasocket.source(outpath, port)
    elif display == 'rib':
        outpath += '.rib'
        print outpath
        lrib.render(lstr, outpath, database)
            
if __name__ == "__main__":
    # Running this script directly in Cutter will the L system to process
    # the following data file - handy for purposes of testing the modules.
    run('FULL_PATH/tree.dat')