Example #1
0
def obj_image_load(imagepath, DIR, IMAGE_SEARCH):
    if b'_' in imagepath:
        image = load_image(imagepath.replace(b'_', b' '), DIR)
        if image:
            return image

    image = load_image(imagepath, DIR)
    if image:
        return image

    print("failed to load %r doesn't exist" % imagepath)
    return None
Example #2
0
def obj_image_load(imagepath, DIR, IMAGE_SEARCH):
    if b'_' in imagepath:
        image = load_image(imagepath.replace(b'_', b' '), DIR)
        if image:
            return image

    image = load_image(imagepath, DIR)
    if image:
        return image

    print("failed to load %r doesn't exist" % imagepath)
    return None
Example #3
0
def import_images(self, context):
    import_list, directory = generate_paths(self)
    images = []
    textures = []
    materials = []
    planes = []
    
    for path in import_list:
        images.append(load_image(path, directory))

    for image in images:
        set_image_options(self, image)
        textures.append(create_image_textures(self, image))

    for texture in textures:
        materials.append(create_material_for_texture(self, texture))

    for material in materials:
        plane = create_image_plane(self, context, material)
        planes.append(plane)
        
    context.scene.update()
    if self.align:
        align_planes(self, planes)
        
    for plane in planes:
        plane.select = True
        
    self.report(type='INFO',
                message='Added %i Image Plane(s)' %len(planes))
Example #4
0
def import_images(self, context):
    import_list, directory = generate_paths(self)
    images = []
    textures = []
    materials = []
    planes = []

    for path in import_list:
        images.append(load_image(path, directory))

    for image in images:
        set_image_options(self, image)
        textures.append(create_image_textures(self, image))

    for texture in textures:
        materials.append(create_material_for_texture(self, texture))

    for material in materials:
        plane = create_image_plane(self, context, material)
        planes.append(plane)

    context.scene.update()
    if self.align:
        align_planes(self, planes)

    for plane in planes:
        plane.select = True

    self.report(type="INFO", message="Added %i Image Plane(s)" % len(planes))
Example #5
0
def create_texture(filename, modelpath):
    name = filename
    texture = bpy.data.textures.new(name, type='IMAGE')
    
    image = load_image(filename, modelpath)
    has_data = False

    if image:
        texture.image = image
        has_data = image.has_data
    
    return texture
Example #6
0
    def read_texture(new_chunk, temp_chunk, name, mapto):
        new_texture = bpy.data.textures.new(name, type='IMAGE')

        img = None
        while (new_chunk.bytes_read < new_chunk.length):
            #print 'MAT_TEXTURE_MAP..while', new_chunk.bytes_read, new_chunk.length
            read_chunk(file, temp_chunk)

            if (temp_chunk.ID == MAT_MAP_FILEPATH):
                texture_name, read_str_len = read_string(file)
                img = TEXTURE_DICT[contextMaterial.name] = load_image(texture_name, dirname)
                new_chunk.bytes_read += read_str_len #plus one for the null character that gets removed

            else:
                skip_to_end(file, temp_chunk)

            new_chunk.bytes_read += temp_chunk.bytes_read

        # add the map to the material in the right channel
        if img:
            add_texture_to_material(img, new_texture, contextMaterial, mapto)
Example #7
0
    def read_texture(new_chunk, temp_chunk, name, mapto):
        new_texture = bpy.data.textures.new(name, type='IMAGE')

        img = None
        while (new_chunk.bytes_read < new_chunk.length):
            #print 'MAT_TEXTURE_MAP..while', new_chunk.bytes_read, new_chunk.length
            read_chunk(file, temp_chunk)

            if (temp_chunk.ID == MAT_MAP_FILEPATH):
                texture_name, read_str_len = read_string(file)
                img = TEXTURE_DICT[contextMaterial.name] = load_image(
                    texture_name, dirname)
                new_chunk.bytes_read += read_str_len  #plus one for the null character that gets removed

            else:
                skip_to_end(file, temp_chunk)

            new_chunk.bytes_read += temp_chunk.bytes_read

        # add the map to the material in the right channel
        if img:
            add_texture_to_material(img, new_texture, contextMaterial, mapto)
Example #8
0
def process_next_chunk(file, previous_chunk, importedObjects, IMAGE_SEARCH):
    #print previous_chunk.bytes_read, 'BYTES READ'
    contextObName = None
    contextLamp = [None, None] # object, Data
    contextMaterial = None
    contextMatrix_rot = None # Blender.mathutils.Matrix(); contextMatrix.identity()
    #contextMatrix_tx = None # Blender.mathutils.Matrix(); contextMatrix.identity()
    contextMesh_vertls = None # flat array: (verts * 3)
    contextMesh_facels = None
    contextMeshMaterials = {} # matname:[face_idxs]
    contextMeshUV = None # flat array (verts * 2)

    TEXTURE_DICT = {}
    MATDICT = {}
