render the world relative to an origin near the camera

World coordinates were passed to GPU as floats: u_model of a chunk and
of a model had the world translation, vertices of translucent blocks,
particles, precipitation, block wrappers, lines and 3D texts were built
in the world space, and the camera position was subtracted in shaders.
The float step grows with the distance from the world origin (6 cm at
1M blocks, 2 m at 30M): blocks got skewed, then stuck together.

Camera::getOrigin() is an integer point near the camera (X and Z are
rounded to 1024 blocks, Y is 0). Camera::getView() is relative to it,
and every position passed to GPU is "world - origin" calculated on CPU,
so the shaders keep working with small numbers and do not change:
u_cameraPos, a_modelpos, u_inverseView and the shadows matrices are in
the same space as before, shifted by the origin. Matrices of a shadow
map are converted from the origin of its camera to the origin of the
player camera. The clouds shader gets the origin wrapped by the period
of its waves, the waves stay bound to the world.

Vertices of translucent blocks are local to the chunk now, as vertices
of opaque ones, and drawn with u_model of the chunk.
This commit is contained in:
ostermine 2026-11-12 00:48:30 +03:00
parent e1f6daabb7
commit 89bdadd6aa
30 changed files with 283 additions and 127 deletions

View file

@ -55,3 +55,9 @@ for i = 0, 63 do
end end
gfx.posteffects.set_array(slot, "u_arrayName", Bytearray_as_string(buffer)) gfx.posteffects.set_array(slot, "u_arrayName", Bytearray_as_string(buffer))
``` ```
## Coordinates in shaders
World-space values available in shaders (`u_cameraPos`, `u_view`, `u_inverseView`, positions of vertices and models) are relative to the rendering origin, not to the world origin. The rendering origin is an integer point near the camera: its X and Z are multiples of 1024 blocks, Y is 0. This keeps `float` precise far from the world origin.
Directions, distances and positions relative to the camera do not depend on the rendering origin. Neither does an effect bound to the blocks grid or repeating with a period that divides 1024.

View file

@ -55,3 +55,9 @@ for i = 0, 63 do
end end
gfx.posteffects.set_array(slot, "u_имяМассива", Bytearray_as_string(buffer)) gfx.posteffects.set_array(slot, "u_имяМассива", Bytearray_as_string(buffer))
``` ```
## Координаты в шейдерах
Значения в мировом пространстве, доступные в шейдерах (`u_cameraPos`, `u_view`, `u_inverseView`, позиции вершин и моделей), заданы относительно начала координат рендера, а не начала координат мира. Начало координат рендера - целочисленная точка рядом с камерой: X и Z кратны 1024 блокам, Y равен 0. Так `float` сохраняет точность вдали от начала координат мира.
Направления, расстояния и позиции относительно камеры от начала координат рендера не зависят. Не зависит и эффект, привязанный к сетке блоков или повторяющийся с периодом, на который делится 1024.

View file

