Exemplo n.º 1
0
def packBackground(src, dst):
    outdir = ['../Imagens/bg_pt/', '../Imagens/bg_pt/pt/']
    originals = ['../Imagens/bg/', '../Imagens/bg/en/']

    bg_path = os.path.join(src, 'bg')
    files = filter(lambda x: x.__contains__('.bmp'), scandirs(bg_path))

    print "Buffering..."

    for name in files:

        input = open(name, 'rb')
        w = images.Reader(input)
        data, colormap = w.as_data(mode=1, bitdepth=8)

        width = len(w.data[0])
        height = len(w.data)

        tilelist = []
        tileset = array.array('c')
        tilemap = array.array('c')

        for x in range(width * height / 64):
            string = data[64 * x:64 * (x + 1)]
            if string in tilelist:
                mapper = tilelist.index(string)
                tilemap.extend(struct.pack('<H', mapper))
            else:
                tilelist.append(string)
                mapper = tilelist.index(string)
                tileset.extend(string)
                tilemap.extend(struct.pack('<H', mapper))

        temp = open('temp', 'w+b')
        # Escrita do arquivo tempor?rio:
        temp.write(struct.pack('<L', 0xE0))  #len(colormap)))
        for x in range(0xE0):  #colormap:
            temp.write(tuple2gba(colormap[x]))
        temp.write(struct.pack('<L', len(tilelist)))
        tileset.tofile(temp)

        temp.write(struct.pack('<H', width / 8))
        temp.write(struct.pack('<H', height / 8))
        tilemap.tofile(temp)

        filepath = dst + name[len(src):]
        path = os.path.dirname(filepath)
        if not os.path.isdir(path):
            os.makedirs(path)

        output = open(filepath.replace('.bmp', ''), 'wb')
        output.write(struct.pack('<L', 2))

        buffer = lzss.compress(temp)
        buffer.tofile(output)

        output.close()
        temp.close()

        print '>> \'' + filepath.replace('.bmp', '') + ' created.'
Exemplo n.º 2
0
def Insert_NPC(src, dst):
    global BASE_PTR
    table = normal_table('mmbn2.tbl')    
    table.set_mode('inverted')
    
    files = filter(lambda x: x.__contains__('.txt'), scandirs(src))       
    # Cria o dicionário invertido de tags
    itagsdict = dict([[v[0],k] for k,v in tagsdict.items()])
   
    print hex(BASE_PTR)
    dest = open(dst, 'r+b')
    dest.seek( BASE_PTR )
    
    pointer_files = []
    
    for i, txtname in enumerate(files):
        print ">> Convertendo e comprimindo " + txtname 

        buffer = array.array("c")
        with open(txtname, 'rb') as fd:
            
            pointer_idx = []
        
            for j, line in enumerate(fd):
                #try:
                    line = line.strip('\r\n')
                    if not line:
                        continue
                    elif line in ( "!---------------------!","!+++++++++++++++++++++!","!*********************!" ):
                        continue
                    else:
                        splitted = re.split( TAG_IN_LINE, line )
                        for string in splitted:
                            tag = re.match( GET_TAG, string )
                            # Se não for uma tag, é texto plano
                            if not tag:                            
                                for char in string:
                                    try:
                                        buffer.extend( table[char] )
                                    except:
                                        print "Line {0} Char {1} Text {2}".format(j, ord(char), line)
                                        raise Exception()
                            # Se for uma tag
                            else:
                                tag = tag.groups()[0]
                                argv = []
                                # Tag com argumentos
                                if ": " in tag:
                                    tag,argv = tag.split(": ")
                                    argv = argv.split(" ")
                                    
                                if tag.startswith("@"): # São labels
                                    if "PointerIdx" in tag:
                                        pointer_idx.append( len(buffer) )
                                    else:
                                        print "Line {0} Label {1} Text {2}".format(j, tag, line)
                                        raise Exception()
                                else:                                                                    
                                    if tag in itagsdict:
                                        buffer.extend( struct.pack("B", itagsdict[tag]) )
                                        for arg in argv:
                                            buffer.extend( struct.pack("B", int(arg)) )                            
                                    else:
                                        buffer.extend( struct.pack("B", int(tag,16)) )                                        
                # except:
                    # print "<< Error"
                    # sys.exit()
                    
            size = len(pointer_idx) * 2 + len(buffer)
            temp = mmap.mmap(-1, size)
            offset = len(pointer_idx) * 2
            for ptr in pointer_idx:
                temp.write( struct.pack("<H", offset+ptr) )
            temp.write(buffer.tostring())
            
            ret = lzss.compress(temp) 
            temp.close()
            
            b,name = os.path.split( txtname )
            i, j = name.replace(".txt", "").split("_")

            pointer_files.append( [int(i), int(j), dest.tell()] )            
            ret.tofile(dest)
            

    BASE_PTR = dest.tell()
            
    print ">> Updating pointer table..."    
    for desc in pointer_files:
        dest.seek( 0x228a8 + 4*desc[1] )
        dest.write( struct.pack("<L", desc[2] | 0x08000000) )

    dest.close()                     