# 	TEXMODE = Mesh.FaceModes['TEX']

    # Localspace variable names, faster.
    STRUCT_SIZE_1CHAR = struct.calcsize('c')
    STRUCT_SIZE_2FLOAT = struct.calcsize('2f')
    STRUCT_SIZE_3FLOAT = struct.calcsize('3f')
    STRUCT_SIZE_4FLOAT = struct.calcsize('4f')
    STRUCT_SIZE_UNSIGNED_SHORT = struct.calcsize('H')
    STRUCT_SIZE_4UNSIGNED_SHORT = struct.calcsize('4H')
    STRUCT_SIZE_4x3MAT = struct.calcsize('ffffffffffff')
    _STRUCT_SIZE_4x3MAT = struct.calcsize('fffffffffffff')
    # STRUCT_SIZE_4x3MAT = calcsize('ffffffffffff')
    # print STRUCT_SIZE_4x3MAT, ' STRUCT_SIZE_4x3MAT'
    # only init once
    object_list = [] # for hierarchy
    object_parent = [] # index of parent in hierarchy, 0xFFFF = no parent
    pivot_list = [] # pivots with hierarchy handling
    
    def putContextMesh(myContextMesh_vertls, myContextMesh_facels, myContextMeshMaterials):
        bmesh = bpy.data.meshes.new(contextObName)

        if myContextMesh_facels is None:
            myContextMesh_facels = []

        if myContextMesh_vertls:

            bmesh.vertices.add(len(myContextMesh_vertls)//3)
            bmesh.faces.add(len(myContextMesh_facels))
            bmesh.vertices.foreach_set("co", myContextMesh_vertls)
            
            eekadoodle_faces = []
            for v1, v2, v3 in myContextMesh_facels:
                eekadoodle_faces.extend([v3, v1, v2, 0] if v3 == 0 else [v1, v2, v3, 0])
            bmesh.faces.foreach_set("vertices_raw", eekadoodle_faces)
            
            if bmesh.faces and contextMeshUV:
                bmesh.uv_textures.new()
                uv_faces = bmesh.uv_textures.active.data[:]
            else:
                uv_faces = None

            for mat_idx, (matName, faces) in enumerate(myContextMeshMaterials.items()):
                if matName is None:
                    bmat = None
                else:
                    bmat = MATDICT[matName][1]
                    img = TEXTURE_DICT.get(bmat.name)

                bmesh.materials.append(bmat) # can be None

                if uv_faces  and img:
                    for fidx in faces:
                        bmesh.faces[fidx].material_index = mat_idx
                        uf = uv_faces[fidx]
                        uf.image = img
                        uf.use_image = True
                else:
                    for fidx in faces:
                        bmesh.faces[fidx].material_index = mat_idx
                
            if uv_faces:
                for fidx, uf in enumerate(uv_faces):
                    face = myContextMesh_facels[fidx]
                    v1, v2, v3 = face
                    
                    # eekadoodle
                    if v3 == 0:
                        v1, v2, v3 = v3, v1, v2
                    
                    uf.uv1 = contextMeshUV[v1 * 2:(v1 * 2) + 2]
                    uf.uv2 = contextMeshUV[v2 * 2:(v2 * 2) + 2]
                    uf.uv3 = contextMeshUV[v3 * 2:(v3 * 2) + 2]
                    # always a tri

        bmesh.validate()
        bmesh.update()

        ob = bpy.data.objects.new(contextObName, bmesh)
        object_dictionary[contextObName] = ob
        SCN.objects.link(ob)
        
        '''
        if contextMatrix_tx:
            ob.setMatrix(contextMatrix_tx)
        '''
        
        if contextMatrix_rot:
            ob.matrix_local = contextMatrix_rot
            object_matrix[ob] = contextMatrix_rot.copy()

        importedObjects.append(ob)

    #a spare chunk
    new_chunk = chunk()
    temp_chunk = chunk()

    CreateBlenderObject = False

    def read_float_color(temp_chunk):
        temp_data = file.read(struct.calcsize('3f'))
        temp_chunk.bytes_read += 12
        return [float(col) for col in struct.unpack('<3f', temp_data)]

    def read_byte_color(temp_chunk):
        temp_data = file.read(struct.calcsize('3B'))
        temp_chunk.bytes_read += 3
        return [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb

    def read_texture(new_chunk, temp_chunk, name, mapto):
        new_texture = bpy.data.textures.new(name, type='IMAGE')

        img = None
        while (new_chunk.bytes_read < new_chunk.length):
            #print 'MAT_TEXTURE_MAP..while', new_chunk.bytes_read, new_chunk.length
            read_chunk(file, temp_chunk)

            if (temp_chunk.ID == MAT_MAP_FILEPATH):
                texture_name, read_str_len = read_string(file)
                img = TEXTURE_DICT[contextMaterial.name] = load_image(texture_name, dirname)
                new_chunk.bytes_read += read_str_len #plus one for the null character that gets removed

            else:
                skip_to_end(file, temp_chunk)

            new_chunk.bytes_read += temp_chunk.bytes_read

        # add the map to the material in the right channel
        if img:
            add_texture_to_material(img, new_texture, contextMaterial, mapto)

    dirname = os.path.dirname(file.name)

    #loop through all the data for this chunk (previous chunk) and see what it is
    while (previous_chunk.bytes_read < previous_chunk.length):
        #print '\t', previous_chunk.bytes_read, 'keep going'
        #read the next chunk
        #print 'reading a chunk'
        read_chunk(file, new_chunk)

        #is it a Version chunk?
        if (new_chunk.ID == VERSION):
            #print 'if (new_chunk.ID == VERSION):'
            #print 'found a VERSION chunk'
            #read in the version of the file
            #it's an unsigned short (H)
            temp_data = file.read(struct.calcsize('I'))
            version = struct.unpack('<I', temp_data)[0]
            new_chunk.bytes_read += 4 #read the 4 bytes for the version number
            #this loader works with version 3 and below, but may not with 4 and above
            if (version > 3):
                print('\tNon-Fatal Error:  Version greater than 3, may not load correctly: ', version)

        #is it an object info chunk?
        elif (new_chunk.ID == OBJECTINFO):
            #print 'elif (new_chunk.ID == OBJECTINFO):'
            # print 'found an OBJECTINFO chunk'
            process_next_chunk(file, new_chunk, importedObjects, IMAGE_SEARCH)

            #keep track of how much we read in the main chunk
            new_chunk.bytes_read += temp_chunk.bytes_read

        #is it an object chunk?
        elif (new_chunk.ID == OBJECT):

            if CreateBlenderObject:
                putContextMesh(contextMesh_vertls, contextMesh_facels, contextMeshMaterials)
                contextMesh_vertls = []; contextMesh_facels = []

                ## preparando para receber o proximo objeto
                contextMeshMaterials = {} # matname:[face_idxs]
                contextMeshUV = None
                #contextMesh.vertexUV = 1 # Make sticky coords.
                # Reset matrix
                contextMatrix_rot = None
                #contextMatrix_tx = None

            CreateBlenderObject = True
            contextObName, read_str_len = read_string(file)
            new_chunk.bytes_read += read_str_len

        #is it a material chunk?
        elif (new_chunk.ID == MATERIAL):

# 			print("read material")

            #print 'elif (new_chunk.ID == MATERIAL):'
            contextMaterial = bpy.data.materials.new('Material')

        elif (new_chunk.ID == MAT_NAME):
            #print 'elif (new_chunk.ID == MAT_NAME):'
            material_name, read_str_len = read_string(file)

# 			print("material name", material_name)

            #plus one for the null character that ended the string
            new_chunk.bytes_read += read_str_len

            contextMaterial.name = material_name.rstrip() # remove trailing  whitespace
            MATDICT[material_name]= (contextMaterial.name, contextMaterial)

        elif (new_chunk.ID == MAT_AMBIENT):
            #print 'elif (new_chunk.ID == MAT_AMBIENT):'
            read_chunk(file, temp_chunk)
            if (temp_chunk.ID == MAT_FLOAT_COLOR):
                contextMaterial.mirror_color = read_float_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3f'))
# 				temp_chunk.bytes_read += 12
# 				contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
            elif (temp_chunk.ID == MAT_24BIT_COLOR):
                contextMaterial.mirror_color = read_byte_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3B'))
# 				temp_chunk.bytes_read += 3
# 				contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
            else:
                skip_to_end(file, temp_chunk)
            new_chunk.bytes_read += temp_chunk.bytes_read

        elif (new_chunk.ID == MAT_DIFFUSE):
            #print 'elif (new_chunk.ID == MAT_DIFFUSE):'
            read_chunk(file, temp_chunk)
            if (temp_chunk.ID == MAT_FLOAT_COLOR):
                contextMaterial.diffuse_color = read_float_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3f'))
# 				temp_chunk.bytes_read += 12
# 				contextMaterial.rgbCol = [float(col) for col in struct.unpack('<3f', temp_data)]
            elif (temp_chunk.ID == MAT_24BIT_COLOR):
                contextMaterial.diffuse_color = read_byte_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3B'))
# 				temp_chunk.bytes_read += 3
# 				contextMaterial.rgbCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
            else:
                skip_to_end(file, temp_chunk)

# 			print("read material diffuse color", contextMaterial.diffuse_color)

            new_chunk.bytes_read += temp_chunk.bytes_read

        elif (new_chunk.ID == MAT_SPECULAR):
            #print 'elif (new_chunk.ID == MAT_SPECULAR):'
            read_chunk(file, temp_chunk)
            if (temp_chunk.ID == MAT_FLOAT_COLOR):
                contextMaterial.specular_color = read_float_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3f'))
# 				temp_chunk.bytes_read += 12
# 				contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
            elif (temp_chunk.ID == MAT_24BIT_COLOR):
                contextMaterial.specular_color = read_byte_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3B'))
# 				temp_chunk.bytes_read += 3
# 				contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
            else:
                skip_to_end(file, temp_chunk)
            new_chunk.bytes_read += temp_chunk.bytes_read

        elif (new_chunk.ID == MAT_TEXTURE_MAP):
            read_texture(new_chunk, temp_chunk, "Diffuse", "COLOR")

        elif (new_chunk.ID == MAT_SPECULAR_MAP):
            read_texture(new_chunk, temp_chunk, "Specular", "SPECULARITY")

        elif (new_chunk.ID == MAT_OPACITY_MAP):
            read_texture(new_chunk, temp_chunk, "Opacity", "ALPHA")

        elif (new_chunk.ID == MAT_BUMP_MAP):
            read_texture(new_chunk, temp_chunk, "Bump", "NORMAL")

        elif (new_chunk.ID == MAT_TRANSPARENCY):
            #print 'elif (new_chunk.ID == MAT_TRANSPARENCY):'
            read_chunk(file, temp_chunk)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)

            temp_chunk.bytes_read += 2
            contextMaterial.alpha = 1-(float(struct.unpack('<H', temp_data)[0])/100)
            new_chunk.bytes_read += temp_chunk.bytes_read


        elif (new_chunk.ID == OBJECT_LAMP): # Basic lamp support.

            temp_data = file.read(STRUCT_SIZE_3FLOAT)

            x,y,z = struct.unpack('<3f', temp_data)
            new_chunk.bytes_read += STRUCT_SIZE_3FLOAT

            # no lamp in dict that would be confusing
            contextLamp[1] = bpy.data.lamps.new("Lamp", 'POINT')
            contextLamp[0] = ob = bpy.data.objects.new("Lamp", contextLamp[1])

            SCN.objects.link(ob)
            importedObjects.append(contextLamp[0])

            #print 'number of faces: ', num_faces
            #print x,y,z
            contextLamp[0].location = (x, y, z)
# 			contextLamp[0].setLocation(x,y,z)

            # Reset matrix
            contextMatrix_rot = None
            #contextMatrix_tx = None
            #print contextLamp.name,

        elif (new_chunk.ID == OBJECT_MESH):
            # print 'Found an OBJECT_MESH chunk'
            pass
        elif (new_chunk.ID == OBJECT_VERTICES):
            '''
            Worldspace vertex locations
            '''
            # print 'elif (new_chunk.ID == OBJECT_VERTICES):'
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_verts = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2

            # print 'number of verts: ', num_verts
            contextMesh_vertls = struct.unpack('<%df' % (num_verts * 3), file.read(STRUCT_SIZE_3FLOAT * num_verts))
            new_chunk.bytes_read += STRUCT_SIZE_3FLOAT * num_verts
            # dummyvert is not used atm!
            
            #print 'object verts: bytes read: ', new_chunk.bytes_read

        elif (new_chunk.ID == OBJECT_FACES):
            # print 'elif (new_chunk.ID == OBJECT_FACES):'
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_faces = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2
            #print 'number of faces: ', num_faces

            # print '\ngetting a face'
            temp_data = file.read(STRUCT_SIZE_4UNSIGNED_SHORT * num_faces)
            new_chunk.bytes_read += STRUCT_SIZE_4UNSIGNED_SHORT * num_faces #4 short ints x 2 bytes each
            contextMesh_facels = struct.unpack('<%dH' % (num_faces * 4), temp_data)
            contextMesh_facels = [contextMesh_facels[i - 3:i] for i in range(3, (num_faces * 4) + 3, 4)]

        elif (new_chunk.ID == OBJECT_MATERIAL):
            # print 'elif (new_chunk.ID == OBJECT_MATERIAL):'
            material_name, read_str_len = read_string(file)
            new_chunk.bytes_read += read_str_len # remove 1 null character.

            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_faces_using_mat = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT

            
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * num_faces_using_mat)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * num_faces_using_mat

            contextMeshMaterials[material_name]= struct.unpack("<%dH" % (num_faces_using_mat), temp_data)

            #look up the material in all the materials

        elif (new_chunk.ID == OBJECT_UV):
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_uv = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2

            temp_data = file.read(STRUCT_SIZE_2FLOAT * num_uv)
            new_chunk.bytes_read += STRUCT_SIZE_2FLOAT * num_uv
            contextMeshUV = struct.unpack('<%df' % (num_uv * 2), temp_data)

        elif (new_chunk.ID == OBJECT_TRANS_MATRIX):
            # How do we know the matrix size? 54 == 4x4 48 == 4x3
            temp_data = file.read(STRUCT_SIZE_4x3MAT)
            data = list( struct.unpack('<ffffffffffff', temp_data)  )
            new_chunk.bytes_read += STRUCT_SIZE_4x3MAT

            contextMatrix_rot = mathutils.Matrix((data[:3] + [0], \
                                                  data[3:6] + [0], \
                                                  data[6:9] + [0], \
                                                  data[9:] + [1], \
                                                  ))

        elif  (new_chunk.ID == MAT_MAP_FILEPATH):
            texture_name, read_str_len = read_string(file)
            try:
                TEXTURE_DICT[contextMaterial.name]
            except:
                #img = TEXTURE_DICT[contextMaterial.name]= BPyImage.comprehensiveImageLoad(texture_name, FILEPATH)
                img = TEXTURE_DICT[contextMaterial.name] = load_image(texture_name, dirname)
# 				img = TEXTURE_DICT[contextMaterial.name]= BPyImage.comprehensiveImageLoad(texture_name, FILEPATH, PLACE_HOLDER=False, RECURSIVE=IMAGE_SEARCH)

            new_chunk.bytes_read += read_str_len #plus one for the null character that gets removed
        elif new_chunk.ID == EDITKEYFRAME:
            pass

        elif new_chunk.ID == ED_KEY_OBJECT_NODE: #another object is being processed
            child = None

        elif new_chunk.ID == EK_OB_NODE_HEADER:
            object_name, read_str_len = read_string(file)
            new_chunk.bytes_read += read_str_len
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
            new_chunk.bytes_read += 4			
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            hierarchy = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2

            child = object_dictionary.get(object_name)

            if child is None:
                child = bpy.data.objects.new(object_name, None) # create an empty object
                SCN.objects.link(child)			

            object_list.append(child)
            object_parent.append(hierarchy)
            pivot_list.append(mathutils.Vector((0.0, 0.0, 0.0)))

        elif new_chunk.ID == EK_OB_INSTANCE_NAME:
            object_name, read_str_len = read_string(file)
            child.name = object_name
            object_dictionary[object_name] = child
            new_chunk.bytes_read += read_str_len
            # print("new instance object:", object_name)

        elif new_chunk.ID == EK_OB_PIVOT: # translation
                temp_data = file.read(STRUCT_SIZE_3FLOAT)
                pivot = struct.unpack('<3f', temp_data)
                new_chunk.bytes_read += STRUCT_SIZE_3FLOAT
                pivot_list[len(pivot_list)-1] = mathutils.Vector(pivot)

        elif new_chunk.ID == EK_OB_POSITION_TRACK: # translation
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 5
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 5)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            nkeys = struct.unpack('<H', temp_data)[0]
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
            for i in range(nkeys):
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
                nframe = struct.unpack('<H', temp_data)[0]
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
                temp_data = file.read(STRUCT_SIZE_3FLOAT)
                loc = struct.unpack('<3f', temp_data)
                new_chunk.bytes_read += STRUCT_SIZE_3FLOAT
                if nframe == 0:
                    child.location = loc

        elif new_chunk.ID == EK_OB_ROTATION_TRACK: # rotation
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 5
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 5)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            nkeys = struct.unpack('<H', temp_data)[0]
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
            for i in range(nkeys):
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
                nframe = struct.unpack('<H', temp_data)[0]
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
                temp_data = file.read(STRUCT_SIZE_4FLOAT)
                rad,axis_x,axis_y,axis_z = struct.unpack('<4f', temp_data)
                new_chunk.bytes_read += STRUCT_SIZE_4FLOAT
                if nframe == 0:
                    child.rotation_euler = mathutils.Quaternion((axis_x, axis_y, axis_z), -rad).to_euler()   # why negative?

        elif new_chunk.ID == EK_OB_SCALE_TRACK: # translation
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 5
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 5)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            nkeys = struct.unpack('<H', temp_data)[0]
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
            for i in range(nkeys):
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
                nframe = struct.unpack('<H', temp_data)[0]
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
                temp_data = file.read(STRUCT_SIZE_3FLOAT)
                sca = struct.unpack('<3f', temp_data)
                new_chunk.bytes_read += STRUCT_SIZE_3FLOAT
                if nframe == 0:
                    child.scale = sca

        else: #(new_chunk.ID!=VERSION or new_chunk.ID!=OBJECTINFO or new_chunk.ID!=OBJECT or new_chunk.ID!=MATERIAL):
            # print 'skipping to end of this chunk'
            #print("unknown chunk: "+hex(new_chunk.ID))
            buffer_size = new_chunk.length - new_chunk.bytes_read
            binary_format='%ic' % buffer_size
            temp_data = file.read(struct.calcsize(binary_format))
            new_chunk.bytes_read += buffer_size


        #update the previous chunk bytes read
        # print 'previous_chunk.bytes_read += new_chunk.bytes_read'
        # print previous_chunk.bytes_read, new_chunk.bytes_read
        previous_chunk.bytes_read += new_chunk.bytes_read
        ## print 'Bytes left in this chunk: ', previous_chunk.length - previous_chunk.bytes_read

    # FINISHED LOOP
    # There will be a number of objects still not added
    if CreateBlenderObject:
        putContextMesh(contextMesh_vertls, contextMesh_facels, contextMeshMaterials)


    # Assign parents to objects    
    for ind, ob in enumerate(object_list):
        parent = object_parent[ind]
        if parent == ROOT_OBJECT:
            ob.parent = None
        else:
            ob.parent = object_list[parent]
            # pivot_list[ind] += pivot_list[parent]  # XXX, not sure this is correct, should parent space matrix be applied before combining?
    # fix pivots
    for ind, ob in enumerate(object_list):
        if ob.type == 'MESH': 
            pivot = pivot_list[ind]
            pivot_matrix = object_matrix.get(ob, mathutils.Matrix())  # unlikely to fail
            pivot_matrix = mathutils.Matrix.Translation(-pivot * pivot_matrix.to_3x3())
            ob.data.transform(pivot_matrix)
def add_textures(images,mappings,current_filepath):
  for (index,image) in images:

    if b'filename' in image:
      texture = bpy.data.textures.get(image[b'name'])
      if texture == None:
        texture = bpy.data.textures.new(name=image[b'name'], type='IMAGE')
      filenpath = image[b'filename']
      (dirname,filename) = os.path.split(filenpath)
      print ("filename: ",filename," dirname: ",dirname)
      if os.path.isfile(filenpath):
        texture.image = load_image(filename,dirname)
      else:
        (current_dir,cfilename) = os.path.split(current_filepath)
        if os.path.isfile(current_dir + filename):
          texture.image = load_image(current_dir,filename)
        else: continue

      has_data = texture.image.has_data
      mapkeys = mappings.keys()
      for mapkey in mapkeys:
        print ("mat name: ",mapkey)
        mat = bpy.data.materials.get(str(mapkey,encoding="utf8"))
        if mat == None: continue
        mapping = mappings[mapkey]
        for i in range(len(mapping)):
          (channel,tex_index)=mapping[i]
          if tex_index == index:
            #print ("channel:",channel)
            if channel == b'diffuse':
              if has_data and image.depth == 32:
                # Image has alpha
                mtex = mat.texture_slots.add()
                mtex.texture = texture
                mtex.texture_coords = 'UV'
                mtex.use_map_color_diffuse = True
                mtex.use_map_alpha = True

                texture.use_mipmap = True
                texture.use_interpolation = True
                texture.use_alpha = True
                mat.use_transparency = True
                mat.alpha = 0.0
              else:
                #print("adding non alpha texture")
                mtex = mat.texture_slots.add()
                mtex.texture = texture
                mtex.texture_coords = 'UV'
                mtex.use_map_color_diffuse = True
            elif channel == b'gloss':
              mtex = mat.texture_slots.add()
              mtex.texture = texture
              mtex.texture_coords = 'UV'
              mtex.use_map_specular = True
            elif channel == b'bump':
              mtex = mat.texture_slots.add()
              mtex.texture = texture
              mtex.texture_coords = 'UV'
              mtex.use_map_normal = True
            elif channel == b'normal':
              mtex = mat.texture_slots.add()
              mtex.texture = texture
              mtex.texture_coords = 'UV'
              mtex.use_map_normal = True
