This commit is contained in:
MihailRis 2026-11-12 22:39:40 +00:00 • committed by GitHub
commit 5e8803c40a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 348 additions and 302 deletions

View file

@ -24,7 +24,6 @@
#include "logic/PlayerController.hpp"
#include "logic/scripting/scripting.hpp"
#include "logic/scripting/scripting_hud.hpp"
#include "maths/voxmaths.hpp"
#include "objects/Players.hpp"
#include "objects/Entities.hpp"
#include "physics/Hitbox.hpp"
@ -257,8 +256,7 @@ void LevelScreen::update(float delta) {
updateHotkeys();
}
updateAudio();
auto menu = gui.getMenu();
bool inputLocked =
gui.getActiveFrame() || hud->isInventoryOpen() || gui.isFocusCaught();
bool paused = hud->isPause();
@ -284,7 +282,7 @@ void LevelScreen::update(float delta) {
renderer->update(camera, delta * !hud->isPause());
}
void LevelScreen::draw(float delta) {
void LevelScreen::draw(float) {
Camera& camera = *playerController->getPlayer().currentCamera;
const DrawContext ctx(nullptr, engine.getWindow(), batch.get());

View file

@ -310,11 +310,24 @@ void ChunksRenderer::drawChunks(
auto denseDistance2 = denseDistance * denseDistance;
// TODO: minimize draw calls number
for (int i = indices.size()-1; i >= 0; i--) {
for (int i = indices.size() - 1; i >= 0; i--) {
auto& chunk = chunks.getChunks()[indices[i].index];
if (chunk == nullptr) {
continue;
}
int cx = chunk->x;
int cz = chunk->z;
if (culling) {
glm::vec3 min(cx * CHUNK_W, chunk->bottom, cz * CHUNK_D);
glm::vec3 max(
cx * CHUNK_W + CHUNK_W, chunk->top, cz * CHUNK_D + CHUNK_D
);
if (!frustum.isBoxVisible(min, max)) {
continue;
}
}
auto found = meshes.find(glm::ivec2(chunk->x, chunk->z));
if (found == meshes.end()) {
continue;
@ -323,33 +336,19 @@ void ChunksRenderer::drawChunks(
if (mesh.mesh == nullptr) {
continue;
}
if (culling) {
const auto& meshAABB = mesh.meshAABB;
auto aabbMin = meshAABB.min();
auto aabbMax = meshAABB.max();
glm::vec3 min(
chunk->x * CHUNK_W + std::min(0.0f, aabbMin.x),
chunk->bottom,
chunk->z * CHUNK_D + std::min(0.0f, aabbMin.z)
);
glm::vec3 max(
chunk->x * CHUNK_W + aabbMax.x,
chunk->top,
chunk->z * CHUNK_D + aabbMax.z
);
if (!frustum.isBoxVisible(min, max)) {
continue;
}
}
glm::vec3 coord(
chunk->x * CHUNK_W + 0.5f, 0.5f, chunk->z * CHUNK_D + 0.5f
);
glm::mat4 model = glm::translate(glm::mat4(1.0f), coord);
shader.uniformMatrix("u_model", model);
mesh.mesh->draw(GL_TRIANGLES, glm::distance2(camera.position * glm::vec3(1, 0, 1),
(coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))) < denseDistance2);
mesh.mesh->draw(
GL_TRIANGLES,
glm::distance2(
camera.position * glm::vec3(1, 0, 1),
(coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))
) < denseDistance2
);
visibleChunks++;
}
}
@ -388,22 +387,23 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
if (chunk == nullptr || !chunk->flags.lighted) {
continue;
}
const auto& found = meshes.find(glm::ivec2(chunk->x, chunk->z));
if (found == meshes.end() || found->second.sortingMeshData.entries.empty()) {
continue;
}
int cx = chunk->x;
int cz = chunk->z;
if (culling) {
glm::vec3 min(chunk->x * CHUNK_W, chunk->bottom, chunk->z * CHUNK_D);
glm::vec3 min(cx * CHUNK_W, chunk->bottom, cz * CHUNK_D);
glm::vec3 max(
chunk->x * CHUNK_W + CHUNK_W,
chunk->top,
chunk->z * CHUNK_D + CHUNK_D
cx * CHUNK_W + CHUNK_W, chunk->top, cz * CHUNK_D + CHUNK_D
);
if (!frustum.isBoxVisible(min, max)) continue;
}
const auto& found = meshes.find(glm::ivec2(cx, cz));
if (found == meshes.end() || found->second.sortingMeshData.entries.empty()) {
continue;
}
auto& chunkEntries = found->second.sortingMeshData.entries;
if (chunkEntries.size() == 1) {

View file

@ -66,6 +66,7 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) {
builder.addSection("chunks");
builder.add("load-distance", &settings.chunks.loadDistance);
builder.add("load-speed", &settings.chunks.loadSpeed);
builder.add("update-distance", &settings.chunks.updateDistance);
builder.add("padding", &settings.chunks.padding);
builder.addSection("graphics");

View file

@ -4,9 +4,7 @@
#include "items/Inventories.hpp"
#include "items/Inventory.hpp"
#include "lighting/Lighting.hpp"
#include "maths/fastmaths.hpp"
#include "scripting/scripting.hpp"
#include "util/timeutil.hpp"
#include "voxels/Block.hpp"
#include "voxels/Chunk.hpp"
#include "voxels/Chunks.hpp"
@ -17,15 +15,19 @@
#include "objects/Player.hpp"
#include "objects/Players.hpp"
#include "util/random.hpp"
#include "settings.hpp"
#include <random>
static inline constexpr int CHUNK_RANDOM_TICK_SEGMENTS = 4;
BlocksController::BlocksController(const Level& level, Lighting* lighting)
BlocksController::BlocksController(
const Level& level, Lighting* lighting, const EngineSettings& settings
)
: level(level),
chunks(*level.chunks),
lighting(lighting),
settings(settings),
randTickClock(20, 3),
blocksTickClock(20, 3),
worldTickClock(20, 1) {
@ -189,6 +191,7 @@ void BlocksController::randomTick(
std::shuffle(randomPattern.begin(), randomPattern.end(), randomEngine);
}
int chunkRand = (chunk.x * 73856093) ^ (chunk.z * 19349663);
for (int s = 0; s < segments; s++) {
int repetions = 4;
for (int i = 0; i < repetions; i++) {
@ -196,7 +199,9 @@ void BlocksController::randomTick(
if (segmentY > chunk.top) {
break;
}
size_t index = randomPattern[(s * repetions + i + randomTickId) % randomPattern.size()];
size_t index = randomPattern
[(s * repetions + i + randomTickId + chunkRand) %
randomPattern.size()];
int bx = index % CHUNK_W;
int bz = (index / CHUNK_W) % CHUNK_D;
int by = (index / (CHUNK_W * CHUNK_D)) + segmentY;
@ -214,13 +219,23 @@ void BlocksController::randomTick(
}
}
static long long calc_chunk_distance2(
const glm::vec3& pos, const Chunk& chunk
) {
int dx = chunk.x - static_cast<int>(std::floor(pos.x / CHUNK_W));
int dz = chunk.z - static_cast<int>(std::floor(pos.z / CHUNK_D));
return dx * dx + dz * dz;
}
void BlocksController::randomTick(int tickid, int parts, uint padding) {
auto indices = level.content.getIndices();
int updateDistance = settings.chunks.updateDistance.get();
for (const auto& [pid, player] : *level.players) {
const auto& chunks = *player->chunks;
int width = chunks.getWidth();
int height = chunks.getHeight();
const auto& playerPos = player->getPosition();
for (uint z = padding; z < height - padding; z++) {
for (uint x = padding; x < width - padding; x++) {
@ -232,6 +247,10 @@ void BlocksController::randomTick(int tickid, int parts, uint padding) {
if (chunk == nullptr || !chunk->flags.ready) {
continue;
}
long long distance = calc_chunk_distance2(playerPos, *chunk);
if (distance > updateDistance * updateDistance) {
continue;
}
if (chunk->lastRandomTickId == randomTickId) {
continue;
}

View file

@ -15,6 +15,7 @@ class Chunks;
class Lighting;
class GlobalChunks;
class ContentIndices;
struct EngineSettings;
enum class BlockInteraction { step, destruction, placing };
@ -27,13 +28,16 @@ class BlocksController {
const Level& level;
GlobalChunks& chunks;
Lighting* lighting;
const EngineSettings& settings;
util::Clock randTickClock;
util::Clock blocksTickClock;
util::Clock worldTickClock;
std::vector<OnBlockInteraction> blockInteractionCallbacks;
uint64_t randomTickId = 0;
public:
BlocksController(const Level& level, Lighting* lighting);
BlocksController(
const Level& level, Lighting* lighting, const EngineSettings& settings
);
void updateSides(int x, int y, int z);
void updateSides(int x, int y, int z, int w, int h, int d);

View file

@ -1,5 +1,6 @@
#include "ChunksController.hpp"
#include <algorithm>
#include <limits.h>
#include <memory>
@ -8,7 +9,6 @@
#include "graphics/core/Mesh.hpp"
#include "lighting/Lighting.hpp"
#include "maths/voxmaths.hpp"
#include "util/timeutil.hpp"
#include "objects/Player.hpp"
#include "voxels/Block.hpp"
#include "voxels/Chunk.hpp"
@ -18,9 +18,16 @@
#include "world/LevelEvents.hpp"
#include "world/World.hpp"
#include "world/generator/WorldGenerator.hpp"
#include "debug/Logger.hpp"
const uint MAX_WORK_PER_FRAME = 128;
const uint MIN_SURROUNDING = 9;
const float WORK_UNITS_PER_SPEED_SECOND = 600.0f;
const float MAX_SECONDS_LIMIT = 0.25f;
const int CREATE_CHUNK_COST = 2;
const int BUILD_LIGHTS_COST = 4;
static debug::Logger logger("chunks-control");
ChunksController::ChunksController(Level& level)
: level(level),
@ -33,12 +40,13 @@ ChunksController::ChunksController(Level& level)
ChunksController::~ChunksController() = default;
void ChunksController::update(
int64_t maxDuration,
float delta,
int loadSpeed,
int loadDistance,
uint padding,
Player& player,
bool isLocalPlayer
) const {
) {
const auto& position = player.getPosition();
int centerX = floordiv<CHUNK_W>(glm::floor(position.x));
int centerY = floordiv<CHUNK_D>(glm::floor(position.z));
@ -50,18 +58,89 @@ void ChunksController::update(
return;
}
int64_t mcstotal = 0;
auto& chunks = *player.chunks;
auto& state = states[player.getId()];
syncState(state, chunks, padding);
for (uint i = 0; i < MAX_WORK_PER_FRAME; i++) {
timeutil::Timer timer;
if (loadVisible(player, padding, isLocalPlayer)) {
int64_t mcs = timer.stop();
if (mcstotal + mcs < maxDuration * 1000) {
mcstotal += mcs;
continue;
float rate = loadSpeed * WORK_UNITS_PER_SPEED_SECOND;
state.budget = std::min(
state.budget + rate * delta, rate * MAX_SECONDS_LIMIT
);
for (uint i = 0; i < MAX_WORK_PER_FRAME && state.budget > 0.0f; i++) {
int cost = loadVisible(state, player, isLocalPlayer);
if (cost == 0) {
state.budget = 0.0f;
break;
}
state.budget -= cost;
}
state.chunksCount = chunks.getChunksCount();
}
void ChunksController::syncState(
LoadingState& state, Chunks& chunks, uint padding
) const {
int sizeX = chunks.getWidth();
int sizeY = chunks.getHeight();
bool layoutChanged = state.width != sizeX || state.height != sizeY ||
state.padding != padding;
bool moved = state.offsetX != chunks.getOffsetX() ||
state.offsetZ != chunks.getOffsetY();
if (layoutChanged) {
state.width = sizeX;
state.height = sizeY;
state.padding = padding;
state.order.clear();
int pad = static_cast<int>(padding);
int minDistance = ((sizeX - pad * 2) / 2) * ((sizeY - pad * 2) / 2);
std::vector<std::pair<int, int>> cells;
for (int z = pad; z < sizeY - pad; z++) {
for (int x = pad; x < sizeX - pad; x++) {
int lx = x - sizeX / 2;
int lz = z - sizeY / 2;
int distance = lx * lx + lz * lz;
if (distance < minDistance) {
cells.emplace_back(distance, z * sizeX + x);
}
}
}
std::sort(cells.begin(), cells.end());
state.order.reserve(cells.size());
for (const auto& [_, index] : cells) {
state.order.push_back(index);
}
}
if (layoutChanged || moved) {
removeFarChunks(chunks);
state.offsetX = chunks.getOffsetX();
state.offsetZ = chunks.getOffsetY();
}
if (layoutChanged || moved || state.chunksCount != chunks.getChunksCount()) {
state.loadIndex = 0;
state.lightIndex = 0;
state.lightsDirty = true;
state.chunksCount = chunks.getChunksCount();
}
}
void ChunksController::removeFarChunks(Chunks& chunks) const {
int sizeX = chunks.getWidth();
int sizeY = chunks.getHeight();
int maxDistance = (sizeX / 2) * (sizeY / 2);
const auto& buffer = chunks.getChunks();
for (int z = 0; z < sizeY; z++) {
for (int x = 0; x < sizeX; x++) {
if (buffer[z * sizeX + x] == nullptr) {
continue;
}
int lx = x - sizeX / 2;
int lz = z - sizeY / 2;
if (lx * lx + lz * lz >= maxDistance) {
chunks.remove(x + chunks.getOffsetX(), z + chunks.getOffsetY());
}
}
break;
}
}
@ -81,68 +160,49 @@ bool ChunksController::isInLoadingZone(
return distance < minDistance;
}
bool ChunksController::loadVisible(
const Player& player, uint padding, bool isLocalPlayer
int ChunksController::loadVisible(
LoadingState& state, const Player& player, bool isLocalPlayer
) const {
auto& chunks = *player.chunks;
const auto& buffer = chunks.getChunks();
const auto& order = state.order;
while (state.loadIndex < order.size() &&
buffer[order[state.loadIndex]] != nullptr) {
state.loadIndex++;
}
if (isLocalPlayer && state.lightsDirty) {
while (state.lightIndex < state.loadIndex) {
const auto& chunk = buffer[order[state.lightIndex]];
if (chunk && chunk->flags.loaded && !chunk->flags.lighted) {
break;
}
state.lightIndex++;
}
for (size_t i = state.lightIndex; i < state.loadIndex; i++) {
const auto& chunk = buffer[order[i]];
if (chunk && chunk->flags.loaded && !chunk->flags.lighted &&
buildLights(player, chunk)) {
return BUILD_LIGHTS_COST;
}
}
state.lightsDirty = false;
}
if (state.loadIndex >= order.size() || !player.isLoadingChunks()) {
return 0;
}
int index = order[state.loadIndex];
int sizeX = chunks.getWidth();
int sizeY = chunks.getHeight();
int nearX = 0;
int nearZ = 0;
bool assigned = false;
int minDistance = ((sizeX - padding * 2) / 2) * ((sizeY - padding * 2) / 2);
int maxDistance = ((sizeX) / 2) * ((sizeY) / 2);
for (uint z = 0; z < sizeY; z++) {
for (uint x = 0; x < sizeX; x++) {
int index = z * sizeX + x;
int lx = x - sizeX / 2;
int lz = z - sizeY / 2;
int distance = (lx * lx + lz * lz);
auto& chunk = chunks.getChunks()[index];
if (chunk != nullptr) {
if (distance >= maxDistance) {
chunks.remove(
x + chunks.getOffsetX(), z + chunks.getOffsetY()
);
}
continue;
}
}
}
for (uint z = padding; z < sizeY - padding; z++) {
for (uint x = padding; x < sizeX - padding; x++) {
int index = z * sizeX + x;
int lx = x - sizeX / 2;
int lz = z - sizeY / 2;
int distance = (lx * lx + lz * lz);
auto& chunk = chunks.getChunks()[index];
if (chunk != nullptr) {
if (chunk->flags.loaded && !chunk->flags.lighted) {
if (isLocalPlayer && buildLights(player, chunk)) {
return true;
}
}
continue;
}
if (distance < minDistance) {
minDistance = distance;
nearX = x;
nearZ = z;
assigned = true;
}
}
}
const auto& chunk = chunks.getChunks()[nearZ * sizeX + nearX];
if (chunk != nullptr || !assigned || !player.isLoadingChunks()) {
return false;
}
int offsetX = chunks.getOffsetX();
int offsetY = chunks.getOffsetY();
createChunk(player, nearX + offsetX, nearZ + offsetY);
return true;
createChunk(
player,
index % sizeX + chunks.getOffsetX(),
index / sizeX + chunks.getOffsetY()
);
state.loadIndex++;
state.lightsDirty = true;
return CREATE_CHUNK_COST;
}
bool ChunksController::buildLights(

View file

@ -1,6 +1,8 @@
#pragma once
#include <memory>
#include <unordered_map>
#include <vector>
#include "typedefs.hpp"
@ -13,32 +15,58 @@ class WorldGenerator;
/// @brief ChunksController manages chunks dynamic loading/unloading
class ChunksController {
private:
Level& level;
std::unique_ptr<WorldGenerator> generator;
/// @brief Process one chunk: load it or calculate lights for it
bool loadVisible(const Player& player, uint padding, bool isLocalPlayer) const;
bool buildLights(const Player& player, const std::shared_ptr<Chunk>& chunk) const;
void createChunk(const Player& player, int x, int y) const;
public:
std::unique_ptr<Lighting> lighting;
ChunksController(Level& level);
~ChunksController();
/// @param maxDuration milliseconds reserved for chunks loading
/// @param delta frame time in seconds
/// @param loadSpeed chunks loading speed
void update(
int64_t maxDuration,
float delta,
int loadSpeed,
int loadDistance,
uint padding,
Player& player,
bool isLocalPlayer
) const;
);
bool isInLoadingZone(const Player& player, uint padding, int x, int z) const;
const WorldGenerator* getGenerator() const {
return generator.get();
}
private:
struct LoadingState {
int width = 0;
int height = 0;
uint padding = 0;
int offsetX = 0;
int offsetZ = 0;
size_t chunksCount = 0;
std::vector<int> order;
size_t loadIndex = 0;
size_t lightIndex = 0;
bool lightsDirty = true;
float budget = 0.0f;
};
Level& level;
std::unique_ptr<WorldGenerator> generator;
std::unordered_map<u64id_t, LoadingState> states;
void syncState(LoadingState& state, Chunks& chunks, uint padding) const;
void removeFarChunks(Chunks& chunks) const;
/// @brief Process one chunk: load it or calculate lights for it
/// @return work units spent, 0 if there is nothing to do
int loadVisible(
LoadingState& state, const Player& player, bool isLocalPlayer
) const;
bool buildLights(const Player& player, const std::shared_ptr<Chunk>& chunk) const;
void createChunk(const Player& player, int x, int y) const;
};

View file

@ -46,7 +46,7 @@ LevelController::LevelController(
);
}
blocks = std::make_unique<BlocksController>(
*level, chunks ? chunks->lighting.get() : nullptr
*level, chunks ? chunks->lighting.get() : nullptr, settings
);
scripting::on_world_load(this);
@ -63,7 +63,7 @@ LevelController::LevelController(
player->chunks->configure(
std::floor(position.x), std::floor(position.z), 1
);
chunks->update(16, 1, 0, *player, player.get() == clientPlayer);
chunks->update(1.0f, 16, 1, 0, *player, player.get() == clientPlayer);
if (player->chunks->get(
std::floor(position.x), 0, std::floor(position.z)
)) {
@ -89,6 +89,7 @@ void LevelController::update(float delta, bool pause) {
settings.chunks.loadDistance.get() + settings.chunks.padding.get()
);
chunks->update(
delta,
settings.chunks.loadSpeed.get(),
settings.chunks.loadDistance.get(),
settings.chunks.padding.get(),

View file

@ -28,102 +28,81 @@ private:
template <Planes a, Planes b, Planes c>
glm::vec3 intersection(const glm::vec3* crosses) const;
glm::vec4 m_planes[Count];
glm::vec3 m_points[8];
glm::vec4 planes[Count];
glm::vec3 points[8];
glm::vec3 minPoint;
glm::vec3 maxPoint;
};
inline void Frustum::update(glm::mat4 m) {
m = glm::transpose(m);
m_planes[Left] = m[3] + m[0];
m_planes[Right] = m[3] - m[0];
m_planes[Bottom] = m[3] + m[1];
m_planes[Top] = m[3] - m[1];
m_planes[Near] = m[3] + m[2];
m_planes[Far] = m[3] - m[2];
planes[Left] = m[3] + m[0];
planes[Right] = m[3] - m[0];
planes[Bottom] = m[3] + m[1];
planes[Top] = m[3] - m[1];
planes[Near] = m[3] + m[2];
planes[Far] = m[3] - m[2];
glm::vec3 crosses[Combinations] = {
glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Right])),
glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Bottom])),
glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Top])),
glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Near])),
glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Far])),
glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Bottom])),
glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Top])),
glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Near])),
glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Far])),
glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Top])),
glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Near])),
glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Far])),
glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Near])),
glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Far])),
glm::cross(glm::vec3(m_planes[Near]), glm::vec3(m_planes[Far]))};
glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Right])),
glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Bottom])),
glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Top])),
glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Near])),
glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Far])),
glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Bottom])),
glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Top])),
glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Near])),
glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Far])),
glm::cross(glm::vec3(planes[Bottom]), glm::vec3(planes[Top])),
glm::cross(glm::vec3(planes[Bottom]), glm::vec3(planes[Near])),
glm::cross(glm::vec3(planes[Bottom]), glm::vec3(planes[Far])),
glm::cross(glm::vec3(planes[Top]), glm::vec3(planes[Near])),
glm::cross(glm::vec3(planes[Top]), glm::vec3(planes[Far])),
glm::cross(glm::vec3(planes[Near]), glm::vec3(planes[Far]))};
m_points[0] = intersection<Left, Bottom, Near>(crosses);
m_points[1] = intersection<Left, Top, Near>(crosses);
m_points[2] = intersection<Right, Bottom, Near>(crosses);
m_points[3] = intersection<Right, Top, Near>(crosses);
m_points[4] = intersection<Left, Bottom, Far>(crosses);
m_points[5] = intersection<Left, Top, Far>(crosses);
m_points[6] = intersection<Right, Bottom, Far>(crosses);
m_points[7] = intersection<Right, Top, Far>(crosses);
points[0] = intersection<Left, Bottom, Near>(crosses);
points[1] = intersection<Left, Top, Near>(crosses);
points[2] = intersection<Right, Bottom, Near>(crosses);
points[3] = intersection<Right, Top, Near>(crosses);
points[4] = intersection<Left, Bottom, Far>(crosses);
points[5] = intersection<Left, Top, Far>(crosses);
points[6] = intersection<Right, Bottom, Far>(crosses);
points[7] = intersection<Right, Top, Far>(crosses);
minPoint = maxPoint = points[0];
for (int i = 1; i < 8; i++) {
minPoint = glm::min(minPoint, points[i]);
maxPoint = glm::max(maxPoint, points[i]);
}
}
inline bool Frustum::isBoxVisible(const glm::vec3& minp, const glm::vec3& maxp)
const {
// check box outside/inside of frustum
for (int i = 0; i < Count; i++) {
if ((glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, minp.z, 1.0f)) <
0.0) &&
(glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, minp.z, 1.0f)) <
0.0) &&
(glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, minp.z, 1.0f)) <
0.0) &&
(glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, minp.z, 1.0f)) <
0.0) &&
(glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, maxp.z, 1.0f)) <
0.0) &&
(glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, maxp.z, 1.0f)) <
0.0) &&
(glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, maxp.z, 1.0f)) <
0.0) &&
(glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, maxp.z, 1.0f)) <
0.0)) {
const glm::vec4& p = planes[i];
glm::vec3 v(
p.x > 0.0f ? maxp.x : minp.x,
p.y > 0.0f ? maxp.y : minp.y,
p.z > 0.0f ? maxp.z : minp.z
);
if (glm::dot(glm::vec3(p), v) + p.w < 0.0f) {
return false;
}
}
// check frustum outside/inside box
int out;
out = 0;
for (int i = 0; i < 8; i++) out += ((m_points[i].x > maxp.x) ? 1 : 0);
if (out == 8) return false;
out = 0;
for (int i = 0; i < 8; i++) out += ((m_points[i].x < minp.x) ? 1 : 0);
if (out == 8) return false;
out = 0;
for (int i = 0; i < 8; i++) out += ((m_points[i].y > maxp.y) ? 1 : 0);
if (out == 8) return false;
out = 0;
for (int i = 0; i < 8; i++) out += ((m_points[i].y < minp.y) ? 1 : 0);
if (out == 8) return false;
out = 0;
for (int i = 0; i < 8; i++) out += ((m_points[i].z > maxp.z) ? 1 : 0);
if (out == 8) return false;
out = 0;
for (int i = 0; i < 8; i++) out += ((m_points[i].z < minp.z) ? 1 : 0);
if (out == 8) return false;
return true;
return !(minPoint.x > maxp.x || maxPoint.x < minp.x ||
minPoint.y > maxp.y || maxPoint.y < minp.y ||
minPoint.z > maxp.z || maxPoint.z < minp.z);
}
template <Frustum::Planes a, Frustum::Planes b, Frustum::Planes c>
inline glm::vec3 Frustum::intersection(const glm::vec3* crosses) const {
float D = glm::dot(glm::vec3(m_planes[a]), crosses[ij2k<b, c>::k]);
float d = glm::dot(glm::vec3(planes[a]), crosses[ij2k<b, c>::k]);
glm::vec3 res = glm::mat3(
crosses[ij2k<b, c>::k],
-crosses[ij2k<a, c>::k],
crosses[ij2k<a, b>::k]
) *
glm::vec3(m_planes[a].w, m_planes[b].w, m_planes[c].w);
return res * (-1.0f / D);
glm::vec3(planes[a].w, planes[b].w, planes[c].w);
return res * (-1.0f / d);
}