Exemplo n.º 3
0
                        tm.extend(
                            struct.pack("<H",
                                        0x8800 | dc[vertical(tilesdict[x])]))
                    elif dc.has_key(diagonal(tilesdict[x])):
                        tm.extend(
                            struct.pack("<H",
                                        0x8C00 | dc[diagonal(tilesdict[x])]))
                    else:
                        raise Exception
                        sys.exit(1)

                tilemaps.append(tm)

        temp = mmap.mmap(-1, len(tileset))
        temp.write(tileset)
        comp = lzss.compress(temp)

        with open(os.path.join(PATH_OUTPUT, "%s.bin" % f), "wb") as fd:
            print "> packing", "%s.bin" % f
            fd.seek(0x10, 0)
            addr_tileset = fd.tell()
            fd.write(struct.pack("<L", 0x14))  # localização do tileset
            fd.write(struct.pack("<L", len(comp)))
            fd.write(struct.pack("<L", 0x80220100))
            fd.write(struct.pack("<L", len(comp) + 8))
            fd.write(struct.pack("<L", 0x08080020))
            comp.tofile(fd)
            fd.write(struct.pack("<L", 0x000003E0))
            fd.write(struct.pack("<L", 0x00007FFF))
            fd.write("\x00" * 24)
                        tm.extend( struct.pack("<H", 0x8000 | dc[tilesdict[x]])) 
                    elif dc.has_key(horizontal(tilesdict[x])):
                        tm.extend( struct.pack("<H", 0x8400 | dc[horizontal(tilesdict[x])]))
                    elif dc.has_key(vertical(tilesdict[x])):
                        tm.extend( struct.pack("<H", 0x8800 | dc[vertical(tilesdict[x])]))
                    elif dc.has_key(diagonal(tilesdict[x])):
                        tm.extend( struct.pack("<H", 0x8C00 | dc[diagonal(tilesdict[x])]))      
                    else:
                        raise Exception
                        sys.exit(1)

                tilemaps.append( tm )
            
        temp = mmap.mmap( -1, len(tileset ) )
        temp.write( tileset )
        comp = lzss.compress(temp)
        
        with open( os.path.join( PATH_OUTPUT , "%s.bin" % f ) , "wb" ) as fd:
            print "> packing" ,  "%s.bin" % f
            fd.seek( 0x10, 0 )
            addr_tileset = fd.tell()
            fd.write( struct.pack( "<L", 0x14 ) ) # localização do tileset
            fd.write( struct.pack( "<L", len( comp ) ) )
            fd.write( struct.pack( "<L" , 0x80220100 ) )
            fd.write( struct.pack( "<L", len( comp ) + 8 ) )
            fd.write( struct.pack( "<L" , 0x08080020 ) )
            comp.tofile( fd )
            fd.write( struct.pack( "<L" , 0x000003E0 ) )
            fd.write( struct.pack( "<L" , 0x00007FFF ) )
            fd.write( "\x00" * 24 )
            
Exemplo n.º 5
0
def packSprite(src, dst, src1):
    holder = {}

    # Passo 1 - Gerar um dicion?rio com todos os sprites a serem empacotados

    ani_path = os.path.join(src, 'ani')
    files = filter(lambda x: x.__contains__('.bmp'), scandirs(ani_path))

    print "Buffering..."

    for name in files:
        print ">>> ", name
        a = re.match(r'(.*)-(.*)-(.*)\.bmp$', name[len(src):])
        if a.group(1) not in holder:
            holder.update({a.group(1): {}})  #[]})

        w = bmp.Reader(name)
        d = w.read()
        p = w.read_palette()
        w.file.close()
        holder[a.group(1)].update({int(a.group(2)) - 1:
                                   (d, p)})  #append((d, p))

    print "Analyzing..."

    compressions = {}
    data = {}
    # Passo 2 - Descompactar os arquivos originais
    for name in holder.keys():
        file = open(src1 + name, "rb")
        type = struct.unpack('<L', file.read(4))[0]
        if type == 1:
            buffer = rle.uncompress(file, 0x4)
        elif type == 2:
            buffer = lzss.uncompress(file, 0x4)
        elif type == 3 or type == 4:
            buffer = huffman.uncompress(file, 0x4)
        else:
            file.seek(0, 0)
            buffer = array.array('c', file.read())
        compressions.update({name: type})
        file.close()

        data.update({name: buffer})

    # Passo 3 - Atualizar os containers com os novos sprites
    #for i, dir in enumerate(outdir):
    for name in data.keys():
        print "Updating ", name
        buffer = data[name]
        arrays = []
        with open("temp", "w+b") as f:
            buffer.tofile(f)
            f.seek(0, 0)
            if re.match(r'^.*\.arc$', name):
                entries = struct.unpack("<H", f.read(2))[0]
                bitdepth = 2**(struct.unpack("<H", f.read(2))[0] - 1)
                for x in range(entries):
                    sprite_data = holder[name][x][0]
                    sprite_pal = holder[name][x][1]
                    # Leitura do header do sprite
                    f.seek(4,
                           1)  # As coordenadas n?o ser?o mudadas a principio
                    obj_entries = struct.unpack("<L", f.read(4))[0]
                    for y in range(obj_entries):
                        xpos = struct.unpack("<H", f.read(2))[0]
                        ypos = struct.unpack("<H", f.read(2))[0]
                        width = 8 * (2**struct.unpack("<H", f.read(2))[0])
                        height = 8 * (2**struct.unpack("<H", f.read(2))[0])
                        obj = []
                        for w in range(height):
                            obj.append(sprite_data[ypos + w][xpos:xpos +
                                                             width])

                        bitarray = array.array('B')
                        for row in obj:
                            if bitdepth < 8:
                                row = zip(*[iter(row)] * (8 / bitdepth))
                                row = map(
                                    lambda e: reduce(
                                        lambda x, y:
                                        (x << bitdepth) + y, reversed(e)), row)
                            bitarray.extend(row)

                        arrays.append(
                            (f.tell(), array.array("c", bitarray.tostring())))
                        f.seek(len(bitarray.tostring()), 1)

                pal_entries = struct.unpack('<L', f.read(4))[0]

            elif re.match(r'^.*\.arj$', name):
                entries = struct.unpack("<H", f.read(2))[0]
                bitdepth = 2**(struct.unpack("<H", f.read(2))[0] - 1)
                colors = struct.unpack("<L", f.read(4))[0]
                for x in range(entries):
                    sprite_data = holder[name][x][0]
                    sprite_pal = holder[name][x][1]

                    sprite_xpos = struct.unpack("<H", f.read(2))[0]
                    sprite_ypos = struct.unpack("<H", f.read(2))[0]
                    obj_entries = struct.unpack("<L", f.read(4))[0]

                    for y in range(obj_entries):
                        obj_shape = struct.unpack('<H', f.read(2))[0]
                        obj_size = struct.unpack('<H', f.read(2))[0]
                        obj_xcoord = struct.unpack('<H', f.read(2))[0]
                        obj_ycoord = struct.unpack('<H', f.read(2))[0]
                        obj_width = 2**struct.unpack('<H', f.read(2))[0]
                        obj_height = 2**struct.unpack('<H', f.read(2))[0]

                        obj = [[list() for p in range(obj_width)]
                               for t in range(obj_height)]

                        for ypos in range(obj_height):
                            for xpos in range(obj_width):
                                for w in range(8):
                                    obj[ypos][xpos] += (
                                        sprite_data[obj_ycoord + ypos * 8 +
                                                    w][obj_xcoord +
                                                       xpos * 8:obj_xcoord +
                                                       xpos * 8 + 8])

                        bitarray = array.array('B')
                        for row in obj:
                            for d in row:
                                bitarray.extend(d)

                        arrays.append(
                            (f.tell(), array.array("c", bitarray.tostring())))
                        f.seek(len(bitarray.tostring()), 1)

        with open("temp", "r+b") as f:
            for par in arrays:
                f.seek(par[0], 0)
                par[1].tofile(f)


# Passo 4
        print "Compressing..."

        with open("temp", "rb") as f:
            type = compressions[name]
            if type == 1:
                buffer = rle.compress(f)
            elif type == 2:
                buffer = lzss.compress(f)
            elif type == 3:
                buffer = huffman.compress(f, 4)
            elif type == 4:
                buffer = huffman.compress(f, 8)

            filepath = dst + name
            path = os.path.dirname(filepath)
            #print path
            if not os.path.isdir(path):
                os.makedirs(path)

            g = open(filepath, "wb")
            g.write(struct.pack("<L", type))
            buffer.tofile(g)
            g.close()

            print '>> \'' + filepath + ' created.'