summaryrefslogtreecommitdiff
path: root/src/main.c
blob: a5f35145b72a2dfd51e124bd451ba31f3f9277dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <stdio.h>

#define TSIZE 8
#define RGB(r, g, b) (((r) << 11) | ((g) << 5) | (b))

static void
output_tile(const uint8_t *data, int x, int y, int w)
{
	for (int iy = 0; iy < TSIZE; iy += 1) {
		putchar('\t');
		for (int ix = 0; ix < TSIZE; ix += 1) {
			const int i = (ix + x + (iy + y) * w) * 3;
			const int v = RGB(data[i]/8, data[i+1]/4, data[i+2]/8);
			printf("%04x ", v);
		}
		putchar('\n');
	}
}

int
main(int argc, char **argv)
{
	if (argc != 1) {
		fprintf(stderr, "usage: %s < tileset.png\n", argv[0]);
		return 1;
	}

	/* Load image. */
	int w, h, chans;
	uint8_t *const data = stbi_load_from_file(stdin, &w, &h, &chans, 3);
	if (data == NULL) {
		fprintf(stderr, "stbi_load_from_file failed\n");
		return 1;
	}

	if (w % TSIZE || h % TSIZE) {
		fprintf(stderr, "invalid dimensions %dx%d, "
		                "expected dimensions divisible by %d\n",
		                w, h, TSIZE);
		goto panic;
	}
	if (chans != 3) {
		fprintf(stderr, "my lame utility only supports "
		                "images using 3 color channels, "
		                "yours has %d channels. too bad\n", chans);
		goto panic;
	}

	for (int y = 0; y < h; y += TSIZE)
		for (int x = 0; x < w; x += TSIZE)
			output_tile(data, x, y, w);

	stbi_image_free(data);
	return 0;
panic:
	stbi_image_free(data);
	return 0;
}