View file

@ -45,6 +45,8 @@ struct ChunksSettings {
IntegerSetting loadSpeed {4, 1, 32};
/// @brief Radius of chunks loading zone (chunk is unit)
IntegerSetting loadDistance {22, 3, 80};
/// @brief Radius of chunks update zone (chunk is unit)
IntegerSetting updateDistance {22, 3, 80};
/// @brief Buffer zone where chunks are not unloading (chunk is unit)
IntegerSetting padding {2, 1, 8};
};

View file

@ -120,9 +120,14 @@ namespace util {
if (lx < 0 || ly < 0 || lx >= sizeX || ly >= sizeY) {
return;
}
auto& element = firstBuffer[ly * sizeX + lx];
if (element == T{}) {
return;
}
if (outCallback)
outCallback(x, y, firstBuffer[ly * sizeX + lx]);
firstBuffer[ly * sizeX + lx] = T{};
outCallback(x, y, element);
element = T{};
valuesCount--;
}
void setOutCallback(const OutCallback& callback) {

View file

@ -1,8 +1,5 @@
#include "WorldGenerator.hpp"
#include <cstring>
#include <algorithm>
#include "maths/util.hpp"
#include "content/Content.hpp"
#include "voxels/Block.hpp"
@ -15,6 +12,9 @@
#include "maths/util.hpp"
#include "debug/Logger.hpp"
#include <cstring>
#include <algorithm>
static debug::Logger logger("world-generator");
/// @brief Max number of biome parameters
@ -49,7 +49,7 @@ WorldGenerator::WorldGenerator(
if (prototypes.find({x, z}) != prototypes.end()) {
return;
}
prototypes[{x, z}] = generatePrototype(x, z);
prototypes[{x, z}] = generatePrototype();
});
surroundMap.setLevelCallback(def.wideStructsChunksRadius + 1,
[this](int const x, int const z) {
@ -144,9 +144,7 @@ static inline const Biome* choose_biome(
return chosenBiome;
}
std::unique_ptr<ChunkPrototype> WorldGenerator::generatePrototype(
int chunkX, int chunkZ
) {
std::unique_ptr<ChunkPrototype> WorldGenerator::generatePrototype() {
return std::make_unique<ChunkPrototype>();
}
@ -237,21 +235,24 @@ void WorldGenerator::placeBlock(const BlockPlacement& block, int priority) {
for (int cz = cza; cz <= czb; cz++) {
for (int cx = cxa; cx <= cxb; cx++) {
const auto& found = prototypes.find({cx, cz});
if (found != prototypes.end()) {
// position becomes relative to prototype chunk
glm::ivec3 rel = block.position - glm::ivec3(cx * CHUNK_W, 0, cz * CHUNK_D);
bool owner = (cx == floordiv<CHUNK_W>(block.position.x)) && (cz == floordiv<CHUNK_D>(block.position.z));
found->second->placements.emplace_back(priority, BlockPlacement{block.block, rel, block.rotation, !owner});
if (found == prototypes.end()) {
continue;
}
// position becomes relative to prototype chunk
glm::ivec3 rel =
block.position - glm::ivec3(cx * CHUNK_W, 0, cz * CHUNK_D);
bool owner = (cx == floordiv<CHUNK_W>(block.position.x)) &&
(cz == floordiv<CHUNK_D>(block.position.z));
found->second->placements.emplace_back(
priority,
BlockPlacement {block.block, rel, block.rotation, !owner}
);
}
}
}
void WorldGenerator::placeStructures(
const std::vector<Placement>& placements,
ChunkPrototype& prototype,
int chunkX,
int chunkZ
const std::vector<Placement>& placements, int chunkX, int chunkZ
) {
for (const auto& placement : placements) {
if (auto sp = std::get_if<StructurePlacement>(&placement.placement)) {
@ -278,7 +279,7 @@ void WorldGenerator::generateStructuresWide(
auto placements = def.script->placeStructuresWide(
{chunkX * CHUNK_W, chunkZ * CHUNK_D}, {CHUNK_W, CHUNK_D}, CHUNK_H
);
placeStructures(placements, prototype, chunkX, chunkZ);
placeStructures(placements, chunkX, chunkZ);
prototype.level = ChunkPrototypeLevel::WIDE_STRUCTS;
}
@ -296,7 +297,7 @@ void WorldGenerator::generateStructures(
{chunkX * CHUNK_W, chunkZ * CHUNK_D}, {CHUNK_W, CHUNK_D},
heightmap, CHUNK_H
);
placeStructures(placements, prototype, chunkX, chunkZ);
placeStructures(placements, chunkX, chunkZ);
util::PseudoRandom structsRand;
structsRand.setSeed(chunkX, chunkZ);
@ -405,12 +406,7 @@ void WorldGenerator::update(int centerX, int centerY, int loadDistance) {
}
void WorldGenerator::generatePlants(
const ChunkPrototype& prototype,
float* heights,
voxel* voxels,
int chunkX,
int chunkZ,
const Biome** biomes
float* heights, voxel* voxels, int chunkX, int chunkZ, const Biome** biomes
) {
const auto& indices = content.getIndices()->blocks;
util::PseudoRandom plantsRand;
@ -447,12 +443,7 @@ void WorldGenerator::generatePlants(
}
void WorldGenerator::generateLand(
const ChunkPrototype& prototype,
float* values,
voxel* voxels,
int chunkX,
int chunkZ,
const Biome** biomes
float* values, voxel* voxels, const Biome** biomes
) {
uint seaLevel = def.seaLevel;
for (uint z = 0; z < CHUNK_D; z++) {
@ -477,27 +468,13 @@ void WorldGenerator::generate(voxel* voxels, int chunkX, int chunkZ) {
const auto& prototype = requirePrototype(chunkX, chunkZ);
const auto values = prototype.heightmap->getValues();
uint seaLevel = def.seaLevel;
std::memset(voxels, 0, sizeof(voxel) * CHUNK_VOL);
const auto& biomes = prototype.biomes.get();
for (uint z = 0; z < CHUNK_D; z++) {
for (uint x = 0; x < CHUNK_W; x++) {
const Biome* biome = biomes[z * CHUNK_W + x];
int height = values[z * CHUNK_W + x] * CHUNK_H;
height = std::max(0, height);
const auto& groundLayers = biome->groundLayers;
const auto& seaLayers = biome->seaLayers;
generate_pole(seaLayers, seaLevel, height, seaLevel, voxels, x, z);
generate_pole(groundLayers, height, 0, seaLevel, voxels, x, z);
}
}
generateLand(values, voxels, biomes);
generatePlacements(prototype, voxels, chunkX, chunkZ);
generatePlants(prototype, values, voxels, chunkX, chunkZ, biomes);
generatePlants(values, voxels, chunkX, chunkZ, biomes);
[[maybe_unused]] const auto& indices = content.getIndices()->blocks;
for (uint i = 0; i < CHUNK_VOL; i++) {
@ -526,20 +503,17 @@ void WorldGenerator::generatePlacements(
);
for (const auto& placement : placements) {
if (auto structure = std::get_if<StructurePlacement>(&placement.placement)) {
generateStructure(prototype, *structure, voxels, chunkX, chunkZ);
generateStructure(*structure, voxels);
} else if (auto line = std::get_if<LinePlacement>(&placement.placement)) {
generateLine(prototype, *line, voxels, chunkX, chunkZ);
generateLine(*line, voxels, chunkX, chunkZ);
} else if (auto block = std::get_if<BlockPlacement>(&placement.placement)) {
generateBlock(prototype, *block, voxels, chunkX, chunkZ);
generateBlock(*block, voxels);
}
}
}
void WorldGenerator::generateStructure(
const ChunkPrototype& prototype,
const StructurePlacement& placement,
voxel* voxels,
int chunkX, int chunkZ
const StructurePlacement& placement, voxel* voxels
) {
if (placement.structure < 0 || placement.structure >= def.structures.size()) {
logger.error() << "invalid structure index " << placement.structure;
@ -577,10 +551,7 @@ void WorldGenerator::generateStructure(
}
void WorldGenerator::generateLine(
const ChunkPrototype& prototype,
const LinePlacement& line,
voxel* voxels,
int chunkX, int chunkZ
const LinePlacement& line, voxel* voxels, int chunkX, int chunkZ
) {
const auto& indices = content.getIndices()->blocks;
@ -610,26 +581,26 @@ void WorldGenerator::generateLine(
glm::ivec3 closest = util::closest_point_on_segment(
a, b, point
);
if (y > 0 &&
util::distance2(closest, point) <= radius * radius
) {
auto& voxel = voxels[vox_index(x, y, z)];
if (line.block != BLOCK_AIR) {
voxel = {line.block, {}};
continue;
}
if (!indices.require(voxel.id).replaceable) {
voxel = {line.block, {}};
}
auto& below = voxels[vox_index(x, y-1, z)];
glm::ivec3 closest2 = util::closest_point_on_segment(
a, b, {gx, y-1, gz}
);
if (util::distance2(closest2, {gx, y-1, gz}) > radius*radius) {
const auto& def = indices.require(below.id);
if (def.rt.surfaceReplacement != below.id) {
below = {def.rt.surfaceReplacement, {}};
}
if (y <= 0 || util::distance2(closest, point) > radius * radius) {
continue;
}
auto& voxel = voxels[vox_index(x, y, z)];
if (line.block != BLOCK_AIR) {
voxel = {line.block, {}};
continue;
}
if (!indices.require(voxel.id).replaceable) {
voxel = {line.block, {}};
}
auto& below = voxels[vox_index(x, y-1, z)];
glm::ivec3 closest2 = util::closest_point_on_segment(
a, b, {gx, y-1, gz}
);
if (util::distance2(closest2, {gx, y - 1, gz}) >
radius * radius) {
const auto& def = indices.require(below.id);
if (def.rt.surfaceReplacement != below.id) {
below = {def.rt.surfaceReplacement, {}};
}
}
}
@ -638,10 +609,7 @@ void WorldGenerator::generateLine(
}
void WorldGenerator::generateBlock(
const ChunkPrototype& prototype,
const BlockPlacement& placement,
voxel* voxels,
int chunkX, int chunkZ
const BlockPlacement& placement, voxel* voxels
) {
const auto& indices = content.getIndices()->blocks;
const auto& def = indices.require(placement.block);

View file

@ -59,9 +59,7 @@ class WorldGenerator {
SurroundMap surroundMap;
/// @brief Generate chunk prototype (see ChunkPrototype)
/// @param x chunk position X divided by CHUNK_W
/// @param z chunk position Y divided by CHUNK_D
std::unique_ptr<ChunkPrototype> generatePrototype(int x, int z);
std::unique_ptr<ChunkPrototype> generatePrototype();
ChunkPrototype& requirePrototype(int x, int z);
@ -85,25 +83,13 @@ class WorldGenerator {
const ChunkPrototype& prototype, voxel* voxels, int x, int z
);
void generateLine(
const ChunkPrototype& prototype,
const LinePlacement& placement,
voxel* voxels,
int x, int z
);
void generateBlock(
const ChunkPrototype& prototype,
const BlockPlacement& placement,
voxel* voxels,
int x, int z
);
void generateStructure(
const ChunkPrototype& prototype,
const StructurePlacement& placement,
voxel* voxels,
int x, int z
);
void generateBlock(const BlockPlacement& placement, voxel* voxels);
void generateStructure(const StructurePlacement& placement, voxel* voxels);
void generatePlants(
const ChunkPrototype& prototype,
float* values,
voxel* voxels,
int x,
@ -111,18 +97,13 @@ class WorldGenerator {
const Biome** biomes
);
void generateLand(
const ChunkPrototype& prototype,
float* values,
voxel* voxels,
int x,
int z,
const Biome** biomes
);
void placeStructures(
const std::vector<Placement>& placements,
ChunkPrototype& prototype,
int x, int z
const std::vector<Placement>& placements, int x, int z
);
public:
WorldGenerator(