8 static int matchtile(struct image *img, int toffs, int th);
10 int img2tiles(struct tilemap *tmap, struct image *img, int tw, int th, int dedup)
12 int i, j, x, y, tx, ty, tileoffs, xtiles, ytiles, ntiles, tileno, tid;
16 if(alloc_image(&orig, img->width, img->height, img->bpp) == -1) {
17 fprintf(stderr, "img2tiles: failed to allocate temporary image\n");
20 memcpy(orig.pixels, img->pixels, img->scansz * img->height);
22 xtiles = (img->width + tw - 1) / tw;
23 ytiles = (img->height + th - 1) / th;
24 ntiles = xtiles * ytiles;
27 img->height = ntiles * th;
28 img->pitch = img->scansz = tw * img->bpp / 8;
32 tmap->height = ytiles;
33 if(!(tmap->map = malloc(ntiles * sizeof *tmap->map))) {
34 fprintf(stderr, "failed to allocate tilemap\n");
43 for(i=0; i<ytiles; i++) {
45 for(j=0; j<xtiles; j++) {
46 for(ty=0; ty<th; ty++) {
47 for(tx=0; tx<tw; tx++) {
48 pix = get_pixel(&orig, x + tx, y + ty);
49 put_pixel(img, tx, ty + tileoffs, pix);
54 if((tid = matchtile(img, tileoffs, th)) == -1) {
56 tmap->map[tileno++] = tileoffs / th;
58 tileoffs += th; /* destination Y offset, inc by th for every tile */
61 tmap->map[tileno++] = tid;
65 tileoffs += th; /* destination Y offset, inc by th for every tile */
74 img->height = tileoffs;
81 static int matchtile(struct image *img, int toffs, int th)
84 int ntiles = toffs / th;
85 unsigned char *pa, *pb;
87 tilesz = img->pitch * th;
88 pa = (unsigned char*)img->pixels;
89 pb = (unsigned char*)img->pixels + toffs * img->pitch;
91 for(i=0; i<ntiles; i++) {
92 if(memcmp(pa, pb, tilesz) == 0) {
101 int dump_tilemap(struct tilemap *tmap, const char *fname)
104 int i, sz = tmap->width * tmap->height;
107 if(sz <= 0) return -1;
109 if(!(fp = fopen(fname, "wb"))) {
110 fprintf(stderr, "dump_tilemap: failed to open %s for writing\n", fname);
114 for(i=0; i<sz; i++) {
115 /* XXX dump in 16bit big endian for the megadrive */
116 id = (tmap->map[i] << 8) | (tmap->map[i] >> 8);
117 fwrite(&id, sizeof id, 1, fp);