Small refactor in makeChunk

This commit is contained in:
Paul Mathieu 2021-12-11 17:34:52 -08:00
parent ce7f4f66c5
commit 5a334fec13

View File

@ -223,7 +223,7 @@ function makeTerrain(x, y) {
function makeChunk(x, y) {
const terrain = makeTerrain(x, y);
const chunk = new Uint8Array(16 * 16 * 256);
const data = new Uint8Array(16 * 16 * 256);
for (let i = 0; i < 16; i++) {
for (let j = 0; j < 16; j++) {
@ -233,19 +233,25 @@ function makeChunk(x, y) {
// everything below is dirt
const offset = i * (16 * 256) + j * 256;
const stoneHeight = Math.min(62, height);
chunk.set(Array(stoneHeight).fill(BlockType.STONE), offset);
data.set(Array(stoneHeight).fill(BlockType.STONE), offset);
if (stoneHeight < height) {
chunk.set(Array(height - 1 - stoneHeight).fill(BlockType.DIRT), offset + stoneHeight);
chunk[offset + height - 1] = BlockType.GRASS;
data.set(Array(height - 1 - stoneHeight).fill(BlockType.DIRT), offset + stoneHeight);
data[offset + height - 1] = BlockType.GRASS;
}
chunk.set(Array(256 - height).fill(BlockType.AIR), offset + height);
data.set(Array(256 - height).fill(BlockType.AIR), offset + height);
}
}
return chunk;
return {
position: {x, y},
data,
};
}
function makeChunkMesh(chunk, z0, x0) {
function makeChunkMesh(chunk) {
const {x: z0, y: x0} = chunk.position;
const {data} = chunk;
const blockPos = i => {
const x = Math.floor(i / (16 * 256));
const y = Math.floor((i - 16 * 258 * x) / 256);
@ -282,20 +288,20 @@ function makeChunkMesh(chunk, z0, x0) {
const bi = blockIndex(i, j, k);
const upTexture = (() => {
switch (chunk[bi - 1]) {
switch (data[bi - 1]) {
case BlockType.GRASS: return [0, 15];
case BlockType.DIRT: return [2, 15];
case BlockType.STONE: return [3, 15];
}
})();
if (chunk[bi] == BlockType.AIR) {
if (data[bi] == BlockType.AIR) {
faces.push(makeFace('+y', upTexture, [x0 + j, k - 0.5, z0 + i]));
break;
}
const sideTexture = (() => {
switch (chunk[bi]) {
switch (data[bi]) {
case BlockType.GRASS: return [1, 15];
case BlockType.DIRT: return [2, 15];
case BlockType.STONE: return [3, 15];
@ -303,7 +309,7 @@ function makeChunkMesh(chunk, z0, x0) {
})();
for ({ pos, dir } of sideNeighbors(i, j)) {
if (chunk[blockIndex(...pos, k)] == BlockType.AIR) {
if (data[blockIndex(...pos, k)] == BlockType.AIR) {
faces.push(makeFace(dir, sideTexture, faceDir(dir, x0 + j, k, z0 + i)));
}
}
@ -328,15 +334,14 @@ function makeChunkMesh(chunk, z0, x0) {
function makeWorldBuffers(gl) {
const chunkFaces = [].concat(
makeChunkMesh(makeChunk(0, -16), 0, -16),
makeChunkMesh(makeChunk(16, -16), 16, -16),
makeChunkMesh(makeChunk(0, 0), 0, 0),
makeChunkMesh(makeChunk(16, 0), 16, 0),
makeChunkMesh(makeChunk(16, 16), 16, 16),
makeChunkMesh(makeChunk(0, 16), 0, 16),
makeChunkMesh(makeChunk(0, -16)),
makeChunkMesh(makeChunk(16, -16)),
makeChunkMesh(makeChunk(0, 0)),
makeChunkMesh(makeChunk(16, 0)),
makeChunkMesh(makeChunk(16, 16)),
makeChunkMesh(makeChunk(0, 16)),
);
return makeBuffersFromFraces(gl, chunkFaces);
}