from collections import namedtuple from utils.xml import StringToTree, FileToTree, subelement, TreeToFile, prettyPrint class Brdf(object): def __init__(self, reflect, alpha, ior=1.0): self.reflect= reflect self.alpha = alpha self.ior = ior def materialsAsXml(materials): tree = StringToTree('') for matname, m in materials.items(): e = subelement(tree.getroot(), 'brdf', attribs={'type': 'basic', 'name': matname}) reflect, alpha, ior = m.reflect, m.alpha, m.ior subelement(e, 'reflect', attribs={'value': reflect}) subelement(e, 'alpha', attribs={'value': alpha}) subelement(e, 'ior', attribs={'value': ior}) return tree def loadMaterialsFromTree(tree): materials = {} for e in tree.getroot().xpath('brdf'): try: reflect = float(e.xpath('string(reflect/@value)')) alpha = float(e.xpath('string(alpha/@value)')) ior = float(e.xpath('string(ior/@value)')) except Exception: print 'cannot load material %s' % e.attrib.get('name') reflect, alpha, ior = 0.5, 0.5, 1.0 materials[e.attrib['name']] = Brdf(reflect, alpha, ior) return materials def loadMaterialsFromString(materialsxml): return loadMaterialsFromTree(StringToTree(materialsxml)) def loadMaterials(materials_file): return loadMaterialsFromTree(FileToTree(materials_file))