ref: cf8a6208b4418f811a94a6db8824a4d8bbd761d4
dir: /img.c/
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <memdraw.h>
#include "dat.h"
#include "fns.h"
extern Image *mapimage;
extern int tilesize;
extern Point drawoffset;
Image *green = nil;
ImageUpdated callbackfunc;
void
loadtile(GBundle b, Point pos)
{
Image *loaded;
int fd;
char file[32];
Rectangle r;
r = Rect(0, 0, 256, 256);
snprint(file, sizeof file, "/mnt/map/%d/%d/%d", b.z, b.x, b.y);
debugprint("loading file: %s\n", file);
fd = open(file, OREAD);
if (fd < 0) {
fprint(2, "unable to load tile %d/%d/%d: %r\n", b.z, b.x, b.y);
return;
}
loaded = readimage(display, fd, 0);
close(fd);
r = rectaddpt(r, pos);
lockmapimage();
draw(mapimage, r, loaded, nil, ZP);
if (debug) {
snprint(file, sizeof file, "%d / %d", b.x, b.y);
border(mapimage, rectaddpt(r, pos), 1, display->black, ZP);
string(mapimage, pos, display->black, ZP, font, file);
if (!green)
green = allocimage(display, Rect(0, 0, 1, 1), screen->chan, 1, DGreen);
border(mapimage, mapimage->r, 1, green, ZP);
}
unlockmapimage();
freeimage(loaded);
}
static void
collapsebundle(GBundle *b, int mod)
{
while (b->x < 0)
b->x += mod;
while (b->y < 0)
b->y += mod;
b->x = b->x % mod;
b->y = b->y % mod;
}
void
requestimage(GBundle from, ImageUpdated cb)
{
GBundle b;
int numx, numy, mod;
b.z = from.z;
callbackfunc = cb;
mod = 1;
for (int i = 0; i < b.z; i++)
mod *= 2;
lockmapimage();
if (!mapimage) {
unlockmapimage();
debugprint("cannot load tiles: no mapimage\n");
return;
}
numx = Dx(mapimage->r)/tilesize + 1;
numy = Dy(mapimage->r)/tilesize + 1;
unlockmapimage();
debugprint("loading tiles from %d/%d\n", from.x, from.y);
for (int x = 0; x < numx; x++) {
for (int y = 0; y < numy; y++) {
b.x = from.x + x;
b.y = from.y + y;
collapsebundle(&b, mod);
loadtile(b, Pt(
x * tilesize,
y * tilesize)
);
}
}
if (callbackfunc)
callbackfunc();
}