# --------------------
# My Batch Export v1.3
# --------------------
# AUTHOR: Zoltan Erdokovy (zoltan.erdokovy@gmail.com) 
# Blog: www.zspline.net
#
# This script plots every take, iterates through them, saves each
# one to a new file (geometry and skeleton included) then reopens
# the original, unplotted scene.
#
# KNOWN ISSUES:
# At this point only the first character gets exported.
#
#
# CHANGELOG:
# ----------
# v1.3:
#   Fixed exporting single frame poses.
# v1.2:
#   Fixed translations not plotted properly.
# v1.1:
#   Fixed save path.
#   Now can export scenes without characters.

from pyfbsdk import *
import os.path

#Utility function to get the name of a file without extension
def getFileName(f):
    import os
    d, filename = os.path.split(f)
    if filename:
        return os.path.splitext(filename)[0]
    else:
        return "unknown"

# Plotting function
def Plot():
    
    lScene = FBSystem().Scene
    lcharactersList = lScene.Characters

    
    # Set options for Plot process

    PlotOptions = FBPlotOptions()

    PlotOptions.ConstantKeyReducerKeepOneKey = True
    PlotOptions.PlotAllTakes = True
    PlotOptions.PlotOnFrame = True
    PlotOptions.PlotPeriod = FBTime( 0, 0, 0, 1 )
    PlotOptions.PlotTranslationOnRootOnly = False
    PlotOptions.PreciseTimeDiscontinuities = True
    PlotOptions.RotationFilterToApply = FBRotationFilter.kFBRotationFilterUnroll
    PlotOptions.UseConstantKeyReducer = False

    print len(lcharactersList)
    if len(lcharactersList)!= 0:
        lCharacter = lcharactersList[0]
        lCharacter.PlotAnimation (FBCharacterPlotWhere.kFBCharacterPlotOnSkeleton,PlotOptions )
    
    return    
    

# ----- MAIN -----
# First get some needed objects.
lSystem         = FBSystem()
lApplication    = FBApplication()
lFileName       = lApplication.FBXFileName
Path            = ""

if lFileName == "":## If no FBX file has been loaded.
    FileDlg = FBFilePopup()
    FileDlg.Style = FBFilePopupStyle.kFBFilePopupSave
    FileDlg.Caption = "MyBatchExport: Open a file."
    FileDlg.FileName = "Untitled.fbx"
    if FileDlg.Execute():
        lFileName = FileDlg.FileName

# We want to make sure that we have a scene with file name
# already, otherwise we might want to open a file popup.
# For now we assume that there is already a name to use as a
# base name.
if lFileName.upper().endswith( '.FBX' ):
    SaveOptions = FBFbxOptions(False)
    LoadOptions = FBFbxOptions(True)
    lOriginalTake = lSystem.CurrentTake
    
    # Plot everything    
    Plot()
    
    # Iterate the list of takes.
# --- START OF FOR LOOP --- #
    for lTake in lSystem.Scene.Takes:

        # Switch the current take to the one we want to save.
        lSystem.CurrentTake = lTake

        # Build the file name to use.     
        Path = os.path.dirname(lFileName)+'\\'    # Original path
        lTakeFileName = "%s%s.fbx" % (Path,lTake.Name )

        # Some feedback for the user...
        print "Saving Take '%s' to file '%s'" % ( lTake.Name, lTakeFileName )

        SaveOptions.UseASCIIFormat = False
        SaveOptions.BaseCameras = False
        SaveOptions.CameraSwitcherSettings = False
        SaveOptions.CurrentCameraSettings = False
        SaveOptions.GlobalLightingSettings = False
        SaveOptions.TransportSettings = False

        # Go through the list of takes to export to tag only
        # the correct take. All the other are disregarded.
        for index in range(SaveOptions.GetTakeCount()): ## take index
            if SaveOptions.GetTakeName(index) == lTake.Name:
                SaveOptions.SetTakeSelect(index, True)
            else:
                SaveOptions.SetTakeSelect(index, False)
        lApplication.FileSave( lTakeFileName, SaveOptions )
# --- END OF FOR LOOP --- #
    
    # Close file.
    lApplication.FileNew()
    # Reopen the original scene.
    lApplication.FileOpen(lFileName, False, LoadOptions)

    del( lOriginalTake, SaveOptions, LoadOptions )

else:

    print 'File name does not end with ".fbx". Unable to proceed!'

# Cleanup of local variables.
del( lSystem, lApplication, lFileName )

# Cleanup of imported symbols.
del( FBSystem, FBApplication, FBFbxManager )
