view LightTools/Map.py @ 0:7e3a0ae9c016

Initial commit
author koryspansel <koryspansel@bendbroadband.com>
date Wed, 07 Sep 2011 12:36:37 -0700
parents
children 50def8c971d9
line wrap: on
line source

#
# Map
#

import sys
import string
import struct
import os
import functools

class MapDefinition:
    Parse = functools.partial(string.split, sep=',')

    def __init__(self, size, position, direction, fcount, functions, grid):
        self.Size = self._ParseVector(size)
        self.Position = self._ParseVector(position)
        self.Direction = self._ParseVector(direction)
        self.Count = self._ParseVector(fcount)
        self.Functions = self._ParseList(functions)
        self.Grid = self._ParseList(grid)

    def Write(self, filename):
        with open(filename, 'wb') as handle:
            handle.write(struct.pack('i' * len(self.Size),      *self.Size))            # 8
            handle.write(struct.pack('i' * len(self.Position),  *self.Position))        # 8
            handle.write(struct.pack('i' * len(self.Direction), *self.Direction))       # 4
            handle.write(struct.pack('i' * len(self.Count),     *self.Count))           # 4

            for function in self.Functions:
                handle.write(struct.pack('i' * len(function), *function))               # 4 * Count

            for tower in self.Grid:
                handle.write(struct.pack('i' * len(tower), *tower))                     # 8 * Size.X * Size.Y

    def _ParseVector(self, line):
        return map(int, self.Parse(line))

    def _ParseList(self, lines):
        return [self._ParseVector(line) for line in lines]

def ReadDefinition(filename):
    def FilterLines(lines):
        for line in map(string.strip, lines):
            if line and not line.startswith('#'):
                yield line.split('#')[0]

    with open(filename, 'rt') as handle:
        lines = handle.readlines()

    definition = tuple(FilterLines(lines))

    offset = 0
    size = definition[offset]
    offset += 1
    position = definition[offset]
    offset += 1
    direction = definition[offset]
    offset += 1
    fcount = definition[offset]
    offset += 1
    length = int(fcount)
    functions = definition[offset:offset+length]
    offset += length
    grid = definition[offset:]

    return MapDefinition(size, position, direction, fcount, functions, grid)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'Usage: Map <map> [output]'
        sys.exit()

    path_input  = os.path.abspath(sys.argv[1])
    path_output = os.path.splitext(path_input)[0] + '.map'

    if len(sys.argv) > 2:
        path_output = os.path.abspath(sys.argv[2])
        if os.path.isdir(path_output):
            path_output += os.path.splitext(os.path.basename(path_input))[0] + '.map'

    definition = ReadDefinition(path_input)
    if definition:
        print 'Building %s from %s' % (os.path.basename(path_output), os.path.basename(path_input))
        definition.Write(path_output)