Advertisement
WNP78

blocks.py

Mar 31st, 2017
1,640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.50 KB | None | 0 0
  1. # This should run in python 3. I hope. It does for me.
  2. # SCRIPT BY WNP78. Post at https://www.simpleplanes.com/Forums/View/597333/Pixel-art-script
  3. # This is to show people how to generate crafts with scripts, in the hope that you can use it for something better. It is *NOT* just for people to download, and upload random pictures with!
  4.  
  5.  
  6. import xml.etree.ElementTree as et
  7. import tkinter,sys,os,time
  8. class XMLCraft:
  9.     def __init__(self, name, theme=None):
  10.         self.root = et.Element("Aircraft",{"name":name,"url":rlu,"theme":"Custom","xmlVersion":"4"})
  11.         self.Assembly = et.SubElement(self.root,"Assembly")
  12.         if theme == None:
  13.             self.Theme = et.fromstring("""<Theme name="Custom"> <Material color="FFFFFF" r="0.15" m="0.5" s="0.7" /> </Theme>""")
  14.         else:
  15.             self.Theme = et.SubElement(self.root, "Theme", {"name":"Custom"})
  16.             for col in theme:
  17.                 et.SubElement(self.Theme, "Material", {"color":col, "r":"0", "m":"0.65", "s":"0.8"})
  18.         self.root.append(self.Theme)
  19.         self.Parts = et.SubElement(self.Assembly,"Parts")
  20.         self.Bodies = et.SubElement(self.Assembly, "Bodies")
  21.         self.Connections = et.SubElement(self.Assembly, "Connections")
  22.         self.body = et.SubElement(self.Bodies,"Body",{"position":"0,0,0", "rotation":"0,0,0", "velocity":"0,0,0", "angularVelocity":"0,0,0",})
  23.         self.rparts = {"1":et.fromstring("""<Part id="1" partType="Cockpit-1" position="0,0,1" rotation="0,0,0" drag="0,0,0,0,0,0" materials="7,0"><Cockpit.State primaryCockpit="True" /></Part>""")}
  24.         self._cid = 1
  25.         self.dps = []
  26.     def cid(self):
  27.         self._cid += 1
  28.         return self._cid
  29.     def addBlock(self,x,y,z,mat=1,connectIds=[[1,0,0]]):
  30.         if (x,y,z) in self.dps: return
  31.         self.dps.append((x,y,z))
  32.         mid = str(self.cid())
  33.         self.rparts[mid] = et.XML('<Part id="'+mid+'" partType="Block-2" position="'+str(x) + "," + str(y) + "," + str(z)+'" rotation="0,0,0" drag="0.008,0.008,0.254,0.254,0.254,0.254" materials="'+str(mat)+'" scale="1,1,1" />')
  34.         for cp in connectIds:
  35.             et.SubElement(self.Connections, "Connection", {
  36.             "partA":str(cp[0]),
  37.             "partB":mid,
  38.             "attachPointsA":str(cp[2]),
  39.             "attachPointsB":str(cp[1])
  40.             })
  41.         return mid
  42.     def save(self,path):
  43.         for p in self.rparts: self.Parts.append(self.rparts[p])
  44.         self.body.set("partIds", ",".join(self.rparts.keys()))
  45.         with open(path, "wb") as f:et.ElementTree(self.root).write(f)
  46. class Utils:
  47.     @staticmethod
  48.     def readimg(path):
  49.         global rlu
  50.         rlu = "vR9" + "ERl"
  51.         t = tkinter.Tk()
  52.         img = tkinter.PhotoImage(None, {"file":path}, t)
  53.         data = []
  54.         for y in range(img.height()):
  55.             c = []
  56.             for x in range(img.width()):
  57.                 c.append(list(img.get(x,y)))
  58.             data.append(c)
  59.         t.destroy()
  60.         return data
  61.     @staticmethod
  62.     def hexcol(col):
  63.         res = ""
  64.         for i in col:
  65.             r = hex(i)[2:].upper()
  66.             if len(r)==1: r = "0"+r
  67.             res += r
  68.         return res
  69.     @staticmethod
  70.     def tryFindSpDir():
  71.         if sys.platform.startswith("win"):
  72.             p = os.path.abspath(os.path.join(os.getenv("APPDATA"),"..\\LocalLow\Jundroo\SimplePlanes\AircraftDesigns\Image.xml"))
  73.             if os.path.isdir("\\".join(  p.split("\\")[:-1] )):
  74.                 return p, "Saved to simpleplanes files as \"Image\""
  75.             return "", "SP save directory not found, move file \"Image.xml\" from the folder this script is in to your simpleplanes aircraftdesigns folder."
  76.         return "", "Non-windows platform detected. Move file \"Image.xml\" from the folder this script is in to your simpleplanes aircraftdesigns folder."
  77.  
  78. print("Image to SimplePlane v1.0 by WNP78. Please note that if the image has too many different colours in it (>250? roughly.) the game can take it badly and glitch out. If this happens, use the posterise function on an image editing suite such as paint.net (free), until it works. You'll probably also want to decrease the resolution a bit, which you can also do in image editing software.")
  79. inPath = input("Enter the file path to an image (png)> ")
  80.  
  81. time.clock()
  82. print("Reading image...")
  83. pixels = Utils.readimg(inPath)
  84. print("Processing image...")
  85. theme = []
  86. mats = []
  87. for row in pixels:
  88.     tr = []
  89.     for p in row:
  90.         px = Utils.hexcol(p)
  91.         if px in theme:
  92.             tr.append(theme.index(px))
  93.         else:
  94.             tr.append(len(theme))
  95.             theme.append(px)
  96.     mats.append(tr)
  97. print("Different colours:",len(theme))
  98. print("Part count:",(len(mats) * len(mats[0]))+1)
  99. print("Constructing craft...")
  100. craft = XMLCraft("Image", theme)
  101. lId = 1
  102. for y,row in enumerate(mats):
  103.     for x,px in enumerate(row):
  104.         connectIds = []
  105.         if x != 0: connectIds = [[lId, 3, 2]]
  106.         if y != 0: connectIds.append([lId - (len(row)-1), 5, 4])
  107.         lId = int(craft.addBlock((len(row)-x)/2,(len(mats)-y)/2,0,px, connectIds=connectIds))
  108.  
  109. print("Saving craft...")
  110. path,msg = Utils.tryFindSpDir()
  111. path = os.path.abspath(path)
  112. craft.save(path)
  113. print(msg)
  114. endT = time.time()
  115. print("Done in",round(time.clock()),"second(s).")
  116. print("You may need to attach your cockpit to the blocks, as they are probably detached.")
  117. input("Press enter to exit")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement