1<?php
2/**
3 * @license   GPL 2 (http://www.gnu.org/licenses/gpl.html)
4 * @author    Andreas Gohr <andi@splitbrain.org>
5 */
6
7build_monster($_REQUEST['seed'], $_REQUEST['size']);
8
9/**
10 * Generates a monster for the given seed
11 * GDlib is required!
12 */
13function build_monster($seed='',$size='') {
14    // create 16 byte hash from seed
15    $hash = md5($seed);
16
17    // calculate part values from seed
18    $parts = array(
19        'legs' => _get_monster_part(substr($hash, 0, 2), 1, 5),
20        'hair' => _get_monster_part(substr($hash, 2, 2), 1, 5),
21        'arms' => _get_monster_part(substr($hash, 4, 2), 1, 5),
22        'body' => _get_monster_part(substr($hash, 6, 2), 1, 15),
23        'eyes' => _get_monster_part(substr($hash, 8, 2), 1, 15),
24        'mouth'=> _get_monster_part(substr($hash, 10, 2), 1, 10),
25    );
26
27    // create background
28    $monster = @imagecreatetruecolor(120, 120)
29        or die("GD image create failed");
30    $white   = imagecolorallocate($monster, 255, 255, 255);
31    imagefill($monster,0,0,$white);
32
33    // add parts
34    foreach($parts as $part => $num) {
35        $file = dirname(__FILE__).'/parts/'.$part.'_'.$num.'.png';
36
37        $im = @imagecreatefrompng($file);
38        if(!$im) die('Failed to load '.$file);
39        imageSaveAlpha($im, true);
40        imagecopy($monster,$im,0,0,0,0,120,120);
41        imagedestroy($im);
42
43        // color the body
44        if($part == 'body') {
45            $r = _get_monster_part(substr($hash, 0, 4), 20, 235);
46            $g = _get_monster_part(substr($hash, 4, 4), 20, 235);
47            $b = _get_monster_part(substr($hash, 8, 4), 20, 235);
48            $color = imagecolorallocate($monster, $r, $g, $b);
49            imagefill($monster,60,60,$color);
50        }
51    }
52
53    // restore random seed
54    if($seed) srand();
55
56    // resize if needed, then output
57    if($size && $size < 400) {
58        $out = @imagecreatetruecolor($size,$size)
59            or die("GD image create failed");
60        imagecopyresampled($out,$monster,0,0,0,0,$size,$size,120,120);
61        header ("Content-type: image/png");
62        imagepng($out);
63        imagedestroy($out);
64        imagedestroy($monster);
65    }else{
66        header ("Content-type: image/png");
67        imagepng($monster);
68        imagedestroy($monster);
69    }
70
71}
72
73function _get_monster_part($seed, $lower = 0, $upper = 255) {
74    return hexdec($seed) % ($upper - $lower) + $lower;
75}
76// vim:ts=4:sw=4:et:enc=utf-8:
77