Example #10
0
def loadMQO(config):
	print("FilePath:" + config.path)
	
	#Reading
	model = ModelMesh.load(config)
	
	#Scene
	scene = config.context.scene
	
	for obj in scene.objects:
		obj.select = False
	
	transformMatrix = Matrix()
	
	#Scaling
	transformMatrix *= Matrix.Scale(config.scale, 4, Vector((1, 0, 0)))
	transformMatrix *= Matrix.Scale(config.scale, 4, Vector((0, 1, 0)))
	transformMatrix *= Matrix.Scale(config.scale, 4, Vector((0, 0, 1)))
	
	#Change AxisY
	if(config.axis == 1):
		transformMatrix *= Matrix.Rotation(radians(-90), 4, "X")
		
	#Change AxisZ
	if(config.axis == 2):
		transformMatrix *= Matrix.Rotation(radians(90), 4, "X")
	
	#Material
	materials = []
	
	for material in model.materials:
		#Material
		mat = bpy.data.materials.new(material.name)
		mat.diffuse_color = material.color.toArray()[0:3]
		mat.diffuse_intensity = material.diffuse
		mat.alpha = material.color.a
		mat.emit = material.emissive
		mat.specular_color = [material.specular, material.specular, material.specular]
		mat.specular_intensity = material.power
		mat.mirror_color = [material.ambient, material.ambient, material.ambient]
		
		#Texture
		img = None
		if(len(material.texture) != 0):
			pathName = material.texture.replace("\\", "/")
			
			if(not os.path.exists(pathName)):
				dirName = os.path.dirname(config.path.replace("\\", "/"))
				pathName = dirName + "/" + pathName
				
			if(os.path.exists(pathName) == True):
				tex = bpy.data.textures.new("Tex_" + mat.name, type="IMAGE")
				tex.image = img = load_image(pathName, os.path.dirname(config.path))
				mtex = mat.texture_slots.add()
				mtex.texture = tex
				mtex.texture_coords = 'UV'
				mtex.use_map_color_diffuse = True
				
				print ("TextureName:" + pathName)
				
			else:
				print("ERROR: Imagefile Loading Faild.")
		
		materials.append([mat, img])
	
	#Mesh
	tree = []
	objects = []
	
	for objIndex, vertices in enumerate(model.vertices):
		objInfo = model.objects[objIndex]
		
		useMtrl = model.useMtrl[objIndex]
		mtrlIndex = model.mtrlIndex[objIndex]
		faces = model.faces[objIndex]
		texcoord = model.texcoords[objIndex]
		
		#Mesh
		me = bpy.data.meshes.new(objInfo.name)
		obj = bpy.data.objects.new(me.name, me)
		objects.append(obj)
		scene.objects.link(obj)
		
		#Tree
		if(len(tree) > objInfo.depth):
			tree[objInfo.depth] = [objInfo, obj]
		else:
			tree.append([objInfo, obj])
		
		if(objInfo.depth > 0):
			tree[objInfo.depth - 1][0].children.append([objInfo, obj])
			objInfo.parent = tree[objInfo.depth - 1][0]
		
		#Use Material
		mtrlMap = {}
		
		for i, mtrlID in enumerate(useMtrl):
			me.materials.append(materials[mtrlID][0])
			mtrlMap[mtrlID] = i
		
		me.vertices.add(len(vertices))
		me.faces.add(len(faces))
		
		for vertexIndex, pos in enumerate(vertices):
			me.vertices[vertexIndex].co = pos * transformMatrix
			
		for faceIndex, face in enumerate(faces):
			for index, value in enumerate(face):
				me.faces[faceIndex].vertices_raw[index] = value
				
		#Texcoord
		me.uv_textures.new()
		uv_faces = me.uv_textures.active.data[:]
		
		for i in range(len(uv_faces)):
			me.faces[i].material_index = mtrlMap[mtrlIndex[i]]
			img = materials[mtrlIndex[i]][1]
			
			if(img):
				uv = uv_faces[i]
				uv.use_image = True
				uv.image = img
				
				uv.uv1 = [texcoord[i][0].x, 1 - texcoord[i][0].y]
				uv.uv2 = [texcoord[i][1].x, 1 - texcoord[i][1].y]
				uv.uv3 = [texcoord[i][2].x, 1 - texcoord[i][2].y]
				
				if(len(texcoord[i]) > 3):
					uv.uv4 = [texcoord[i][3][0], 1 - texcoord[i][3][1]]
	
	#Remove Doubles & Smooth & Create Edge
	for obj in objects:
		obj.select = True
		scene.objects.active = obj
		bpy.ops.object.mode_set(mode='EDIT')
		
		if config.remove_doubles:
			bpy.ops.mesh.remove_doubles()
			
		if config.smooth:
			bpy.ops.mesh.faces_shade_smooth()
			
		bpy.ops.object.mode_set(mode='OBJECT')
		
	#Create Group
	name, ext = os.path.splitext(os.path.basename(config.path))
	group = bpy.data.objects.new(name + ext.replace(".", "_"), None)
	
	scene.objects.link(group)
	group.select = True
	scene.objects.active = group
	bpy.ops.group.create(name=group.name)
	
	#Tree
	for i, obj in enumerate(model.objects):
		for child in obj.children:
			child[1].parent = objects[i]
		
		if(obj.parent == None):
			objects[i].parent = group
			
		objects[i].hide = (obj.visible == 0)
		objects[i].hide_select = (obj.lock == 1)
		
	scene.update()
