#RE 2 Remake .tex [PC] - ".10" Loader
#v1.0 by zaramot

from inc_noesis import *

def registerNoesisTypes():
	handle = noesis.register("RE 2 Remake Texture [PC]", ".10",)
	noesis.setHandlerTypeCheck(handle, datCheckType)
	noesis.setHandlerLoadRGBA(handle, datLoadDDS)
	noesis.logPopup()
	return 1
		
def datCheckType(data):
	bs = NoeBitStream(data)
	fileMagic = bs.readUInt()
	if fileMagic == 0x584554:
		return 1
	else: 
		print("Fatal Error: Unknown file magic: " + str(hex(fileMagic) + " expected 0x584554!"))
		return 0

def datLoadDDS(data, texList):
	bs = NoeBitStream(data)
	
	numTextures  = 1
	fileMagic = bs.readUInt()
	
	for i in range (1):
		bs.seek((0x4), NOESEEK_REL)
		ddsWidth =  bs.readUShort()
		ddsHeight =  bs.readUShort()
		unk1 =  bs.readUShort()
		unk2 =  bs.readUShort()
		dxtType =  bs.readUInt()
		bs.seek((0xC), NOESEEK_REL)
		dataOff = bs.readUInt()
		bs.seek((0x8), NOESEEK_REL)
		ddsSize = bs.readUInt()
		ddsName = rapi.getLocalFileName(rapi.getInputName())
		bs.seek((dataOff), NOESEEK_ABS)
		print (ddsSize)
		print (dxtType)
		print (dataOff)
		ddsData = bs.readBytes(ddsSize)	  
		#DXT1
		if dxtType == 7:
		    ddsFmt = noesis.NOESISTEX_DXT1
		#DXT3
		if dxtType == 26:
		    ddsFmt = noesis.NOESISTEX_DXT3
		#DXT5
		elif dxtType == 26:
		    ddsFmt = noesis.NOESISTEX_DXT5
		#ATI1
		elif dxtType == 7:
		    ddsData = rapi.imageDecodeDXT(ddsData, ddsWidth, ddsHeight, noesis.FOURCC_ATI1)
		    ddsFmt = noesis.NOESISTEX_RGBA32	
		#ATI2
		elif dxtType == 26:
		    ddsData = rapi.imageDecodeDXT(ddsData, ddsWidth, ddsHeight, noesis.FOURCC_ATI2)
		    ddsFmt = noesis.NOESISTEX_RGBA32
		#BC7
		elif dxtType == 98:
		    ddsData = rapi.imageDecodeDXT(ddsData, ddsWidth, ddsHeight, noesis.FOURCC_BC7)
		    ddsFmt = noesis.NOESISTEX_RGBA32	
		#ATI1
		elif dxtType == 80:
		    ddsData = rapi.imageDecodeDXT(ddsData, ddsWidth, ddsHeight, noesis.FOURCC_ATI1)
		    ddsFmt = noesis.NOESISTEX_RGBA32
		#BC7
		elif dxtType == 99:
		    ddsData = rapi.imageDecodeDXT(ddsData, ddsWidth, ddsHeight, noesis.FOURCC_BC7)
		    ddsFmt = noesis.NOESISTEX_RGBA32
		#DXT1 packed normal map
		elif dxtType == 71:
		    ddsFmt = noesis.NOESISTEX_DXT1
        #raw
		elif dxtType == 7:
			ddsData = rapi.imageDecodeRaw(ddsData, ddsWidth, ddsHeight, "a8r8g8b8")
			ddsFmt = noesis.NOESISTEX_RGBA32
		#print (ddsType)   
		#print (dxtType)      
		texList.append(NoeTexture(ddsName, ddsWidth, ddsHeight, ddsData, ddsFmt))
	return 1
	