65 lines
2.4 KiB
TypeScript
65 lines
2.4 KiB
TypeScript
import { System } from "$/common/ecs/mod.ts";
|
|
import { ClientWorld } from "../client_world.ts";
|
|
import { Position } from "../../common/components/position.ts";
|
|
import { CHUNK_SIZE } from "../components/dimension.ts";
|
|
import { PlayerComponent } from "$/client/player.ts";
|
|
|
|
export class WorldGenerationSystem extends System {
|
|
constructor() {
|
|
super();
|
|
}
|
|
|
|
update(world: ClientWorld, _delta: number): void {
|
|
const [player] = world.get_tag("player")!;
|
|
const position = player.get(Position)!;
|
|
const player_component = player.get(PlayerComponent)!;
|
|
const dimension = world.dimension;
|
|
|
|
const player_chunk_x = Math.floor(position.x / CHUNK_SIZE);
|
|
const player_chunk_z = Math.floor(position.z / CHUNK_SIZE);
|
|
|
|
// one extra ring gets generated so the edge of the render distance has neighbors to mesh against
|
|
const load_distance = player_component.render_distance + 1;
|
|
const out_of_range = (x: number, z: number) =>
|
|
Math.max(Math.abs(x - player_chunk_x), Math.abs(z - player_chunk_z)) > load_distance;
|
|
|
|
// collect first, deleting from the map while iterating it skips entries
|
|
const to_unload = [];
|
|
for (const chunk of dimension.chunks.values()) {
|
|
if (out_of_range(chunk.x, chunk.z)) {
|
|
to_unload.push(chunk);
|
|
}
|
|
}
|
|
for (const chunk of to_unload) {
|
|
dimension.unload_chunk(chunk.x, chunk.z);
|
|
}
|
|
for (const pending of [...dimension.pending_generation.values()]) {
|
|
if (out_of_range(pending.x, pending.z)) {
|
|
dimension.cancel_chunk_request(pending.x, pending.z);
|
|
}
|
|
}
|
|
|
|
// dont queue up the whole area at once, so walking somewhere new gets the close chunks first
|
|
const max_in_flight = dimension.workers.size * 2;
|
|
if (dimension.pending_generation.size >= max_in_flight) {
|
|
return;
|
|
}
|
|
|
|
const missing: { x: number; z: number; distance: number }[] = [];
|
|
for (let x = player_chunk_x - load_distance; x <= player_chunk_x + load_distance; x += 1) {
|
|
for (let z = player_chunk_z - load_distance; z <= player_chunk_z + load_distance; z += 1) {
|
|
if (!dimension.is_generated(x, z) && !dimension.is_generating(x, z)) {
|
|
const dx = x - player_chunk_x;
|
|
const dz = z - player_chunk_z;
|
|
missing.push({ x, z, distance: dx * dx + dz * dz });
|
|
}
|
|
}
|
|
}
|
|
missing.sort((a, b) => a.distance - b.distance);
|
|
|
|
for (const chunk of missing.slice(0, max_in_flight - dimension.pending_generation.size)) {
|
|
dimension.request_chunk(chunk.x, chunk.z);
|
|
}
|
|
}
|
|
}
|