Example #11
0
def loadMQO(config):
	print("FilePath:" + config.path)
	
	#Reading
	model = ModelMesh.load(config)
	
	#Scene
	scene = config.context.scene
	
	for obj in scene.objects:
		obj.select = False
	
	transformMatrix = Matrix()
	
	#Scaling
	transformMatrix *= Matrix.Scale(config.scale, 4, Vector((1, 0, 0)))
	transformMatrix *= Matrix.Scale(config.scale, 4, Vector((0, 1, 0)))
	transformMatrix *= Matrix.Scale(config.scale, 4, Vector((0, 0, 1)))
	
	#Change AxisY
	if(config.axis == 1):
		transformMatrix *= Matrix.Rotation(radians(-90), 4, "X")
		
	#Change AxisZ
	if(config.axis == 2):
		transformMatrix *= Matrix.Rotation(radians(90), 4, "X")
	
	#Material
	materials = []
	
	for material in model.materials:
		#Material
		mat = bpy.data.materials.new(material.name)
		mat.diffuse_color = material.color.toArray()[0:3]
		mat.diffuse_intensity = material.diffuse
		mat.alpha = material.color.a
		mat.emit = material.emissive
		mat.specular_color = [material.specular, material.specular, material.specular]
		mat.specular_intensity = material.power
		mat.mirror_color = [material.ambient, material.ambient, material.ambient]
		
		#Texture
		img = None
		if(len(material.texture) != 0):
			pathName = material.texture.replace("\\", "/")
			
			if(not os.path.exists(pathName)):
				dirName = os.path.dirname(config.path.replace("\\", "/"))
				pathName = dirName + "/" + pathName
				
			if(os.path.exists(pathName) == True):
				tex = bpy.data.textures.new("Tex_" + mat.name, type="IMAGE")
				tex.image = img = load_image(pathName, os.path.dirname(config.path))
				mtex = mat.texture_slots.add()
				mtex.texture = tex
				mtex.texture_coords = 'UV'
				mtex.use_map_color_diffuse = True
				
				print ("TextureName:" + pathName)
				
			else:
				print("ERROR: Imagefile Loading Faild.")
		
		materials.append([mat, img])
	
	#Mesh
	tree = []
	objects = []
	
	for objIndex, vertices in enumerate(model.vertices):
		objInfo = model.objects[objIndex]
		
		useMtrl = model.useMtrl[objIndex]
		mtrlIndex = model.mtrlIndex[objIndex]
		faces = model.faces[objIndex]
		texcoord = model.texcoords[objIndex]
		
		#Mesh
		me = bpy.data.meshes.new(objInfo.name)
		obj = bpy.data.objects.new(me.name, me)
		objects.append(obj)
		scene.objects.link(obj)
		
		#Tree
		if(len(tree) > objInfo.depth):
			tree[objInfo.depth] = [objInfo, obj]
		else:
			tree.append([objInfo, obj])
		
		if(objInfo.depth > 0):
			tree[objInfo.depth - 1][0].children.append([objInfo, obj])
			objInfo.parent = tree[objInfo.depth - 1][0]
		
		#Use Material
		mtrlMap = {}
		
		for i, mtrlID in enumerate(useMtrl):
			me.materials.append(materials[mtrlID][0])
			mtrlMap[mtrlID] = i
		
		me.vertices.add(len(vertices))
		me.faces.add(len(faces))
		
		for vertexIndex, pos in enumerate(vertices):
			me.vertices[vertexIndex].co = pos * transformMatrix
			
		for faceIndex, face in enumerate(faces):
			for index, value in enumerate(face):
				me.faces[faceIndex].vertices_raw[index] = value
				
		#Texcoord
		me.uv_textures.new()
		uv_faces = me.uv_textures.active.data[:]
		
		for i in range(len(uv_faces)):
			me.faces[i].material_index = mtrlMap[mtrlIndex[i]]
			img = materials[mtrlIndex[i]][1]
			
			if(img):
				uv = uv_faces[i]
				uv.use_image = True
				uv.image = img
				
				uv.uv1 = [texcoord[i][0].x, 1 - texcoord[i][0].y]
				uv.uv2 = [texcoord[i][1].x, 1 - texcoord[i][1].y]
				uv.uv3 = [texcoord[i][2].x, 1 - texcoord[i][2].y]
				
				if(len(texcoord[i]) > 3):
					uv.uv4 = [texcoord[i][3][0], 1 - texcoord[i][3][1]]
	
	#Remove Doubles & Smooth & Create Edge
	for obj in objects:
		obj.select = True
		scene.objects.active = obj
		bpy.ops.object.mode_set(mode='EDIT')
		
		if config.remove_doubles:
			bpy.ops.mesh.remove_doubles()
			
		if config.smooth:
			bpy.ops.mesh.faces_shade_smooth()
			
		bpy.ops.object.mode_set(mode='OBJECT')
		
	#Create Group
	name, ext = os.path.splitext(os.path.basename(config.path))
	group = bpy.data.objects.new(name + ext.replace(".", "_"), None)
	
	scene.objects.link(group)
	group.select = True
	scene.objects.active = group
	bpy.ops.group.create(name=group.name)
	
	#Tree
	for i, obj in enumerate(model.objects):
		for child in obj.children:
			child[1].parent = objects[i]
		
		if(obj.parent == None):
			objects[i].parent = group
			
		objects[i].hide = (obj.visible == 0)
		objects[i].hide_select = (obj.lock == 1)
		
	scene.update()
Example #12
0
def read(file, context, op):
    """Imports as an m3 file"""
    global verFlag
    h = hdr(file)
    if h.magic[::-1] == b'MD34':
        print('m3_import: !WARNING! MD34 files not full tested...')
        verFlag = True
    elif h.magic[::-1] == b'MD33':
        verFlag = False
    else:
        raise Exception('m3_import: !ERROR! Not a valid or supported m3 file')
    file.seek(h.ofsTag)  # Jump to the Tag table
    print('m3_import: !INFO! Reading TagTable...')
    tagTable = [Tag(file) for _ in range(h.nTag)]
    file.seek(tagTable[h.MODLref.refid].ofs)
    m = MODL(file, tagTable[h.MODLref.refid].version)
    if not m.flags & 0x20000:
        raise Exception('m3_import: !ERROR! Model doesn\'t have any vertices')
    print('m3_import: !INFO! Reading Vertices...')
    vert_flags = m.flags & 0x1E0000  # Mask out the vertex version
    file.seek(tagTable[m.views.refid].ofs)
    d = div(file)
    file.seek(tagTable[m.vert.refid].ofs)
    verts = [vertex(file, vert_flags) \
       for _ in range(tagTable[m.vert.refid].nTag // vertex.size(vert_flags))]
    file.seek(tagTable[d.faces.refid].ofs)
    print('m3_import: !INFO! Reading Faces...')
    rawfaceTable = struct.unpack('H' * (tagTable[d.faces.refid].nTag), \
                    file.read(tagTable[d.faces.refid].nTag * 2))
    faceTable = []
    for i in range(1, len(rawfaceTable) + 1):
        faceTable.append(rawfaceTable[i - 1])
        if i % 3 == 0:  # Add a zero for the fourth index to the face.
            faceTable.append(0)
    print("m3_import: !INFO! Read %d vertices and %d faces" \
            % (len(verts), len(faceTable)))
    print('m3_import: !INFO! Adding Geometry...')
    mesh = bpy.data.meshes.new(os.path.basename(op.properties.filepath))
    mobj = bpy.data.objects.new(os.path.basename(op.properties.filepath), mesh)
    context.scene.objects.link(mobj)
    v, n = [], []
    for vert in verts:  # "Flatten" the vertex array...
        v.extend(vert.pos.v)
        n.extend(vert.normal)
    mesh.vertices.add(len(verts))
    mesh.faces.add(len(rawfaceTable) // 3)
    mesh.vertices.foreach_set('co', v)
    mesh.vertices.foreach_set('normal', n)
    mesh.faces.foreach_set('vertices_raw', faceTable)
    uvtex = mesh.uv_textures.new()
    for i, face in enumerate(mesh.faces):
        uf = uvtex.data[i]
        uf.uv1 = verts[faceTable[i * 4 + 0]].uv
        uf.uv2 = verts[faceTable[i * 4 + 1]].uv
        uf.uv3 = verts[faceTable[i * 4 + 2]].uv
        uf.uv4 = (0, 0)
    print('m3_import: !INFO! Importing materials...')
    material = bpy.data.materials.new('Mat00')
    mesh.materials.append(material)
    file.seek(tagTable[m.materials.refid].ofs)
    mm = mat(file)
    tex_map = [('use_map_color_diffuse', 0), ('use_map_specular', 2),\
                ('use_map_normal', 9)]
    for map, i in tex_map:
        file.seek(tagTable[mm.layers[i].refid].ofs)
        nref = layr(file).name
        file.seek(tagTable[nref.refid].ofs)
        name = bytes.decode(file.read(nref.entries - 1))
        name = os.path.basename(str(name))
        tex = bpy.data.textures.new(name=name, type='IMAGE')
        tex.image = load_image(name, os.path.dirname(op.filepath))
        if tex.image != None:
            print("m3_import: !INFO! Loaded %s" % (name))
        else:
            print("m3_import: !WARNING! Cannot find texture \"%s\"" % (name))
        mtex = material.texture_slots.add()
        mtex.texture = tex
        mtex.texture_coords = 'UV'
        if i == 9:
            mtex.normal_factor = 0.1  # Just a guess, seems to look nice
        mtex.use_map_color_diffuse = (i == 0)
        setattr(mtex, map, True)
Example #13
0
def read(file, context, op):
    """Imports as an m3 file"""
    global verFlag
    h = hdr(file)
    if h.magic[::-1] == b'MD34':
        print('m3_import: !WARNING! MD34 files not full tested...')
        verFlag = True
    elif h.magic[::-1] == b'MD33':
        verFlag = False
    else:
        raise Exception('m3_import: !ERROR! Not a valid or supported m3 file')
    file.seek(h.ofsTag)    # Jump to the Tag table
    print('m3_import: !INFO! Reading TagTable...')
    tagTable = [Tag(file) for _ in range(h.nTag)]
    file.seek(tagTable[h.MODLref.refid].ofs)
    m = MODL(file, tagTable[h.MODLref.refid].version)
    if not m.flags & 0x20000:
        raise Exception('m3_import: !ERROR! Model doesn\'t have any vertices')
    print('m3_import: !INFO! Reading Vertices...')
    vert_flags = m.flags & 0x1E0000        # Mask out the vertex version
    file.seek(tagTable[m.views.refid].ofs)
    d = div(file)
    file.seek(tagTable[m.vert.refid].ofs)
    verts = [vertex(file, vert_flags) \
       for _ in range(tagTable[m.vert.refid].nTag // vertex.size(vert_flags))]
    file.seek(tagTable[d.faces.refid].ofs)
    print('m3_import: !INFO! Reading Faces...')
    rawfaceTable = struct.unpack('H' * (tagTable[d.faces.refid].nTag), \
                    file.read(tagTable[d.faces.refid].nTag * 2))
    faceTable = []
    for i in range(1, len(rawfaceTable) + 1):
        faceTable.append(rawfaceTable[i - 1])
        if i % 3 == 0:    # Add a zero for the fourth index to the face.
            faceTable.append(0)
    print("m3_import: !INFO! Read %d vertices and %d faces" \
            % (len(verts), len(faceTable)))
    print('m3_import: !INFO! Adding Geometry...')
    mesh = bpy.data.meshes.new(os.path.basename(op.properties.filepath))
    mobj = bpy.data.objects.new(os.path.basename(op.properties.filepath), mesh)
    context.scene.objects.link(mobj)
    v, n = [], []
    for vert in verts:        # "Flatten" the vertex array...
        v.extend(vert.pos.v)
        n.extend(vert.normal)
    mesh.vertices.add(len(verts))
    mesh.faces.add(len(rawfaceTable) // 3)
    mesh.vertices.foreach_set('co', v)
    mesh.vertices.foreach_set('normal', n)
    mesh.faces.foreach_set('vertices_raw', faceTable)
    uvtex = mesh.uv_textures.new()
    for i, face in enumerate(mesh.faces):
        uf = uvtex.data[i]
        uf.uv1 = verts[faceTable[i * 4 + 0]].uv
        uf.uv2 = verts[faceTable[i * 4 + 1]].uv
        uf.uv3 = verts[faceTable[i * 4 + 2]].uv
        uf.uv4 = (0, 0)
    print('m3_import: !INFO! Importing materials...')
    material = bpy.data.materials.new('Mat00')
    mesh.materials.append(material)
    file.seek(tagTable[m.materials.refid].ofs)
    mm = mat(file)
    tex_map = [('use_map_color_diffuse', 0), ('use_map_specular', 2),\
                ('use_map_normal', 9)]
    for map, i in tex_map:
        file.seek(tagTable[mm.layers[i].refid].ofs)
        nref = layr(file).name
        file.seek(tagTable[nref.refid].ofs)
        name = bytes.decode(file.read(nref.entries - 1))
        name = os.path.basename(str(name))
        tex = bpy.data.textures.new(name=name, type='IMAGE')
        tex.image = load_image(name, os.path.dirname(op.filepath))
        if tex.image != None:
            print("m3_import: !INFO! Loaded %s" % (name))
        else:
            print("m3_import: !WARNING! Cannot find texture \"%s\"" % (name))
        mtex = material.texture_slots.add()
        mtex.texture = tex
        mtex.texture_coords = 'UV'
        if i == 9:
            mtex.normal_factor = 0.1    # Just a guess, seems to look nice
        mtex.use_map_color_diffuse = (i == 0)
        setattr(mtex, map, True)
Example #14
0
def add_textures(images, mappings, current_filepath):
    for (index, image) in images:

        if b'filename' in image:
            texture = bpy.data.textures.get(image[b'name'])
            if texture == None:
                texture = bpy.data.textures.new(name=image[b'name'],
                                                type='IMAGE')
            filenpath = image[b'filename']
            (dirname, filename) = os.path.split(filenpath)
            print("filename: ", filename, " dirname: ", dirname)
            if os.path.isfile(filenpath):
                texture.image = load_image(filename, dirname)
            else:
                (current_dir, cfilename) = os.path.split(current_filepath)
                if os.path.isfile(current_dir + filename):
                    texture.image = load_image(current_dir, filename)
                else:
                    continue

            has_data = texture.image.has_data
            mapkeys = mappings.keys()
            for mapkey in mapkeys:
                print("mat name: ", mapkey)
                mat = bpy.data.materials.get(str(mapkey, encoding="utf8"))
                if mat == None: continue
                mapping = mappings[mapkey]
                for i in range(len(mapping)):
                    (channel, tex_index) = mapping[i]
                    if tex_index == index:
                        #print ("channel:",channel)
                        if channel == b'diffuse':
                            if has_data and image.depth == 32:
                                # Image has alpha
                                mtex = mat.texture_slots.add()
                                mtex.texture = texture
                                mtex.texture_coords = 'UV'
                                mtex.use_map_color_diffuse = True
                                mtex.use_map_alpha = True

                                texture.use_mipmap = True
                                texture.use_interpolation = True
                                texture.use_alpha = True
                                mat.use_transparency = True
                                mat.alpha = 0.0
                            else:
                                #print("adding non alpha texture")
                                mtex = mat.texture_slots.add()
                                mtex.texture = texture
                                mtex.texture_coords = 'UV'
                                mtex.use_map_color_diffuse = True
                        elif channel == b'gloss':
                            mtex = mat.texture_slots.add()
                            mtex.texture = texture
                            mtex.texture_coords = 'UV'
                            mtex.use_map_specular = True
                        elif channel == b'bump':
                            mtex = mat.texture_slots.add()
                            mtex.texture = texture
                            mtex.texture_coords = 'UV'
                            mtex.use_map_normal = True
                        elif channel == b'normal':
                            mtex = mat.texture_slots.add()
                            mtex.texture = texture
                            mtex.texture_coords = 'UV'
                            mtex.use_map_normal = True
Example #15
0
def process_next_chunk(file, previous_chunk, importedObjects, IMAGE_SEARCH):
    #print previous_chunk.bytes_read, 'BYTES READ'
    contextObName = None
    contextLamp = [None, None]  # object, Data
    contextMaterial = None
    contextMatrix_rot = None  # Blender.mathutils.Matrix(); contextMatrix.identity()
    #contextMatrix_tx = None # Blender.mathutils.Matrix(); contextMatrix.identity()
    contextMesh_vertls = None  # flat array: (verts * 3)
    contextMesh_facels = None
    contextMeshMaterials = {}  # matname:[face_idxs]
    contextMeshUV = None  # flat array (verts * 2)

    TEXTURE_DICT = {}
    MATDICT = {}
    # 	TEXMODE = Mesh.FaceModes['TEX']

    # Localspace variable names, faster.
    STRUCT_SIZE_1CHAR = struct.calcsize('c')
    STRUCT_SIZE_2FLOAT = struct.calcsize('2f')
    STRUCT_SIZE_3FLOAT = struct.calcsize('3f')
    STRUCT_SIZE_4FLOAT = struct.calcsize('4f')
    STRUCT_SIZE_UNSIGNED_SHORT = struct.calcsize('H')
    STRUCT_SIZE_4UNSIGNED_SHORT = struct.calcsize('4H')
    STRUCT_SIZE_4x3MAT = struct.calcsize('ffffffffffff')
    _STRUCT_SIZE_4x3MAT = struct.calcsize('fffffffffffff')
    # STRUCT_SIZE_4x3MAT = calcsize('ffffffffffff')
    # print STRUCT_SIZE_4x3MAT, ' STRUCT_SIZE_4x3MAT'
    # only init once
    object_list = []  # for hierarchy
    object_parent = []  # index of parent in hierarchy, 0xFFFF = no parent
    pivot_list = []  # pivots with hierarchy handling

    def putContextMesh(myContextMesh_vertls, myContextMesh_facels,
                       myContextMeshMaterials):
        bmesh = bpy.data.meshes.new(contextObName)

        if myContextMesh_facels is None:
            myContextMesh_facels = []

        if myContextMesh_vertls:

            bmesh.vertices.add(len(myContextMesh_vertls) // 3)
            bmesh.faces.add(len(myContextMesh_facels))
            bmesh.vertices.foreach_set("co", myContextMesh_vertls)

            eekadoodle_faces = []
            for v1, v2, v3 in myContextMesh_facels:
                eekadoodle_faces.extend([v3, v1, v2, 0] if v3 ==
                                        0 else [v1, v2, v3, 0])
            bmesh.faces.foreach_set("vertices_raw", eekadoodle_faces)

            if bmesh.faces and contextMeshUV:
                bmesh.uv_textures.new()
                uv_faces = bmesh.uv_textures.active.data[:]
            else:
                uv_faces = None

            for mat_idx, (matName,
                          faces) in enumerate(myContextMeshMaterials.items()):
                if matName is None:
                    bmat = None
                else:
                    bmat = MATDICT[matName][1]
                    img = TEXTURE_DICT.get(bmat.name)

                bmesh.materials.append(bmat)  # can be None

                if uv_faces and img:
                    for fidx in faces:
                        bmesh.faces[fidx].material_index = mat_idx
                        uf = uv_faces[fidx]
                        uf.image = img
                        uf.use_image = True
                else:
                    for fidx in faces:
                        bmesh.faces[fidx].material_index = mat_idx

            if uv_faces:
                for fidx, uf in enumerate(uv_faces):
                    face = myContextMesh_facels[fidx]
                    v1, v2, v3 = face

                    # eekadoodle
                    if v3 == 0:
                        v1, v2, v3 = v3, v1, v2

                    uf.uv1 = contextMeshUV[v1 * 2:(v1 * 2) + 2]
                    uf.uv2 = contextMeshUV[v2 * 2:(v2 * 2) + 2]
                    uf.uv3 = contextMeshUV[v3 * 2:(v3 * 2) + 2]
                    # always a tri

        bmesh.validate()
        bmesh.update()

        ob = bpy.data.objects.new(contextObName, bmesh)
        object_dictionary[contextObName] = ob
        SCN.objects.link(ob)
        '''
        if contextMatrix_tx:
            ob.setMatrix(contextMatrix_tx)
        '''

        if contextMatrix_rot:
            ob.matrix_local = contextMatrix_rot
            object_matrix[ob] = contextMatrix_rot.copy()

        importedObjects.append(ob)

    #a spare chunk
    new_chunk = chunk()
    temp_chunk = chunk()

    CreateBlenderObject = False

    def read_float_color(temp_chunk):
        temp_data = file.read(struct.calcsize('3f'))
        temp_chunk.bytes_read += 12
        return [float(col) for col in struct.unpack('<3f', temp_data)]

    def read_byte_color(temp_chunk):
        temp_data = file.read(struct.calcsize('3B'))
        temp_chunk.bytes_read += 3
        return [float(col) / 255 for col in struct.unpack('<3B', temp_data)
                ]  # data [0,1,2] == rgb

    def read_texture(new_chunk, temp_chunk, name, mapto):
        new_texture = bpy.data.textures.new(name, type='IMAGE')

        img = None
        while (new_chunk.bytes_read < new_chunk.length):
            #print 'MAT_TEXTURE_MAP..while', new_chunk.bytes_read, new_chunk.length
            read_chunk(file, temp_chunk)

            if (temp_chunk.ID == MAT_MAP_FILEPATH):
                texture_name, read_str_len = read_string(file)
                img = TEXTURE_DICT[contextMaterial.name] = load_image(
                    texture_name, dirname)
                new_chunk.bytes_read += read_str_len  #plus one for the null character that gets removed

            else:
                skip_to_end(file, temp_chunk)

            new_chunk.bytes_read += temp_chunk.bytes_read

        # add the map to the material in the right channel
        if img:
            add_texture_to_material(img, new_texture, contextMaterial, mapto)

    dirname = os.path.dirname(file.name)

    #loop through all the data for this chunk (previous chunk) and see what it is
    while (previous_chunk.bytes_read < previous_chunk.length):
        #print '\t', previous_chunk.bytes_read, 'keep going'
        #read the next chunk
        #print 'reading a chunk'
        read_chunk(file, new_chunk)

        #is it a Version chunk?
        if (new_chunk.ID == VERSION):
            #print 'if (new_chunk.ID == VERSION):'
            #print 'found a VERSION chunk'
            #read in the version of the file
            #it's an unsigned short (H)
            temp_data = file.read(struct.calcsize('I'))
            version = struct.unpack('<I', temp_data)[0]
            new_chunk.bytes_read += 4  #read the 4 bytes for the version number
            #this loader works with version 3 and below, but may not with 4 and above
            if (version > 3):
                print(
                    '\tNon-Fatal Error:  Version greater than 3, may not load correctly: ',
                    version)

        #is it an object info chunk?
        elif (new_chunk.ID == OBJECTINFO):
            #print 'elif (new_chunk.ID == OBJECTINFO):'
            # print 'found an OBJECTINFO chunk'
            process_next_chunk(file, new_chunk, importedObjects, IMAGE_SEARCH)

            #keep track of how much we read in the main chunk
            new_chunk.bytes_read += temp_chunk.bytes_read

        #is it an object chunk?
        elif (new_chunk.ID == OBJECT):

            if CreateBlenderObject:
                putContextMesh(contextMesh_vertls, contextMesh_facels,
                               contextMeshMaterials)
                contextMesh_vertls = []
                contextMesh_facels = []

                ## preparando para receber o proximo objeto
                contextMeshMaterials = {}  # matname:[face_idxs]
                contextMeshUV = None
                #contextMesh.vertexUV = 1 # Make sticky coords.
                # Reset matrix
                contextMatrix_rot = None
                #contextMatrix_tx = None

            CreateBlenderObject = True
            contextObName, read_str_len = read_string(file)
            new_chunk.bytes_read += read_str_len

        #is it a material chunk?
        elif (new_chunk.ID == MATERIAL):

            # 			print("read material")

            #print 'elif (new_chunk.ID == MATERIAL):'
            contextMaterial = bpy.data.materials.new('Material')

        elif (new_chunk.ID == MAT_NAME):
            #print 'elif (new_chunk.ID == MAT_NAME):'
            material_name, read_str_len = read_string(file)

            # 			print("material name", material_name)

            #plus one for the null character that ended the string
            new_chunk.bytes_read += read_str_len

            contextMaterial.name = material_name.rstrip(
            )  # remove trailing  whitespace
            MATDICT[material_name] = (contextMaterial.name, contextMaterial)

        elif (new_chunk.ID == MAT_AMBIENT):
            #print 'elif (new_chunk.ID == MAT_AMBIENT):'
            read_chunk(file, temp_chunk)
            if (temp_chunk.ID == MAT_FLOAT_COLOR):
                contextMaterial.mirror_color = read_float_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3f'))
# 				temp_chunk.bytes_read += 12
# 				contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
            elif (temp_chunk.ID == MAT_24BIT_COLOR):
                contextMaterial.mirror_color = read_byte_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3B'))
# 				temp_chunk.bytes_read += 3
# 				contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
            else:
                skip_to_end(file, temp_chunk)
            new_chunk.bytes_read += temp_chunk.bytes_read

        elif (new_chunk.ID == MAT_DIFFUSE):
            #print 'elif (new_chunk.ID == MAT_DIFFUSE):'
            read_chunk(file, temp_chunk)
            if (temp_chunk.ID == MAT_FLOAT_COLOR):
                contextMaterial.diffuse_color = read_float_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3f'))
# 				temp_chunk.bytes_read += 12
# 				contextMaterial.rgbCol = [float(col) for col in struct.unpack('<3f', temp_data)]
            elif (temp_chunk.ID == MAT_24BIT_COLOR):
                contextMaterial.diffuse_color = read_byte_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3B'))
# 				temp_chunk.bytes_read += 3
# 				contextMaterial.rgbCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
            else:
                skip_to_end(file, temp_chunk)

# 			print("read material diffuse color", contextMaterial.diffuse_color)

            new_chunk.bytes_read += temp_chunk.bytes_read

        elif (new_chunk.ID == MAT_SPECULAR):
            #print 'elif (new_chunk.ID == MAT_SPECULAR):'
            read_chunk(file, temp_chunk)
            if (temp_chunk.ID == MAT_FLOAT_COLOR):
                contextMaterial.specular_color = read_float_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3f'))
# 				temp_chunk.bytes_read += 12
# 				contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
            elif (temp_chunk.ID == MAT_24BIT_COLOR):
                contextMaterial.specular_color = read_byte_color(temp_chunk)
# 				temp_data = file.read(struct.calcsize('3B'))
# 				temp_chunk.bytes_read += 3
# 				contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
            else:
                skip_to_end(file, temp_chunk)
            new_chunk.bytes_read += temp_chunk.bytes_read

        elif (new_chunk.ID == MAT_TEXTURE_MAP):
            read_texture(new_chunk, temp_chunk, "Diffuse", "COLOR")

        elif (new_chunk.ID == MAT_SPECULAR_MAP):
            read_texture(new_chunk, temp_chunk, "Specular", "SPECULARITY")

        elif (new_chunk.ID == MAT_OPACITY_MAP):
            read_texture(new_chunk, temp_chunk, "Opacity", "ALPHA")

        elif (new_chunk.ID == MAT_BUMP_MAP):
            read_texture(new_chunk, temp_chunk, "Bump", "NORMAL")

        elif (new_chunk.ID == MAT_TRANSPARENCY):
            #print 'elif (new_chunk.ID == MAT_TRANSPARENCY):'
            read_chunk(file, temp_chunk)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)

            temp_chunk.bytes_read += 2
            contextMaterial.alpha = 1 - (
                float(struct.unpack('<H', temp_data)[0]) / 100)
            new_chunk.bytes_read += temp_chunk.bytes_read

        elif (new_chunk.ID == OBJECT_LAMP):  # Basic lamp support.

            temp_data = file.read(STRUCT_SIZE_3FLOAT)

            x, y, z = struct.unpack('<3f', temp_data)
            new_chunk.bytes_read += STRUCT_SIZE_3FLOAT

            # no lamp in dict that would be confusing
            contextLamp[1] = bpy.data.lamps.new("Lamp", 'POINT')
            contextLamp[0] = ob = bpy.data.objects.new("Lamp", contextLamp[1])

            SCN.objects.link(ob)
            importedObjects.append(contextLamp[0])

            #print 'number of faces: ', num_faces
            #print x,y,z
            contextLamp[0].location = (x, y, z)
            # 			contextLamp[0].setLocation(x,y,z)

            # Reset matrix
            contextMatrix_rot = None
            #contextMatrix_tx = None
            #print contextLamp.name,

        elif (new_chunk.ID == OBJECT_MESH):
            # print 'Found an OBJECT_MESH chunk'
            pass
        elif (new_chunk.ID == OBJECT_VERTICES):
            '''
            Worldspace vertex locations
            '''
            # print 'elif (new_chunk.ID == OBJECT_VERTICES):'
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_verts = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2

            # print 'number of verts: ', num_verts
            contextMesh_vertls = struct.unpack(
                '<%df' % (num_verts * 3),
                file.read(STRUCT_SIZE_3FLOAT * num_verts))
            new_chunk.bytes_read += STRUCT_SIZE_3FLOAT * num_verts
            # dummyvert is not used atm!

            #print 'object verts: bytes read: ', new_chunk.bytes_read

        elif (new_chunk.ID == OBJECT_FACES):
            # print 'elif (new_chunk.ID == OBJECT_FACES):'
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_faces = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2
            #print 'number of faces: ', num_faces

            # print '\ngetting a face'
            temp_data = file.read(STRUCT_SIZE_4UNSIGNED_SHORT * num_faces)
            new_chunk.bytes_read += STRUCT_SIZE_4UNSIGNED_SHORT * num_faces  #4 short ints x 2 bytes each
            contextMesh_facels = struct.unpack('<%dH' % (num_faces * 4),
                                               temp_data)
            contextMesh_facels = [
                contextMesh_facels[i - 3:i]
                for i in range(3, (num_faces * 4) + 3, 4)
            ]

        elif (new_chunk.ID == OBJECT_MATERIAL):
            # print 'elif (new_chunk.ID == OBJECT_MATERIAL):'
            material_name, read_str_len = read_string(file)
            new_chunk.bytes_read += read_str_len  # remove 1 null character.

            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_faces_using_mat = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT

            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT *
                                  num_faces_using_mat)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * num_faces_using_mat

            contextMeshMaterials[material_name] = struct.unpack(
                "<%dH" % (num_faces_using_mat), temp_data)

            #look up the material in all the materials

        elif (new_chunk.ID == OBJECT_UV):
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            num_uv = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2

            temp_data = file.read(STRUCT_SIZE_2FLOAT * num_uv)
            new_chunk.bytes_read += STRUCT_SIZE_2FLOAT * num_uv
            contextMeshUV = struct.unpack('<%df' % (num_uv * 2), temp_data)

        elif (new_chunk.ID == OBJECT_TRANS_MATRIX):
            # How do we know the matrix size? 54 == 4x4 48 == 4x3
            temp_data = file.read(STRUCT_SIZE_4x3MAT)
            data = list(struct.unpack('<ffffffffffff', temp_data))
            new_chunk.bytes_read += STRUCT_SIZE_4x3MAT

            contextMatrix_rot = mathutils.Matrix((data[:3] + [0], \
                                                  data[3:6] + [0], \
                                                  data[6:9] + [0], \
                                                  data[9:] + [1], \
                                                  ))

        elif (new_chunk.ID == MAT_MAP_FILEPATH):
            texture_name, read_str_len = read_string(file)
            try:
                TEXTURE_DICT[contextMaterial.name]
            except:
                #img = TEXTURE_DICT[contextMaterial.name]= BPyImage.comprehensiveImageLoad(texture_name, FILEPATH)
                img = TEXTURE_DICT[contextMaterial.name] = load_image(
                    texture_name, dirname)


# 				img = TEXTURE_DICT[contextMaterial.name]= BPyImage.comprehensiveImageLoad(texture_name, FILEPATH, PLACE_HOLDER=False, RECURSIVE=IMAGE_SEARCH)

            new_chunk.bytes_read += read_str_len  #plus one for the null character that gets removed
        elif new_chunk.ID == EDITKEYFRAME:
            pass

        elif new_chunk.ID == ED_KEY_OBJECT_NODE:  #another object is being processed
            child = None

        elif new_chunk.ID == EK_OB_NODE_HEADER:
            object_name, read_str_len = read_string(file)
            new_chunk.bytes_read += read_str_len
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
            new_chunk.bytes_read += 4
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            hierarchy = struct.unpack('<H', temp_data)[0]
            new_chunk.bytes_read += 2

            child = object_dictionary.get(object_name)

            if child is None:
                child = bpy.data.objects.new(object_name,
                                             None)  # create an empty object
                SCN.objects.link(child)

            object_list.append(child)
            object_parent.append(hierarchy)
            pivot_list.append(mathutils.Vector((0.0, 0.0, 0.0)))

        elif new_chunk.ID == EK_OB_INSTANCE_NAME:
            object_name, read_str_len = read_string(file)
            child.name = object_name
            object_dictionary[object_name] = child
            new_chunk.bytes_read += read_str_len
            # print("new instance object:", object_name)

        elif new_chunk.ID == EK_OB_PIVOT:  # translation
            temp_data = file.read(STRUCT_SIZE_3FLOAT)
            pivot = struct.unpack('<3f', temp_data)
            new_chunk.bytes_read += STRUCT_SIZE_3FLOAT
            pivot_list[len(pivot_list) - 1] = mathutils.Vector(pivot)

        elif new_chunk.ID == EK_OB_POSITION_TRACK:  # translation
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 5
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 5)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            nkeys = struct.unpack('<H', temp_data)[0]
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
            for i in range(nkeys):
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
                nframe = struct.unpack('<H', temp_data)[0]
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
                temp_data = file.read(STRUCT_SIZE_3FLOAT)
                loc = struct.unpack('<3f', temp_data)
                new_chunk.bytes_read += STRUCT_SIZE_3FLOAT
                if nframe == 0:
                    child.location = loc

        elif new_chunk.ID == EK_OB_ROTATION_TRACK:  # rotation
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 5
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 5)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            nkeys = struct.unpack('<H', temp_data)[0]
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
            for i in range(nkeys):
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
                nframe = struct.unpack('<H', temp_data)[0]
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
                temp_data = file.read(STRUCT_SIZE_4FLOAT)
                rad, axis_x, axis_y, axis_z = struct.unpack('<4f', temp_data)
                new_chunk.bytes_read += STRUCT_SIZE_4FLOAT
                if nframe == 0:
                    child.rotation_euler = mathutils.Quaternion(
                        (axis_x, axis_y, axis_z),
                        -rad).to_euler()  # why negative?

        elif new_chunk.ID == EK_OB_SCALE_TRACK:  # translation
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 5
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 5)
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            nkeys = struct.unpack('<H', temp_data)[0]
            temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
            new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
            for i in range(nkeys):
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT)
                nframe = struct.unpack('<H', temp_data)[0]
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
                temp_data = file.read(STRUCT_SIZE_UNSIGNED_SHORT * 2)
                new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT * 2
                temp_data = file.read(STRUCT_SIZE_3FLOAT)
                sca = struct.unpack('<3f', temp_data)
                new_chunk.bytes_read += STRUCT_SIZE_3FLOAT
                if nframe == 0:
                    child.scale = sca

        else:  #(new_chunk.ID!=VERSION or new_chunk.ID!=OBJECTINFO or new_chunk.ID!=OBJECT or new_chunk.ID!=MATERIAL):
            # print 'skipping to end of this chunk'
            #print("unknown chunk: "+hex(new_chunk.ID))
            buffer_size = new_chunk.length - new_chunk.bytes_read
            binary_format = '%ic' % buffer_size
            temp_data = file.read(struct.calcsize(binary_format))
            new_chunk.bytes_read += buffer_size

        #update the previous chunk bytes read
        # print 'previous_chunk.bytes_read += new_chunk.bytes_read'
        # print previous_chunk.bytes_read, new_chunk.bytes_read
        previous_chunk.bytes_read += new_chunk.bytes_read
        ## print 'Bytes left in this chunk: ', previous_chunk.length - previous_chunk.bytes_read

    # FINISHED LOOP
    # There will be a number of objects still not added
    if CreateBlenderObject:
        putContextMesh(contextMesh_vertls, contextMesh_facels,
                       contextMeshMaterials)

    # Assign parents to objects
    for ind, ob in enumerate(object_list):
        parent = object_parent[ind]
        if parent == ROOT_OBJECT:
            ob.parent = None
        else:
            ob.parent = object_list[parent]
            # pivot_list[ind] += pivot_list[parent]  # XXX, not sure this is correct, should parent space matrix be applied before combining?
    # fix pivots
    for ind, ob in enumerate(object_list):
        if ob.type == 'MESH':
            pivot = pivot_list[ind]
            pivot_matrix = object_matrix.get(
                ob, mathutils.Matrix())  # unlikely to fail
            pivot_matrix = mathutils.Matrix.Translation(-pivot *
                                                        pivot_matrix.to_3x3())
            ob.data.transform(pivot_matrix)