@ -11,14 +11,17 @@ layout (location = 3) in vec4 v_normal;
#include <sky> #include <sky>
uniform float u_dayTime; uniform float u_dayTime;
uniform vec2 u_waveOffset;
out vec4 a_torchLight; out vec4 a_torchLight;
void main() { void main() {
a_modelpos = u_model * vec4(v_position, 1.0f); a_modelpos = u_model * vec4(v_position, 1.0f);
a_modelpos.xz += u_waveOffset;
a_modelpos.x += sin(u_timer * 0.05 + a_modelpos.z * 0.002) * 1.5; a_modelpos.x += sin(u_timer * 0.05 + a_modelpos.z * 0.002) * 1.5;
a_modelpos.z += sin(u_timer * 0.2 + a_modelpos.x * 0.002) * 1.5; a_modelpos.z += sin(u_timer * 0.2 + a_modelpos.x * 0.002) * 1.5;
a_modelpos.y += sin(u_timer * 0.1 + (a_modelpos.x + a_modelpos.z) * 0.001) * 2.0; a_modelpos.y += sin(u_timer * 0.1 + (a_modelpos.x + a_modelpos.z) * 0.001) * 2.0;
a_modelpos.xz -= u_waveOffset;
vec3 pos3d = a_modelpos.xyz - u_cameraPos; vec3 pos3d = a_modelpos.xyz - u_cameraPos;

View file

@ -8,6 +8,7 @@
#include "data/dv_util.hpp" #include "data/dv_util.hpp"
#include "graphics/commons/Model.hpp" #include "graphics/commons/Model.hpp"
#include "graphics/render/ModelBatch.hpp" #include "graphics/render/ModelBatch.hpp"
#include "maths/util.hpp"
using namespace rigging; using namespace rigging;
@ -160,13 +161,15 @@ void SkeletonConfig::update(
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const glm::vec3& position,
const glm::vec3& scale const glm::vec3& scale,
const glm::ivec3& origin
) const { ) const {
glm::vec3 pos = position; glm::vec3 pos = position;
const auto& interpolation = skeleton.interpolation; const auto& interpolation = skeleton.interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) { if (interpolation.isEnabled() && interpolation.isRefreshed()) {
pos = interpolation.getCurrent(); pos = interpolation.getCurrent();
} }
pos = util::to_local(pos, origin);
glm::mat3 rot = rotation; glm::mat3 rot = rotation;
const auto& rotationInterpolation = skeleton.rotationInterpolation; const auto& rotationInterpolation = skeleton.rotationInterpolation;
if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) { if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) {
@ -253,18 +256,25 @@ void SkeletonConfig::render(
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const glm::vec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin,
bool translucent bool translucent
) const { ) const {
if (skeleton.config->root == nullptr) { if (skeleton.config->root == nullptr) {
return; return;
} }
update(skeleton, rotation, position, scale); update(skeleton, rotation, position, scale, origin);
if (!skeleton.visible) { if (!skeleton.visible) {
return; return;
} }
processModels( processModels(
assets, skeleton, position, scale, &batch, lightingMode, translucent assets,
skeleton,
util::to_local(position, origin),
scale,
&batch,
lightingMode,
translucent
); );
} }
@ -273,16 +283,17 @@ void SkeletonConfig::updateBounds(
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const glm::vec3& position,
const glm::vec3& scale const glm::vec3& scale,
const glm::ivec3& origin
) const { ) const {
if (skeleton.config->root == nullptr) { if (skeleton.config->root == nullptr) {
return; return;
} }
update(skeleton, rotation, position, scale); update(skeleton, rotation, position, scale, origin);
processModels( processModels(
assets, assets,
skeleton, skeleton,
position, util::to_local(position, origin),
scale, scale,
nullptr, nullptr,
ModelLightingMode::SOLID, ModelLightingMode::SOLID,

View file

@ -152,7 +152,8 @@ namespace rigging {
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const glm::vec3& position,
const glm::vec3& scale const glm::vec3& scale,
const glm::ivec3& origin
) const; ) const;
void render( void render(
@ -163,6 +164,7 @@ namespace rigging {
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const glm::vec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin,
bool translucent = false bool translucent = false
) const; ) const;
@ -171,7 +173,8 @@ namespace rigging {
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const glm::vec3& position,
const glm::vec3& scale const glm::vec3& scale,
const glm::ivec3& origin
) const; ) const;
Skeleton instance() const { Skeleton instance() const {

View file

@ -109,7 +109,7 @@ void PostProcessing::configureEffect(
shader.uniform1i("u_noise", TARGET_SSAO); // used in SSAO pass shader.uniform1i("u_noise", TARGET_SSAO); // used in SSAO pass
shader.uniform1i("u_ssao", TARGET_SSAO); shader.uniform1i("u_ssao", TARGET_SSAO);
shader.uniform2i("u_screenSize", viewport / downsample); shader.uniform2i("u_screenSize", viewport / downsample);
shader.uniform3f("u_cameraPos", camera.position); shader.uniform3f("u_cameraPos", camera.getLocalPosition());
shader.uniform1f("u_timer", timer); shader.uniform1f("u_timer", timer);
shader.uniformMatrix("u_projection", camera.getProjection()); shader.uniformMatrix("u_projection", camera.getProjection());
const auto view = camera.getView(); const auto view = camera.getView();

View file

@ -95,7 +95,17 @@ void Shadows::setQuality(int quality) {
this->quality = quality; this->quality = quality;
} }
void Shadows::setup(Shader& shader, const Weather& weather) { static glm::mat4 calc_shadows_matrix(
const Camera& shadowCamera, const glm::ivec3& origin
) {
return glm::translate(
shadowCamera.getProjView(), glm::vec3(origin - shadowCamera.getOrigin())
);
}
void Shadows::setup(
Shader& shader, const Camera& camera, const Weather& weather
) {
if (!shadows) { if (!shadows) {
return; return;
} }
@ -106,8 +116,13 @@ void Shadows::setup(Shader& shader, const Weather& weather) {
glm::mod((worldInfo.daytime + 0.5f) * 2.0f, 1.0f) * 2.0f - 1.0f glm::mod((worldInfo.daytime + 0.5f) * 2.0f, 1.0f) * 2.0f - 1.0f
)); ));
shader.uniform1i("u_screen", 0); shader.uniform1i("u_screen", 0);
shader.uniformMatrix("u_shadowsMatrix[0]", shadowCamera.getProjView()); const glm::ivec3 origin = camera.getOrigin();
shader.uniformMatrix("u_shadowsMatrix[1]", wideShadowCamera.getProjView()); shader.uniformMatrix(
"u_shadowsMatrix[0]", calc_shadows_matrix(shadowCamera, origin)
);
shader.uniformMatrix(
"u_shadowsMatrix[1]", calc_shadows_matrix(wideShadowCamera, origin)
);
shader.uniform3f("u_sunDir", shadowCamera.front); shader.uniform3f("u_sunDir", shadowCamera.front);
shader.uniform1i("u_shadowsRes", shadowMap->getResolution()); shader.uniform1i("u_shadowsRes", shadowMap->getResolution());
shader.uniform1f("u_shadowsOpacity", shadowsOpacity); // TODO: make it configurable shader.uniform1f("u_shadowsOpacity", shadowsOpacity); // TODO: make it configurable
@ -197,7 +212,7 @@ void Shadows::generateShadowsMap(
auto view = shadowCamera.getView(); auto view = shadowCamera.getView();
auto currentPos = shadowCamera.position; auto currentPos = shadowCamera.getLocalPosition();
auto topRight = shadowCamera.right + shadowCamera.up; auto topRight = shadowCamera.right + shadowCamera.up;
auto min = view * glm::vec4(currentPos - topRight * shadowMapSize * 0.5f, 1.0f); auto min = view * glm::vec4(currentPos - topRight * shadowMapSize * 0.5f, 1.0f);
auto max = view * glm::vec4(currentPos + topRight * shadowMapSize * 0.5f, 1.0f); auto max = view * glm::vec4(currentPos + topRight * shadowMapSize * 0.5f, 1.0f);

View file

@ -19,7 +19,7 @@ public:
Shadows(const Level& level); Shadows(const Level& level);
~Shadows(); ~Shadows();
void setup(Shader& shader, const Weather& weather); void setup(Shader& shader, const Camera& camera, const Weather& weather);
void setQuality(int quality); void setQuality(int quality);
void refresh( void refresh(
const Camera& camera, const Camera& camera,

View file

@ -10,6 +10,7 @@
#include "lighting/Lightmap.hpp" #include "lighting/Lightmap.hpp"
#include "voxels/Block.hpp" #include "voxels/Block.hpp"
#include "voxels/Chunks.hpp" #include "voxels/Chunks.hpp"
#include "window/Camera.hpp"
#include <algorithm> #include <algorithm>
@ -24,7 +25,9 @@ BlockWrapsRenderer::BlockWrapsRenderer(
BlockWrapsRenderer::~BlockWrapsRenderer() = default; BlockWrapsRenderer::~BlockWrapsRenderer() = default;
void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) { void BlockWrapsRenderer::draw(
BlockWrapper& wrapper, const Texture* texture, const glm::ivec3& origin
) {
if (wrapper.cullingBits == 0x0) { if (wrapper.cullingBits == 0x0) {
return; return;
} }
@ -60,7 +63,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) {
switch (wrapper.modelType) { switch (wrapper.modelType) {
case BlockModelType::BLOCK: case BlockModelType::BLOCK:
batch->cube( batch->cube(
glm::vec3(wrapper.position) + glm::vec3(0.5f), glm::vec3(wrapper.position - origin) + glm::vec3(0.5f),
glm::vec3(1.01f), glm::vec3(1.01f),
wrapper.uvRegions, wrapper.uvRegions,
light, light,
@ -73,7 +76,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) {
const auto& aabb = def.getHitboxes(vox->state).at(0); const auto& aabb = def.getHitboxes(vox->state).at(0);
const auto& size = aabb.size(); const auto& size = aabb.size();
batch->cube( batch->cube(
glm::vec3(wrapper.position) + aabb.center(), glm::vec3(wrapper.position - origin) + aabb.center(),
size * glm::vec3(1.01f), size * glm::vec3(1.01f),
wrapper.uvRegions, wrapper.uvRegions,
light, light,
@ -134,8 +137,9 @@ void BlockWrapsRenderer::refreshWrapper(BlockWrapper& wrapper) {
} }
} }
void BlockWrapsRenderer::draw(const DrawContext& pctx) { void BlockWrapsRenderer::draw(const DrawContext& pctx, const Camera& camera) {
auto ctx = pctx.sub(); auto ctx = pctx.sub();
const glm::ivec3 origin = camera.getOrigin();
auto& shader = assets.require<Shader>("entity"); auto& shader = assets.require<Shader>("entity");
shader.use(); shader.use();
@ -151,7 +155,7 @@ void BlockWrapsRenderer::draw(const DrawContext& pctx) {
} }
for (const auto& [texture, wrapper] : renderOrder) { for (const auto& [texture, wrapper] : renderOrder) {
batch->setTexture(texture); batch->setTexture(texture);
draw(*wrapper, texture); draw(*wrapper, texture, origin);
} }
batch->flush(); batch->flush();
} }

View file

@ -12,6 +12,7 @@
#include <map> #include <map>
class Assets; class Assets;
class Camera;
class Content; class Content;
class Chunks; class Chunks;
class Texture; class Texture;
@ -41,7 +42,9 @@ class BlockWrapsRenderer {
std::unordered_map<u64id_t, std::unique_ptr<BlockWrapper>> wrappers; std::unordered_map<u64id_t, std::unique_ptr<BlockWrapper>> wrappers;
u64id_t nextWrapper = 1; u64id_t nextWrapper = 1;
void draw(BlockWrapper& wrapper, const Texture* texture); void draw(
BlockWrapper& wrapper, const Texture* texture, const glm::ivec3& origin
);
void refreshWrapper(BlockWrapper& wrapper); void refreshWrapper(BlockWrapper& wrapper);
void clearOrder(const BlockWrapper* const wrapper); void clearOrder(const BlockWrapper* const wrapper);
@ -51,7 +54,7 @@ public:
); );
~BlockWrapsRenderer(); ~BlockWrapsRenderer();
void draw(const DrawContext& ctx); void draw(const DrawContext& ctx, const Camera& camera);
u64id_t add( u64id_t add(
const glm::ivec3& position, const glm::ivec3& position,

View file

@ -637,12 +637,7 @@ SortingMeshData BlocksRenderer::renderTranslucent(
continue; continue;
} }
SortingMeshEntry entry { SortingMeshEntry entry {
glm::vec3( glm::vec3(x, y, z), util::Buffer<ChunkVertex>(indexCount), 0};
x + chunk->x * CHUNK_W + 0.5f,
y + 0.5f,
z + chunk->z * CHUNK_D + 0.5f
),
util::Buffer<ChunkVertex>(indexCount), 0};
totalSize += entry.vertexData.size(); totalSize += entry.vertexData.size();
@ -660,10 +655,6 @@ SortingMeshData BlocksRenderer::renderTranslucent(
} else { } else {
aabb.addPoint(vertex.position); aabb.addPoint(vertex.position);
} }
vertex.position.x += chunk->x * CHUNK_W + 0.5f;
vertex.position.y += 0.5f;
vertex.position.z += chunk->z * CHUNK_D + 0.5f;
} }
sortingMesh.entries.push_back(std::move(entry)); sortingMesh.entries.push_back(std::move(entry));
vertexCount = 0; vertexCount = 0;

View file

@ -12,6 +12,7 @@
#include "window/Camera.hpp" #include "window/Camera.hpp"
#include "maths/FrustumCulling.hpp" #include "maths/FrustumCulling.hpp"
#include "maths/util.hpp" #include "maths/util.hpp"
#include "maths/voxmaths.hpp"
#include "util/listutil.hpp" #include "util/listutil.hpp"
#include "util/ObjectsPool.hpp" #include "util/ObjectsPool.hpp"
#include "util/timeutil.hpp" #include "util/timeutil.hpp"
@ -241,6 +242,9 @@ void ChunksRenderer::drawShadowsPass(
auto denseDistance = settings.graphics.denseRenderDistance.get(); auto denseDistance = settings.graphics.denseRenderDistance.get();
auto denseDistance2 = denseDistance * denseDistance; auto denseDistance2 = denseDistance * denseDistance;
const glm::ivec3 origin = camera.getOrigin();
const glm::vec3 playerPos = util::to_local(playerCamera.position, origin);
for (const auto& chunk : chunks.getChunks()) { for (const auto& chunk : chunks.getChunks()) {
if (chunk == nullptr) { if (chunk == nullptr) {
continue; continue;
@ -251,16 +255,12 @@ void ChunksRenderer::drawShadowsPass(
continue; continue;
} }
glm::vec3 coord( int x = pos.x * CHUNK_W - origin.x;
pos.x * CHUNK_W + 0.5f, 0.5f, pos.y * CHUNK_D + 0.5f int z = pos.y * CHUNK_D - origin.z;
); glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f);
glm::vec3 min(pos.x * CHUNK_W, chunk->bottom, pos.y * CHUNK_D); glm::vec3 min(x, chunk->bottom, z);
glm::vec3 max( glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D);
pos.x * CHUNK_W + CHUNK_W,
chunk->top,
pos.y * CHUNK_D + CHUNK_D
);
if (!frustum.isBoxVisible(min, max)) { if (!frustum.isBoxVisible(min, max)) {
continue; continue;
@ -268,7 +268,7 @@ void ChunksRenderer::drawShadowsPass(
glm::mat4 model = glm::translate(glm::mat4(1.0f), coord); glm::mat4 model = glm::translate(glm::mat4(1.0f), coord);
shader.uniformMatrix("u_model", model); shader.uniformMatrix("u_model", model);
found->second.mesh->draw(GL_TRIANGLES, found->second.mesh->draw(GL_TRIANGLES,
glm::distance2(playerCamera.position * glm::vec3(1, 0, 1), glm::distance2(playerPos * glm::vec3(1, 0, 1),
(min + max) * 0.5f * glm::vec3(1, 0, 1)) < denseDistance2); (min + max) * 0.5f * glm::vec3(1, 0, 1)) < denseDistance2);
} }
} }
@ -292,8 +292,13 @@ void ChunksRenderer::drawChunks(
indices.push_back(ChunksSortEntry {i, 0}); indices.push_back(ChunksSortEntry {i, 0});
} }
} }
float px = camera.position.x / static_cast<float>(CHUNK_W) - 0.5f; const glm::ivec3 origin = camera.getOrigin();
float pz = camera.position.z / static_cast<float>(CHUNK_D) - 0.5f; const glm::vec3 cameraPos = camera.getLocalPosition();
chunksOffsetX -= floordiv<CHUNK_W>(origin.x);
chunksOffsetY -= floordiv<CHUNK_D>(origin.z);
float px = cameraPos.x / static_cast<float>(CHUNK_W) - 0.5f;
float pz = cameraPos.z / static_cast<float>(CHUNK_D) - 0.5f;
for (auto& index : indices) { for (auto& index : indices) {
float x = index.index % chunksWidth + chunksOffsetX - px; float x = index.index % chunksWidth + chunksOffsetX - px;
float z = index.index / chunksWidth + chunksOffsetY - pz; float z = index.index / chunksWidth + chunksOffsetY - pz;
@ -323,32 +328,28 @@ void ChunksRenderer::drawChunks(
if (mesh.mesh == nullptr) { if (mesh.mesh == nullptr) {
continue; continue;
} }
int x = chunk->x * CHUNK_W - origin.x;
int z = chunk->z * CHUNK_D - origin.z;
if (culling) { if (culling) {
const auto& meshAABB = mesh.meshAABB; const auto& meshAABB = mesh.meshAABB;
auto aabbMin = meshAABB.min(); auto aabbMin = meshAABB.min();
auto aabbMax = meshAABB.max(); auto aabbMax = meshAABB.max();
glm::vec3 min( glm::vec3 min(
chunk->x * CHUNK_W + std::min(0.0f, aabbMin.x), x + std::min(0.0f, aabbMin.x),
chunk->bottom, chunk->bottom,
chunk->z * CHUNK_D + std::min(0.0f, aabbMin.z) z + std::min(0.0f, aabbMin.z)
);
glm::vec3 max(
chunk->x * CHUNK_W + aabbMax.x,
chunk->top,
chunk->z * CHUNK_D + aabbMax.z
); );
glm::vec3 max(x + aabbMax.x, chunk->top, z + aabbMax.z);
if (!frustum.isBoxVisible(min, max)) { if (!frustum.isBoxVisible(min, max)) {
continue; continue;
} }
} }
glm::vec3 coord( glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f);
chunk->x * CHUNK_W + 0.5f, 0.5f, chunk->z * CHUNK_D + 0.5f
);
glm::mat4 model = glm::translate(glm::mat4(1.0f), coord); glm::mat4 model = glm::translate(glm::mat4(1.0f), coord);
shader.uniformMatrix("u_model", model); shader.uniformMatrix("u_model", model);
mesh.mesh->draw(GL_TRIANGLES, glm::distance2(camera.position * glm::vec3(1, 0, 1), mesh.mesh->draw(GL_TRIANGLES, glm::distance2(cameraPos * glm::vec3(1, 0, 1),
(coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))) < denseDistance2); (coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))) < denseDistance2);
visibleChunks++; visibleChunks++;
} }
@ -375,12 +376,12 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
bool culling = settings.graphics.frustumCulling.get(); bool culling = settings.graphics.frustumCulling.get();
const auto& chunks = this->chunks.getChunks(); const auto& chunks = this->chunks.getChunks();
const auto& cameraPos = camera.position; const glm::ivec3 origin = camera.getOrigin();
const glm::vec3 cameraPos = camera.getLocalPosition();
const auto& atlas = assets.require<Atlas>("blocks"); const auto& atlas = assets.require<Atlas>("blocks");
shader.use(); shader.use();
atlas.getTexture()->bind(); atlas.getTexture()->bind();
shader.uniformMatrix("u_model", glm::mat4(1.0f));
shader.uniform1i("u_alphaClip", false); shader.uniform1i("u_alphaClip", false);
for (const auto& index : indices) { for (const auto& index : indices) {
@ -393,16 +394,18 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
continue; continue;
} }
int x = chunk->x * CHUNK_W - origin.x;
int z = chunk->z * CHUNK_D - origin.z;
if (culling) { if (culling) {
glm::vec3 min(chunk->x * CHUNK_W, chunk->bottom, chunk->z * CHUNK_D); glm::vec3 min(x, chunk->bottom, z);
glm::vec3 max( glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D);
chunk->x * CHUNK_W + CHUNK_W,
chunk->top,
chunk->z * CHUNK_D + CHUNK_D
);
if (!frustum.isBoxVisible(min, max)) continue; if (!frustum.isBoxVisible(min, max)) continue;
} }
glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f);
shader.uniformMatrix(
"u_model", glm::translate(glm::mat4(1.0f), coord)
);
auto& chunkEntries = found->second.sortingMeshData.entries; auto& chunkEntries = found->second.sortingMeshData.entries;
@ -418,7 +421,7 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
} }
for (auto& entry : chunkEntries) { for (auto& entry : chunkEntries) {
entry.distance = static_cast<long long>( entry.distance = static_cast<long long>(
glm::distance2(entry.position, cameraPos) glm::distance2(entry.position, cameraPos - coord)
); );
} }
if (found->second.sortedMesh == nullptr || if (found->second.sortedMesh == nullptr ||

View file

@ -25,6 +25,7 @@ static debug::Logger logger("clouds-render");
static inline constexpr int MAP_SIZE = 512; static inline constexpr int MAP_SIZE = 512;
static inline constexpr float CLOUD_VOXEL_SCALE = 8.0f; static inline constexpr float CLOUD_VOXEL_SCALE = 8.0f;
static inline constexpr float CLOUDS_SPEED = 4.0f; static inline constexpr float CLOUDS_SPEED = 4.0f;
static inline constexpr double CLOUDS_WAVE_PERIOD = glm::two_pi<double>() * 1e3;
class CloudsMap { class CloudsMap {
public: public:
@ -269,8 +270,15 @@ void CloudsRenderer::draw(
float scale = CLOUD_VOXEL_SCALE; float scale = CLOUD_VOXEL_SCALE;
int totalDiameter = layer.segmentSize * scale; int totalDiameter = layer.segmentSize * scale;
int gcellX = floordiv(camera.position.x, totalDiameter); const glm::ivec3 origin = camera.getOrigin();
int gcellZ = floordiv(camera.position.z, totalDiameter); const glm::vec3 cameraPos = camera.getLocalPosition();
int gcellX = floordiv(
origin.x + static_cast<int>(glm::floor(cameraPos.x)), totalDiameter
);
int gcellZ = floordiv(
origin.z + static_cast<int>(glm::floor(cameraPos.z)), totalDiameter
);
float speed = CLOUDS_SPEED; float speed = CLOUDS_SPEED;
float speedX = glm::sin(layerId * 0.3f + 0.4f) * speed / (layerId + 1); float speedX = glm::sin(layerId * 0.3f + 0.4f) * speed / (layerId + 1);
@ -283,10 +291,10 @@ void CloudsRenderer::draw(
int lcellX = gcellX - floordiv(glm::floor(timer * speedX), totalDiameter); int lcellX = gcellX - floordiv(glm::floor(timer * speedX), totalDiameter);
int lcellZ = gcellZ - floordiv(glm::floor(timer * speedZ), totalDiameter); int lcellZ = gcellZ - floordiv(glm::floor(timer * speedZ), totalDiameter);
glm::vec3 position( glm::vec3 position(
-128 * scale + (x + gcellX) * layer.segmentSize * scale + -128 * scale + ((x + gcellX) * totalDiameter - origin.x) +
glm::mod(timer * speedX, static_cast<float>(totalDiameter)), glm::mod(timer * speedX, static_cast<float>(totalDiameter)),
250 + layerId * 200, 250 + layerId * 200,
-128 * scale + (z + gcellZ) * layer.segmentSize * scale + -128 * scale + ((z + gcellZ) * totalDiameter - origin.z) +
glm::mod(timer * speedZ, static_cast<float>(totalDiameter)) glm::mod(timer * speedZ, static_cast<float>(totalDiameter))
); );
if (glm::distance2( if (glm::distance2(
@ -294,7 +302,7 @@ void CloudsRenderer::draw(
position.x + totalDiameter * 0.5f, position.x + totalDiameter * 0.5f,
position.z + totalDiameter * 0.5f position.z + totalDiameter * 0.5f
), ),
glm::vec2(camera.position.x, camera.position.z) glm::vec2(cameraPos.x, cameraPos.z)
) > 4e6) { ) > 4e6) {
continue; continue;
} }
@ -331,6 +339,13 @@ void CloudsRenderer::draw(
shader.uniform1f("u_fogFactor", fogFactor * 0.03f); shader.uniform1f("u_fogFactor", fogFactor * 0.03f);
shader.uniform1f("u_fogCurve", 0.4f); shader.uniform1f("u_fogCurve", 0.4f);
const glm::ivec3 origin = camera.getOrigin();
shader.uniform2f(
"u_waveOffset",
std::fmod(origin.x, CLOUDS_WAVE_PERIOD),
std::fmod(origin.z, CLOUDS_WAVE_PERIOD)
);
for (int i = 0; i < std::min<int>(quality, layers.size()); i++) { for (int i = 0; i < std::min<int>(quality, layers.size()); i++) {
draw(layers[i], frustum, shader, camera, timer, i); draw(layers[i], frustum, shader, camera, timer, i);
} }

View file

@ -11,15 +11,17 @@
bool DebugLinesRenderer::showPaths = false; bool DebugLinesRenderer::showPaths = false;
static void draw_route(LineBatch& batch, const voxels::Agent& agent) { static void draw_route(
LineBatch& batch, const voxels::Agent& agent, const glm::ivec3& origin
) {
const auto& route = agent.route; const auto& route = agent.route;
if (!route.found) return; if (!route.found) return;
batch.lineWidth(1.0f); batch.lineWidth(1.0f);
for (int i = 1; i < route.nodes.size(); i++) { for (int i = 1; i < route.nodes.size(); i++) {
const auto& a = glm::vec3(route.nodes.at(i - 1).pos); const auto& a = glm::vec3(route.nodes.at(i - 1).pos - origin);
const auto& b = glm::vec3(route.nodes.at(i).pos); const auto& b = glm::vec3(route.nodes.at(i).pos - origin);
glm::vec3 a_base = a + glm::vec3(0.5); glm::vec3 a_base = a + glm::vec3(0.5);
glm::vec3 b_base = b + glm::vec3(0.5); glm::vec3 b_base = b + glm::vec3(0.5);
@ -99,10 +101,12 @@ void DebugLinesRenderer::render(
Shader& linesShader, Shader& linesShader,
bool showChunkBorders bool showChunkBorders
) { ) {
const glm::ivec3 origin = camera.getOrigin();
// In-world lines // In-world lines
if (showPaths) { if (showPaths) {
for (const auto& [_, agent] : level.pathfinding->getAgents()) { for (const auto& [_, agent] : level.pathfinding->getAgents()) {
draw_route(linesBatch, agent); draw_route(linesBatch, agent, origin);
} }
} }
DrawContext ctx = pctx.sub(&linesBatch); DrawContext ctx = pctx.sub(&linesBatch);
@ -122,12 +126,12 @@ void DebugLinesRenderer::render(
drawBorders( drawBorders(
linesBatch, linesBatch,
cx * CHUNK_W, cx * CHUNK_W - origin.x,
0, 0,
cz * CHUNK_D, cz * CHUNK_D - origin.z,
(cx + 1) * CHUNK_W, (cx + 1) * CHUNK_W - origin.x,
CHUNK_H, CHUNK_H,
(cz + 1) * CHUNK_D (cz + 1) * CHUNK_D - origin.z
); );
} }

View file

@ -5,6 +5,7 @@
#include "graphics/core/DrawContext.hpp" #include "graphics/core/DrawContext.hpp"
#include "graphics/core/LineBatch.hpp" #include "graphics/core/LineBatch.hpp"
#include "maths/FrustumCulling.hpp" #include "maths/FrustumCulling.hpp"
#include "maths/util.hpp"
#include "objects/Entities.hpp" #include "objects/Entities.hpp"
#include "objects/Entity.hpp" #include "objects/Entity.hpp"
#include "objects/EntityDef.hpp" #include "objects/EntityDef.hpp"
@ -46,10 +47,12 @@ static bool check_frustum(
const Frustum& frustum, const Frustum& frustum,
const Transform& transform, const Transform& transform,
const Rigidbody& rigidbody, const Rigidbody& rigidbody,
const rigging::Skeleton& skeleton const rigging::Skeleton& skeleton,
const glm::ivec3& origin
) { ) {
glm::vec3 pos = util::to_local(transform.pos, origin);
glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); glm::vec3 ext = calc_extent(transform, rigidbody, skeleton);
return frustum.isBoxVisible(transform.pos - ext, transform.pos + ext); return frustum.isBoxVisible(pos - ext, pos + ext);
} }
EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities) EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities)
@ -57,8 +60,12 @@ EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities)
} }
void EntitiesRenderer::render( void EntitiesRenderer::render(
ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity ModelBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum,
entityid_t fpsEntity
) { ) {
batch.setLightsOffset(origin);
for (const auto& [uid, entity] : entities.getEntities()) { for (const auto& [uid, entity] : entities.getEntities()) {
if (!entity->getSkeleton() || uid == fpsEntity) { if (!entity->getSkeleton() || uid == fpsEntity) {
continue; continue;
@ -73,12 +80,17 @@ void EntitiesRenderer::render(
if (rigConfig == nullptr) { if (rigConfig == nullptr) {
continue; continue;
} }
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { if (frustum &&
!check_frustum(*frustum, transform, rigidbody, skeleton, origin)) {
if (!skeleton.boundsDirty || !skeleton.visible) { if (!skeleton.boundsDirty || !skeleton.visible) {
continue; continue;
} }
rigConfig->updateBounds(assets, skeleton, transform.rot, pos, size); rigConfig->updateBounds(
if (!check_frustum(*frustum, transform, rigidbody, skeleton)) { assets, skeleton, transform.rot, pos, size, origin
);
if (!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue; continue;
} }
} }
@ -90,6 +102,7 @@ void EntitiesRenderer::render(
transform.rot, transform.rot,
pos, pos,
size, size,
origin,
def.translucent def.translucent
); );
} }
@ -97,6 +110,7 @@ void EntitiesRenderer::render(
void EntitiesRenderer::renderDebug( void EntitiesRenderer::renderDebug(
LineBatch& batch, LineBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum, const Frustum* frustum,
const DrawContext& pctx, const DrawContext& pctx,
entityid_t fpsEntity entityid_t fpsEntity
@ -113,20 +127,27 @@ void EntitiesRenderer::renderDebug(
const auto& rigidbody = entity->getRigidbody(); const auto& rigidbody = entity->getRigidbody();
const auto& skeleton = *entity->getSkeleton(); const auto& skeleton = *entity->getSkeleton();
const auto& hitbox = rigidbody.hitbox; const auto& hitbox = rigidbody.hitbox;
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { if (frustum &&
!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue; continue;
} }
batch.box( batch.box(
hitbox.position, hitbox.getHalfSize() * 2.0f, glm::vec4(1.0f) util::to_local(hitbox.position, origin),
hitbox.getHalfSize() * 2.0f,
glm::vec4(1.0f)
); );
glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); glm::vec3 ext = calc_extent(transform, rigidbody, skeleton);
batch.box( batch.box(
transform.pos, ext * 2.0f, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f) util::to_local(transform.pos, origin),
ext * 2.0f,
glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)
); );
for (auto& sensor : rigidbody.sensors) { for (auto& sensor : rigidbody.sensors) {
if (sensor.type != SensorType::AABB) continue; if (sensor.type != SensorType::AABB) continue;
batch.box( batch.box(
sensor.calculated.aabb.center(), util::to_local(sensor.calculated.aabb.center(), origin),
sensor.calculated.aabb.size(), sensor.calculated.aabb.size(),
glm::vec4(1.0f, 1.0f, 0.0f, 1.0f) glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)
); );
@ -149,7 +170,10 @@ void EntitiesRenderer::renderDebug(
if (config == nullptr) { if (config == nullptr) {
continue; continue;
} }
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { if (frustum &&
!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue; continue;
} }
auto bone = config->getRoot(); auto bone = config->getRoot();
@ -159,7 +183,7 @@ void EntitiesRenderer::renderDebug(
} }
void EntitiesRenderer::updateCulling( void EntitiesRenderer::updateCulling(
const Frustum* frustum, entityid_t fpsEntity const glm::ivec3& origin, const Frustum* frustum, entityid_t fpsEntity
) { ) {
for (const auto& [uid, entity] : entities.getEntities()) { for (const auto& [uid, entity] : entities.getEntities()) {
if (!entity->getSkeleton()) { if (!entity->getSkeleton()) {
@ -171,7 +195,11 @@ void EntitiesRenderer::updateCulling(
continue; continue;
} }
skeleton.culled = !check_frustum( skeleton.culled = !check_frustum(
*frustum, entity->getTransform(), entity->getRigidbody(), skeleton *frustum,
entity->getTransform(),
entity->getRigidbody(),
skeleton,
origin
); );
} }
} }

View file

@ -2,6 +2,8 @@
#include "typedefs.hpp" #include "typedefs.hpp"
#include <glm/vec3.hpp>
class Assets; class Assets;
class DrawContext; class DrawContext;
class Entities; class Entities;
@ -16,15 +18,21 @@ public:
EntitiesRenderer(const Assets& assets, Entities& entities); EntitiesRenderer(const Assets& assets, Entities& entities);
void render( void render(
ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity ModelBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum,
entityid_t fpsEntity
); );
void renderDebug( void renderDebug(
LineBatch& batch, LineBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum, const Frustum* frustum,
const DrawContext& ctx, const DrawContext& ctx,
entityid_t fpsEntity entityid_t fpsEntity
); );
void updateCulling(const Frustum* frustum, entityid_t fpsEntity); void updateCulling(
const glm::ivec3& origin, const Frustum* frustum, entityid_t fpsEntity
);
}; };

View file

@ -33,7 +33,8 @@ void HandsRenderer::render(const Camera& camera) {
ModelLightingMode::SOLID, ModelLightingMode::SOLID,
glm::mat3(1.0f), glm::mat3(1.0f),
glm::vec3(), glm::vec3(),
glm::vec3(1.0f) glm::vec3(1.0f),
glm::ivec3()
); );
modelBatch.render(); modelBatch.render();

View file

@ -63,11 +63,11 @@ void MainBatch::prepare(int vertices) {
} }
glm::vec4 MainBatch::sampleLight( glm::vec4 MainBatch::sampleLight(
const glm::vec3 &pos, const Chunks &chunks, bool backlight const glm::dvec3 &pos, const Chunks &chunks, bool backlight
) { ) {
light_t light = chunks.getLight( light_t light = chunks.getLight(
std::floor(pos.x), std::floor(pos.x),
std::floor(std::min(CHUNK_H - 1.0f, pos.y)), std::floor(std::min(CHUNK_H - 1.0, pos.y)),
std::floor(pos.z)); std::floor(pos.z));
light_t minIntensity = backlight ? 1 : 0; light_t minIntensity = backlight ? 1 : 0;
return { return {

View file

@ -46,7 +46,7 @@ public:
void flush(); void flush();
static glm::vec4 sampleLight( static glm::vec4 sampleLight(
const glm::vec3& pos, const Chunks& chunks, bool backlight const glm::dvec3& pos, const Chunks& chunks, bool backlight
); );
inline void vertex( inline void vertex(

View file

@ -106,8 +106,8 @@ void ModelBatch::draw(
auto& queue = auto& queue =
translucent || tint.a < 1.0f ? translucentEntries : entries; translucent || tint.a < 1.0f ? translucentEntries : entries;
const auto& gpuModel = upload(model); const auto& gpuModel = upload(model);
glm::vec3 lightSamplePos = glm::dvec3 lightSamplePos =
glm::vec3(matrix[3]) + lightsOffset + lightSampleOffset; glm::dvec3(matrix[3]) + lightsOffset + glm::dvec3(lightSampleOffset);
for (size_t i = 0; i < model->meshes.size(); i++) { for (size_t i = 0; i < model->meshes.size(); i++) {
const auto& mesh = model->meshes[i]; const auto& mesh = model->meshes[i];
if (mesh.vertices.empty()) { if (mesh.vertices.empty()) {
@ -219,6 +219,6 @@ void ModelBatch::renderTranslucent(const glm::vec3& cameraPosition) {
finishFrame(); finishFrame();
} }
void ModelBatch::setLightsOffset(const glm::vec3& offset) { void ModelBatch::setLightsOffset(const glm::dvec3& offset) {
lightsOffset = offset; lightsOffset = offset;
} }

View file

@ -50,13 +50,13 @@ public:
void renderTranslucent(const glm::vec3& cameraPosition); void renderTranslucent(const glm::vec3& cameraPosition);
void setLightsOffset(const glm::vec3& offset); void setLightsOffset(const glm::dvec3& offset);
private: private:
const Assets& assets; const Assets& assets;
const Chunks& chunks; const Chunks& chunks;
const EngineSettings& settings; const EngineSettings& settings;
glm::vec3 lightsOffset {}; glm::dvec3 lightsOffset {};
struct Vertex { struct Vertex {
glm::vec3 coord; glm::vec3 coord;
@ -103,7 +103,7 @@ private:
struct DrawEntry { struct DrawEntry {
const Texture* texture; const Texture* texture;
const Mesh<Vertex>* mesh; const Mesh<Vertex>* mesh;
glm::vec3 lightSamplePos; glm::dvec3 lightSamplePos;
bool shading; bool shading;
Instance instance; Instance instance;
}; };

View file

@ -154,7 +154,7 @@ void ParticlesRenderer::renderParticle(
camera.front * rotatedUp.z; camera.front * rotatedUp.z;
} }
batch->quad( batch->quad(
particle.position, util::to_local(particle.position, camera.getOrigin()),
localRight, localRight,
localUp, localUp,
-camera.front, -camera.front,

View file

@ -67,7 +67,7 @@ static constexpr float K = 21.41149;
static constexpr glm::ivec2 FACE_SIZE {1, 16}; static constexpr glm::ivec2 FACE_SIZE {1, 16};
static UVRegion calc_uv( static UVRegion calc_uv(
const glm::vec3& pos, const glm::ivec3& pos,
const glm::vec3& right, const glm::vec3& right,
float timer, float timer,
const WeatherPreset& weather const WeatherPreset& weather
@ -84,8 +84,10 @@ static UVRegion calc_uv(
} }
random.setSeed(uz); random.setSeed(uz);
float hspeed = (random.randFloat() * 2.0f - 1.0f) * weather.fall.hspeed; float hspeed = (random.randFloat() * 2.0f - 1.0f) * weather.fall.hspeed;
float u1 = ux * scale + timer * hspeed * -m; float u1 =
float v1 = timer * weather.fall.vspeed + pos.y * scale + uz * K; glm::fract(ux * static_cast<double>(scale)) + timer * hspeed * -m;
float v1 = timer * weather.fall.vspeed + pos.y * scale +
glm::fract(uz * static_cast<double>(K));
return {u1, v1, u1 + m * scale, v1 + FACE_SIZE.y * scale}; return {u1, v1, u1 + m * scale, v1 + FACE_SIZE.y * scale};
} }
@ -104,6 +106,8 @@ void PrecipitationRenderer::render(
int y = glm::floor(camera.position.y); int y = glm::floor(camera.position.y);
int z = glm::floor(camera.position.z); int z = glm::floor(camera.position.z);
const glm::ivec3 origin = camera.getOrigin();
util::CentredMatrix<int, (depth + 1) * 2> heights; util::CentredMatrix<int, (depth + 1) * 2> heights;
heights.setCenter(x, z); heights.setCenter(x, z);
for (int z = heights.beginY(); z < heights.endY(); z++) { for (int z = heights.beginY(); z < heights.endY(); z++) {
@ -135,17 +139,16 @@ void PrecipitationRenderer::render(
for (int lx = -radius; lx <= radius; lx++) { for (int lx = -radius; lx <= radius; lx++) {
for (int lz = depth; lz > 0; lz--) { for (int lz = depth; lz > 0; lz--) {
// Position calculations // Position calculations
glm::vec3 pos = face.right * static_cast<float>(lx) + glm::ivec3 pos =
face.front * static_cast<float>(lz); glm::ivec3(face.right) * lx + glm::ivec3(face.front) * lz;
pos += glm::vec3(x, 0, z); pos += glm::ivec3(x, 0, z);
pos.y = pos.y =
glm::max(y - FACE_SIZE.y / 2, heights.at(pos.x, pos.z)) + glm::max(y - FACE_SIZE.y / 2, heights.at(pos.x, pos.z)) +
FACE_SIZE.y / 2 + 1; FACE_SIZE.y / 2 + 1;
pos += glm::vec3(0.5f, 0.0f, 0.5f);
// Draw // Draw
batch->quad( batch->quad(
pos, glm::vec3(pos - origin) + glm::vec3(0.5f, 0.0f, 0.5f),
face.right, face.right,
{0, 1, 0}, {0, 1, 0},
glm::cross(glm::vec3(0, 1, 0), face.right), glm::cross(glm::vec3(0, 1, 0), face.right),

View file

@ -44,7 +44,10 @@ void TextsRenderer::renderNote(
} }
} }
if (util::distance2(pos, camera.position) > pos = util::to_local(pos, camera.getOrigin());
const glm::vec3 cameraPos = camera.getLocalPosition();
if (util::distance2(pos, cameraPos) >
util::sqr(preset.renderDistance / camera.zoom)) { util::sqr(preset.renderDistance / camera.zoom)) {
return; return;
} }
@ -70,7 +73,7 @@ void TextsRenderer::renderNote(
int height = font.getLineHeight(); int height = font.getLineHeight();
if (preset.displayMode == NoteDisplayMode::Y_FREE_BILLBOARD || if (preset.displayMode == NoteDisplayMode::Y_FREE_BILLBOARD ||
preset.displayMode == NoteDisplayMode::XY_FREE_BILLBOARD) { preset.displayMode == NoteDisplayMode::XY_FREE_BILLBOARD) {
xvec = camera.position - pos; xvec = cameraPos - pos;
xvec.y = 0; xvec.y = 0;
std::swap(xvec.x, xvec.z); std::swap(xvec.x, xvec.z);
xvec.z *= -1; xvec.z *= -1;
@ -80,9 +83,7 @@ void TextsRenderer::renderNote(
} }
float scale = float scale =
(1.0f - preset.perspective) * (1.0f - preset.perspective) *
glm::pow( glm::pow(glm::distance(cameraPos, pos), 1.0f - preset.perspective);
glm::distance(camera.position, pos), 1.0f - preset.perspective
);
xvec *= 1.0f + scale; xvec *= 1.0f + scale;
yvec *= 1.0f + scale; yvec *= 1.0f + scale;
} }
@ -91,7 +92,7 @@ void TextsRenderer::renderNote(
float scale = 1.0f; float scale = 1.0f;
if (glm::abs(preset.perspective) > 0.0001f) { if (glm::abs(preset.perspective) > 0.0001f) {
float scale2 = float scale2 =
scale / (glm::distance(camera.position, pos) * camera.zoom * scale / (glm::distance(cameraPos, pos) * camera.zoom *
glm::sqrt(glm::tan(camera.getFov() * 0.5f))); glm::sqrt(glm::tan(camera.getFov() * 0.5f)));
scale = scale2 * preset.perspective + scale = scale2 * preset.perspective +
scale * (1.0f - preset.perspective); scale * (1.0f - preset.perspective);

View file

@ -42,6 +42,7 @@
#include "items/ItemStack.hpp" #include "items/ItemStack.hpp"
#include "logic/PlayerController.hpp" #include "logic/PlayerController.hpp"
#include "maths/FrustumCulling.hpp" #include "maths/FrustumCulling.hpp"
#include "maths/util.hpp"
#include "maths/voxmaths.hpp" #include "maths/voxmaths.hpp"
#include "objects/Entities.hpp" #include "objects/Entities.hpp"
#include "objects/Player.hpp" #include "objects/Player.hpp"
@ -213,7 +214,7 @@ static void setup_camera(Shader& shader, const Camera& camera) {
shader.uniformMatrix("u_model", glm::mat4(1.0f)); shader.uniformMatrix("u_model", glm::mat4(1.0f));
shader.uniformMatrix("u_proj", camera.getProjection()); shader.uniformMatrix("u_proj", camera.getProjection());
shader.uniformMatrix("u_view", camera.getView()); shader.uniformMatrix("u_view", camera.getView());
shader.uniform3f("u_cameraPos", camera.position); shader.uniform3f("u_cameraPos", camera.getLocalPosition());
} }
void WorldRenderer::setupWorldShader( void WorldRenderer::setupWorldShader(
@ -226,7 +227,7 @@ void WorldRenderer::setupWorldShader(
setup_camera(shader, camera); setup_camera(shader, camera);
setup_weather(shader, weather); setup_weather(shader, weather);
shadowMapping->setup(shader, weather); shadowMapping->setup(shader, camera, weather);
shader.uniform1f("u_timer", timer); shader.uniform1f("u_timer", timer);
shader.uniform1f("u_gamma", settings.graphics.gamma.get()); shader.uniform1f("u_gamma", settings.graphics.gamma.get());
@ -283,6 +284,7 @@ void WorldRenderer::renderOpaque(
setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f}); setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f});
entitiesRenderer->render( entitiesRenderer->render(
*modelBatch, *modelBatch,
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr, culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0 : 0
@ -297,7 +299,7 @@ void WorldRenderer::renderOpaque(
setupWorldShader(mainShader, camera, settings, fogFactor); setupWorldShader(mainShader, camera, settings, fogFactor);
chunksRenderer->drawChunks(camera, mainShader); chunksRenderer->drawChunks(camera, mainShader);
blockWraps->draw(ctx); blockWraps->draw(ctx, camera);
if (level.environment.sky.clouds) { if (level.environment.sky.clouds) {
int cloudsQuality = settings.graphics.cloudsQuality.get(); int cloudsQuality = settings.graphics.cloudsQuality.get();
@ -315,13 +317,14 @@ void WorldRenderer::renderOpaque(
} }
} }
void WorldRenderer::renderBlockSelection() { void WorldRenderer::renderBlockSelection(const Camera& camera) {
const auto& selection = player.selection; const auto& selection = player.selection;
auto indices = level.content.getIndices(); auto indices = level.content.getIndices();
blockid_t id = selection.vox.id; blockid_t id = selection.vox.id;
auto& block = indices->blocks.require(id); auto& block = indices->blocks.require(id);
const glm::ivec3 origin = camera.getOrigin();
const glm::ivec3 pos = player.selection.position; const glm::ivec3 pos = player.selection.position;
const glm::vec3 point = selection.hitPosition; const glm::vec3 point = util::to_local(selection.hitPosition, origin);
const glm::vec3 norm = selection.normal; const glm::vec3 norm = selection.normal;
const auto& hitboxes = block.getHitboxes( const auto& hitboxes = block.getHitboxes(
@ -330,7 +333,7 @@ void WorldRenderer::renderBlockSelection() {
lineBatch->lineWidth(2.0f); lineBatch->lineWidth(2.0f);
for (auto& hitbox : hitboxes) { for (auto& hitbox : hitboxes) {
const glm::vec3 center = glm::vec3(pos) + hitbox.center(); const glm::vec3 center = glm::vec3(pos - origin) + hitbox.center();
const glm::vec3 size = hitbox.size(); const glm::vec3 size = hitbox.size();
lineBatch->box( lineBatch->box(
center, size + glm::vec3(0.01), glm::vec4(0.f, 0.f, 0.f, 1.0f) center, size + glm::vec3(0.01), glm::vec4(0.f, 0.f, 0.f, 1.0f)
@ -350,13 +353,16 @@ void WorldRenderer::renderInWorldLines(
linesShader.use(); linesShader.use();
linesShader.uniformMatrix("u_projview", camera.getProjView()); linesShader.uniformMatrix("u_projview", camera.getProjView());
if (player.selection.vox.id != BLOCK_VOID) { if (player.selection.vox.id != BLOCK_VOID) {
renderBlockSelection(); renderBlockSelection(camera);
} }
if (debug && showEntitiesDebug) { if (debug && showEntitiesDebug) {
auto ctx = pctx.sub(lineBatch.get()); auto ctx = pctx.sub(lineBatch.get());
bool culling = engine.getSettings().graphics.frustumCulling.get(); bool culling = engine.getSettings().graphics.frustumCulling.get();
entitiesRenderer->renderDebug( entitiesRenderer->renderDebug(
*lineBatch, culling ? frustumCulling.get() : nullptr, ctx, *lineBatch,
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr,
ctx,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0
); );
} }
@ -368,6 +374,7 @@ void WorldRenderer::updateEntitiesCulling(const Camera& camera) {
frustumCulling->update(camera.getProjView()); frustumCulling->update(camera.getProjView());
} }
entitiesRenderer->updateCulling( entitiesRenderer->updateCulling(
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr, culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0 : 0
@ -587,7 +594,7 @@ void WorldRenderer::renderTranslucency(
auto& shader = assets.require<Shader>("model"); auto& shader = assets.require<Shader>("model");
setupWorldShader(shader, camera, settings, fogFactor); setupWorldShader(shader, camera, settings, fogFactor);
setup_entity_pass(shader, {0.002f, false, true, true, 1.0f}); setup_entity_pass(shader, {0.002f, false, true, true, 1.0f});
modelBatch->renderTranslucent(camera.position); modelBatch->renderTranslucent(camera.getLocalPosition());
} }
{ {
auto lctx = ctx.sub(); auto lctx = ctx.sub();

View file

@ -91,7 +91,7 @@ private:
bool dirtySettings = true; bool dirtySettings = true;
/// @brief Render block selection lines /// @brief Render block selection lines
void renderBlockSelection(); void renderBlockSelection(const Camera& camera);
/// @brief Render lines (selection and debug) /// @brief Render lines (selection and debug)
/// @param camera active camera /// @param camera active camera

View file

@ -17,6 +17,10 @@ namespace util {
constexpr inline float EPSILON = 1e-6f; constexpr inline float EPSILON = 1e-6f;
inline glm::vec3 to_local(const glm::vec3& pos, const glm::ivec3& origin) {
return glm::dvec3(pos) - glm::dvec3(origin);
}
class PseudoRandom { class PseudoRandom {
uint32_t seed; uint32_t seed;

View file

@ -3,6 +3,8 @@
#include <cmath> #include <cmath>
#include <glm/ext.hpp> #include <glm/ext.hpp>
inline constexpr double ORIGIN_STEP = 1024.0;
Camera::Camera(glm::vec3 position, float fov) : fov(fov), position(position) { Camera::Camera(glm::vec3 position, float fov) : fov(fov), position(position) {
updateVectors(); updateVectors();
} }
@ -40,10 +42,22 @@ glm::mat4 Camera::getProjection() const {
} }
} }
glm::ivec3 Camera::getOrigin() const {
return glm::ivec3(
std::round(position.x / ORIGIN_STEP) * ORIGIN_STEP,
0,
std::round(position.z / ORIGIN_STEP) * ORIGIN_STEP
);
}
glm::vec3 Camera::getLocalPosition() const {
return glm::dvec3(position) - glm::dvec3(getOrigin());
}
glm::mat4 Camera::getView(bool pos) const { glm::mat4 Camera::getView(bool pos) const {
glm::mat4 view = glm::lookAt(glm::vec3(0.0f), front, up); glm::mat4 view = glm::lookAt(glm::vec3(0.0f), front, up);
if (pos) { if (pos) {
view = glm::translate(view, -position); view = glm::translate(view, -getLocalPosition());
} }
return view; return view;
} }

View file

@ -32,6 +32,11 @@ public:
void updateVectors(); void updateVectors();
void rotate(float x, float y, float z); void rotate(float x, float y, float z);
/// @brief Get origin of the rendering coordinate system: an integer point
/// near the camera, getView() is relative to it
glm::ivec3 getOrigin() const;
glm::vec3 getLocalPosition() const;
glm::mat4 getProjection() const; glm::mat4 getProjection() const;
glm::mat4 getView(bool position = true) const; glm::mat4 getView(bool position = true) const;
glm::mat4 getProjView(bool position = true) const; glm::mat4 getProjView(bool position = true) const;

View file

@ -29,3 +29,24 @@ TEST(Camera, ViewRotationFarFromOrigin) {
} }
} }
} }
TEST(Camera, ViewRelativeToOrigin) {
for (float coord : {0.0f, 500.0f, -1e5f, 1e6f, 3e7f}) {
Camera camera(glm::vec3(coord, 64.0f, -coord), 1.0f);
camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f);
glm::dvec3 origin = camera.getOrigin();
glm::vec3 local = camera.getLocalPosition();
EXPECT_LE(glm::abs(local.x), 512.0f) << "at " << coord;
EXPECT_LE(glm::abs(local.z), 512.0f) << "at " << coord;
EXPECT_EQ(glm::dvec3(camera.position), origin + glm::dvec3(local));
glm::dvec3 point =
glm::dvec3(camera.position) + glm::dvec3(camera.front) * 10.0;
glm::vec4 viewPoint =
camera.getView() * glm::vec4(glm::vec3(point - origin), 1.0f);
EXPECT_NEAR(viewPoint.x, 0.0f, 1e-3f) << "at " << coord;
EXPECT_NEAR(viewPoint.y, 0.0f, 1e-3f) << "at " << coord;
EXPECT_NEAR(viewPoint.z, -10.0f, 1e-3f) << "at " << coord;
}
}