#!BPY

"""
Name: 'Stl Batch (.stl)...'
Blender: 236
Group: 'Import'
Tooltip: 'Import Stereo Lithography (.stl) File Format'
"""

__author__ = "Mitch Hughes (lobo)"
__url__ = ("Author's homepage, http://blender.formworks.co.nz")
__version__ = "0.1"

__bpydoc__ = """\
This script batch imports binary Stereo Lithography files into Blender.

Usage:
    
Add the script to your blender/scripts directory
Execute this script from the "File->Import" menu and choose an STL Batch file,
select a file in the directory you would like to batch import .stl files from.
"""

# +---------------------------------------------------------+
# | Copyright (c) 2005 Mitch Hughes                         |
# | http://blender.formworks.co.nz                          |
# | blender@formworks.co.nz                                 |
# | Feb 19, 2005                                            |
# | Released under the Blender Artistic Licence (BAL)       |
# +---------------------------------------------------------+
# | Batch Import Directory of STL Binary Files (*.stl)      |
# +---------------------------------------------------------+

import Blender, mod_meshtools, os, struct, re
from struct import *
from os import path

# ================================
# === Read STL Triangle Format ===
# ================================

def read(filename):
    file = open(filename, "rb")
    
    #80 Any text such as the creator's name
    header = unpack("<80s", file.read(80))
    
    #4 int equal to the number of facets in file
    facets = unpack("i", file.read(4))
    
    # Collect vert data from RAW format
    faces = []
    for i in range(0, facets[0]):
        n_x = unpack("f", file.read(4))
        n_y = unpack("f", file.read(4))
        n_z = unpack("f", file.read(4))
        v1_x = unpack("f", file.read(4))
        v1_y = unpack("f", file.read(4))
        v1_z = unpack("f", file.read(4))
        v2_x = unpack("f", file.read(4))
        v2_y = unpack("f", file.read(4))
        v2_z = unpack("f", file.read(4))
        v3_x = unpack("f", file.read(4))
        v3_y = unpack("f", file.read(4))
        v3_z = unpack("f", file.read(4))
        unused = file.read(2)
        
        faces.append([(v1_x[0], v1_y[0], v1_z[0]), (v2_x[0], v2_y[0], v2_z[0]), (v3_x[0], v3_y[0], v3_z[0])])
    
    # The fine piece of code below for eliminating duplicate verts
    # and creating the object in blender was copied directly from
    # the slp import export script written by
    # Anthony D'Agostino (Scorpius)
    # Generate verts and faces lists, without duplicates
    verts = []
    coords = {}
    index = 0
    for i in range(len(faces)):
        for j in range(len(faces[i])):
            vertex = faces[i][j]
            if not coords.has_key(vertex):
                coords[vertex] = index
                index += 1
                verts.append(vertex)
            faces[i][j] = coords[vertex]

    objname = Blender.sys.splitext(Blender.sys.basename(filename))[0]

    mod_meshtools.create_mesh(verts, faces, objname)
    Blender.Window.DrawProgressBar(1.0, '')  # clear progressbar
    file.close()
    
    message = "Successfully imported " + Blender.sys.basename(filename)
    mod_meshtools.print_boxed(message)

# ================================
# === Read Files in Directory  ===
# ================================

def iterate_directory(filename_in_dir):
    # Not sure how to select a directory so we
    # get the current directory by taking of the
    # filename at the end of the path to the selected file
    path_parts = filename_in_dir.split('/')    
    path_parts[len(path_parts)-1] = ''
    
    working_dir = "/".join(path_parts)
    
    
    #Check for stl extension so we dont try and 
    #import other files in the directory
    stl_extension = re.compile('\.stl$', re.IGNORECASE)
    
    for file_name in os.listdir (working_dir):
        has_stl_extension = stl_extension.search(file_name)
        if has_stl_extension:
            read(working_dir+file_name)
        else:
            print file_name+" no match"
            
    
def fs_callback(filename_in_dir):
    iterate_directory(filename_in_dir)
    
Blender.Window.FileSelector(fs_callback, "Batch STL")



    


















