From 5a19b8b375049cf59ee88a0eb62233e5c4c9da89 Mon Sep 17 00:00:00 2001 From: Aaron Griffith Date: Sat, 23 Oct 2010 12:57:37 -0400 Subject: [PATCH 1/7] Added a PIL alpha_over extension in C, and code to setup.py to build it I needed a way to let py2exe options be provided only when py2exe is available. My solution (maybe not the best) was to put all the arguments for the final setup() call into a dictionary, that is filled in conditionally during the script's execution. This is why the file is completely changed; however, it still does what it used to do (when py2exe is available). --- .gitignore | 7 ++ _composite.c | 217 +++++++++++++++++++++++++++++++++++++++++++++++++++ setup.py | 77 +++++++++++++++--- 3 files changed, 290 insertions(+), 11 deletions(-) create mode 100644 _composite.c diff --git a/.gitignore b/.gitignore index 0d20b64..ec813ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,8 @@ *.pyc +build + +# various forms of compiled _composite extensions +_composite.so +_composite.pyd +_composite_d.pyd +_composite.dylib diff --git a/_composite.c b/_composite.c new file mode 100644 index 0000000..93c2c69 --- /dev/null +++ b/_composite.c @@ -0,0 +1,217 @@ +/* + * This file is part of the Minecraft Overviewer. + * + * Minecraft Overviewer is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published + * by the Free Software Foundation, either version 3 of the License, or (at + * your option) any later version. + * + * Minecraft Overviewer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with the Overviewer. If not, see . + */ + +/* + * This file implements a custom alpha_over function for (some) PIL + * images. It's designed to be used through composite.py, which + * includes a proxy alpha_over function that falls back to the default + * PIL paste if this extension is not found. + */ + +#include +#include + +/* like (a * b + 127) / 255), but much faster on most platforms + from PIL's _imaging.c */ +#define MULDIV255(a, b, tmp) \ + (tmp = (a) * (b) + 128, ((((tmp) >> 8) + (tmp)) >> 8)) + +typedef struct +{ + PyObject_HEAD + Imaging image; +} ImagingObject; + +static Imaging imaging_python_to_c(PyObject* obj) +{ + /* first, get the 'im' attribute */ + PyObject* im = PyObject_GetAttrString(obj, "im"); + if (!im) + return NULL; + + /* make sure 'im' is the right type */ + if (strcmp(im->ob_type->tp_name, "ImagingCore") != 0) + { + /* it's not -- raise an error and exit */ + PyErr_SetString(PyExc_TypeError, "image attribute 'im' is not a core Imaging type"); + return NULL; + } + + Imaging image = ((ImagingObject*)im)->image; + Py_DECREF(im); + return image; +} + +static PyObject* _composite_alpha_over(PyObject* self, PyObject* args) +{ + PyObject* dest, * src, * pos, * mask; + + if (!PyArg_ParseTuple(args, "OOOO", &dest, &src, &pos, &mask)) + return NULL; + + Imaging imDest = imaging_python_to_c(dest); + Imaging imSrc = imaging_python_to_c(src); + Imaging imMask = imaging_python_to_c(mask); + + if (!imDest || !imSrc || !imMask) + return NULL; + + /* check the various image modes, make sure they make sense */ + if (strcmp(imDest->mode, "RGBA") != 0) + { + PyErr_SetString(PyExc_ValueError, "given destination image does not have mode \"RGBA\""); + return NULL; + } + + if (strcmp(imSrc->mode, "RGBA") != 0 && strcmp(imSrc->mode, "RGB") != 0) + { + PyErr_SetString(PyExc_ValueError, "given source image does not have mode \"RGBA\" or \"RGB\""); + return NULL; + } + + if (strcmp(imMask->mode, "RGBA") != 0 && strcmp(imMask->mode, "L") != 0) + { + PyErr_SetString(PyExc_ValueError, "given mask image does not have mode \"RGBA\" or \"L\""); + return NULL; + } + + /* make sure mask size matches src size */ + if (imSrc->xsize != imMask->xsize || imSrc->ysize != imMask->ysize) + { + PyErr_SetString(PyExc_ValueError, "mask and source image sizes do not match"); + return NULL; + } + + /* set up flags for the src/mask type */ + int src_has_alpha = (imSrc->pixelsize == 4 ? 1 : 0); + /* how far into image the first alpha byte resides */ + int mask_offset = (imMask->pixelsize == 4 ? 3 : 0); + /* how many bytes to skip to get to the next alpha byte */ + int mask_stride = imMask->pixelsize; + + /* destination position read */ + int dx, dy, xsize, ysize; + if (!PyArg_ParseTuple(pos, "iiii", &dx, &dy, &xsize, &ysize)) + { + PyErr_SetString(PyExc_TypeError, "given blend destination rect is not valid"); + return NULL; + } + + /* set up the source position, size and destination position */ + int sx, sy; + + /* handle negative dest pos */ + if (dx < 0) + { + sx = -dx; + dx = 0; + } else { + sx = 0; + } + + if (dy < 0) + { + sy = -dy; + dy = 0; + } else { + sy = 0; + } + + /* set up source dimensions */ + xsize -= sx; + ysize -= sy; + + /* clip dimensions, if needed */ + if (dx + xsize > imDest->xsize) + xsize = imDest->xsize - dx; + if (dy + ysize > imDest->ysize) + ysize = imDest->ysize - dy; + + /* check that there remains any blending to be done */ + if (xsize <= 0 || ysize <= 0) + { + /* nothing to do, return */ + Py_INCREF(dest); + return dest; + } + + /* iteration variables */ + unsigned int x, y, i; + + /* temporary calculation variables */ + int tmp1, tmp2, tmp3; + + for (y = 0; y < ysize; y++) + { + UINT8* out = (UINT8*) imDest->image[dy + y] + dx*4; + UINT8* outmask = (UINT8*) imDest->image[dy + y] + dx*4 + 3; + UINT8* in = (UINT8*) imSrc->image[sy + y] + sx*(imSrc->pixelsize); + UINT8* inmask = (UINT8*) imMask->image[sy + y] + sx*mask_stride + mask_offset; + + for (x = 0; x < xsize; x++) + { + /* special cases */ + if (*inmask == 255 || *outmask == 0) + { + *outmask = *inmask; + + *out = *in; + out++, in++; + *out = *in; + out++, in++; + *out = *in; + out++, in++; + } else if (*inmask == 0) { + /* do nothing -- source is fully transparent */ + out += 3; + in += 3; + } else { + /* general case */ + int alpha = *inmask + MULDIV255(*outmask, 255 - *inmask, tmp1); + for (i = 0; i < 3; i++) + { + /* general case */ + *out = MULDIV255(*in, *inmask, tmp1) + MULDIV255(MULDIV255(*out, *outmask, tmp2), 255 - *inmask, tmp3); + *out = (*out * 255) / alpha; + out++, in++; + } + + *outmask = alpha; + } + + out++; + if (src_has_alpha) + in++; + outmask += 4; + inmask += mask_stride; + } + } + + Py_INCREF(dest); + return dest; +} + +static PyMethodDef _CompositeMethods[] = +{ + {"alpha_over", _composite_alpha_over, METH_VARARGS, "alpha over composite function"}, + {NULL, NULL, 0, NULL} +}; + +PyMODINIT_FUNC init_composite(void) +{ + (void) Py_InitModule("_composite", _CompositeMethods); +} diff --git a/setup.py b/setup.py index 49d1d22..95bba2a 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,68 @@ -from distutils.core import setup -import py2exe +from distutils.core import setup, Extension +from distutils.command.build import build +from distutils.command.clean import clean +from distutils.dir_util import remove_tree +from distutils import log +import os, os.path -setup(console=['gmap.py'], - data_files=[('textures', ['textures/lava.png', 'textures/water.png']), - ('', ['template.html'])], - zipfile = None, - options = {'py2exe': { - 'bundle_files': 1, - }}, +try: + import py2exe +except ImportError: + py2exe = None + +# now, setup the keyword arguments for setup +# (because we don't know until runtime if py2exe is available) +setup_kwargs = {} +setup_kwargs['options'] = {} +setup_kwargs['ext_modules'] = [] +setup_kwargs['cmdclass'] = {} + +# +# py2exe options +# + +if py2exe != None: + setup_kwargs['console'] = ['gmap.py'] + setup_kwargs['data_files'] = [('textures', ['textures/lava.png', 'textures/water.png']), + ('', ['template.html'])] + setup_kwargs['zipfile'] = None + setup_kwargs['options']['py2exe'] = {'bundle_files' : 1} + +# +# _composite.c extension +# + +setup_kwargs['ext_modules'].append(Extension('_composite', ['_composite.c'])) +# tell build_ext to build the extension in-place +# (NOT in build/) +setup_kwargs['options']['build_ext'] = {'inplace' : 1} +# tell the build command to only run build_ext +build.sub_commands = [('build_ext', None)] + +# custom clean command to remove in-place extension +class CustomClean(clean): + def run(self): + # do the normal cleanup + clean.run(self) - - ) + # try to remove '_composite.{so,pyd,...}' extension, + # regardless of the current system's extension name convention + build_ext = self.get_finalized_command('build_ext') + fname = build_ext.get_ext_fullpath('_composite') + pretty_fname = os.path.split(fname)[1] + if os.path.exists(fname): + try: + if not self.dry_run: + os.remove(fname) + log.info("removing '%s'", pretty_fname) + except OSError: + log.warn("'%s' could not be cleaned -- permission denied", + pretty_fname) + else: + log.debug("'%s' does not exist -- can't clean it", + pretty_fname) +setup_kwargs['cmdclass']['clean'] = CustomClean + +### + +setup(**setup_kwargs) From 8120bcd4559694f70629f30443df732e75b444b4 Mon Sep 17 00:00:00 2001 From: Aaron Griffith Date: Sat, 23 Oct 2010 13:09:19 -0400 Subject: [PATCH 2/7] added a wrapper for alpha_over that falls back on PIL paste() if needed --- composite.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 composite.py diff --git a/composite.py b/composite.py new file mode 100644 index 0000000..45719a9 --- /dev/null +++ b/composite.py @@ -0,0 +1,51 @@ +# This file is part of the Minecraft Overviewer. +# +# Minecraft Overviewer is free software: you can redistribute it and/or +# modify it under the terms of the GNU General Public License as published +# by the Free Software Foundation, either version 3 of the License, or (at +# your option) any later version. +# +# Minecraft Overviewer is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with the Overviewer. If not, see . + +import logging + +from PIL import Image + +""" +This module has an alpha-over function that is used throughout +Overviewer. It defaults to the PIL paste function when the custom +alpha-over extension cannot be found. +""" + +extension_alpha_over = None +try: + from _composite import alpha_over as _extension_alpha_over + extension_alpha_over = _extension_alpha_over +except ImportError: + logging.warning("alpha_over extension not found; using default PIL paste()") + +def alpha_over(dest, src, pos_or_rect=(0, 0), mask=None): + """Composite src over dest, using mask as the alpha channel (if + given), otherwise using src's alpha channel. pos_or_rect can + either be a position or a rectangle, specifying where on dest to + put src. Falls back to dest.paste() if the alpha_over extension + can't be found.""" + if mask == None: + mask = src + + global extension_alpha_over + if extension_alpha_over != None: + # extension ALWAYS expects rects, so convert if needed + if len(pos_or_rect) == 2: + pos_or_rect = (pos_or_rect[0], pos_or_rect[1], src.size[0], src.size[1]) + extension_alpha_over(dest, src, pos_or_rect, mask) + else: + # fallback + dest.paste(src, pos_or_rect, mask) + From 395e26ef9c0ab4b0bd976f401af3e2b3038010bc Mon Sep 17 00:00:00 2001 From: Aaron Griffith Date: Sat, 23 Oct 2010 13:36:55 -0400 Subject: [PATCH 3/7] changed most PIL paste() calls into composite.alpha_over() calls The ones I have not changed are those where paste() is really preferred, and I've noted why in comments. Calls to "dest.paste(src, rect, mask)" were converted to calls to "composite.alpha_over(dest, src, rect, mask)". --- chunk.py | 23 ++++++++++------ quadtree.py | 8 ++++-- textures.py | 79 +++++++++++++++++++++++++++-------------------------- 3 files changed, 61 insertions(+), 49 deletions(-) diff --git a/chunk.py b/chunk.py index aefcab7..5b8fea5 100644 --- a/chunk.py +++ b/chunk.py @@ -22,6 +22,7 @@ import logging import nbt import textures import world +import composite """ This module has routines related to rendering one particular chunk into an @@ -36,7 +37,11 @@ image # of the dest image will have its alpha channel modified. To prevent this: # first use im.split() and take the third item which is the alpha channel and # use that as the mask. Then take the image and use im.convert("RGB") to strip -# the image from its alpha channel, and use that as the source to paste() +# the image from its alpha channel, and use that as the source to alpha_over() + +# (note that this workaround is NOT technically needed when using the +# alpha_over extension, BUT this extension may fall back to PIL's +# paste(), which DOES need the workaround.) def get_lvldata(filename): """Takes a filename and returns the Level struct, which contains all the @@ -556,36 +561,36 @@ class ChunkRenderer(object): # tint the block with a color proportional to its depth if cave: # no lighting for cave -- depth is probably more useful - img.paste(Image.blend(t[0],depth_colors[z],0.3), (imgx, imgy), t[1]) + composite.alpha_over(img, Image.blend(t[0],depth_colors[z],0.3), (imgx, imgy), t[1]) else: if not self.world.lighting: # no lighting at all - img.paste(t[0], (imgx, imgy), t[1]) + composite.alpha_over(img, t[0], (imgx, imgy), t[1]) elif blockid in transparent_blocks: # transparent means draw the whole # block shaded with the current # block's light black_coeff, _ = self.get_lighting_coefficient(x, y, z) - img.paste(Image.blend(t[0], black_color, black_coeff), (imgx, imgy), t[1]) + composite.alpha_over(img, Image.blend(t[0], black_color, black_coeff), (imgx, imgy), t[1]) else: # draw each face lit appropriately, # but first just draw the block - img.paste(t[0], (imgx, imgy), t[1]) + composite.alpha_over(img, t[0], (imgx, imgy), t[1]) # top face black_coeff, face_occlude = self.get_lighting_coefficient(x, y, z + 1) if not face_occlude: - img.paste((0,0,0), (imgx, imgy), ImageEnhance.Brightness(facemasks[0]).enhance(black_coeff)) + composite.alpha_over(img, black_color, (imgx, imgy), ImageEnhance.Brightness(facemasks[0]).enhance(black_coeff)) # left face black_coeff, face_occlude = self.get_lighting_coefficient(x - 1, y, z) if not face_occlude: - img.paste((0,0,0), (imgx, imgy), ImageEnhance.Brightness(facemasks[1]).enhance(black_coeff)) + composite.alpha_over(img, black_color, (imgx, imgy), ImageEnhance.Brightness(facemasks[1]).enhance(black_coeff)) # right face black_coeff, face_occlude = self.get_lighting_coefficient(x, y + 1, z) if not face_occlude: - img.paste((0,0,0), (imgx, imgy), ImageEnhance.Brightness(facemasks[2]).enhance(black_coeff)) + composite.alpha_over(img, black_color, (imgx, imgy), ImageEnhance.Brightness(facemasks[2]).enhance(black_coeff)) # Draw edge lines if blockid in (44,): # step block @@ -616,6 +621,8 @@ def generate_facemasks(): toppart = textures.transform_image(white) leftpart = textures.transform_image_side(white) + # using the real PIL paste here (not alpha_over) because there is + # no alpha channel (and it's mode "L") top.paste(toppart, (0,0)) left.paste(leftpart, (0,6)) right = left.transpose(Image.FLIP_LEFT_RIGHT) diff --git a/quadtree.py b/quadtree.py index af4d15e..223deb2 100644 --- a/quadtree.py +++ b/quadtree.py @@ -29,6 +29,7 @@ import util from PIL import Image from optimizeimages import optimize_image +import composite """ @@ -449,7 +450,10 @@ def render_innertile(dest, name, imgformat, optimizeimg): # Create the actual image now img = Image.new("RGBA", (384, 384), (38,92,255,0)) - + + # we'll use paste (NOT alpha_over) for quadtree generation because + # this is just straight image stitching, not alpha blending + if q0path: try: quad0 = Image.open(q0path).resize((192,192), Image.ANTIALIAS) @@ -613,7 +617,7 @@ def render_worldtile(chunks, colstart, colend, rowstart, rowend, path, imgformat xpos = -192 + (col-colstart)*192 ypos = -96 + (row-rowstart)*96 - tileimg.paste(chunkimg.convert("RGB"), (xpos, ypos), chunkimg) + composite.alpha_over(tileimg, chunkimg.convert("RGB"), (xpos, ypos), chunkimg) # Save them tileimg.save(imgpath) diff --git a/textures.py b/textures.py index b942168..3f9a3bc 100644 --- a/textures.py +++ b/textures.py @@ -24,6 +24,7 @@ import numpy from PIL import Image, ImageEnhance import util +import composite def _find_file(filename, mode="rb"): """Searches for the given file and returns an open handle to it. @@ -157,13 +158,13 @@ def transform_image_side(img, blockID=None): # img to be unchanged mask = img.crop((0,8,16,16)) n = Image.new(img.mode, img.size, (38,92,255,0)) - n.paste(mask,(0,0,16,8), mask) + composite.alpha_over(n, mask,(0,0,16,8), mask) img = n if blockID in (78,): # snow # make the top three quarters transparent mask = img.crop((0,12,16,16)) n = Image.new(img.mode, img.size, (38,92,255,0)) - n.paste(mask,(0,12,16,16), mask) + composite.alpha_over(n, mask,(0,12,16,16), mask) img = n # Size of the cube side before shear @@ -189,7 +190,7 @@ def _build_block(top, side, blockID=None): top = transform_image(top, blockID) if not side: - img.paste(top, (0,0), top) + composite.alpha_over(img, top, (0,0), top) return img side = transform_image_side(side, blockID) @@ -212,29 +213,29 @@ def _build_block(top, side, blockID=None): if blockID in (37,38,6,39,40,50,83): ## flowers, sapling, mushrooms, regular torch, reeds # instead of pasting these blocks at the cube edges, place them in the middle: # and omit the top - img.paste(side, (6,3), side) - img.paste(otherside, (6,3), otherside) + composite.alpha_over(img, side, (6,3), side) + composite.alpha_over(img, otherside, (6,3), otherside) return img if blockID in (81,): # cacti! - img.paste(side, (2,6), side) - img.paste(otherside, (10,6), otherside) - img.paste(top, (0,2), top) + composite.alpha_over(img, side, (2,6), side) + composite.alpha_over(img, otherside, (10,6), otherside) + composite.alpha_over(img, top, (0,2), top) elif blockID in (44,): # half step # shift each texture down 6 pixels - img.paste(side, (0,12), side) - img.paste(otherside, (12,12), otherside) - img.paste(top, (0,6), top) + composite.alpha_over(img, side, (0,12), side) + composite.alpha_over(img, otherside, (12,12), otherside) + composite.alpha_over(img, top, (0,6), top) elif blockID in (78,): # snow # shift each texture down 9 pixels - img.paste(side, (0,6), side) - img.paste(otherside, (12,6), otherside) - img.paste(top, (0,9), top) + composite.alpha_over(img, side, (0,6), side) + composite.alpha_over(img, otherside, (12,6), otherside) + composite.alpha_over(img, top, (0,9), top) else: - img.paste(side, (0,6), side) - img.paste(otherside, (12,6), otherside) - img.paste(top, (0,0), top) + composite.alpha_over(img, side, (0,6), side) + composite.alpha_over(img, otherside, (12,6), otherside) + composite.alpha_over(img, top, (0,0), top) # Manually touch up 6 pixels that leave a gap because of how the # shearing works out. This makes the blocks perfectly tessellate-able @@ -366,7 +367,7 @@ def generate_special_texture(blockID, data): track = transform_image(raw_straight, blockID) img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(track, (0,12), track) + composite.alpha_over(img, track, (0,12), track) return (img.convert("RGB"), img.split()[3]) if blockID == 59: # crops @@ -376,9 +377,9 @@ def generate_special_texture(blockID, data): crop3 = crop2.transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(crop1, (0,12), crop1) - img.paste(crop2, (6,3), crop2) - img.paste(crop3, (6,3), crop3) + composite.alpha_over(img, crop1, (0,12), crop1) + composite.alpha_over(img, crop2, (6,3), crop2) + composite.alpha_over(img, crop3, (6,3), crop3) return (img.convert("RGB"), img.split()[3]) if blockID == 61: #furnace @@ -388,9 +389,9 @@ def generate_special_texture(blockID, data): img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(side1, (0,6), side1) - img.paste(side2, (12,6), side2) - img.paste(top, (0,0), top) + composite.alpha_over(img, side1, (0,6), side1) + composite.alpha_over(img, side2, (12,6), side2) + composite.alpha_over(img, top, (0,0), top) return (img.convert("RGB"), img.split()[3]) if blockID == 62: # lit furnace @@ -400,9 +401,9 @@ def generate_special_texture(blockID, data): img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(side1, (0,6), side1) - img.paste(side2, (12,6), side2) - img.paste(top, (0,0), top) + composite.alpha_over(img, side1, (0,6), side1) + composite.alpha_over(img, side2, (12,6), side2) + composite.alpha_over(img, top, (0,0), top) return (img.convert("RGB"), img.split()[3]) if blockID == 65: # ladder @@ -414,22 +415,22 @@ def generate_special_texture(blockID, data): # have to render this thing anyway. same for data == 2 tex = transform_image_side(raw_texture) img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(tex, (0,6), tex) + composite.alpha_over(img, tex, (0,6), tex) return (img.convert("RGB"), img.split()[3]) if data == 2: tex = transform_image_side(raw_texture).transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(tex, (12,6), tex) + composite.alpha_over(img, tex, (12,6), tex) return (img.convert("RGB"), img.split()[3]) if data == 3: tex = transform_image_side(raw_texture).transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(tex, (0,0), tex) + composite.alpha_over(img, tex, (0,0), tex) return (img.convert("RGB"), img.split()[3]) if data == 4: tex = transform_image_side(raw_texture) img = Image.new("RGBA", (24,24), (38,92,255,0)) - img.paste(tex, (12,0), tex) + composite.alpha_over(img, tex, (12,0), tex) return (img.convert("RGB"), img.split()[3]) if blockID in (64,71): #wooden door, or iron door @@ -450,36 +451,36 @@ def generate_special_texture(blockID, data): if (data & 0x03) == 0: if not swung: tex = transform_image_side(raw_door) - img.paste(tex, (0,6), tex) + composite.alpha_over(img, tex, (0,6), tex) else: # flip first to set the doornob on the correct side tex = transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) tex = tex.transpose(Image.FLIP_LEFT_RIGHT) - img.paste(tex, (0,0), tex) + composite.alpha_over(img, tex, (0,0), tex) if (data & 0x03) == 1: if not swung: tex = transform_image_side(raw_door).transpose(Image.FLIP_LEFT_RIGHT) - img.paste(tex, (0,0), tex) + composite.alpha_over(img, tex, (0,0), tex) else: tex = transform_image_side(raw_door) - img.paste(tex, (12,0), tex) + composite.alpha_over(img, tex, (12,0), tex) if (data & 0x03) == 2: if not swung: tex = transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) - img.paste(tex, (12,0), tex) + composite.alpha_over(img, tex, (12,0), tex) else: tex = transform_image_side(raw_door).transpose(Image.FLIP_LEFT_RIGHT) - img.paste(tex, (12,6), tex) + composite.alpha_over(img, tex, (12,6), tex) if (data & 0x03) == 3: if not swung: tex = transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)).transpose(Image.FLIP_LEFT_RIGHT) - img.paste(tex, (12,6), tex) + composite.alpha_over(img, tex, (12,6), tex) else: tex = transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) - img.paste(tex, (0,6), tex) + composite.alpha_over(img, tex, (0,6), tex) return (img.convert("RGB"), img.split()[3]) From d01244a7d808fc46b1ec5d8f15aee71f9d78c1c7 Mon Sep 17 00:00:00 2001 From: Aaron Griffith Date: Sat, 23 Oct 2010 18:30:03 -0400 Subject: [PATCH 4/7] added note to README about compiling the extension (marked optional) --- README.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.rst b/README.rst index c9df344..5e467b3 100644 --- a/README.rst +++ b/README.rst @@ -85,6 +85,21 @@ you can use the Overviewer: hidden directory). You can also get this file from any of the third party texture packs out there. +Compiling the C Extension (optional) +------------------------------------ +The C Extension for Overviewer is completely optional. It provides a higher +quality image compositing function that looks better on maps with lighting +enabled, and a slight performance boost. + +If you downloaded Overviewer as a binary package, this extension may be already +compiled for you. Overviewer emits a warning if the extension is not found, but +will still work fine. + +If you have a C compiler and the Python development libraries set up, you can +compile this extension like this:: + + python setup.py build + Running ------- To generate a set of Google Map tiles, use the gmap.py script like this:: From 8dfeccc141483c28a3369199cf600f79a5adf9d4 Mon Sep 17 00:00:00 2001 From: Alex Jurkiewicz Date: Tue, 26 Oct 2010 07:45:23 -0400 Subject: [PATCH 5/7] explicitly mentioning python headers in extension section in README --- README.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.rst b/README.rst index 5e467b3..b5989c6 100644 --- a/README.rst +++ b/README.rst @@ -100,6 +100,9 @@ compile this extension like this:: python setup.py build +Note that you need the development headers for your version of Python installed, +look for a package named 'python-dev', 'python-devel' or similar. + Running ------- To generate a set of Google Map tiles, use the gmap.py script like this:: From 169d5533607d11a80474128225199a8aa599bef8 Mon Sep 17 00:00:00 2001 From: Aaron Griffith Date: Tue, 26 Oct 2010 07:53:48 -0400 Subject: [PATCH 6/7] added note to README about missing Imaging.h on some platforms --- README.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index b5989c6..b459ec2 100644 --- a/README.rst +++ b/README.rst @@ -101,7 +101,11 @@ compile this extension like this:: python setup.py build Note that you need the development headers for your version of Python installed, -look for a package named 'python-dev', 'python-devel' or similar. +look for a package named 'python-dev', 'python-devel' or similar. Also, some +Python distributions do not install "Imaging.h" and "ImPlatform.h" properly. If +you get errors complaining about them, you can get them from the PIL source, or +at . Just put them in +the same directory as "_composite.c". Running ------- From 759a9663af679eb84be2dda2000f02315288c114 Mon Sep 17 00:00:00 2001 From: Aaron Griffith Date: Thu, 28 Oct 2010 16:56:10 -0400 Subject: [PATCH 7/7] shuffled around the code a bit to make it C89 compliant On my machine, the code now compiles with "-std=c89 -pedantic -Wall", with no warnings (except for those emitted by the Python headers, grr...) --- _composite.c | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/_composite.c b/_composite.c index 93c2c69..7ed9f71 100644 --- a/_composite.c +++ b/_composite.c @@ -38,8 +38,11 @@ typedef struct static Imaging imaging_python_to_c(PyObject* obj) { + PyObject* im; + Imaging image; + /* first, get the 'im' attribute */ - PyObject* im = PyObject_GetAttrString(obj, "im"); + im = PyObject_GetAttrString(obj, "im"); if (!im) return NULL; @@ -51,21 +54,34 @@ static Imaging imaging_python_to_c(PyObject* obj) return NULL; } - Imaging image = ((ImagingObject*)im)->image; + image = ((ImagingObject*)im)->image; Py_DECREF(im); return image; } static PyObject* _composite_alpha_over(PyObject* self, PyObject* args) { + /* raw input python variables */ PyObject* dest, * src, * pos, * mask; + /* libImaging handles */ + Imaging imDest, imSrc, imMask; + /* cached blend properties */ + int src_has_alpha, mask_offset, mask_stride; + /* destination position and size */ + int dx, dy, xsize, ysize; + /* source position */ + int sx, sy; + /* iteration variables */ + unsigned int x, y, i; + /* temporary calculation variables */ + int tmp1, tmp2, tmp3; if (!PyArg_ParseTuple(args, "OOOO", &dest, &src, &pos, &mask)) return NULL; - Imaging imDest = imaging_python_to_c(dest); - Imaging imSrc = imaging_python_to_c(src); - Imaging imMask = imaging_python_to_c(mask); + imDest = imaging_python_to_c(dest); + imSrc = imaging_python_to_c(src); + imMask = imaging_python_to_c(mask); if (!imDest || !imSrc || !imMask) return NULL; @@ -97,14 +113,13 @@ static PyObject* _composite_alpha_over(PyObject* self, PyObject* args) } /* set up flags for the src/mask type */ - int src_has_alpha = (imSrc->pixelsize == 4 ? 1 : 0); + src_has_alpha = (imSrc->pixelsize == 4 ? 1 : 0); /* how far into image the first alpha byte resides */ - int mask_offset = (imMask->pixelsize == 4 ? 3 : 0); + mask_offset = (imMask->pixelsize == 4 ? 3 : 0); /* how many bytes to skip to get to the next alpha byte */ - int mask_stride = imMask->pixelsize; + mask_stride = imMask->pixelsize; /* destination position read */ - int dx, dy, xsize, ysize; if (!PyArg_ParseTuple(pos, "iiii", &dx, &dy, &xsize, &ysize)) { PyErr_SetString(PyExc_TypeError, "given blend destination rect is not valid"); @@ -112,8 +127,6 @@ static PyObject* _composite_alpha_over(PyObject* self, PyObject* args) } /* set up the source position, size and destination position */ - int sx, sy; - /* handle negative dest pos */ if (dx < 0) { @@ -149,12 +162,6 @@ static PyObject* _composite_alpha_over(PyObject* self, PyObject* args) return dest; } - /* iteration variables */ - unsigned int x, y, i; - - /* temporary calculation variables */ - int tmp1, tmp2, tmp3; - for (y = 0; y < ysize; y++) { UINT8* out = (UINT8*) imDest->image[dy + y] + dx*4;