Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import struct
- from struct import unpack
- from time import time
- class Tile(object):
- __slots__ = 'items', 'counts'
- def __init__(self, items):
- self.items = items
- self.counts = len(items)
- class Item(object):
- __slots__ = 'itemId', 'count', 'attributes'
- def __init__(self, itemId, count=1, **attributes):
- self.itemId = itemId
- self.count = count
- self.attributes = attributes
- # 16 x 32 x 32 x 4
- real = {}
- for z in xrange(16):
- real[z] = []
- for x in xrange(32):
- real[z].append([])
- for y in xrange(32):
- real[z][x].append([100, 102, 10, 10])
- def generator(obj):
- code = ""
- for level in obj:
- code += "%s" % chr(level)
- for x in obj[level]:
- for y in x:
- items = []
- for item in y:
- items.append(struct.pack("HBB", item, 1, 0))
- code += ','.join(items)
- code +=";"
- return code
- with open("w", "w+b") as f:
- f.write(generator(real))
- code = open("w").read()
- print "Length: %d" % len(code)
- itemCache = {}
- def reader(code):
- w = {}
- pos = 0
- l = len(code)
- # Avoid 1k calls to making the format :)
- #l_unpack = struct.Struct("HBB").unpack
- l_unpack = struct.unpack
- # Bind them locally, this is suppose to make a small speedup as well, local things can be more optimized :)
- # Pypy gain nothing, but CPython does.
- l_Item = Item
- l_Tile = Tile
- # Also attempt to local the itemCache, pypy doesn't like this tho.
- l_itemCache = itemCache
- while True:
- level = ord(code[pos])
- pos += 1
- xlevel = []
- l_xlevel_append = xlevel.append
- for xr in xrange(32):
- ywork = []
- l_ywork_append = ywork.append
- for yr in xrange(32):
- items = []
- l_items_append = items.append
- while True:
- itemId, count, attrNr = l_unpack("HBB", code[pos:pos+4])
- #itemId, count, attrNr = l_unpack(code[pos:pos+4])
- if attrNr:
- pos += 4
- attr = {}
- for n in xrange(attrNr):
- name=''
- value=''
- data=code[pos]
- while data != "\xff":
- name += data
- pos += 1
- data = code[pos]
- pos += 1
- data=code[pos]
- while data != "\xff":
- value += data
- pos += 1
- data = code[pos]
- pos +=2
- attr[name] = value
- l_items_append(l_Item(itemId, count, **attr))
- else:
- pos += 5
- try:
- l_items_append(l_itemCache[itemId])
- except KeyError:
- i = l_itemCache[itemId] = l_Item(itemId, count)
- l_items_append(i)
- if code[pos-1] == ';': break
- l_ywork_append(l_Tile(items))
- l_xlevel_append(ywork)
- w[level] = xlevel
- if pos >= l:
- return w
- t = time()
- for x in xrange(100):
- reader(code)
- print("Struct: %f" % (time() - t))
Advertisement
Add Comment
Please, Sign In to add comment