Example #1
0
def disassemble(path, to, parser):
	print('\tD %s -> %s' % (path, to))
	if(os.path.isfile(path)):
		dmi = None
		try:
			dmi = DMI(path)
			dmi.extractTo(to, parser.suppress_post_process)
		except SystemError as e:
			print("!!! Received SystemError in %s, halting: %s" % (dmi.filename, traceback.format_exc(e)))
			print('# of cells: %d' % len(dmi.states))
			print('Image h/w: %s' % repr(dmi.size))
			sys.exit(1)
		except Exception as e:
			print("Received error, continuing: %s" % traceback.format_exc())
Example #2
0
def make_dmi(path, dest, parser):
	if(os.path.isfile(path)):
		dmi = None
		try:
			dmi = DMI(dest)
			dmi.make(path)
			dmi.save(dest)
		except SystemError as e:
			print("!!! Received SystemError in %s, halting: %s" % (dmi.filename, traceback.format_exc(e)))
			print('# of cells: %d' % len(dmi.states))
			print('Image h/w: %s' % repr(dmi.size))
			sys.exit(1)
		except Exception as e:
			print("Received error, continuing: %s" % traceback.format_exc())
Example #3
0
def makeDMI():
    dmi = DMI('state_limit.dmi')
    #
    for i in range(513):
        # Make a new tile
        img = Image.new('RGBA', (32, 32))
        # Set up PIL's drawing stuff
        draw = ImageDraw.Draw(img)
        # Define a font.
        font = ImageFont.truetype('arial.ttf', 10)
        # Draw the tile number
        draw.text((10, 0), str(i + 1), (0, 0, 0), font=font)
        # Make state
        state_name='state {0}'.format(i+1)
        state=State(state_name)
        state.dirs=1
        state.frames=1
        state.icons=[img]
        # Add state to DMI
        dmi.states[state_name]=state
    #save
    dmi.save('state_limit.dmi', sort=False)
Example #4
0
            'orange',
            'purple',
            'brown',
            'vault'
        ]
    }
}
knownQuads = [
    {}, {}, {}, {}
]
def isKnownQuad(i, im, icon_state):
    for name, kq in knownQuads[i].items():
        if equal(kq, im):
            return True
    return False
floors = DMI(sys.argv[1])
floors.loadAll()
basedir = 'floor_quads'
if os.path.isdir('floor_quads'):
    shutil.rmtree(basedir)
os.makedirs('floor_quads')
for icon_state in extract:
    if icon_state not in floors.states:
        print('Can\'t find state {0}!'.format(icon_state))
        continue
    for d in range(floors.states[icon_state].dirs):
        dirf = 0
        dirn = 'SOUTH'
        if floors.states[icon_state].dirs > 1:
            dirf = directions.IMAGE_INDICES[d]
            dirn = directions.getNameFromDir(dirf)
Example #5
0
def set_dmi_data(path, headerFile, parser):
	if(os.path.isfile(path)):
		dmi = DMI(path)
		with open(headerFile, 'r') as f:
			dmi.setHeader(f.read(), path)
Example #6
0
def get_dmi_data(path, dest, parser):
	if(os.path.isfile(path)):
		dmi = DMI(path)
		with open(dest, 'w') as f:
			f.write(dmi.getHeader())
