Textures

I have this code to read the textures from a binary format, but it doesn’t quite work like I want.

def tmb_read_texture(file_object):
    data_chunk = file_object.read(32) # Read texture name
    bmpname = data_chunk[0:data_chunk.find('\0', 0)]
    name, ext = Blender.sys.splitext(bmpname)
    name=name+".tga"
    print "Texname: ",name
    texture = Blender.Texture.New(name)
    Globals.textures.append(name)  # store texture names in list
    data_chunk = file_object.read(4) # Read image size
    width,height=struct.unpack_from('<2H', data_chunk)
    newImg=Blender.Image.New(name,width,height,32) # This should be for RGBA, i.e. including transparency, right?
    for y in xrange(height): 
        for x in xrange(width):     
            data_chunk = file_object.read(4) # Read pixel values
            b,g,r,a=struct.unpack_from('<4B', data_chunk)
            newImg.setPixelI(x, y, ( r,g,b,a))
    newImg.save()
    newImg=Blender.Image.Load(name) # Todo: There MUST be a better way to force blender to see all the setpixel changes
    texture.setType('Image')
    texture.image=newImg
    return texture

While it looks ok, there’s still 2 things wrong.

  1. In “UV/Image Editor” I see 2 images, one from New() and one from Load()
  2. Parts that should be transparent aren’t.

Anyone who has any suggestions how to do this in a better way?

Well, I managed to work out a few things. Here’s an improved version:

def tmb_read_texture(file_object):
    data_chunk = file_object.read(32) # Read texture name
    bmpname = data_chunk[0:data_chunk.find('\0', 0)]
    name, ext = Blender.sys.splitext(bmpname)
    name=name+".png"
    print "Texname: ",name
    texture = Blender.Texture.New(name)
    Globals.textures.append(name)  # store texture names in list
    data_chunk = file_object.read(4) # Read image size
    width,height=struct.unpack_from('<2H', data_chunk)
    newImg=Blender.Image.New(name,width,height,32) # Apparently this will create a TGA file, ignoring the extension on 'name'
    for y in xrange(height): 
        for x in xrange(width):     
            data_chunk = file_object.read(4) # Read pixel values
            b,g,r,a=struct.unpack_from('<4B', data_chunk)
            newImg.setPixelI(x, y, ( r,g,b,a))
    newImg.updateDisplay()
    newImg.pack() # and this function, inexplicably, turns it into a png file
    newImg.save() # which is good, because this function apparently doesn't save the alpha channel of a 32-bit tga file, but can save a 32-bit png
    texture.setImage(newImg)
    texture.imageFlags|=Blender.Texture.ImageFlags.USEALPHA
    texture.flags|=Blender.Texture.Flags.PREVIEW_ALPHA
    newImg.updateDisplay()
    return texture