#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <stdint.h>
#include "tiles.h"
#include "image.h"
+static int matchtile(struct image *img, int toffs, int th);
+
int img2tiles(struct tilemap *tmap, struct image *img, int tw, int th, int dedup)
{
- int i, j, x, y, tx, ty, tileoffs, xtiles, ytiles, ntiles;
+ int i, j, x, y, tx, ty, tileoffs, xtiles, ytiles, ntiles, tileno, tid;
struct image orig;
unsigned int pix;
}
}
+ tileno = 0;
tileoffs = 0;
y = 0;
for(i=0; i<ytiles; i++) {
put_pixel(img, tx, ty + tileoffs, pix);
}
}
- tileoffs += th; /* destination Y offset, inc by th for every tile */
+
+ if(!dedup || (tid = matchtile(img, tileoffs, th)) == -1) {
+ tmap->map[tileno] = tileno;
+ tileoffs += th; /* destination Y offset, inc by th for every tile */
+ } else {
+ tmap->map[tileno] = tid;
+ }
+ tileno++;
x += tw;
}
y += th;
return 0;
}
-int dump_tilemap(struct tilemap *tmap, const char *fname)
+static int matchtile(struct image *img, int toffs, int th)
{
+ int i, tilesz;
+ int ntiles = toffs / th;
+ unsigned char *pa, *pb;
+
+ tilesz = img->pitch * th;
+ pa = (unsigned char*)img->pixels;
+ pb = (unsigned char*)img->pixels + toffs * tilesz;
+
+ for(i=0; i<ntiles; i++) {
+ if(memcmp(pa, pb, tilesz) == 0) {
+ return i;
+ }
+ pa += tilesz;
+ }
+
return -1;
}
+
+int dump_tilemap(struct tilemap *tmap, const char *fname)
+{
+ FILE *fp;
+ int i, sz = tmap->width * tmap->height;
+ uint16_t id;
+
+ if(sz <= 0) return -1;
+
+ if(!(fp = fopen(fname, "wb"))) {
+ fprintf(stderr, "dump_tilemap: failed to open %s for writing\n", fname);
+ return -1;
+ }
+
+ for(i=0; i<sz; i++) {
+ /* XXX dump in 16bit big endian for the megadrive */
+ id = (tmap->map[i] << 8) | (tmap->map[i] >> 8);
+ fwrite(&id, sizeof id, 1, fp);
+ }
+
+ fclose(fp);
+ return 0;
+}