Example #7
0
def compare(theirsfile, minefile, parser, reportstream, **kwargs):
	# print('\tD %s -> %s' % (theirsfile, minefile))
	theirs = []
	theirsDMI = None
	mine = []
	mineDMI = None
	states = []
	
	new2mineFilename = minefile.replace('.dmi', '.new.dmi')
	new2theirsFilename = theirsfile.replace('.dmi', '.new.dmi')
	
	new2mine=None
	if os.path.isfile(new2mineFilename):
		os.remove(new2mineFilename)
	if kwargs.get('newfile_mine',True):
		new2mine = DMI(new2mineFilename)
	
	new2theirs=None
	if os.path.isfile(new2theirsFilename):
		os.remove(new2theirsFilename)
	if kwargs.get('newfile_theirs',False):
		new2theirs = DMI(new2theirsFilename)
	
	
	o = ''
	if(os.path.isfile(theirsfile)):
		try:
			theirsDMI = DMI(theirsfile)
			theirsDMI.loadAll()
			theirs = theirsDMI.states
		except SystemError as e:
			print("!!! Received SystemError in %s, halting: %s" % (theirs.filename, traceback.format_exc(e)))
			print('# of cells: %d' % len(theirs.states))
			print('Image h/w: %s' % repr(theirs.size))
			sys.exit(1)
		except Exception as e:
			print("Received error, continuing: %s" % traceback.format_exc())
			o += "\n {0}: Received error, continuing: {1}".format(theirsfile, traceback.format_exc())
		for stateName in theirs:
			if stateName not in states:
				states.append(stateName)
	if(os.path.isfile(minefile)):
		try:
			mineDMI = DMI(minefile)
			mineDMI.loadMetadata()
			mine = mineDMI.states
		except SystemError as e:
			print("!!! Received SystemError in %s, halting: %s" % (mine.filename, traceback.format_exc(e)))
			print('# of cells: %d' % len(mine.states))
			print('Image h/w: %s' % repr(mine.size))
			sys.exit(1)
		except Exception as e:
			print("Received error, continuing: %s" % traceback.format_exc())
			o += "\n {0}: Received error, continuing: {1}".format(minefile, traceback.format_exc())
		for stateName in mine:
			if stateName not in states:
				states.append(stateName)
	for state in sorted(states):
		inTheirs = state in theirs
		inMine = state in mine 
		if inTheirs and not inMine:
			o += '\n + {1}'.format(minefile, state)
			if new2mine is not None:
				new2mine.states[state] = theirsDMI.states[state]
		elif not inTheirs and inMine:
			o += '\n - {1}'.format(theirsfile, state)
			if new2theirs is not None:
				new2theirs.states[state] = mineDMI.states[state]
		elif inTheirs and inMine:
			if theirs[state].ToString() != mine[state].ToString():
				o += '\n - {0}: {1}'.format(state, mine[state].ToString())
				o += '\n + {0}: {1}'.format(state, theirs[state].ToString())
	if o != '': 
		reportstream.write('\n--- {0}'.format(theirsfile))
		reportstream.write('\n+++ {0}'.format(minefile))
		reportstream.write(o)
		
		if new2mine is not None:
			if len(new2mine.states) > 0:
				new2mine.save(new2mineFilename)
			else:
				if os.path.isfile(new2mineFilename):
					os.remove(new2mineFilename)
					#print('RM {0}'.format(new2mineFilename))
		if new2theirs is not None:
			if len(new2theirs.states) > 0:
				new2theirs.save(new2theirsFilename)
			else:
				if os.path.isfile(new2theirsFilename):
					os.remove(new2theirsFilename)
Example #8
0
 def renderAtom(self, atom, basedir, skip_alpha=False):
     if 'icon' not in atom.properties:
         logging.critical('UNKNOWN ICON IN ATOM #{0}'.format(atom.id))
         logging.info(atom.MapSerialize())
         logging.info(atom.MapSerialize(Atom.FLAG_INHERITED_PROPERTIES))
         return None
     
     dmi_file = atom.properties['icon'].value
     
     # Grab default icon_state ('') if we can't find the one defined.
     state = atom.getProperty('icon_state', '')
     
     direction = SOUTH
     if 'dir' in atom.properties:
         try:
             direction = int(atom.properties['dir'].value)
         except ValueError:
             logging.critical('FAILED TO READ dir = ' + repr(atom.properties['dir'].value))
             return None
     
     icon_key = '{0}|{1}|{2}'.format(dmi_file, state, direction)
     frame = None
     pixel_x = 0
     pixel_y = 0
     if icon_key in _icons:
         frame, pixel_x, pixel_y = _icons[icon_key]
     else:
         dmi_path = os.path.join(basedir, dmi_file)
         dmi = None
         if dmi_path in _dmis:
             dmi = _dmis[dmi_path]
         else:
             try:
                 dmi = DMI(dmi_path)
                 dmi.loadAll()
                 _dmis[dmi_path] = dmi
             except Exception as e:
                 print(str(e))
                 for prop in ['icon', 'icon_state', 'dir']:
                     print('\t{0}'.format(atom.dumpPropInfo(prop)))
                 pass
         if dmi.img is None:
             logging.warning('Unable to open {0}!'.format(dmi_path))
             return None
         
         if dmi.img.mode not in ('RGBA', 'P'):
             logging.warn('{} is mode {}!'.format(dmi_file, dmi.img.mode))
             
         if direction not in IMAGE_INDICES:
             logging.warn('Unrecognized direction {} on atom {}!'.format(direction, atom.MapSerialize()))
             direction = SOUTH  # DreamMaker property editor shows dir = 2.  WTF?
             
         frame = dmi.getFrame(state, direction, 0)
         if frame == None:
             # Get the error/default state.
             frame = dmi.getFrame("", direction, 0)
         
         if frame == None:
             return None
         
         if frame.mode != 'RGBA':
             frame = frame.convert("RGBA")
             
         pixel_x = 0
         if 'pixel_x' in atom.properties:
             pixel_x = int(atom.properties['pixel_x'].value)
             
         pixel_y = 0
         if 'pixel_y' in atom.properties:
             pixel_y = int(atom.properties['pixel_y'].value)
         
         _icons[icon_key] = (frame, pixel_x, pixel_y)
             
     # Handle BYOND alpha and coloring
     c_frame = frame
     alpha = int(atom.getProperty('alpha', 255))
     if skip_alpha:
         alpha = 255
     color = atom.getProperty('color', '#FFFFFF')
     if alpha != 255 or color != '#FFFFFF':
         c_frame = tint_image(frame, BYOND2RGBA(color, alpha))
     return c_frame
Example #9
0
    def RenderToMapTile(self, passnum, basedir, renderflags, **kwargs):
        img = Image.new('RGBA', (96, 96))
        self.offset = (32, 32)
        foundAPixelOffset = False
        render_types = kwargs.get('render_types', ())
        skip_alpha = kwargs.get('skip_alpha', False)
        # for atom in sorted(self.GetAtoms(), reverse=True):
        for atom in self.SortAtoms():
            if len(render_types) > 0:
                found = False
                for path in render_types:
                    if atom.path.startswith(path):
                        found = True
                if not found:
                    continue

            aid = atom.id
            # Ignore /areas.  They look like ass.
            if atom.path.startswith('/area'):
                if not (renderflags & MapRenderFlags.RENDER_AREAS):
                    continue
            
            # We're going to turn space black for smaller images.
            if atom.path == '/turf/space':
                if not (renderflags & MapRenderFlags.RENDER_STARS):
                    continue
                
            if 'icon' not in atom.properties:
                logging.critical('UNKNOWN ICON IN {0} (atom #{1})'.format(self.origID, aid))
                logging.info(atom.MapSerialize())
                logging.info(atom.MapSerialize(Atom.FLAG_INHERITED_PROPERTIES))
                continue
            
            dmi_file = atom.properties['icon'].value
            
            if 'icon_state' not in atom.properties:
                # Grab default icon_state ('') if we can't find the one defined.
                atom.properties['icon_state'] = BYONDString("")
            
            state = atom.properties['icon_state'].value
            
            direction = SOUTH
            if 'dir' in atom.properties:
                try:
                    direction = int(atom.properties['dir'].value)
                except ValueError:
                    logging.critical('FAILED TO READ dir = ' + repr(atom.properties['dir'].value))
                    continue
            
            icon_key = '{0}|{1}|{2}'.format(dmi_file, state, direction)
            frame = None
            pixel_x = 0
            pixel_y = 0
            if icon_key in _icons:
                frame, pixel_x, pixel_y = _icons[icon_key]
            else:
                dmi_path = os.path.join(basedir, dmi_file)
                dmi = None
                if dmi_path in _dmis:
                    dmi = _dmis[dmi_path]
                else:
                    try:
                        dmi = DMI(dmi_path)
                        dmi.loadAll()
                        _dmis[dmi_path] = dmi
                    except Exception as e:
                        print(str(e))
                        for prop in ['icon', 'icon_state', 'dir']:
                            print('\t{0}'.format(atom.dumpPropInfo(prop)))
                        pass
                if dmi.img is None:
                    logging.warning('Unable to open {0}!'.format(dmi_path))
                    continue
                
                if dmi.img.mode not in ('RGBA', 'P'):
                    logging.warn('{} is mode {}!'.format(dmi_file, dmi.img.mode))
                    
                if direction not in IMAGE_INDICES:
                    logging.warn('Unrecognized direction {} on atom {} in tile {}!'.format(direction, atom.MapSerialize(), self.origID))
                    direction = SOUTH  # DreamMaker property editor shows dir = 2.  WTF?
                    
                frame = dmi.getFrame(state, direction, 0)
                if frame == None:
                    # Get the error/default state.
                    frame = dmi.getFrame("", direction, 0)
                
                if frame == None:
                    continue
                
                if frame.mode != 'RGBA':
                    frame = frame.convert("RGBA")
                    
                pixel_x = 0
                if 'pixel_x' in atom.properties:
                    pixel_x = int(atom.properties['pixel_x'].value)
                    
                pixel_y = 0
                if 'pixel_y' in atom.properties:
                    pixel_y = int(atom.properties['pixel_y'].value)
                
                _icons[icon_key] = (frame, pixel_x, pixel_y)
                    
            # Handle BYOND alpha and coloring
            c_frame = frame
            alpha = int(atom.getProperty('alpha', 255))
            if skip_alpha:
                alpha = 255
            color = atom.getProperty('color', '#FFFFFF')
            if alpha != 255 or color != '#FFFFFF':
                c_frame = tint_image(frame, BYOND2RGBA(color, alpha))
            img.paste(c_frame, (32 + pixel_x, 32 - pixel_y), c_frame)  # Add to the top of the stack.
            if pixel_x != 0 or pixel_y != 0:
                if passnum == 0: return  # Wait for next pass
                foundAPixelOffset = True
        
        if passnum == 1 and not foundAPixelOffset:
            return None
        if not self.areaSelected:
            # Fade out unselected tiles.
            bands = list(img.split())
            # Excluding alpha band
            for i in range(3):
                bands[i] = bands[i].point(lambda x: x * 0.4)
            img = Image.merge(img.mode, bands)
        
        return img