Advertisement
Guest User

sc_compress.py

a guest
May 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.26 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. # Author: Xset
  4. # Version: 2.0
  5. # Last updated: 2017-03-24
  6.  
  7. import re
  8. import os
  9. import sys
  10. import lzma
  11. import struct
  12. import sqlite3
  13. import binascii
  14. import subprocess
  15.  
  16. from PIL import Image, ImageDraw
  17. from modules import *
  18.  
  19. compileDir = '/sdcard/Download/png2sc-maste/png2sc-master/compile/'
  20. compiledDir = '/sdcard/Download/png2sc-maste/png2sc-master/compiled/'
  21.  
  22. findFiles = {}
  23. picCount = 0
  24.  
  25. dbcon = sqlite3.connect("/sdcard/Download/png2sc-maste/png2sc-master/PixelData.db")
  26. dbcon.isolation_level = None
  27. dbcur = dbcon.cursor()
  28. dbcon.row_factory = sqlite3.Row
  29. dbcon.text_factory = str
  30.  
  31. def _(message):
  32.     print(u"[RELEASE] %s" % message)
  33.  
  34. def checkAlreadyExists(filename):
  35.     dbcur.execute('select * from PixelType where filename = ?', [filename])
  36.     rrf = dbcur.fetchone()
  37.    
  38.     if rrf is None:
  39.         return None
  40.    
  41.     return rrf
  42.  
  43. def file2bytes(fileName):
  44.     with open(fileName, "rb+") as handle:
  45.         bytes = handle.read()
  46.  
  47.     return bytes
  48.  
  49. def bytes2file(bytes, fileName):
  50.     handler = open(fileName, "wb+")
  51.     handler.write(bytes)
  52.     handler.close()
  53.  
  54. def convert_pixel(pixels, type):
  55.     value = None
  56.    
  57.     if type == 0:  # RGB8888
  58.         return pixels
  59.    
  60.     elif type == 2:  # RGB4444
  61.         r = (pixels[0] >> 4) << 12
  62.         g = (pixels[1] >> 4) << 8
  63.         b = (pixels[2] >> 4) << 4
  64.         a = (pixels[3] >> 4)
  65.        
  66.         value = r | g | b | a
  67.    
  68.     elif type == 4:  # RGB565
  69.         r = (pixels[0] >> 3) << 11
  70.         g = (pixels[1] >> 2) << 5
  71.         b = (pixels[2] >> 3)
  72.  
  73.         value = r | g | b
  74.    
  75.     elif type == 6:  # LA88
  76.         r = pixels[0] << 8
  77.         g = pixels[1] << 8
  78.         b = pixels[2] << 8
  79.         a = pixels[3]
  80.  
  81.         value = r | g | b | a
  82.    
  83.     elif type == 10:  # L8
  84.         value = pixels[0] | pixels[1] | pixels[2]
  85.     else:
  86.         raise Exception("Unknown pixel type {}.".format(type))
  87.  
  88.     return value
  89.  
  90. def writeImage(file, baseName, fileName, pp = 1):
  91.     _("Collecting information...")
  92.  
  93.     image = Image.open(file)
  94.     data = checkAlreadyExists(baseName)
  95.  
  96.     if not data is None:
  97.         fileType = data[1]
  98.         subType = data[2]
  99.     else:
  100.         _("Sorry, we can\'t find this texture in out database... May be you changed filename?")
  101.         _("We will use standart fileType, subType and headerBytes. (1, 0, None)" + "\n")
  102.        
  103.         fileType = 1
  104.         subType = 0
  105.    
  106.     width  = image.size[0]
  107.     height = image.size[1]
  108.  
  109.     pixels = []
  110.     iSrcPix = 0
  111.  
  112.     if subType == 0:
  113.         BFPXFormat = 4
  114.     elif subType == 2 or subType == 4 or subType == 6:
  115.         BFPXFormat = 2
  116.     elif subType == 10:
  117.         BFPXFormat = 1
  118.     else:
  119.         _("Unknown pixel type %s" % (subType))
  120.         sys.exit(0)
  121.        
  122.     if BFPXFormat:
  123.         packetSize = ((width) * (height) * BFPXFormat) + 5;
  124.    
  125.     _("About: fileType %s, fileSize: %s, subType: %s, width: %s, height: %s" % (fileType, packetSize, subType, width, height))
  126.    
  127.     imgl = image.load()
  128.    
  129.     if fileType == 28 or fileType == 27:
  130.         for y in range(0, height):
  131.             for x in range(0, width):
  132.                 c = image.getpixel((x, y))
  133.                 pixels.append(c)
  134.  
  135.         for l in range(int(height / 32)):
  136.             for k in range(int(width / 32)):
  137.                 for j in range(32):
  138.                     for h in range(32):
  139.                         pixels[iSrcPix] = imgl[h + (k * 32), j + (l * 32)]
  140.                         iSrcPix += 1
  141.                        
  142.             for j in range(32):
  143.                 for h in range(width % 32):
  144.                     pixels[iSrcPix] = imgl[h + (width - (width % 32)), j + (l * 32)]
  145.                     iSrcPix += 1
  146.  
  147.         for k in range(int(width / 32)):
  148.             for j in range(int(height % 32)):
  149.                 for h in range(32):
  150.                     pixels[iSrcPix] = imgl[h + (k * 32), j + (height - (height % 32))]
  151.                     iSrcPix += 1
  152.  
  153.         for j in range(height % 32):
  154.             for h in range(width % 32):
  155.                 pixels[iSrcPix] = imgl[h + (width - (width % 32)), j + (height - (height % 32))]
  156.                 iSrcPix += 1
  157.  
  158.     image.putdata(pixels)
  159.    
  160.     # Create new packet
  161.     p = BytesWriter(fileName)
  162.  
  163.     # Start Handler
  164.     p.WStart()
  165.  
  166.     # Packet
  167.     p.WByte(28)
  168.     p.WUnsignedInt(packetSize)
  169.     p.WByte(subType)
  170.     p.WUnsignedShort(width)
  171.     p.WUnsignedShort(height)
  172.  
  173.     for y in range(0, height):
  174.         for x in range(0, width):
  175.             pixels = image.getpixel((x, y))
  176.             converted = convert_pixel(pixels, subType)
  177.  
  178.             if subType == 0:
  179.                 p.W4Bytes(*converted)
  180.                
  181.             elif subType == 2: # RGB4444 to RGB8888
  182.                 p.WUnsignedShort(converted)
  183.                
  184.             elif subType == 4: # RGB565 to RGB8888
  185.                 p.WUnsignedShort(converted)
  186.  
  187.             elif subType == 6: # RGB555 to RGB8888                
  188.                 p.WUnsignedShort(converted)
  189.  
  190.             elif subType == 10:
  191.                 p.WUnsignedByte(converted)
  192.                
  193.     if fileName.endswith((pp * "_") + "tex.sc"):
  194.         p.WByte(0)
  195.         p.WByte(0)
  196.         p.WByte(0)
  197.         p.WByte(0)
  198.         p.WByte(0)
  199.  
  200.     p.WStop()
  201.  
  202. def compressLZMA(fileName):
  203.     _("Saving as sprite...")
  204.    
  205.     result = subprocess.check_output(["lzma.exe", "e", "temp_tex.sc", "temp_.tex_sc"])
  206.    
  207.     os.remove("temp_tex.sc")
  208.     os.rename("temp_.tex_sc", "temp_tex.sc")
  209.    
  210.     # Module with LZMA
  211.     with open("temp_tex.sc", "rb") as lz:
  212.         lzModule = lz.read()
  213.         lzModule = lzModule[0:9] + lzModule[13:]
  214.  
  215.         mModule = open("./compiled/" + re.sub("\_*tex\_*", "_tex.sc", fileName), "wb+")
  216.         mModule.write(lzModule)
  217.         mModule.close()
  218.        
  219.         lz.close()
  220.         os.remove("temp_tex.sc")
  221.  
  222.         _("Saving completed" + "\n")
  223.        
  224. def generateFilesList(dir):
  225.     if findFiles.get(dir) is None:
  226.         findFiles[dir] = []
  227.                
  228.     toCompile = os.listdir(dir)
  229.  
  230.     for file in toCompile:
  231.         fullname = dir + file
  232.         if os.path.isdir(fullname):
  233.             dir_ = fullname + "/"
  234.            
  235.             if findFiles.get(dir_) is None:
  236.                 findFiles[dir_] = []
  237.                
  238.             generateFilesList(dir_)
  239.         else:
  240.             if file.endswith("png"):
  241.                 findFiles[dir].append(file)
  242.  
  243. generateFilesList(compileDir)
  244.  
  245. for dirName in findFiles:
  246.     for file in findFiles[dirName]:
  247.         file = dirName + file
  248.         baseName, ext = os.path.splitext(os.path.basename(file))
  249.        
  250.         # If we will compile 2 files in one
  251.         if not dirName == compileDir:            
  252.             fileName = "temp_" + ("_" * picCount) + "tex.sc"
  253.             writeImage(file, baseName, fileName, len(findFiles[dirName]))
  254.  
  255.             picCount += 1
  256.  
  257.             if picCount == len(findFiles[dirName]):
  258.                 b_bytes = b''
  259.                
  260.                 for j in range(picCount):
  261.                     f_name = "temp_" + ("_" * j) + "tex.sc"
  262.                     b_bytes += file2bytes(f_name)
  263.                     os.remove(f_name)
  264.                    
  265.                 bytes2file(b_bytes, "temp_tex.sc")
  266.                 compressLZMA(baseName)
  267.                    
  268.         # if we have standart file (1 file)
  269.         elif file.endswith("png"):
  270.            
  271.             fileName = "temp_tex.sc"
  272.             writeImage(file, baseName, fileName)
  273.            
  274.             compressLZMA(baseName)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement