2011-05-31

Minecraft mapping – Diagnostic texture

(Part of a series on rendering a top-down Minecraft map.)

As we will soon see, terrain.png isn't great for diagnosing problems if something goes wrong. For one thing, it has lots of gaps, so if we accidentally get the wrong textures there's a good chance we'll just end up rendering blank space and not being able to figure out how our calculation is wrong. Also, many of the textures in it don't have an obvious orientation, so if we flip them or rotate them we might not notice. To avoid these problems, it's useful to make ourselves a diagnostic texture without these problems.

Rather than spend hours of tedious work in a paint package, we can do this programmatically with Pygame. On Ubuntu, Python 2.6 was already installed and I installed Pygame with:
sudo apt-get install python-pygame
We're making a 512×512 texture that's a 16×16 grid of 32×32 pixel squares. Each square has a number between 0 and 255 printed in the middle and a solid grey background with intensity equal to the value printed on it. In Pygame, you render text to a new surface and then blit that surface onto your target. Also note that we need to initialize Pygame before we do any font rendering. Other than that, there's not a lot to comment on here.
import pygame

def make_numbered_texture_atlas():
    surface = pygame.Surface((512,512))
    font = pygame.font.SysFont("arial",14,bold=True)
    for i in xrange(256):
        y = 15 - (i // 16)
        x = i % 16
        fg = (255,255,255) if i<=127 else (0,0,0)
        bg = (i,i,i)
        textimage = font.render(str(i), True, fg)
        w,h = textimage.get_size()
        surface.fill(bg, (32*x, 32*y, 32, 32))
        surface.blit(textimage, (32*x+16-w//2, 32*y+16-h//2))
    return surface

def main():
    pygame.init()
    pygame.image.save(
        make_numbered_texture_atlas(),
        "numbered_texture_atlas.png")

if __name__ == "__main__":
    main()
Next time we'll use PyOpenGL to render something on-screen.

No comments:

Post a Comment