Skip to content

Instantly share code, notes, and snippets.

@yamahigashi
Last active January 19, 2016 13:04
Show Gist options
  • Save yamahigashi/6111100 to your computer and use it in GitHub Desktop.
Save yamahigashi/6111100 to your computer and use it in GitHub Desktop.
batch export sample for fbx (or some file type) from #maya
# -*- coding: utf-8 -*-
##############################################################################
__status__ = "Prototype"
##############################################################################
import os
import re
import glob
import csv
import maya.cmds as cmds
###############################################################################
class FolderProcessor(object):
"""process scenes by the function under specify directory.
"""
def __init__(
self, function, prefix="", suffix="",
title_cap="", ok_cap="", save_dir="", input_file_ext="m[ab]"):
self.main = function
self.doc = function.__doc__
default_title = "フォルダを選択してください"
default_ok = "このフォルダ"
self.title_cap = default_title if title_cap == "" else title_cap
self.ok_cap = default_ok if title_cap == "" else ok_cap
self.prefix = prefix
self.suffix = suffix
self.input_file_ext = input_file_ext
self.success = []
self.failed = []
self.target_dir = self._choose_folder()
self.file_list = self._get_filelist(self.target_dir)
# ファイル上書き確認
if save_dir == "" and self.prefix == "" and self.suffix == "":
res = cmds.confirmDialog(
title="Confirm",
message="files will overritten. OK?",
button=["Yes", "No"],
defaultButton="No",
cancelButton="No",
dismissString="No")
if res == "No": return
self.save_directory = self.target_dir + save_dir + "/"
try:
os.mkdir(self.save_directory)
except:
pass
def execute(self):
print("enter execute")
if not self._show_confirmation(): return
for f in self.file_list:
filename = self.target_dir + f
try:
print("file opening")
scene_name = self._file_open(filename)
print("file success")
except:
import sys
print(sys.exc_info()[0])
cmds.warning("fail at file open: %s" % filename)
self.failed.append(f)
continue
try:
print("main rountine: %s" % f)
self.main()
cmds.file(rename=scene_name)
cmds.file(save=True, type="mayaBinary", f=True)
self.success.append(f)
print("main rountine success: %s" % f)
except:
import sys
print(sys.exc_info())
cmds.warning("fail at plot scene: %s" % filename)
self.failed.append(f)
continue
self._show_results()
def _file_open(self, filename):
cmds.file(filename, f=True, open=True)
short_name = cmds.file(q=True, sceneName=True, shortName=True)
short_name = short_name.rstrip(".mb").rstrip(".ma")
scene_name = (
self.save_directory +
self.prefix + short_name + self.suffix + ".mb")
return scene_name
def _show_confirmation(self):
files_string = "\n\t".join((self.file_list)).replace("[|]", "")
text = ("%s, using this settings, Are You Sure?\n\n"
"prefix:\n\t%s\n"
"suffix:\n%s\n\n"
"save directory: %s\n\n"
"files:\n\t%s" % (
re.sub("\n *$", " ", self.doc, re.MULTILINE),
self.prefix,
self.suffix,
self.save_directory,
files_string))
res = cmds.confirmDialog(
title="Confirm",
message=text,
button=["Yes","No"],
defaultButton="Yes",
cancelButton="No",
dismissString="No")
print(text)
return res == "Yes"
def _show_results(self):
f = lambda x: "\n\t".join(x).replace("[|]", "")
success = f(self.success)
failed = f(self.failed)
text = ("Success!:\n\t%s\n\nFailed!?:\n\t%s" % (success, failed))
cmds.confirmDialog(title="Results",message=text)
def _choose_folder(self):
multipleFilters = ("Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;"
"Maya Binary (*.mb);;All Files (*.*)")
sd = cmds.workspace(q=True, directory=True)
directory = ""
if re.match("2008", cmds.about(v=True)):
self.hoge = ""
def dummy(x, y):
self.hoge = x + "\\"
cmds.fileBrowserDialog(m=4, ds=0, fc=dummy, an="")
directory = self.hoge
else:
directory = cmds.fileDialog2(
dialogStyle=2,
caption=self.title_cap,
startingDirectory=sd,
fileMode=3,
fileFilter=multipleFilters,
okCaption=self.ok_cap)
directory = directory[0] + "\\"
if directory == None: raise
return directory
def _get_filelist(self, target_dir):
file_list = glob.glob(target_dir + "*."+ self.input_file_ext)
file_list = [x.split("\\")[-1] for x in file_list]
return file_list
##############################################################################
#
# 使用例
#
#
# こいつをmaya から実行
def bat_export_animation():
processor = fu.FolderProcessor(
export,
save_dir="hoehoe",
suffix=env.HAKIDASI_SUFFIX)
processor.execute()
# 別ファイル内
def export():
"""
"""
_preparation_for_export(rename_scene=False)
_export_fbx()
def _export_fbx():
dst = _get_fname()
cmds.select([env.MOT_EXPORT_MODEL_ROOT], r=True, hi=True)
p = env.FBX_EXPORT_CHRMODEL_PRESET
mel.eval('FBXLoadExportPresetFile -f "%s"' % p.replace("\\", "/"))
mel.eval('FBXExport -f "%s" -s' % dst)
def _get_fname():
sd = cmds.file(q=True, sceneName=True, shortName=False)
if not sd == "":
sd = "/".join(sd.split("/")[0:-1]) + "/"
else:
sd = cmds.workspace(q=True, directory=True)
short_name = cmds.file(q=True, sceneName=True, shortName=True)
short_name = short_name.split(".")[0].replace(env.HAKIDASI_SUFFIX, "")
if not dst_directory:
dst_directory = ("/".join(sd.split("/")[0:-2]) + "/" + "fbx")
dst_path = (dst_directory + "/" + short_name + ".fbx")
return dst_path
def _preparation_for_export():
pass
if __name__ == "__main__":
bat_export_animation()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment