# Implement XGen Export callbacks for mental ray

import ctypes
import types
import maya.cmds as cmds

def castSelf(selfid):
    # Can't pass self as an object.
    # It's cast to id(self) by the caller
    # and we convert it back to a python object here
    if isinstance(selfid,str):
        return ctypes.cast( int(selfid), ctypes.py_object ).value
    else:
        return selfid

# Export Init callback. Must fill in som arrays on self
def xgmrArchiveExportInit( selfid ):
    self = castSelf(selfid)
    self.batch_plugins.append( "Mayatomr" )
    self.batch_plugins.append( "xgenMR.py" )

# Export Info callback. Must fill in som arrays on self
def xgmrArchiveExportInfo( selfid ):
    self = castSelf(selfid)
    self.archiveDirs.append( "mi" )
    self.archiveLODBeforeExt.append( ".${FRAME}.mi" )
    self.archiveLODBeforeExt.append( ".${FRAME}.mi.gz" )
    self.archiveLODBeforeExt.append( ".mi" )
    self.archiveLODBeforeExt.append( ".mi.gz" )

# Main Export callback
# Arguments are passed in self.invokeArgs
def xgmrArchiveExport( selfid ):
    self = castSelf(selfid)
    miExport( self, self.invokeArgs[0], self.invokeArgs[1], self.invokeArgs[2], self.invokeArgs[3] )

def miExportFrame( self, frame, objFilename ):
    '''Export a single mental ray archive frame.'''
    cmds.currentTime( frame )

    cmds.Mayatomr( 	mi=True, exportFilter=7020488, 
                active=True, binary=True, compression=9, 
                fragmentExport=True, fragmentChildDag =True, passContributionMaps =True, 
                assembly=True, assemblyRootName="obj", exportPathNames="n", 
                file=objFilename + ".mi" )

    self.log( "miExport " + objFilename + ".mi")

def miExportAppendFile( self, miFilename, material, obj, lod ):
    lodList = self.tweakLodAppend( self.curFiles, lod  )
    for l in lodList:
        self.addArchiveFile( "mi", miFilename, material, "", l, 3 )
        
def miExport( self, objs, filename, lod, materialNS ):
    '''Export mental ray archives'''
    filename = self.nestFilenameInDirectory( filename, "mi" )
    
    lastProgress = self.progress
    self.splitProgress( len(objs) )
    
    self.log( "miExport " + filename + lod )
    
    # force units to centimeters when exporting mi.
    prevUnits = cmds.currentUnit( query=True, linear=True, fullName=True )
    cmds.currentUnit( linear="centimeter" )
    
    prevTime = cmds.currentTime( query=True )

    for obj in objs:
        objFilename = filename + "_" + obj + lod
        cmds.select( obj, r=True )

        filenames = []
        # Choose to export single file or a sequence.
        frameToken = ""
        if self.startFrame != self.endFrame:
            frameToken =".${FRAME}"

            dummyFrameFile = open( objFilename + frameToken + ".mi.gz", "wt" )
            dummyFrameFile.write( "STARTFRAME=%4.4d\nENDFRAME=%4.4d\n" % (int( self.startFrame), int(self.endFrame) ) )
            dummyFrameFile.close()

            for curFrame in range( int(self.startFrame), int(self.endFrame)+ 1 ):
                miExportFrame( self, curFrame, objFilename + ".%4.4d" % int(curFrame) )
        else:
            miExportFrame( self, self.startFrame, objFilename )
        
        if self.curFiles != None:
            materials = self.getSGsFromObj( obj )
            if materials and len(materials)>0 :
                miFilename = objFilename + frameToken + ".mi.gz"
                miExportAppendFile( self, miFilename, materialNS+materials[0], obj, lod )
        self.incProgress()
    
    cmds.currentUnit( linear=prevUnits )
    cmds.currentTime( prevTime )
    
    self.progress = lastProgress

#-
# ==========================================================================
# Copyright (C) 2012 Autodesk, Inc. and/or its licensors.  All
# rights reserved.
#
# The coded instructions, statements, computer programs, and/or related
# material (collectively the "Data") in these files contain unpublished
# information proprietary to Autodesk, Inc. ("Autodesk") and/or its
# licensors, which is protected by U.S. and Canadian federal copyright
# law and by international treaties.
#
# The Data is provided for use exclusively by You. You have the right
# to use, modify, and incorporate this Data into other products for
# purposes authorized by the Autodesk software license agreement,
# without fee.
#
# The copyright notices in the Software and this entire statement,
# including the above license grant, this restriction and the
# following disclaimer, must be included in all copies of the
# Software, in whole or in part, and all derivative works of
# the Software, unless such copies or derivative works are solely
# in the form of machine-executable object code generated by a
# source language processor.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
# AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED
# WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
# NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
# PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE, OR
# TRADE PRACTICE. IN NO EVENT WILL AUTODESK AND/OR ITS LICENSORS
# BE LIABLE FOR ANY LOST REVENUES, DATA, OR PROFITS, OR SPECIAL,
# DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK
# AND/OR ITS LICENSORS HAS BEEN ADVISED OF THE POSSIBILITY
# OR PROBABILITY OF SUCH DAMAGES.
#
# ==========================================================================
