Skip to content

Instantly share code, notes, and snippets.

@whaison
Created February 6, 2017 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whaison/8ae6eb863b00bca71ddc411763ab253f to your computer and use it in GitHub Desktop.
Save whaison/8ae6eb863b00bca71ddc411763ab253f to your computer and use it in GitHub Desktop.
ImportScene_00100.py
# -*- coding: utf-8 -*-
from fbx import *
import os, sys
import re
#===================class Node=========================
import FbxCommon
#===================class Node=========================
#====================================================
#================== DisplayCommon.py ===================
#====================================================
def DisplayString(pHeader, pValue="" , pSuffix=""):
lString = pHeader
lString += str(pValue)
lString += pSuffix
print(lString)
def DisplayBool(pHeader, pValue, pSuffix=""):
lString = pHeader
if pValue:
lString += "true"
else:
lString += "false"
lString += pSuffix
print(lString)
def DisplayInt(pHeader, pValue, pSuffix=""):
lString = pHeader
lString += str(pValue)
lString += pSuffix
print(lString)
def DisplayDouble(pHeader, pValue, pSuffix=""):
print("%s%f%s" % (pHeader, pValue, pSuffix))
def Display2DVector(pHeader, pValue, pSuffix=""):
print("%s%f, %f%s" % (pHeader, pValue[0], pValue[1], pSuffix))
def Display3DVector(pHeader, pValue, pSuffix=""):
print("%s%f, %f, %f%s" % (pHeader, pValue[0], pValue[1], pValue[2], pSuffix))
def Display4DVector(pHeader, pValue, pSuffix=""):
print("%s%f, %f, %f, %f%s" % (pHeader, pValue[0], pValue[1], pValue[2], pValue[3], pSuffix))
def DisplayColor(pHeader, pValue, pSuffix=""):
print("%s%f (red), %f (green), %f (blue)%s" % (pHeader, pValue.mRed, pValue.mGreen, pValue.mBlue, pSuffix))
#====================================================
#================== DisplayGlobalSettings.py ===================
#====================================================
#from DisplayGlobalSettings import *
from fbx import FbxGlobalLightSettings
from fbx import FbxGlobalCameraSettings
def DisplayGlobalLightSettings(pScene):
lGlobalLightSettings = pScene.GlobalLightSettings()
DisplayColor("Ambient Color: ", lGlobalLightSettings.GetAmbientColor())
DisplayBool("Fog Enabled: ", lGlobalLightSettings.GetFogEnable())
DisplayColor("Fog Color: ", lGlobalLightSettings.GetFogColor())
lFogMode = lGlobalLightSettings.GetFogMode()
if(lFogMode == FbxGlobalLightSettings.eLinear):
DisplayString("Fog Mode: Linear")
elif(lFogMode == FbxGlobalLightSettings.eExponential):
DisplayString("Fog Mode: Exponential")
elif(lFogMode == FbxGlobalLightSettings.eExponentialSquareRoot):
DisplayString("Fog Mode: Exponential Square Root")
else:
DisplayString("Fog Mode: UNKNOWN")
DisplayDouble("Fog Density: ", lGlobalLightSettings.GetFogDensity())
DisplayDouble("Fog Start: ", lGlobalLightSettings.GetFogStart())
DisplayDouble("Fog End: ", lGlobalLightSettings.GetFogEnd())
DisplayBool("Shadow Enabled: ", lGlobalLightSettings.GetShadowEnable())
DisplayDouble("Fog Density: ", lGlobalLightSettings.GetShadowIntensity())
DisplayInt("Shadow Planes Count: ", lGlobalLightSettings.GetShadowPlaneCount())
DisplayString("")
def DisplayGlobalCameraSettings(pScene):
lGlobalSettings = pScene.GetGlobalSettings()
DisplayString("Default Camera: ", lGlobalSettings.GetDefaultCamera().Buffer())
DisplayString("")
def DisplayGlobalTimeSettings(pGlobalSettings):
lTimeModes = [ "Default Mode", "Cinema", "PAL", "Frames 30",
"NTSC Drop Frame", "Frames 50", "Frames 60",
"Frames 100", "Frames 120", "NTSC Full Frame",
"Frames 30 Drop", "Frames 1000" ]
DisplayString("Time Mode: ", lTimeModes[pGlobalSettings.GetTimeMode()])
lTs = pGlobalSettings.GetTimelineDefaultTimeSpan()
lStart = lTs.GetStart()
lEnd = lTs.GetStop()
DisplayString("Timeline default timespan: ")
lTmpStr=""
DisplayString(" Start: ", lStart.GetTimeString(lTmpStr, 10))
DisplayString(" Stop : ", lEnd.GetTimeString(lTmpStr, 10))
DisplayString("")
#====================================================
#================== DisplayGlobalLightSettings.py ===================
#====================================================
#====================================================
#================== DisplayCommon.py ===================
#====================================================
"""
from DisplayHierarchy import DisplayHierarchy
from DisplayMarker import DisplayMarker
from DisplayMesh import DisplayMesh
from DisplayUserProperties import DisplayUserProperties
from DisplayPivotsAndLimits import DisplayPivotsAndLimits
from DisplaySkeleton import DisplaySkeleton
from DisplayNurb import DisplayNurb
from DisplayPatch import DisplayPatch
from DisplayCamera import DisplayCamera
from DisplayLight import DisplayLight
from DisplayLodGroup import DisplayLodGroup
from DisplayPose import DisplayPose
from DisplayAnimation import DisplayAnimation
from DisplayGenericInfo import DisplayGenericInfo
"""
"""
import DisplayHierarchy
import DisplayMarker
import DisplayMesh
import DisplayUserProperties
import DisplayPivotsAndLimits
import DisplaySkeleton
import DisplayNurb
import DisplayPatch
import DisplayCamera
import DisplayLight
import DisplayLodGroup
import DisplayPose
import DisplayAnimation
import DisplayGenericInfo
"""
#====================================================
#================== ImportScene.py ===================
#====================================================
#===================class Node=========================
class ImportScene_00100() :
#======================================================================================================
#======================================================================================================
#============= ==============================================
#======================================================================================================
#======================================================================================================
#======================================================================================================
def DisplayString(self,pHeader, pValue="" , pSuffix=""):
lString = "ImportScene_00100.py ImportScene_00100 Class Method 017 DisplayString() "
lString += " pHeader = "
lString += pHeader
lString += " pValue = "
lString += str(pValue)
lString += " pSuffix = "
lString += pSuffix
#print(lString)
DebugLog(str(lString))
#====================================================
#================== ImportScene.py ===================
#====================================================
def DisplayMetaData(self,pScene):
sceneInfo = pScene.GetSceneInfo()
if sceneInfo:
self.DebugLog("--------------------")
self.DebugLog(" Meta-Data ")
self.DebugLog("--------------------")
self.DebugLog(" 00100 Title : " + str( sceneInfo.mTitle.Buffer () ) )
self.DebugLog(" 00200 Subject : " + str( sceneInfo.mSubject.Buffer () ) )
self.DebugLog(" 00300 Author : " + str( sceneInfo.mAuthor.Buffer () ) )
self.DebugLog(" 00400 Keywords: " + str( sceneInfo.mKeywords.Buffer () ) )
self.DebugLog(" 00500 Revision: " + str( sceneInfo.mRevision.Buffer () ) )
self.DebugLog(" 00600 Comment : " + str( sceneInfo.mComment.Buffer () ) )
thumbnail = sceneInfo.GetSceneThumbnail()
if thumbnail:
self.DebugLog(" Thumbnail:")
if thumbnail.GetDataFormat() == FbxThumbnail.eRGB_24 :
self.DebugLog(" Format: RGB")
elif thumbnail.GetDataFormat() == FbxThumbnail.eRGBA_32:
self.DebugLog(" Format: RGBA")
if thumbnail.GetSize() == FbxThumbnail.eNOT_SET:
self.DebugLog(" Size: no dimensions specified ("+ str( thumbnail.GetSizeInBytes() ) +" bytes)")
elif thumbnail.GetSize() == FbxThumbnail.e64x64:
self.DebugLog(" Size: 64 x 64 pixels ("+ str( thumbnail.GetSizeInBytes() ) +" bytes)")
elif thumbnail.GetSize() == FbxThumbnail.e128x128:
self.DebugLog(" Size: 128 x 128 pixels ("+ str( thumbnail.GetSizeInBytes() ) +" bytes)")
def DisplayContent(self,pScene):
lNode = pScene.GetRootNode()
if lNode:
for i in range(lNode.GetChildCount()):
self.DisplayNodeContent(lNode.GetChild(i))
def DisplayNodeContent(self,pNode):
if pNode.GetNodeAttribute() == None:
self.DebugLog("NULL Node Attribute \n")
else:
lAttributeType = ( pNode.GetNodeAttribute().GetAttributeType() )
if lAttributeType == FbxNodeAttribute.eMarker:
self.DisplayMarker(pNode)
elif lAttributeType == FbxNodeAttribute.eSkeleton:
self.DisplaySkeleton(pNode)
elif lAttributeType == FbxNodeAttribute.eMesh:
self.DisplayMesh(pNode)
elif lAttributeType == FbxNodeAttribute.eNurbs:
self.DisplayNurb(pNode)
elif lAttributeType == FbxNodeAttribute.ePatch:
self.DisplayPatch(pNode)
elif lAttributeType == FbxNodeAttribute.eCamera:
self.DisplayCamera(pNode)
elif lAttributeType == FbxNodeAttribute.eLight:
self.DisplayLight(pNode)
self.DisplayUserProperties(pNode)
self.DisplayTarget(pNode)
self.DisplayPivotsAndLimits(pNode)
self.DisplayTransformPropagation(pNode)
self.DisplayGeometricTransform(pNode)
for i in range(pNode.GetChildCount()):
self.DisplayNodeContent( pNode.GetChild(i) )
def DisplayTarget(self,pNode):
if pNode.GetTarget():
self.DisplayString(" Target Name: ", pNode.GetTarget().GetName())
def DisplayTransformPropagation(self,pNode):
self.DebugLog(" Transformation Propagation")
# Rotation Space
lRotationOrder = pNode.GetRotationOrder(FbxNode.eSourcePivot)
self.DebugLog(" Rotation Space:")
if lRotationOrder == eEulerXYZ:
self.DebugLog("Euler XYZ")
elif lRotationOrder == eEulerXZY:
self.DebugLog("Euler XZY")
elif lRotationOrder == eEulerYZX:
self.DebugLog("Euler YZX")
elif lRotationOrder == eEulerYXZ:
self.DebugLog("Euler YXZ")
elif lRotationOrder == eEulerZXY:
self.DebugLog("Euler ZXY")
elif lRotationOrder == eEulerZYX:
self.DebugLog("Euler ZYX")
elif lRotationOrder == eSphericXYZ:
self.DebugLog("Spheric XYZ")
# Use the Rotation space only for the limits
# (keep using eEULER_XYZ for the rest)
if pNode.GetUseRotationSpaceForLimitOnly(FbxNode.eSourcePivot):
self.DebugLog(" Use the Rotation Space for Limit specification only: Yes")
else:
self.DebugLog(" Use the Rotation Space for Limit specification only: No")
# Inherit Type
lInheritType = pNode.GetTransformationInheritType()
self.DebugLog(" Transformation Inheritance:")
if lInheritType == FbxTransform.eInheritRrSs:
self.DebugLog("RrSs")
elif lInheritType == FbxTransform.eInheritRSrs:
self.DebugLog("RSrs")
elif lInheritType == FbxTransform.eInheritRrs:
self.DebugLog("Rrs")
#====================================================
#================== ImportScene.py ===================
#====================================================
Yen="\\"
FileName= "ImportScene_00100__Log.csv"
#print("HD FULL PATH =")
#HD_FULL_PATH=os.path.abspath(__file__)
#print("os.path.abspath(__file__) = " + HD_FULL_PATH)
FullPass_DustDataTextFile_TXT= "D:"+Yen+"vs"+Yen+"py"+Yen+FileName
def ImportScene_00100(self):
print("ImportScene_00100_Start............. filepath = "+str(filepath))
#self.FullPass_DustDataTextFile_TXT=filepath
#文字をエスケープする/エスケープを外す ///////////////////////http://lightson.dip.jp/zope/ZWiki/053_e6_96_87_e5_ad_97_e3_82_92_e3_82_a8_e3_82_b9_e3_82_b1_e3_83_bc_e3_83_97_e3_81_99_e3_82_8b_ef_bc_8f_e3_82_a8_e3_82_b9_e3_82_b1_e3_83_bc_e3_83_97_e3_82_92_e5_a4_96_e3_81_99
def escape(self,s, quoted=u'\'"\\', escape=u'\\'):
return re.sub(u'[%s]' % re.escape(quoted),lambda mo: escape + mo.group(),s)
def unescape(self,s, quoted=u'\'"\\', escape=u'\\'):
return re.sub(ur'%s([%s])' % (re.escape(escape), re.escape(quoted)),ur'\1',s)
def DebugLog(self,strData):
mystr=strData
print(mystr)
if mystr=="":
print("DebugLog (mystr ) is empty....................")
else:
#mystr=str(mystr)+","
mystr=str(mystr)+"\n"
#mystr=mystr+"\n"
escapedStrData=self.escape(mystr)
self.fileReWrite(self.FullPass_DustDataTextFile_TXT,escapedStrData)
#fileReWrite(FullPass_DustDataTextFile_TXT,mystr)
#fileWrite(FullPass_DustDataTextFile_TXT,mystr)
#fileWrite("C:\Users\akiyaman\AppData\Roaming\Adobe\Common","ABC")
#----------------ファイルを作る------------------
def ExportWrite(self,strData):
strData_str=str(strData)
e_infinity_str_first_to_end_count=strData_str.find("e")
new_float_string= strData_str
if e_infinity_str_first_to_end_count==-1:
new_float_string= strData_str
else:
new_float_string= strData_str[0:e_infinity_str_first_to_end_count]
#new_float_string= strData_str[0:4]
self.DebugLog(new_float_string)
def fileWrite(self,fullPass,DataStr):
print("fileWrite fullPass= "+fullPass)
print("fileWrite DataStr= "+DataStr)
f = open(fullPass, 'w') # 書き込みモードで開く
#str = "This Data is Temp Please Delete" # 書き込む文字列
#f = open('text.txt', 'w') # 書き込みモードで開く
#f.write(str) # 引数の文字列をファイルに書き込む
f.write(DataStr) # 引数の文字列をファイルに書き込む
f.close() # ファイルを閉じる
def fileDataZeroReset(self):
self.fileWrite(self.FullPass_DustDataTextFile_TXT,"")
def fileReWrite(self,fullPass,DataStr):
print("fileWrite fullPass= "+fullPass)#///////////////////////////////////////////////////////////////////////////////////////////////////////////
print("fileWrite DataStr= "+DataStr)
f = open(fullPass, 'a') # 追記書き込みモードで開く
#str = "This Data is Temp Please Delete" # 書き込む文字列
#f = open('text.txt', 'w') # 書き込みモードで開く
#f.write(str) # 引数の文字列をファイルに書き込む
f.write(DataStr) # 引数の文字列をファイルに書き込む
f.close() # ファイルを閉じる
def fileWriteTemp(self,fullPass):
fileWrite(fullPass,"DustDataTextFile")
#//////////////////////////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////// Class Unit Test /////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////////////////////////
def getClassName(self):
print( u"className= " + self.__class__.__name__)
return self.__class__.__name__
class TxtReaderTrans_Z_00320() :
def fileRead(self,filepath):
print("088 fileRead() filepath = "+str(filepath))
returnData=""
f = open(filepath, 'r')
#returnData = f
poolStr=""
for row in f:
print row
poolStr=poolStr+row
f.close()
print("099 fileRead() poolStr = "+poolStr)
returnData=str(poolStr)
print("101 fileRead() returnData = "+returnData)
return returnData
def ReadTransFile(self):
returnData=""
ImportScene_00100_Instance = ImportScene_00100()
returnData =self.fileRead(ImportScene_00100_Instance.FullPass_DustDataTextFile_TXT)
print("107 ReadSimple() returnData = "+ str(returnData))
return returnData
#//////////////////////////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////// Class Unit Test /////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////////////////////////
def getClassName(self):
print( u"className= " + self.__class__.__name__)
return self.__class__.__name__
ImportScene_00100_Instance = ImportScene_00100() # Class export instance.
print(" ImportScene_00100 Class __name__="+__name__)
#//////////////////////////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////// Class Unit Test /////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////////////////////////
def DebugLog(DataStr):
ImportScene_00100_Instance.DebugLog( str(DataStr) )
def StartMainLine(ImportScene_00100_Instance):
print("StartMainLine")
ImportScene_00100_Instance.fileDataZeroReset()
# Prepare the FBX SDK.
#lSdkManager, lScene = InitializeSdkObjects()
Yen="\\"
IMPORT_FBX_FileName ="walkTest.fbx"
FBX_FILE_PATH_AND_NAME_AND_EXT= "D:"+Yen+"vs"+Yen+"py"+Yen+IMPORT_FBX_FileName
manager = FbxManager.Create()
ios = FbxIOSettings.Create(manager, IOSROOT)
manager.SetIOSettings(ios)
importer = FbxImporter.Create(manager, "")
fbxImportSuccesBool=importer.Initialize(FBX_FILE_PATH_AND_NAME_AND_EXT, -1, manager.GetIOSettings())
#DebugLog("fbxImportSuccesBool=")
if not fbxImportSuccesBool:
DebugLog("fbxImportSuccesBool==False")
print ("==============Failed to load file.==============")
return
else:
DebugLog("fbxImportSuccesBool==True")
scene = FbxScene.Create(manager, "MyScene")
lScene=scene
importer.Import(scene)
#==========================================================
#importScene.py Timeing
#==========================================================
ImportScene_00100_Instance.DisplayMetaData(lScene)
DebugLog("\n\n---------------------\nGlobal Light Settings\n---------------------\n")
DisplayGlobalLightSettings(lScene)
DebugLog("\n\n----------------------\nGlobal Camera Settings\n----------------------\n")
#DisplayGlobalCameraSettings(lScene)
DebugLog("\n\n--------------------\nGlobal Time Settings\n--------------------\n")
#ImportScene_00100_Instance.DisplayGlobalTimeSettings(lScene.GetGlobalSettings())
DebugLog("\n\n---------\nHierarchy\n---------\n")
#ImportScene_00100_Instance.DisplayHierarchy(lScene)
DebugLog("\n\n------------\nNode Content\n------------\n")
#ImportScene_00100_Instance.DisplayContent(lScene)
DebugLog("\n\n----\nPose\n----\n")
#ImportScene_00100_Instance.DisplayPose(lScene)
DebugLog("\n\n---------\nAnimation\n---------\n")
#ImportScene_00100_Instance.DisplayAnimation(lScene)
#now display generic information
DebugLog("\n\n---------\nGeneric Information\n---------\n")
#ImportScene_00100_Instance.DisplayGenericInfo(lScene)
#ImportScene_00100_Instance.ExportWrite("0.111");
#ImportScene_00100_Instance.ExportWrite("0.222");
#ImportScene_00100_Instance.ExportWrite("0.333");
#ImportScene_00100_Instance.ExportWrite("0.444");
"""
#=============================================================================
print("========================= Write Start==========================")
floatList = [1.111, 1.222, 1.333, 1.444, 1.555]
floatListLength=len(floatList)
for i in range(0, floatListLength):
print( str(i) )
print(floatList[i])
floatNum=floatList[i]
floatNumstr=str(floatNum)
#ImportScene_00100_Instance.ExportWrite("0.111");
ImportScene_00100_Instance.ExportWrite( str(floatNumstr) );
#=============================================================================
print("========================= Read Start==========================")
ImportScene_00100_Instance2 = TxtReaderTrans_Z_00320() # Class export instance.
TransZstrData = ImportScene_00100_Instance2.ReadTransFile()
TransZstr=str(TransZstrData)
print("TransZstr = _ "+str(TransZstr)+" _ END ")
print("========================= add list Start==========================")
TransZstrList=TransZstr.split(",") # 「,」を区切り文字としてリストを返す
print("TransZstrList = _ "+str(TransZstrList)+" _ END ")
TransZstrListLength=len(TransZstrList)
print("TransZstrListLength = "+str(TransZstrListLength))
#==========================================
#==========================================
TransZ_list = [0]
#指定のインデックスの要素を削除する
TransZ_list.pop(0)
#----------------------------------------------
for j in range(0, TransZstrListLength):
print( "TransZ Loop "+str(j) )
print(TransZstrList[j])
TransZnumStr=TransZstrList[j]
print("TransZnumStr= "+TransZnumStr)
if(TransZnumStr == ""):
print("TransZ empty string ")
else:
TransZnumFloat=float(TransZnumStr)
TransZ_list.append(TransZnumFloat)
#===================TransZ_list debug==============================
print("========================= =TransZ_list debug Start==========================")
TransZ_listLength=len(TransZ_list)
for d in range(0, TransZ_listLength):
print( "TransZ_list Loop Debug "+str(d) )
TransZnumFloat_d=TransZ_list[d]
TransZnumStr_d = str(TransZnumFloat_d)
print("TransZnumStr_d = "+TransZnumStr_d)
#DebugLog (u"__name__==self.__class__.__name__ Same!! File Test")
#DebugLog (u"=============Simple Single Class Unit Test Start==========")
#Instance.ImportScene_00100() #Call Method
"""
#//////////////////////////////////////////////////////////////////////////////////////////////////
#////////////////////////////////////ImportScene_00100_Instance Class Unit Test /////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////////////////////////
if(__name__ == ImportScene_00100_Instance.getClassName()):
print (u"=============Simple Single Class Unit Test Start====Instance.getClassName() = "+ImportScene_00100_Instance.getClassName()+" =====")
#StartMainLine(ImportScene_00100_Instance)
elif(__name__ == "ImportScene_00100"):
print (u"=============Simple Single Class Unit Test Start===== StartMainLine =====")
StartMainLine(ImportScene_00100_Instance)
#Instance.loadFile(FBX_FILE_PATH_AND_NAME_AND_EXT)
elif(__name__ == "__main__"):
print (u"=============Simple Single Class Unit Test Start===== __main__ =====")
StartMainLine(ImportScene_00100_Instance)
else:
print (u"__name__!=self.__class__.__name__ Othor File Import")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment