'''
This file contains utility functions to load titopo (Theta_in / Theta_out / Phi_out) brdf Files into Keras
Titopo files are generated by BrdfModifier with the -O option
'''

import struct
import numpy as np
import math
from merl_nrec import Merl
import string
import os.path

def LoadTitopo(material_path):
	if os.path.isfile(material_path) == False:
		print("Error : material file" + material_path + "not found.")
		exit

	titopoData = open(material_path,'rb').read()
	dataOffset = 0
	length = 90*90*360*3

	returnBrdf = np.array(struct.unpack_from(str(length) +'f',titopoData)).reshape(90,90,360,3)

	return returnBrdf
 
def LoadTitopoFromMERL(merlFile):
	returnBrdf = np.empty((90,90,360,3))

	merlData = Merl(merlFile)
	print("Loading...")
	for Tin in np.arange(0,90):
		print(".", end=' ')
		for Tou in np.arange(0,90):
			for Pou in np.arange(0,360):
				evalValue = merlData.eval_interp_theta_phi(Tin*np.pi/180, 0, Tou*np.pi/180, Pou*np.pi/180)
				returnBrdf[Tin, Tou, Pou, :] = evalValue            
	return returnBrdf
