118 lines
No EOL
2.4 KiB
C
118 lines
No EOL
2.4 KiB
C
#include "cubes.h"
|
|
#include "noise.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
struct chunk *chunks = NULL;
|
|
int lastI = 0;
|
|
int prevExists = 0;
|
|
|
|
struct chunk gen_chunk(int x, int y, int z, int ci, int h) {
|
|
|
|
struct chunk *chunks2 = chunks; // &chunks[CBUF_ALL * ci];
|
|
|
|
struct chunk chunk;
|
|
|
|
if (x < 0 || y < 0 || z < 0) {
|
|
chunk.exists = 0;
|
|
return chunk;
|
|
}
|
|
|
|
int cbuf2 = CHUNK_ALL; // CBUF_ALL * (CHUNK_DIAMETER_H + (MAX_R * 2));
|
|
|
|
int i, j;
|
|
int r = (h == 0);
|
|
|
|
h = h * 16;
|
|
|
|
for (j = 0; j < (r ? 16 : 1) && h; j++) {
|
|
i = (j + h + cbuf2) % cbuf2;
|
|
chunk = chunks2[i];
|
|
if (chunk.x == x && chunk.y == y && chunk.z == z && chunk.exists != 0) {
|
|
|
|
chunk.exists = i / 16;
|
|
if (chunk.exists == 0)
|
|
chunk.exists = 1;
|
|
return chunk;
|
|
}
|
|
}
|
|
|
|
// printf("fail\n");
|
|
for (j = 0; j < cbuf2; j += 16) {
|
|
i = (j + h + cbuf2) % cbuf2;
|
|
chunk = chunks2[i];
|
|
if (chunk.exists == 0) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
char fname[1024];
|
|
snprintf(fname, 1023, "./db/chunk_%i_%i_%i.dat", x, y, z);
|
|
|
|
FILE *fp = fopen(fname, "rb+");
|
|
|
|
int code = (fp) ? fread(&chunk, sizeof(struct chunk), 1, fp) : 0;
|
|
if (code != 0) {
|
|
fclose(fp);
|
|
fp = 0;
|
|
if (chunk.exists != 0) {
|
|
chunk.exists = i / 16;
|
|
if (chunk.exists == 0)
|
|
chunk.exists = 1;
|
|
return chunk;
|
|
}
|
|
}
|
|
if (!fp) {
|
|
fp = fopen(fname, "wb");
|
|
}
|
|
|
|
lastI = i;
|
|
|
|
chunk.exists = i / 16;
|
|
if (chunk.exists == 0)
|
|
chunk.exists = 1;
|
|
chunk.x = x;
|
|
chunk.y = y;
|
|
chunk.z = z;
|
|
|
|
int c = 0;
|
|
|
|
chunk = noise_chunk(chunk, x, y, z);
|
|
|
|
chunks2[i] = chunk;
|
|
|
|
if (!fp) {
|
|
return chunk;
|
|
}
|
|
|
|
fwrite(&chunk, sizeof(struct chunk), 1, fp);
|
|
fclose(fp);
|
|
|
|
return chunk;
|
|
}
|
|
|
|
void gen_init() {
|
|
if (chunks == NULL) {
|
|
chunks = calloc(CHUNK_ALL, sizeof(struct chunk));
|
|
}
|
|
}
|
|
|
|
void gen_free() { free(chunks); }
|
|
|
|
int gen_cube(int x, int y, int z, struct chunk dat, int ci) {
|
|
if (x < 0 || y < 0 || z < 0)
|
|
return 0;
|
|
|
|
if (dat.exists == 0 || dat.x != (x / CHUNK_LENGTH) ||
|
|
dat.y != (y / CHUNK_LENGTH) || dat.z != (z / CHUNK_LENGTH)) {
|
|
dat = gen_chunk((x / CHUNK_LENGTH), (y / CHUNK_LENGTH),
|
|
(z / CHUNK_LENGTH), ci, dat.exists);
|
|
prevExists = dat.exists;
|
|
}
|
|
|
|
int h = dat.blocks[(y % CHUNK_LENGTH) + (z % CHUNK_LENGTH) * CHUNK_LENGTH +
|
|
(x % CHUNK_LENGTH) * CHUNK_LENGTH * CHUNK_LENGTH];
|
|
|
|
return h;
|
|
} |