This commit is contained in:
Andrew Oster 2026-11-12 10:34:21 +03:00 • committed by GitHub
commit ebb181c60d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
85 changed files with 833 additions and 445 deletions

94
dev/tests/far_coords.lua Normal file
View file

@ -0,0 +1,94 @@
local util = require "core:tests_util"
util.create_demo_world("core:default")
app.set_setting("chunks.load-distance", 3)
app.set_setting("chunks.load-speed", 1)
local pid = player.create("Xerxes")
local function is_loaded(x, z)
return block.get(math.floor(x), 0, math.floor(z)) ~= -1
end
local function wait_chunk(x, z)
player.set_spawnpoint(pid, x, 100, z)
player.set_pos(pid, x, 100, z)
app.sleep_until(function () return is_loaded(x, z) end)
end
local function spawn_drop(x, y, z)
return entities.spawn("base:drop", {x, y, z}, {base__drop={
id=item.index("base:stone.item"),
count=1
}})
end
local function move_body(coord)
local x, z = coord + 8.5, -coord - 8.5
wait_chunk(x - 5, z)
local entity = spawn_drop(x, 50.5, z)
for _ = 1, 20 do
entity.rigidbody:set_vel({3, 0, -2})
app.tick()
end
local pos = entity.transform:get_pos()
entity:despawn()
return {pos[1] - x, pos[2] - 50.5, pos[3] - z}
end
local moved = move_body(0)
debug.print(moved)
assert(moved[1] > 1.0, "body didn't move")
for _, coord in ipairs({1000000, 30000000}) do
local x, y, z = coord + 0.3, 100.6, -coord - 0.7
player.set_pos(pid, x, y, z)
util.check_vec3({x, y, z}, {player.get_pos(pid)}, "player.get_pos", 1e-6)
player.set_spawnpoint(pid, x, y, z)
util.check_vec3(
{x, y, z}, {player.get_spawnpoint(pid)}, "player.get_spawnpoint", 1e-6
)
wait_chunk(x, z)
local entity = spawn_drop(x, y, z)
util.check_vec3({x, y, z}, entity.transform:get_pos(), "spawn pos", 1e-6)
entity.transform:set_pos({x + 0.25, y, z - 0.25})
util.check_vec3(
{x + 0.25, y, z - 0.25}, entity.transform:get_pos(), "set_pos", 1e-6
)
entity:despawn()
local ray = world.raycast({
start = {x, 8, z},
dir = {0, -1, 0},
distance = 10,
})
assert(ray, "ray didn't hit")
util.check_vec3({x, 1, z}, ray.endpoint, "ray.endpoint")
util.check_vec3(
{math.floor(x), 0, math.floor(z)}, ray.iendpoint, "ray.iendpoint"
)
util.check_float(7, ray.length, "ray.length")
local far_moved = move_body(coord)
debug.print(far_moved)
util.check_vec3(moved, far_moved, "body displacement", 1e-3)
end
local x, z = 30000000.3, -30000000.7
player.set_spawnpoint(pid, x, 100.6, z)
player.set_pos(pid, x, 100.6, z)
app.close_world(true)
app.open_world("demo")
local px, _, pz = player.get_pos(pid)
util.check_float(x, px, "saved x", 1e-6)
util.check_float(z, pz, "saved z", 1e-6)
util.check_vec3(
{x, 100.6, z}, {player.get_spawnpoint(pid)}, "saved spawnpoint", 1e-6
)
app.close_world(false)
app.delete_world("demo")

View file

@ -55,3 +55,9 @@ for i = 0, 63 do
end
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
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>
uniform float u_dayTime;
uniform vec2 u_waveOffset;
out vec4 a_torchLight;
void main() {
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.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.xz -= u_waveOffset;
vec3 pos3d = a_modelpos.xyz - u_cameraPos;

View file

@ -8,6 +8,7 @@
#include "data/dv_util.hpp"
#include "graphics/commons/Model.hpp"
#include "graphics/render/ModelBatch.hpp"
#include "maths/util.hpp"
using namespace rigging;
@ -159,10 +160,11 @@ static glm::mat4 build_matrix(
void SkeletonConfig::update(
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
const worldvec3& position,
const glm::vec3& scale,
const glm::ivec3& origin
) const {
glm::vec3 pos = position;
worldvec3 pos = position;
const auto& interpolation = skeleton.interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) {
pos = interpolation.getCurrent();
@ -172,7 +174,12 @@ void SkeletonConfig::update(
if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) {
rot = glm::mat3_cast(rotationInterpolation.getCurrent());
}
update(0, skeleton, root.get(), build_matrix(rot, pos, scale));
update(
0,
skeleton,
root.get(),
build_matrix(rot, util::to_local(pos, origin), scale)
);
}
static float max_component(const glm::vec3& v) {
@ -251,20 +258,27 @@ void SkeletonConfig::render(
Skeleton& skeleton,
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const worldvec3& position,
const glm::vec3& scale,
const glm::ivec3& origin,
bool translucent
) const {
if (skeleton.config->root == nullptr) {
return;
}
update(skeleton, rotation, position, scale);
update(skeleton, rotation, position, scale, origin);
if (!skeleton.visible) {
return;
}
processModels(
assets, skeleton, position, scale, &batch, lightingMode, translucent
assets,
skeleton,
util::to_local(position, origin),
scale,
&batch,
lightingMode,
translucent
);
}
@ -272,17 +286,18 @@ void SkeletonConfig::updateBounds(
const Assets& assets,
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
const worldvec3& position,
const glm::vec3& scale,
const glm::ivec3& origin
) const {
if (skeleton.config->root == nullptr) {
return;
}
update(skeleton, rotation, position, scale);
update(skeleton, rotation, position, scale, origin);
processModels(
assets,
skeleton,
position,
util::to_local(position, origin),
scale,
nullptr,
ModelLightingMode::SOLID,

View file

@ -104,7 +104,7 @@ namespace rigging {
glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f};
std::vector<glm::vec4> boneTints;
util::VecInterpolation<3, float> interpolation {false};
util::VecInterpolation<3, double> interpolation {false};
util::RotationInterpolation rotationInterpolation {false};
Skeleton(std::shared_ptr<const SkeletonConfig> config);
@ -151,8 +151,9 @@ namespace rigging {
void update(
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
const worldvec3& position,
const glm::vec3& scale,
const glm::ivec3& origin
) const;
void render(
@ -161,8 +162,9 @@ namespace rigging {
Skeleton& skeleton,
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const worldvec3& position,
const glm::vec3& scale,
const glm::ivec3& origin,
bool translucent = false
) const;
@ -170,8 +172,9 @@ namespace rigging {
const Assets& assets,
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
const worldvec3& position,
const glm::vec3& scale,
const glm::ivec3& origin
) const;
Skeleton instance() const {

View file

@ -342,6 +342,7 @@ void ALSpeaker::update(const Channel* channel) {
if (source == 0) return;
float gain = this->volume * channel->getVolume();
AL_CHECK(alSourcef(source, AL_GAIN, gain));
refreshPosition();
if (!paused) {
if (isPaused() && !channel->isPaused()) {
@ -451,12 +452,18 @@ void ALSpeaker::setTime(duration_t time) {
AL_CHECK(alSourcef(source, AL_SEC_OFFSET, static_cast<float>(time)));
}
void ALSpeaker::setPosition(glm::vec3 pos) {
void ALSpeaker::refreshPosition() {
glm::vec3 pos(relative ? position : position - al->listenerPosition);
AL_CHECK(alSource3f(source, AL_POSITION, pos.x, pos.y, pos.z));
}
glm::vec3 ALSpeaker::getPosition() const {
return AL::getSource3f(source, AL_POSITION);
void ALSpeaker::setPosition(worldvec3 pos) {
position = pos;
refreshPosition();
}
worldvec3 ALSpeaker::getPosition() const {
return position;
}
void ALSpeaker::setVelocity(glm::vec3 vel) {
@ -468,9 +475,11 @@ glm::vec3 ALSpeaker::getVelocity() const {
}
void ALSpeaker::setRelative(bool relative) {
this->relative = relative;
AL_CHECK(
alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE)
);
refreshPosition();
}
bool ALSpeaker::isRelative() const {
@ -782,11 +791,12 @@ void ALAudio::freeBuffer(uint buffer) {
}
void ALAudio::setListener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
worldvec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
) {
ALfloat listenerOri[] = {at.x, at.y, at.z, up.x, up.y, up.z};
AL_CHECK(alListener3f(AL_POSITION, position.x, position.y, position.z));
listenerPosition = position;
AL_CHECK(alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f));
AL_CHECK(alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z));
AL_CHECK(alListenerfv(AL_ORIENTATION, listenerOri));
AL_CHECK(alListenerf(AL_GAIN, get_channel(0)->getVolume()));

View file

@ -121,6 +121,10 @@ namespace audio {
int priority;
int channel;
float volume = 0.0f;
worldvec3 position {};
bool relative = false;
void refreshPosition();
public:
ALStream* stream = nullptr;
bool manuallyStopped = true;
@ -153,8 +157,8 @@ namespace audio {
duration_t getDuration() const override;
void setTime(duration_t time) override;
void setPosition(glm::vec3 pos) override;
glm::vec3 getPosition() const override;
void setPosition(worldvec3 pos) override;
worldvec3 getPosition() const override;
void setVelocity(glm::vec3 vel) override;
glm::vec3 getVelocity() const override;
@ -188,6 +192,7 @@ namespace audio {
std::array<uint, 1> filters;
bool useEffects;
worldvec3 listenerPosition {};
ALAudio(
ALCdevice* device,
@ -221,7 +226,7 @@ namespace audio {
std::vector<std::string> getInputDeviceNames() override;
void setListener(
glm::vec3 position,
worldvec3 position,
glm::vec3 velocity,
glm::vec3 lookAt,
glm::vec3 up

View file

@ -97,7 +97,7 @@ namespace audio {
}
void setListener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
worldvec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
) override {
}

View file

@ -352,7 +352,7 @@ void audio::set_input_device(const std::string& deviceName) {
}
void audio::set_listener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
) {
backend->setListener(position, velocity, lookAt, up);
}
@ -380,7 +380,7 @@ void remove_lower_priority_speaker(int priority) {
speakerid_t audio::play(
Sound* sound,
glm::vec3 position,
worldvec3 position,
bool relative,
float volume,
float pitch,
@ -419,7 +419,7 @@ speakerid_t audio::play(
speakerid_t audio::play(
const std::shared_ptr<Stream>& stream,
glm::vec3 position,
worldvec3 position,
bool relative,
float volume,
float pitch,
@ -451,7 +451,7 @@ speakerid_t audio::play(
speakerid_t audio::play_stream(
const io::path& file,
glm::vec3 position,
worldvec3 position,
bool relative,
float volume,
float pitch,

View file

@ -331,11 +331,11 @@ namespace audio {
/// @brief Set speaker 3D position in the world
/// @param pos new position
virtual void setPosition(glm::vec3 pos) = 0;
virtual void setPosition(worldvec3 pos) = 0;
/// @brief Get speaker 3D position in the world
/// @return position
virtual glm::vec3 getPosition() const = 0;
virtual worldvec3 getPosition() const = 0;
/// @brief Set speaker movement velocity used for Doppler effect
/// @param vel velocity vector
@ -391,7 +391,7 @@ namespace audio {
uint bitsPerSample
) = 0;
virtual void setListener(
glm::vec3 position,
worldvec3 position,
glm::vec3 velocity,
glm::vec3 lookAt,
glm::vec3 up
@ -482,7 +482,7 @@ namespace audio {
/// @param lookAt point the listener look at
/// @param up camera up vector
void set_listener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
);
/// @brief Play 3D sound in the world
@ -498,7 +498,7 @@ namespace audio {
/// @return speaker id or 0
speakerid_t play(
Sound* sound,
glm::vec3 position,
worldvec3 position,
bool relative,
float volume,
float pitch,
@ -518,7 +518,7 @@ namespace audio {
/// @return speaker id or 0
speakerid_t play(
const std::shared_ptr<Stream>& stream,
glm::vec3 position,
worldvec3 position,
bool relative,
float volume,
float pitch,
@ -537,7 +537,7 @@ namespace audio {
/// @return speaker id or 0
speakerid_t play_stream(
const io::path& file,
glm::vec3 position,
worldvec3 position,
bool relative,
float volume,
float pitch,

View file

@ -34,8 +34,8 @@ namespace dv {
return values;
}
template <int n>
void get_vec(const dv::value& list, glm::vec<n, float>& vec) {
template <int n, typename T>
void get_vec(const dv::value& list, glm::vec<n, T>& vec) {
for (size_t i = 0; i < n; i++) {
vec[i] = list[i].asNumber();
}

View file

@ -74,7 +74,7 @@ LevelFrontend::LevelFrontend(
}
auto sound = assets.get<audio::Sound>(material->stepsSound);
glm::vec3 pos {};
worldvec3 pos {};
auto soundsCamera = currentPlayer.currentCamera.get();
if (currentPlayer.isCurrentCameraBuiltin()) {
soundsCamera = currentPlayer.fpCamera.get();
@ -117,7 +117,7 @@ LevelFrontend::LevelFrontend(
}
audio::play(
sound,
glm::vec3(pos.x, pos.y, pos.z) + 0.5f,
worldvec3(pos.x, pos.y, pos.z) + 0.5,
false,
1.0f,
1.0f + (rand() % 6 - 3) * 0.05f,

View file

@ -292,7 +292,7 @@ std::shared_ptr<UINode> create_debug_panel(
if (allowDebugCheats) {
box->setTextConsumer([&player, ax](const std::wstring& text) {
try {
glm::vec3 position = player.getPosition();
worldvec3 position = player.getPosition();
position[ax] = std::stoi(text);
player.teleport(position);
} catch (std::exception& _) {

View file

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

View file

@ -95,7 +95,17 @@ void Shadows::setQuality(int 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) {
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
));
shader.uniform1i("u_screen", 0);
shader.uniformMatrix("u_shadowsMatrix[0]", shadowCamera.getProjView());
shader.uniformMatrix("u_shadowsMatrix[1]", wideShadowCamera.getProjView());
const glm::ivec3 origin = camera.getOrigin();
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.uniform1i("u_shadowsRes", shadowMap->getResolution());
shader.uniform1f("u_shadowsOpacity", shadowsOpacity); // TODO: make it configurable
@ -165,10 +180,10 @@ void Shadows::generateShadowsMap(
float shadowMapScale = 0.32f / (1 << glm::max(0, quality)) * scale;
float shadowMapSize = resolution * shadowMapScale;
glm::vec3 basePos = glm::floor(camera.position / 4.0f) * 4.0f;
glm::vec3 prevPos = shadowCamera.position;
worldvec3 basePos = glm::floor(camera.position / 4.0) * 4.0;
worldvec3 prevPos = shadowCamera.position;
shadowCamera = Camera(
glm::distance2(prevPos, basePos) > 25.0f ? basePos : prevPos,
glm::distance2(prevPos, basePos) > 25.0 ? basePos : prevPos,
shadowMapSize
);
shadowCamera.near = 0.1f;
@ -191,13 +206,13 @@ void Shadows::generateShadowsMap(
glm::radians(0.0f)
);
shadowCamera.position -= shadowCamera.front * 500.0f;
shadowCamera.position += shadowCamera.up * 0.0f;
shadowCamera.position += camera.front * 0.0f;
shadowCamera.position -= worldvec3(shadowCamera.front * 500.0f);
shadowCamera.position += worldvec3(shadowCamera.up * 0.0f);
shadowCamera.position += worldvec3(camera.front * 0.0f);
auto view = shadowCamera.getView();
auto currentPos = shadowCamera.position;
auto currentPos = shadowCamera.getLocalPosition();
auto topRight = shadowCamera.right + shadowCamera.up;
auto min = 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();
void setup(Shader& shader, const Weather& weather);
void setup(Shader& shader, const Camera& camera, const Weather& weather);
void setQuality(int quality);
void refresh(
const Camera& camera,

View file

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

View file

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

View file

@ -637,12 +637,7 @@ SortingMeshData BlocksRenderer::renderTranslucent(
continue;
}
SortingMeshEntry entry {
glm::vec3(
x + chunk->x * CHUNK_W + 0.5f,
y + 0.5f,
z + chunk->z * CHUNK_D + 0.5f
),
util::Buffer<ChunkVertex>(indexCount), 0};
glm::vec3(x, y, z), util::Buffer<ChunkVertex>(indexCount), 0};
totalSize += entry.vertexData.size();
@ -660,10 +655,6 @@ SortingMeshData BlocksRenderer::renderTranslucent(
} else {
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));
vertexCount = 0;

View file

@ -12,6 +12,7 @@
#include "window/Camera.hpp"
#include "maths/FrustumCulling.hpp"
#include "maths/util.hpp"
#include "maths/voxmaths.hpp"
#include "util/listutil.hpp"
#include "util/ObjectsPool.hpp"
#include "util/timeutil.hpp"
@ -241,6 +242,9 @@ void ChunksRenderer::drawShadowsPass(
auto denseDistance = settings.graphics.denseRenderDistance.get();
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()) {
if (chunk == nullptr) {
continue;
@ -251,16 +255,12 @@ void ChunksRenderer::drawShadowsPass(
continue;
}
glm::vec3 coord(
pos.x * CHUNK_W + 0.5f, 0.5f, pos.y * CHUNK_D + 0.5f
);
int x = pos.x * CHUNK_W - origin.x;
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 max(
pos.x * CHUNK_W + CHUNK_W,
chunk->top,
pos.y * CHUNK_D + CHUNK_D
);
glm::vec3 min(x, chunk->bottom, z);
glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D);
if (!frustum.isBoxVisible(min, max)) {
continue;
@ -268,7 +268,7 @@ void ChunksRenderer::drawShadowsPass(
glm::mat4 model = glm::translate(glm::mat4(1.0f), coord);
shader.uniformMatrix("u_model", model);
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);
}
}
@ -292,8 +292,13 @@ void ChunksRenderer::drawChunks(
indices.push_back(ChunksSortEntry {i, 0});
}
}
float px = camera.position.x / static_cast<float>(CHUNK_W) - 0.5f;
float pz = camera.position.z / static_cast<float>(CHUNK_D) - 0.5f;
const glm::ivec3 origin = camera.getOrigin();
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) {
float x = index.index % chunksWidth + chunksOffsetX - px;
float z = index.index / chunksWidth + chunksOffsetY - pz;
@ -323,32 +328,28 @@ void ChunksRenderer::drawChunks(
if (mesh.mesh == nullptr) {
continue;
}
int x = chunk->x * CHUNK_W - origin.x;
int z = chunk->z * CHUNK_D - origin.z;
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),
x + 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
z + std::min(0.0f, aabbMin.z)
);
glm::vec3 max(x + aabbMax.x, chunk->top, z + 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::vec3 coord(x + 0.5f, 0.5f, z + 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),
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);
visibleChunks++;
}
@ -375,12 +376,12 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
bool culling = settings.graphics.frustumCulling.get();
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");
shader.use();
atlas.getTexture()->bind();
shader.uniformMatrix("u_model", glm::mat4(1.0f));
shader.uniform1i("u_alphaClip", false);
for (const auto& index : indices) {
@ -393,16 +394,18 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
continue;
}
int x = chunk->x * CHUNK_W - origin.x;
int z = chunk->z * CHUNK_D - origin.z;
if (culling) {
glm::vec3 min(chunk->x * CHUNK_W, chunk->bottom, chunk->z * CHUNK_D);
glm::vec3 max(
chunk->x * CHUNK_W + CHUNK_W,
chunk->top,
chunk->z * CHUNK_D + CHUNK_D
);
glm::vec3 min(x, chunk->bottom, z);
glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D);
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;
@ -418,7 +421,7 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
}
for (auto& entry : chunkEntries) {
entry.distance = static_cast<long long>(
glm::distance2(entry.position, cameraPos)
glm::distance2(entry.position, cameraPos - coord)
);
}
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 float CLOUD_VOXEL_SCALE = 8.0f;
static inline constexpr float CLOUDS_SPEED = 4.0f;
static inline constexpr double CLOUDS_WAVE_PERIOD = glm::two_pi<double>() * 1e3;
class CloudsMap {
public:
@ -269,8 +270,15 @@ void CloudsRenderer::draw(
float scale = CLOUD_VOXEL_SCALE;
int totalDiameter = layer.segmentSize * scale;
int gcellX = floordiv(camera.position.x, totalDiameter);
int gcellZ = floordiv(camera.position.z, totalDiameter);
const glm::ivec3 origin = camera.getOrigin();
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 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 lcellZ = gcellZ - floordiv(glm::floor(timer * speedZ), totalDiameter);
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)),
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))
);
if (glm::distance2(
@ -294,7 +302,7 @@ void CloudsRenderer::draw(
position.x + totalDiameter * 0.5f,
position.z + totalDiameter * 0.5f
),
glm::vec2(camera.position.x, camera.position.z)
glm::vec2(cameraPos.x, cameraPos.z)
) > 4e6) {
continue;
}
@ -331,6 +339,13 @@ void CloudsRenderer::draw(
shader.uniform1f("u_fogFactor", fogFactor * 0.03f);
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++) {
draw(layers[i], frustum, shader, camera, timer, i);
}

View file

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

View file

@ -83,7 +83,7 @@ void Decorator::addParticles(const Block& def, const glm::ivec3& pos) {
);
blockEmitters[pos] = renderer.particles->add(std::make_unique<Emitter>(
level,
glm::vec3{pos.x + 0.5, pos.y + 0.5, pos.z + 0.5},
worldvec3 {pos.x + 0.5, pos.y + 0.5, pos.z + 0.5},
*def.particles,
treg.texture,
treg.region,
@ -120,7 +120,7 @@ void Decorator::updateAcoustics(const Camera& camera) {
glm::vec3 dir = { r * std::cos(phi), r * std::sin(phi), z };
dir = glm::normalize(dir);
glm::vec3 end;
worldvec3 end;
glm::ivec3 norm;
glm::ivec3 iend;
blocks_agent::RaycastSettings raycast {};
@ -128,7 +128,7 @@ void Decorator::updateAcoustics(const Camera& camera) {
if (vox == nullptr) {
continue;
}
auto distance = glm::distance(start, end);
float distance = glm::distance(start, end);
if (distance >= length * 0.98f) {
continue;
}
@ -205,7 +205,7 @@ void Decorator::updateRandom(
);
renderer.particles->add(std::make_unique<Emitter>(
level,
glm::vec3 {
worldvec3 {
pos.x + random.randFloat(),
pos.y + 1.1,
pos.z + random.randFloat()},
@ -308,11 +308,11 @@ void Decorator::updateTextNotes() {
renderer.texts->remove(textsIter->second);
textsIter = playerTexts.erase(textsIter);
} else {
glm::vec3 position = player->getPosition();
worldvec3 position = player->getPosition();
if (auto entity = level.entities->get(player->getEntity())) {
position = entity->getInterpolatedPosition();
}
note->setPosition(position + glm::vec3(0, 1, 0));
note->setPosition(position + worldvec3(0, 1, 0));
if (note->getText() != player->getName()) {
note->setText(player->getName());
}

View file

@ -14,7 +14,7 @@
Emitter::Emitter(
const Level& level,
std::variant<glm::vec3, entityid_t> origin,
EmitterOrigin origin,
ParticlesPreset preset,
const Texture* texture,
const UVRegion& region,
@ -50,15 +50,15 @@ static inline glm::vec3 generate_coord(ParticleSpawnShape shape) {
void Emitter::update(
float delta,
const glm::vec3& cameraPosition,
const worldvec3& cameraPosition,
std::vector<Particle>& particles
) {
const float spawnInterval = preset.spawnInterval;
if (count == 0 || (count == -1 && spawnInterval < FLT_EPSILON)) {
return;
}
glm::vec3 position {};
if (auto staticPos = std::get_if<glm::vec3>(&origin)) {
worldvec3 position {};
if (auto staticPos = std::get_if<worldvec3>(&origin)) {
position = *staticPos;
} else if (auto entityId = std::get_if<entityid_t>(&origin)) {
if (auto entity = level.entities->get(*entityId)) {
@ -105,7 +105,7 @@ void Emitter::update(
spawnOffset *= preset.spawnSpread;
spawnOffset += preset.spawnOffset;
particle.position = position + spawnOffset;
particle.position = position + worldvec3(spawnOffset);
particle.lifetime *= 1.0f - preset.lifetimeSpread * random.randFloat();
particle.velocity += glm::ballRand(1.0f) * preset.explosion;
if (preset.randomSubUV < 1.0f) {

View file

@ -20,7 +20,7 @@ struct Particle {
/// @brief Some random integer for visuals configuration.
int random;
/// @brief Global position
glm::vec3 position;
worldvec3 position;
/// @brief Linear velocity
glm::vec3 velocity;
/// @brief Remaining life time
@ -35,7 +35,7 @@ struct Particle {
class Texture;
using EmitterOrigin = std::variant<glm::vec3, entityid_t>;
using EmitterOrigin = std::variant<worldvec3, entityid_t>;
class Emitter {
const Level& level;
@ -61,7 +61,7 @@ public:
Emitter(
const Level& level,
std::variant<glm::vec3, entityid_t> origin,
EmitterOrigin origin,
ParticlesPreset preset,
const Texture* texture,
const UVRegion& region,
@ -79,7 +79,7 @@ public:
/// @param particles destination particles vector
void update(
float delta,
const glm::vec3& cameraPosition,
const worldvec3& cameraPosition,
std::vector<Particle>& particles
);

View file

@ -5,6 +5,7 @@
#include "graphics/core/DrawContext.hpp"
#include "graphics/core/LineBatch.hpp"
#include "maths/FrustumCulling.hpp"
#include "maths/util.hpp"
#include "objects/Entities.hpp"
#include "objects/Entity.hpp"
#include "objects/EntityDef.hpp"
@ -46,10 +47,12 @@ static bool check_frustum(
const Frustum& frustum,
const Transform& transform,
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);
return frustum.isBoxVisible(transform.pos - ext, transform.pos + ext);
return frustum.isBoxVisible(pos - ext, pos + ext);
}
EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities)
@ -57,8 +60,12 @@ EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities)
}
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()) {
if (!entity->getSkeleton() || uid == fpsEntity) {
continue;
@ -73,12 +80,17 @@ void EntitiesRenderer::render(
if (rigConfig == nullptr) {
continue;
}
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) {
if (frustum &&
!check_frustum(*frustum, transform, rigidbody, skeleton, origin)) {
if (!skeleton.boundsDirty || !skeleton.visible) {
continue;
}
rigConfig->updateBounds(assets, skeleton, transform.rot, pos, size);
if (!check_frustum(*frustum, transform, rigidbody, skeleton)) {
rigConfig->updateBounds(
assets, skeleton, transform.rot, pos, size, origin
);
if (!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue;
}
}
@ -90,6 +102,7 @@ void EntitiesRenderer::render(
transform.rot,
pos,
size,
origin,
def.translucent
);
}
@ -97,6 +110,7 @@ void EntitiesRenderer::render(
void EntitiesRenderer::renderDebug(
LineBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum,
const DrawContext& pctx,
entityid_t fpsEntity
@ -113,20 +127,31 @@ void EntitiesRenderer::renderDebug(
const auto& rigidbody = entity->getRigidbody();
const auto& skeleton = *entity->getSkeleton();
const auto& hitbox = rigidbody.hitbox;
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) {
if (frustum &&
!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue;
}
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);
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) {
if (sensor.type != SensorType::AABB) continue;
batch.box(
sensor.calculated.aabb.center(),
util::to_local(
sensor.position +
worldvec3(sensor.calculated.aabb.center()),
origin
),
sensor.calculated.aabb.size(),
glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)
);
@ -149,7 +174,10 @@ void EntitiesRenderer::renderDebug(
if (config == nullptr) {
continue;
}
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) {
if (frustum &&
!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue;
}
auto bone = config->getRoot();
@ -159,7 +187,7 @@ void EntitiesRenderer::renderDebug(
}
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()) {
if (!entity->getSkeleton()) {
@ -171,7 +199,11 @@ void EntitiesRenderer::updateCulling(
continue;
}
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 <glm/vec3.hpp>
class Assets;
class DrawContext;
class Entities;
@ -16,15 +18,21 @@ public:
EntitiesRenderer(const Assets& assets, Entities& entities);
void render(
ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity
ModelBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum,
entityid_t fpsEntity
);
void renderDebug(
LineBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum,
const DrawContext& ctx,
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,
glm::mat3(1.0f),
glm::vec3(),
glm::vec3(1.0f)
glm::vec3(1.0f),
glm::ivec3()
);
modelBatch.render();

View file

@ -63,11 +63,11 @@ void MainBatch::prepare(int vertices) {
}
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(
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));
light_t minIntensity = backlight ? 1 : 0;
return {

View file

@ -46,7 +46,7 @@ public:
void flush();
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(

View file

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

View file

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

View file

@ -38,10 +38,10 @@ static inline void update_particle(
auto& angle = particle.angle;
vel += delta * preset.acceleration;
if (preset.collision && chunks.isObstacleAt(pos + vel * delta)) {
if (preset.collision && chunks.isObstacleAt(pos + worldvec3(vel * delta))) {
vel *= 0.0f;
}
pos += vel * delta;
pos += worldvec3(vel * delta);
angle += particle.angularVelocity * delta;
particle.lifetime -= delta;
}
@ -114,7 +114,8 @@ static inline glm::vec4 calc_lights(
light = glm::max(
light,
MainBatch::sampleLight(
particle.position - size * glm::vec3(x, y, z),
particle.position -
worldvec3(size * glm::vec3(x, y, z)),
chunks,
backlight
)
@ -154,7 +155,7 @@ void ParticlesRenderer::renderParticle(
camera.front * rotatedUp.z;
}
batch->quad(
particle.position,
util::to_local(particle.position, camera.getOrigin()),
localRight,
localUp,
-camera.front,

View file

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

View file

@ -1,6 +1,6 @@
#include "TextNote.hpp"
TextNote::TextNote(std::wstring text, NotePreset preset, glm::vec3 position)
TextNote::TextNote(std::wstring text, NotePreset preset, worldvec3 position)
: text(std::move(text)),
preset(std::move(preset)),
position(std::move(position)) {
@ -30,11 +30,11 @@ void TextNote::updatePreset(const dv::value& data) {
preset.deserialize(data);
}
void TextNote::setPosition(const glm::vec3& position) {
void TextNote::setPosition(const worldvec3& position) {
this->position = position;
}
const glm::vec3& TextNote::getPosition() const {
const worldvec3& TextNote::getPosition() const {
return position;
}

View file

@ -7,13 +7,13 @@
class TextNote {
std::wstring text;
NotePreset preset;
glm::vec3 position;
worldvec3 position;
entityid_t entity = ENTITY_NONE;
glm::vec3 xAxis {1, 0, 0};
glm::vec3 yAxis {0, 1, 0};
public:
TextNote(std::wstring text, NotePreset preset, glm::vec3 position);
TextNote(std::wstring text, NotePreset preset, worldvec3 position);
void setText(std::wstring_view text);
void setEntity(entityid_t eid);
@ -25,8 +25,8 @@ public:
void updatePreset(const dv::value& data);
void setPosition(const glm::vec3& position);
const glm::vec3& getPosition() const;
void setPosition(const worldvec3& position);
const worldvec3& getPosition() const;
const glm::vec3& getAxisX() const;
const glm::vec3& getAxisY() const;

View file

@ -35,16 +35,19 @@ void TextsRenderer::renderNote(
) {
const auto& text = note.getText();
const auto& preset = note.getPreset();
auto pos = note.getPosition();
auto worldPos = note.getPosition();
entityid_t eid = note.getEntity();
if (eid != ENTITY_NONE) {
if (auto entity = level.entities->get(eid)) {
pos += entity->getTransform().displayPos;
worldPos += entity->getTransform().displayPos;
}
}
if (util::distance2(pos, camera.position) >
glm::vec3 pos = util::to_local(worldPos, camera.getOrigin());
const glm::vec3 cameraPos = camera.getLocalPosition();
if (util::distance2(pos, cameraPos) >
util::sqr(preset.renderDistance / camera.zoom)) {
return;
}
@ -70,7 +73,7 @@ void TextsRenderer::renderNote(
int height = font.getLineHeight();
if (preset.displayMode == NoteDisplayMode::Y_FREE_BILLBOARD ||
preset.displayMode == NoteDisplayMode::XY_FREE_BILLBOARD) {
xvec = camera.position - pos;
xvec = cameraPos - pos;
xvec.y = 0;
std::swap(xvec.x, xvec.z);
xvec.z *= -1;
@ -80,9 +83,7 @@ void TextsRenderer::renderNote(
}
float scale =
(1.0f - preset.perspective) *
glm::pow(
glm::distance(camera.position, pos), 1.0f - preset.perspective
);
glm::pow(glm::distance(cameraPos, pos), 1.0f - preset.perspective);
xvec *= 1.0f + scale;
yvec *= 1.0f + scale;
}
@ -91,7 +92,7 @@ void TextsRenderer::renderNote(
float scale = 1.0f;
if (glm::abs(preset.perspective) > 0.0001f) {
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)));
scale = scale2 * preset.perspective +
scale * (1.0f - preset.perspective);

View file

@ -42,6 +42,7 @@
#include "items/ItemStack.hpp"
#include "logic/PlayerController.hpp"
#include "maths/FrustumCulling.hpp"
#include "maths/util.hpp"
#include "maths/voxmaths.hpp"
#include "objects/Entities.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_proj", camera.getProjection());
shader.uniformMatrix("u_view", camera.getView());
shader.uniform3f("u_cameraPos", camera.position);
shader.uniform3f("u_cameraPos", camera.getLocalPosition());
}
void WorldRenderer::setupWorldShader(
@ -226,7 +227,7 @@ void WorldRenderer::setupWorldShader(
setup_camera(shader, camera);
setup_weather(shader, weather);
shadowMapping->setup(shader, weather);
shadowMapping->setup(shader, camera, weather);
shader.uniform1f("u_timer", timer);
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});
entitiesRenderer->render(
*modelBatch,
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0
@ -297,7 +299,7 @@ void WorldRenderer::renderOpaque(
setupWorldShader(mainShader, camera, settings, fogFactor);
chunksRenderer->drawChunks(camera, mainShader);
blockWraps->draw(ctx);
blockWraps->draw(ctx, camera);
if (level.environment.sky.clouds) {
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;
auto indices = level.content.getIndices();
blockid_t id = selection.vox.id;
auto& block = indices->blocks.require(id);
const glm::ivec3 origin = camera.getOrigin();
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 auto& hitboxes = block.getHitboxes(
@ -330,7 +333,7 @@ void WorldRenderer::renderBlockSelection() {
lineBatch->lineWidth(2.0f);
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();
lineBatch->box(
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.uniformMatrix("u_projview", camera.getProjView());
if (player.selection.vox.id != BLOCK_VOID) {
renderBlockSelection();
renderBlockSelection(camera);
}
if (debug && showEntitiesDebug) {
auto ctx = pctx.sub(lineBatch.get());
bool culling = engine.getSettings().graphics.frustumCulling.get();
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
);
}
@ -368,6 +374,7 @@ void WorldRenderer::updateEntitiesCulling(const Camera& camera) {
frustumCulling->update(camera.getProjView());
}
entitiesRenderer->updateCulling(
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0
@ -587,7 +594,7 @@ void WorldRenderer::renderTranslucency(
auto& shader = assets.require<Shader>("model");
setupWorldShader(shader, camera, settings, fogFactor);
setup_entity_pass(shader, {0.002f, false, true, true, 1.0f});
modelBatch->renderTranslucent(camera.position);
modelBatch->renderTranslucent(camera.getLocalPosition());
}
{
auto lctx = ctx.sub();

View file

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

View file

@ -59,7 +59,7 @@ LevelController::LevelController(
confirmed++;
continue;
}
glm::vec3 position = player->getPosition();
const auto& position = player->getPosition();
player->chunks->configure(
std::floor(position.x), std::floor(position.z), 1
);
@ -82,7 +82,7 @@ void LevelController::update(float delta, bool pause) {
continue;
}
player->rotationInterpolation.updateTimer(delta);
glm::vec3 position = player->getPosition();
const auto& position = player->getPosition();
player->chunks->configure(
glm::floor(position.x),
glm::floor(position.z),

View file

@ -54,7 +54,7 @@ CameraControl::CameraControl(
}
void CameraControl::refreshPosition() {
camera->position = player.getPosition() + offset;
camera->position = player.getPosition() + worldvec3(offset);
}
void CameraControl::refreshRotation() {
@ -200,7 +200,7 @@ void CameraControl::update(
refreshPosition();
auto castRay = [](Player& player, Camera& camera, const glm::vec3& front)
-> glm::vec3 {
-> worldvec3 {
auto blockEnd = player.chunks->rayCastToObstacle(camera.position, front, 3.0f);
Entities::RaycastSettings raycast {};
@ -212,7 +212,7 @@ void CameraControl::update(
);
if (entityRay.has_value() &&
entityRay->distance < glm::distance(camera.position, blockEnd)) {
return (camera.position + front * entityRay->distance);
return camera.position + worldvec3(front * entityRay->distance);
} else {
return blockEnd;
}
@ -220,14 +220,14 @@ void CameraControl::update(
camera->updateVectors();
if (player.currentCamera == spCamera) {
spCamera->position =
castRay(player, *camera, camera->front) - 0.4f * camera->front;
spCamera->position = castRay(player, *camera, camera->front) -
worldvec3(0.4f * camera->front);
spCamera->dir = -camera->dir;
spCamera->front = -camera->front;
spCamera->right = -camera->right;
} else if (player.currentCamera == tpCamera) {
tpCamera->position = castRay(player, *camera, camera->front * -1.0f) +
0.4f * camera->front;
worldvec3(0.4f * camera->front);
tpCamera->dir = camera->dir;
tpCamera->front = camera->front;
tpCamera->right = camera->right;
@ -366,7 +366,7 @@ voxel* PlayerController::updateSelection(float maxDistance) {
auto camera = player.fpCamera.get();
auto& selection = player.selection;
glm::vec3 end;
worldvec3 end;
glm::ivec3 iend;
glm::ivec3 norm;
voxel* vox = chunks.rayCast(
@ -393,7 +393,7 @@ voxel* PlayerController::updateSelection(float maxDistance) {
)) {
selection.entity = result->entity;
selection.hitPosition =
camera->position + camera->front * result->distance;
camera->position + worldvec3(camera->front * result->distance);
selection.position = selection.hitPosition;
selection.actualPosition = selection.position;
selection.normal = result->normal;
@ -461,8 +461,7 @@ void PlayerController::processRightClick(
if (def.obstacle) {
const auto& hitboxes = def.getHitboxes(state);
for (const AABB& blockAABB : hitboxes) {
if (level.entities->hasBlockingInside(blockAABB.translated(coord)
)) {
if (level.entities->hasBlockingInside(coord, blockAABB)) {
return;
}
}

View file

@ -2,7 +2,7 @@
#include "maths/util.hpp"
static void check_valid(const glm::vec3& vec) {
static void check_valid(const worldvec3& vec) {
if (util::is_nan_or_inf(vec)) {
throw std::invalid_argument(
"invalid vector: " + std::to_string(vec.x) + ", " +
@ -21,14 +21,14 @@ static void check_valid(const glm::mat3& vec) {
static int l_get_pos(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
return lua::pushvec3(L, entity->getTransform().pos);
return lua::pushvec(L, entity->getTransform().pos);
}
return 0;
}
static int l_set_pos(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
auto vec = lua::tovec3(L, 2);
auto vec = lua::tovec<3, double>(L, 2);
check_valid(vec);
entity->getTransform().setPos(vec);
entity->getRigidbody().hitbox.setPos(vec);

View file

@ -42,9 +42,7 @@ static audio::speakerid_t play_sound(
}
return audio::play(
sound,
glm::vec3(
static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)
),
worldvec3(x, y, z),
relative,
volume,
pitch,
@ -75,11 +73,7 @@ static audio::speakerid_t play_stream(
if (stream) {
return audio::play(
audio::open_stream(std::move(stream), true),
glm::vec3(
static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(z)
),
worldvec3(x, y, z),
relative,
volume,
pitch,
@ -96,15 +90,7 @@ static audio::speakerid_t play_stream(
file = paths.find(filename);
}
return audio::play_stream(
file,
glm::vec3(
static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)
),
relative,
volume,
pitch,
loop,
channel
file, worldvec3(x, y, z), relative, volume, pitch, loop, channel
);
}
@ -277,9 +263,7 @@ static int l_audio_set_position(lua::State* L) {
auto x = lua::tonumber(L, 2);
auto y = lua::tonumber(L, 3);
auto z = lua::tonumber(L, 4);
speaker->setPosition(glm::vec3(
static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)
));
speaker->setPosition(worldvec3(x, y, z));
}
return 0;
}

View file

@ -548,7 +548,7 @@ static int l_destruct(lua::State* L) {
static int l_raycast(lua::State* L) {
const auto& level = require_level();
auto start = lua::tovec<3>(L, 1);
auto start = lua::tovec<3, double>(L, 1);
auto dir = lua::tovec<3>(L, 2);
auto maxDistance = lua::tonumber(L, 3);
@ -576,7 +576,7 @@ static int l_raycast(lua::State* L) {
if (luaStackSize >= 6) {
raycast.includeNonSelectable = lua::toboolean(L, 6);
}
glm::vec3 end;
worldvec3 end;
glm::ivec3 normal;
glm::ivec3 iend;
@ -589,7 +589,7 @@ static int l_raycast(lua::State* L) {
lua::createtable(L, 0, 5);
}
lua::pushvec3(L, end);
lua::pushvec(L, end);
lua::setfield(L, "endpoint");
lua::pushvec3(L, normal);
@ -598,7 +598,7 @@ static int l_raycast(lua::State* L) {
lua::pushnumber(L, glm::distance(start, end));
lua::setfield(L, "length");
lua::pushvec3(L, iend);
lua::pushvec(L, iend);
lua::setfield(L, "iendpoint");
lua::pushinteger(L, voxel->id);

View file

@ -7,7 +7,7 @@
using namespace scripting;
static int l_wrap(lua::State* L) {
auto position = lua::tovec3(L, 1);
auto position = lua::tovec<3, double>(L, 1);
std::string texture = lua::require_string(L, 2);
float emission = lua::isnumber(L, 3) ? lua::tonumber(L, 3) : 1.0f;
glm::vec4 tint =
@ -31,7 +31,7 @@ static int l_unwrap(lua::State* L) {
static int l_set_pos(lua::State* L) {
if (auto wrapper = renderer->blockWraps->get(lua::tointeger(L, 1))) {
wrapper->position = lua::tovec3(L, 2);
wrapper->position = lua::tovec<3, double>(L, 2);
}
return 0;
}

View file

@ -47,11 +47,11 @@ static int l_name(lua::State* L) {
}
static int getter_pos(lua::State* L, const Camera& camera) {
return lua::pushvec3(L, camera.position);
return lua::pushvec(L, camera.position);
}
static void setter_pos(lua::State* L, Camera& camera, int idx) {
camera.position = lua::tovec<3>(L, idx);
camera.position = lua::tovec<3, double>(L, idx);
}
static int getter_rot(lua::State* L, const Camera& camera) {
@ -104,9 +104,11 @@ static int getter_up(lua::State* L, const Camera& camera) {
static int l_look_at(lua::State* L) {
size_t index = static_cast<size_t>(lua::tointeger(L, 1));
auto& camera = *require_level().cameras.at(index);
auto center = lua::tovec<3>(L, 2);
auto center = lua::tovec<3, double>(L, 2);
auto matrix = glm::inverse(
glm::lookAt(glm::vec3(), center - camera.position, glm::vec3(0, 1, 0))
glm::lookAt(
glm::vec3(), glm::vec3(center - camera.position), glm::vec3(0, 1, 0)
)
);
if (lua::isnumber(L, 3)) {
matrix = glm::mat4_cast(glm::slerp(

View file

@ -72,7 +72,7 @@ static int l_spawn(lua::State* L) {
auto level = controller->getLevel();
auto defname = lua::require_string(L, 1);
auto& def = content->entities.require(defname);
auto pos = lua::tovec3(L, 2);
auto pos = lua::tovec<3, double>(L, 2);
dv::value args = nullptr;
if (lua::gettop(L) > 2) {
args = lua::tovalue(L, 3);
@ -133,9 +133,9 @@ static int l_set_skeleton(lua::State* L) {
}
static int l_get_all_in_box(lua::State* L) {
auto pos = lua::tovec<3>(L, 1);
auto size = lua::tovec<3>(L, 2);
auto found = level->entities->getAllInside(AABB(pos, pos + size));
auto pos = lua::tovec<3, double>(L, 1);
auto size = lua::tovec<3, double>(L, 2);
auto found = level->entities->getAllInside(pos, pos + size);
lua::createtable(L, found.size(), 0);
for (size_t i = 0; i < found.size(); i++) {
lua::pushinteger(L, found[i]->getUID());
@ -145,7 +145,7 @@ static int l_get_all_in_box(lua::State* L) {
}
static int l_get_all_in_radius(lua::State* L) {
auto pos = lua::tovec<3>(L, 1);
auto pos = lua::tovec<3, double>(L, 1);
auto radius = lua::tonumber(L, 2);
auto found = level->entities->getAllInRadius(pos, radius);
lua::createtable(L, found.size(), 0);
@ -160,9 +160,9 @@ static int l_push_ray(
lua::State* L,
const std::optional<Entities::RaycastResult>& ray,
blockid_t block,
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
const glm::vec3& end,
const worldvec3& end,
const glm::ivec3& iend,
const glm::ivec3& normal
) {
@ -175,7 +175,7 @@ static int l_push_ray(
lua::createtable(L, 0, 6);
}
lua::pushvec3(L, ray ? (start + dir * ray->distance) : end);
lua::pushvec(L, ray ? (start + worldvec3(dir * ray->distance)) : end);
lua::setfield(L, "endpoint");
lua::pushvec3(L, ray ? ray->normal : normal);
@ -184,7 +184,7 @@ static int l_push_ray(
lua::pushnumber(L, ray ? ray->distance : glm::distance(start, end));
lua::setfield(L, "length");
lua::pushvec3(L, iend);
lua::pushvec(L, iend);
lua::setfield(L, "iendpoint");
lua::pushinteger(L, block);
@ -202,14 +202,14 @@ static int l_push_ray(
static int l_raycast(
lua::State* L,
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxDistance,
const blocks_agent::RaycastSettings& voxelRaycast,
const Entities::RaycastSettings& entityRaycast,
bool entities
) {
glm::vec3 end;
worldvec3 end;
glm::ivec3 normal;
glm::ivec3 iend;
@ -276,7 +276,8 @@ static int l_world_raycast(lua::State* L) {
std::set<blockid_t> filteredBlocks {};
std::set<entitydefid_t> filteredEntities {};
glm::vec3 start, dir;
worldvec3 start;
glm::vec3 dir;
float maxDistance;
bool entities = true;
@ -285,7 +286,7 @@ static int l_world_raycast(lua::State* L) {
}
lua::requirefield(L, "start", 1);
start = lua::tovec3(L, -1);
start = lua::tovec<3, double>(L, -1);
lua::requirefield(L, "dir", 1);
dir = lua::tovec3(L, -1);
@ -341,7 +342,7 @@ static int l_raycast(lua::State* L) {
std::set<blockid_t> filteredBlocks {};
const int luaStackSize = lua::gettop(L);
glm::vec3 start = lua::tovec<3>(L, 1);
worldvec3 start = lua::tovec<3, double>(L, 1);
glm::vec3 dir = lua::tovec<3>(L, 2);
float maxDistance = lua::tonumber(L, 3);

View file

@ -24,8 +24,8 @@ static int l_save_fragment(lua::State* L) {
}
static int l_create_fragment(lua::State* L) {
auto pointA = lua::tovec<3>(L, 1);
auto pointB = lua::tovec<3>(L, 2);
auto pointA = lua::tovec<3, double>(L, 1);
auto pointB = lua::tovec<3, double>(L, 2);
bool crop = lua::toboolean(L, 3);
bool saveEntities = lua::toboolean(L, 4);

View file

@ -9,7 +9,7 @@ using namespace scripting;
static int l_emit(lua::State* L) {
EmitterOrigin origin;
if (lua::istable(L, 1)) {
origin = lua::tovec3(L, 1);
origin = lua::tovec<3, double>(L, 1);
} else {
origin = static_cast<entityid_t>(lua::tointeger(L, 1));
}
@ -47,8 +47,8 @@ static int l_get_origin(lua::State* L) {
u64id_t id = lua::touinteger(L, 1);
if (auto emitter = renderer->particles->getEmitter(id)) {
const auto& origin = emitter->getOrigin();
if (auto pos = std::get_if<glm::vec3>(&origin)) {
return lua::pushvec3(L, *pos);
if (auto pos = std::get_if<worldvec3>(&origin)) {
return lua::pushvec(L, *pos);
} else if (auto entityid = std::get_if<entityid_t>(&origin)) {
return lua::pushinteger(L, *entityid);
}
@ -60,7 +60,7 @@ static int l_set_origin(lua::State* L) {
u64id_t id = lua::touinteger(L, 1);
if (auto emitter = renderer->particles->getEmitter(id)) {
if (lua::istable(L, 2)) {
emitter->setOrigin(lua::tovec3(L, 2));
emitter->setOrigin(lua::tovec<3, double>(L, 2));
} else {
emitter->setOrigin(static_cast<entityid_t>(lua::tointeger(L, 2)));
}

View file

@ -36,7 +36,7 @@ static int l_is_enabled(lua::State* L) {
static int push_route(lua::State* L, const voxels::Route& route) {
lua::createtable(L, route.nodes.size(), 1);
for (int i = 0; i < route.nodes.size(); i++) {
lua::pushvec3(L, route.nodes[i].pos);
lua::pushvec(L, route.nodes[i].pos);
lua::rawseti(L, i + 1);
}
lua::pushinteger(L, route.totalVisited);
@ -46,8 +46,8 @@ static int push_route(lua::State* L, const voxels::Route& route) {
static int l_make_route(lua::State* L) {
if (auto agent = get_agent(L)) {
auto start = lua::tovec3(L, 2);
auto target = lua::tovec3(L, 3);
auto start = lua::tovec<3, double>(L, 2);
auto target = lua::tovec<3, double>(L, 3);
agent->state = {};
agent->start = glm::floor(start);
agent->target = target;
@ -62,8 +62,8 @@ static int l_make_route(lua::State* L) {
static int l_make_route_async(lua::State* L) {
if (auto agent = get_agent(L)) {
auto start = lua::tovec3(L, 2);
auto target = lua::tovec3(L, 3);
auto start = lua::tovec<3, double>(L, 2);
auto target = lua::tovec<3, double>(L, 3);
agent->state = {};
agent->start = glm::floor(start);
agent->target = target;

View file

@ -47,7 +47,7 @@ static int l_set_pos(lua::State* L) {
auto x = lua::tonumber(L, 2);
auto y = lua::tonumber(L, 3);
auto z = lua::tonumber(L, 4);
player->teleport(glm::vec3(x, y, z));
player->teleport(worldvec3(x, y, z));
return 0;
}
@ -256,7 +256,7 @@ static int l_set_spawnpoint(lua::State* L) {
auto x = lua::tonumber(L, 2);
auto y = lua::tonumber(L, 3);
auto z = lua::tonumber(L, 4);
player->setSpawnPoint(glm::vec3(x, y, z));
player->setSpawnPoint(worldvec3(x, y, z));
}
return 0;
}
@ -359,7 +359,7 @@ static int l_set_suspended(lua::State* L) {
static int l_get_all_in_radius(lua::State* L) {
auto& level = require_level();
auto center = lua::tovec3(L, 1);
auto center = lua::tovec<3, double>(L, 1);
auto radius = static_cast<float>(lua::tonumber(L, 2));
auto players = level.players->getAllInRadius(center, radius);
@ -383,7 +383,7 @@ static int l_get_all(lua::State* L) {
static int l_get_nearest(lua::State* L) {
auto& level = require_level();
auto position = lua::tovec3(L, 1);
auto position = lua::tovec<3, double>(L, 1);
if (auto player = level.players->getNearest(position)) {
lua::pushinteger(L, player->getId());
return 1;

View file

@ -6,7 +6,7 @@
using namespace scripting;
static int l_show(lua::State* L) {
auto position = lua::tovec3(L, 1);
auto position = lua::tovec<3, double>(L, 1);
auto text = lua::require_wstring(L, 2);
auto preset = lua::tovalue(L, 3);
auto extension = lua::tovalue(L, 4);
@ -47,7 +47,7 @@ static int l_get_pos(lua::State* L) {
}
static int l_set_pos(lua::State* L) {
if (auto note = renderer->texts->get(lua::tointeger(L, 1))) {
note->setPosition(lua::tovec3(L, 2));
note->setPosition(lua::tovec<3, double>(L, 2));
}
return 0;
}

View file

@ -100,8 +100,8 @@ namespace lua {
return 1;
}
template <int n>
inline int pushvec_stack(lua::State* L, const glm::vec<n, float>& vec) {
template <int n, typename T = float>
inline int pushvec_stack(lua::State* L, const glm::vec<n, T>& vec) {
for (int i = 0; i < n; i++) {
pushnumber(L, vec[i]);
}

View file

@ -1,5 +1,7 @@
#pragma once
#include "typedefs.hpp"
#include <stdint.h>
#include <ctime>
@ -17,6 +19,10 @@ namespace util {
constexpr inline float EPSILON = 1e-6f;
inline glm::vec3 to_local(const worldvec3& pos, const glm::ivec3& origin) {
return glm::vec3(pos - worldvec3(origin));
}
class PseudoRandom {
uint32_t seed;

View file

@ -43,7 +43,7 @@ Entity* Entities::get(entityid_t id) {
entityid_t Entities::spawn(
const EntityDef& def,
glm::vec3 position,
worldvec3 position,
dv::value args,
dv::value saved,
entityid_t uid
@ -159,7 +159,7 @@ void Entities::loadEntity(const dv::value& map, Entity& entity) {
}
std::optional<Entities::RaycastResult> Entities::rayCast(
glm::vec3 start,
worldvec3 start,
glm::vec3 dir,
float maxDistance,
const RaycastSettings& settings
@ -187,7 +187,11 @@ std::optional<Entities::RaycastResult> Entities::rayCast(
glm::ivec3 normal;
double distance;
if (ray.intersectAABB(
glm::vec3(), hitbox.getAABB(), maxDistance, normal, distance
hitbox.position,
AABB(-hitbox.halfsize, hitbox.halfsize),
maxDistance,
normal,
distance
) > RayRelation::None) {
foundUID = eid.uid;
foundNormal = normal;
@ -268,17 +272,22 @@ void Entities::updateSensors(
sensor.nextEntered.clear();
switch (sensor.type) {
case SensorType::AABB:
case SensorType::AABB: {
glm::mat4 matrix = tsf.combined;
matrix[3] = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
sensor.calculated.aabb = sensor.params.aabb;
sensor.calculated.aabb.transform(tsf.combined);
sensor.calculated.aabb.transform(matrix);
sensor.position = tsf.displayPos;
break;
}
case SensorType::RADIUS:
sensor.calculated.radial = glm::vec4(
body.hitbox.position.x,
body.hitbox.position.y,
body.hitbox.position.z,
0.0f,
0.0f,
0.0f,
sensor.params.radial.w * sensor.params.radial.w
);
sensor.position = body.hitbox.position;
break;
}
sensors.push_back(&sensor);
@ -405,10 +414,10 @@ void Entities::update(float delta) {
}
}
bool Entities::hasBlockingInside(AABB aabb) {
bool Entities::hasBlockingInside(const worldvec3& origin, AABB aabb) {
constexpr float eps = 0.05f;
for (const auto& [uid, entity] : entities) {
AABB bodyAABB(entity->getRigidbody().hitbox.getAABB());
AABB bodyAABB(entity->getRigidbody().hitbox.getAABB(origin));
bodyAABB.scale(glm::vec3(1.0f - eps));
if (entity->getID().def.blocking && aabb.intersects(bodyAABB)) {
return true;
@ -417,17 +426,24 @@ bool Entities::hasBlockingInside(AABB aabb) {
return false;
}
std::vector<Entity*> Entities::getAllInside(AABB aabb) {
std::vector<Entity*> Entities::getAllInside(
const worldvec3& a, const worldvec3& b
) {
const worldvec3 min = glm::min(a, b);
const worldvec3 max = glm::max(a, b);
std::vector<Entity*> collected;
for (const auto& [uid, entity] : entities) {
if (!entity->getID().destroyFlag && aabb.contains(entity->getTransform().pos)) {
const auto& pos = entity->getTransform().pos;
if (!entity->getID().destroyFlag &&
glm::all(glm::greaterThanEqual(pos, min)) &&
glm::all(glm::lessThan(pos, max))) {
collected.push_back(entity.get());
}
}
return collected;
}
std::vector<Entity*> Entities::getAllInRadius(glm::vec3 center, float radius) {
std::vector<Entity*> Entities::getAllInRadius(worldvec3 center, float radius) {
std::vector<Entity*> collected;
for (const auto& [uid, entity] : entities) {
if (glm::distance2(entity->getTransform().pos, center) <= radius * radius) {

View file

@ -52,7 +52,7 @@ public:
entityid_t spawn(
const EntityDef& def,
glm::vec3 position,
worldvec3 position,
dv::value args = nullptr,
dv::value saved = nullptr,
entityid_t uid = 0
@ -84,7 +84,7 @@ public:
/// @param maxDistance Max ray length
/// @return An optional structure containing entity, normal and distance
std::optional<RaycastResult> rayCast(
glm::vec3 start,
worldvec3 start,
glm::vec3 dir,
float maxDistance,
const RaycastSettings& settings
@ -94,9 +94,9 @@ public:
void loadEntity(const dv::value& map);
void loadEntity(const dv::value& map, Entity& entity);
void onSave(const Entity& entity);
bool hasBlockingInside(AABB aabb);
std::vector<Entity*> getAllInside(AABB aabb);
std::vector<Entity*> getAllInRadius(glm::vec3 center, float radius);
bool hasBlockingInside(const worldvec3& origin, AABB aabb);
std::vector<Entity*> getAllInside(const worldvec3& a, const worldvec3& b);
std::vector<Entity*> getAllInRadius(worldvec3 center, float radius);
void despawn(entityid_t id);
void despawn(const std::vector<Entity*>& entities);
dv::value serialize(const std::vector<Entity*>& entities);

View file

@ -26,13 +26,13 @@ Entity::Entity(
Entity::~Entity() = default;
void Entity::setInterpolatedPosition(const glm::vec3& position) {
void Entity::setInterpolatedPosition(const worldvec3& position) {
if (skeleton) {
skeleton->interpolation.refresh(position);
}
}
glm::vec3 Entity::getInterpolatedPosition() const {
worldvec3 Entity::getInterpolatedPosition() const {
if (skeleton) {
const auto& interpolation = skeleton->interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) {

View file

@ -104,9 +104,9 @@ public:
void setPlayer(int64_t player);
void setInterpolatedPosition(const glm::vec3& position);
void setInterpolatedPosition(const worldvec3& position);
glm::vec3 getInterpolatedPosition() const;
worldvec3 getInterpolatedPosition() const;
void setInterpolatedRotation(const glm::quat& rotation);

View file

@ -31,7 +31,7 @@ Player::Player(
Level& level,
int64_t id,
const std::wstring& name,
glm::vec3 position,
worldvec3 position,
float speed,
std::shared_ptr<Inventory> inv,
entityid_t eid
@ -121,7 +121,7 @@ void Player::postUpdate() {
}
}
void Player::teleport(glm::vec3 position) {
void Player::teleport(worldvec3 position) {
this->position = position;
if (auto entity = level.entities->get(eid)) {
@ -138,7 +138,7 @@ void Player::attemptToChooseSpawnpoint() {
int minHeight = generatorDef.playerMinSpawnHeight;
int maxHeight = generatorDef.playerMaxSpawnHeight;
glm::vec3 newpos {0.0f, random.randFloat() * (maxHeight - minHeight + 1) + minHeight, 0.0f};
worldvec3 newpos {0.0f, random.randFloat() * (maxHeight - minHeight + 1) + minHeight, 0.0f};
double angle = random.randDouble() * glm::two_pi<double>();
double radius = glm::sqrt(random.randDouble());
newpos.x += glm::cos(angle) * generatorDef.playerSpawnRadius * radius;
@ -154,7 +154,7 @@ void Player::attemptToChooseSpawnpoint() {
headvox == nullptr || headvox->id != 0) {
return;
}
spawnpoint = newpos + glm::vec3(0.5f, 0.0f, 0.5f);
spawnpoint = newpos + worldvec3(0.5, 0.0, 0.5);
teleport(spawnpoint);
}
@ -259,11 +259,11 @@ const std::shared_ptr<Inventory>& Player::getInventory() const {
return inventory;
}
void Player::setSpawnPoint(glm::vec3 spawnpoint) {
void Player::setSpawnPoint(worldvec3 spawnpoint) {
this->spawnpoint = spawnpoint;
}
glm::vec3 Player::getSpawnPoint() const {
worldvec3 Player::getSpawnPoint() const {
return spawnpoint;
}
@ -324,7 +324,7 @@ void Player::deserialize(const dv::value& src) {
dv::get_vec(rotarr, rotation);
const auto& sparr = src["spawnpoint"];
setSpawnPoint(glm::vec3(
setSpawnPoint(worldvec3(
sparr[0].asNumber(), sparr[1].asNumber(), sparr[2].asNumber()));
src.at("interaction-distance").get(interactionDistance);

View file

@ -38,7 +38,7 @@ struct CursorSelection {
glm::ivec3 position {};
glm::ivec3 actualPosition {};
glm::ivec3 normal {};
glm::vec3 hitPosition;
worldvec3 hitPosition;
entityid_t entity = ENTITY_NONE;
};
@ -50,8 +50,8 @@ class Player : public Serializable {
int chosenSlot;
int hotbarSize;
glm::vec3 position;
glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")};
worldvec3 position;
worldvec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")};
std::shared_ptr<Inventory> inventory;
bool suspended = false;
bool flight = false;
@ -81,14 +81,14 @@ public:
Level& level,
int64_t id,
const std::wstring& name,
glm::vec3 position,
worldvec3 position,
float speed,
std::shared_ptr<Inventory> inv,
entityid_t eid
);
~Player();
void teleport(glm::vec3 position);
void teleport(worldvec3 position);
void updateEntity();
void updateSelectedEntity();
void postUpdate();
@ -134,7 +134,7 @@ public:
const std::shared_ptr<Inventory>& getInventory() const;
const glm::vec3& getPosition() const {
const worldvec3& getPosition() const {
return position;
}
@ -142,8 +142,8 @@ public:
Hitbox* getHitbox() const;
void setSpawnPoint(glm::vec3 point);
glm::vec3 getSpawnPoint() const;
void setSpawnPoint(worldvec3 point);
worldvec3 getSpawnPoint() const;
glm::vec3 getRotation(bool interpolated=false) const;
void setRotation(const glm::vec3& rotation);

View file

@ -25,7 +25,7 @@ Player* Players::get(int64_t id) const {
}
std::vector<Player*> Players::getAllInRadius(
const glm::vec3& center, float radius
const worldvec3& center, float radius
) const {
std::vector<Player*> foundPlayers;
@ -48,9 +48,9 @@ std::vector<Player*> Players::getAll() const {
return allPlayers;
}
Player* Players::getNearest(const glm::vec3& position) const {
Player* Players::getNearest(const worldvec3& position) const {
Player* nearest = nullptr;
float nearestDist2 = std::numeric_limits<float>::max();
double nearestDist2 = std::numeric_limits<double>::max();
for (const auto& pair : players) {
auto player = pair.second.get();
if (player->isSuspended()) {

View file

@ -36,9 +36,11 @@ public:
void remove(int64_t id);
std::vector<Player*> getAllInRadius(const glm::vec3& center, float radius) const;
std::vector<Player*> getAllInRadius(
const worldvec3& center, float radius
) const;
std::vector<Player*> getAll() const;
Player* getNearest(const glm::vec3& position) const;
Player* getNearest(const worldvec3& position) const;
dv::value serialize() const override;

View file

@ -11,7 +11,7 @@ static debug::Logger logger("entity-transform");
void Transform::refresh() {
combined = glm::mat4(1.0f);
combined = glm::translate(combined, pos);
combined = glm::translate(combined, glm::vec3(pos));
combined = combined * glm::mat4(rot);
combined = glm::scale(combined, size);
displayPos = pos;
@ -37,7 +37,7 @@ void Transform::deserialize(const dv::value& root) {
dv::get_mat(root, "rot", rot);
}
bool Transform::checkValue(const glm::vec3& vector, std::string_view name) {
bool Transform::checkValue(const worldvec3& vector, std::string_view name) {
if (util::is_nan_or_inf(vector)) {
auto message = "invalid vector attempted set to " + std::string(name) +
" : " + std::to_string(vector.x) + ", " +

View file

@ -2,6 +2,8 @@
#define GLM_ENABLE_EXPERIMENTAL
#include "typedefs.hpp"
#include <stdexcept>
#include <glm/vec3.hpp>
#include <glm/mat4x4.hpp>
@ -10,13 +12,13 @@
struct Transform {
static inline constexpr float EPSILON = 1e-7f;
glm::vec3 pos;
worldvec3 pos;
glm::vec3 size;
glm::mat3 rot;
glm::mat4 combined;
bool dirty = true;
glm::vec3 displayPos {};
worldvec3 displayPos {};
glm::vec3 displaySize {};
dv::value serialize() const;
@ -33,7 +35,7 @@ struct Transform {
}
inline void setSize(const glm::vec3& v) {
if (!checkValue(v, "size")) {
if (!checkValue(worldvec3(v), "size")) {
return;
}
if (glm::distance2(displaySize, v) >= EPSILON) {
@ -42,7 +44,7 @@ struct Transform {
size = v;
}
inline void setPos(const glm::vec3& v) {
inline void setPos(const worldvec3& v) {
if (!checkValue(v, "position")) {
return;
}
@ -52,6 +54,6 @@ struct Transform {
pos = v;
}
static bool checkValue(const glm::vec3& v, std::string_view name);
static bool checkValue(const worldvec3& v, std::string_view name);
static bool checkValue(const glm::mat3& v, std::string_view name);
};

View file

@ -29,10 +29,10 @@ private:
glm::vec3 gravity;
SpatialGrid grid;
std::vector<std::vector<Hitbox*>> nearbySolids;
std::vector<glm::vec3> nearbyOrigins;
std::vector<worldvec3> nearbyOrigins;
std::vector<float> nearbyBudgets;
std::vector<glm::vec3> nearbyReaches;
std::vector<glm::vec3> solidOrigins;
std::vector<worldvec3> solidOrigins;
std::vector<float> solidBudgets;
std::vector<uint> candidates;
std::vector<size_t> solidStamps;

View file

@ -1,7 +1,7 @@
#include "Hitbox.hpp"
Hitbox::Hitbox(
entityid_t entity, BodyType type, glm::vec3 position, glm::vec3 halfsize
entityid_t entity, BodyType type, worldvec3 position, glm::vec3 halfsize
)
: entity(entity),
type(type),

View file

@ -19,7 +19,7 @@ enum class SensorType {
union SensorParams {
AABB aabb;
glm::vec4 radial; // x,y,z calculated entity coords + w - radius
glm::vec4 radial; // w - radius
constexpr SensorParams() : aabb() {
}
@ -38,6 +38,7 @@ struct Sensor {
std::set<entityid_t> nextEntered;
sensorcallback enterCallback;
sensorcallback exitCallback;
worldvec3 position {};
};
enum class BodyType {
@ -53,7 +54,7 @@ VC_ENUM_END
struct Hitbox {
entityid_t entity;
BodyType type;
glm::vec3 position;
worldvec3 position;
glm::vec3 halfsize;
glm::vec3 velocity;
glm::vec3 scale {1.0f, 1.0f, 1.0f};
@ -70,7 +71,7 @@ struct Hitbox {
std::string groundMaterial;
glm::vec3 groundVelocity {};
glm::vec3 prevPosition {};
worldvec3 prevPosition {};
glm::vec3 prevVelocity {};
bool prevGrounded = false;
float substepTime = 0.0f;
@ -80,18 +81,19 @@ struct Hitbox {
static inline constexpr float TELEPORT_THRESOLD_SQR = 0.5f;
Hitbox(
entityid_t entity, BodyType type, glm::vec3 position, glm::vec3 halfsize
entityid_t entity, BodyType type, worldvec3 position, glm::vec3 halfsize
);
AABB getAABB() const {
return AABB(position - halfsize, position + halfsize);
AABB getAABB(const worldvec3& origin) const {
glm::vec3 pos(position - origin);
return AABB(pos - halfsize, pos + halfsize);
}
glm::vec3 getHalfSize() const {
return halfsize * scale;
}
void setPos(const glm::vec3& vec) {
void setPos(const worldvec3& vec) {
position = vec;
if (glm::distance2(position, prevPosition) >= TELEPORT_THRESOLD_SQR) {
prevPosition = vec;

View file

@ -2,9 +2,9 @@
#include <algorithm>
inline constexpr float GRID_CELL_SIZE = 4.0f;
inline constexpr float GRID_PADDING = 0.01f;
inline constexpr float GRID_MAX_COORD = 1e9f;
inline constexpr double GRID_CELL_SIZE = 4.0;
inline constexpr double GRID_PADDING = 0.01;
inline constexpr double GRID_MAX_COORD = 1e9;
inline constexpr int GRID_MAX_CELLS = 64;
void SpatialGrid::clear() {
@ -13,7 +13,7 @@ void SpatialGrid::clear() {
}
void SpatialGrid::insert(
uint id, const glm::vec3& center, const glm::vec3& extents
uint id, const worldvec3& center, const glm::vec3& extents
) {
glm::ivec2 min, max;
if (!calcRange(center, extents, min, max)) {
@ -37,20 +37,20 @@ uint64_t SpatialGrid::calcKey(int x, int z) {
}
bool SpatialGrid::calcRange(
const glm::vec3& center,
const worldvec3& center,
const glm::vec3& extents,
glm::ivec2& min,
glm::ivec2& max
) {
glm::vec2 c(center.x, center.z);
glm::vec2 e = glm::vec2(extents.x, extents.z) + GRID_PADDING;
glm::vec2 a = glm::floor((c - e) / GRID_CELL_SIZE);
glm::vec2 b = glm::floor((c + e) / GRID_CELL_SIZE);
glm::dvec2 c(center.x, center.z);
glm::dvec2 e = glm::dvec2(extents.x, extents.z) + GRID_PADDING;
glm::dvec2 a = glm::floor((c - e) / GRID_CELL_SIZE);
glm::dvec2 b = glm::floor((c + e) / GRID_CELL_SIZE);
if (!(glm::abs(a.x) < GRID_MAX_COORD && glm::abs(a.y) < GRID_MAX_COORD &&
glm::abs(b.x) < GRID_MAX_COORD && glm::abs(b.y) < GRID_MAX_COORD)) {
return false;
}
if ((b.x - a.x + 1.0f) * (b.y - a.y + 1.0f) > GRID_MAX_CELLS) {
if ((b.x - a.x + 1.0) * (b.y - a.y + 1.0) > GRID_MAX_CELLS) {
return false;
}
min = glm::ivec2(a);

View file

@ -10,13 +10,13 @@ class SpatialGrid {
public:
void clear();
void insert(uint id, const glm::vec3& center, const glm::vec3& extents);
void insert(uint id, const worldvec3& center, const glm::vec3& extents);
void build();
template <typename Func>
bool query(
const glm::vec3& center, const glm::vec3& extents, const Func& func
const worldvec3& center, const glm::vec3& extents, const Func& func
) const {
glm::ivec2 min, max;
if (!calcRange(center, extents, min, max)) {
@ -46,7 +46,7 @@ private:
static uint64_t calcKey(int x, int z);
static bool calcRange(
const glm::vec3& center,
const worldvec3& center,
const glm::vec3& extents,
glm::ivec2& min,
glm::ivec2& max

View file

@ -2,6 +2,7 @@
#include "scheduling.hpp"
#include "maths/aabb.hpp"
#include "maths/util.hpp"
#include "voxels/GlobalChunks.hpp"
#define GLM_ENABLE_EXPERIMENTAL
@ -28,6 +29,7 @@ static glm::vec3 calc_collsion_velocity_result(
static float calc_step_height(
const GlobalChunks& chunks,
const glm::vec3& pos,
const glm::ivec3& origin,
const glm::vec3& half,
float stepHeight
) {
@ -41,7 +43,9 @@ static float calc_step_height(
float x = (pos.x - half.x) + ix;
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) {
float z = (pos.z - half.z) + iz;
if (chunks.isObstacleAt(x, pos.y + half.y + stepHeight, z, aabb)) {
if (chunks.isObstacleAt(
origin, x, pos.y + half.y + stepHeight, z, aabb
)) {
return 0.0f;
}
}
@ -54,18 +58,20 @@ static float calc_step_height(
template <int nx, int ny, int nz, int sign>
static void calc_collision(
Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const GlobalChunks& chunks,
const std::vector<Hitbox*>& solidHitboxes,
const glm::vec3& half,
float stepHeight,
uint wakeSubstep
) {
auto& pos = hitbox.position;
auto& vel = hitbox.velocity;
glm::vec3 offset(0.0f, stepHeight + E, 0.0f);
for (auto box : solidHitboxes) {
if (glm::distance2(box->position, pos) < E) {
glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue;
}
auto boxhalf = box->getHalfSize();
@ -77,12 +83,13 @@ static void calc_collision(
aabb = aabb + offset;
aabb.b.y -= stepHeight + E * 2;
if ((box->position[nx] - pos[nx]) * sign <= 0.0f || !box->getAABB().intersects(aabb)) {
if ((boxpos[nx] - pos[nx]) * sign <= 0.0f ||
!box->getAABB(origin).intersects(aabb)) {
continue;
}
float newnegx = box->position[nx] - boxhalf[nx] - half[nx];
float newposx = box->position[nx] + boxhalf[nx] + half[nx];
float newnegx = boxpos[nx] - boxhalf[nx] - half[nx];
float newposx = boxpos[nx] + boxhalf[nx] + half[nx];
float newx;
if ((glm::abs(newnegx - pos[nx]) - glm::abs(newposx - pos[nx]))*sign < 0.0f) {
newx = sign > 0 ? newnegx : newposx;
@ -116,7 +123,9 @@ static void calc_collision(
aabb = aabb + offset;
aabb.b.y -= stepHeight + E * 2;
if (const auto obstacle = chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) {
if (const auto obstacle = chunks.isObstacleAt(
origin, coord.x, coord.y, coord.z, aabb
)) {
float newx = std::floor(coord[nx]) - half[nx] * sign +
(sign > 0 ? obstacle->min() : obstacle->max())[nx];
if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) {
@ -130,15 +139,19 @@ static void calc_collision(
}
static bool calc_collision_neg_y(
Hitbox& hitbox, const glm::vec3& half, const CollisionContext& ctx
Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const glm::vec3& half,
const CollisionContext& ctx
) {
const auto& chunks = ctx.chunks;
const auto& solids = ctx.solids;
auto& pos = hitbox.position;
auto& vel = hitbox.velocity;
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue;
}
auto aabb = AABB(pos - half, pos + half);
@ -148,8 +161,8 @@ static bool calc_collision_neg_y(
aabb.scale(scale);
auto boxhalf = box->getHalfSize();
if (box->position.y < pos.y && box->getAABB().intersects(aabb)) {
float newy = box->position.y + boxhalf.y + half.y;
if (boxpos.y < pos.y && box->getAABB(origin).intersects(aabb)) {
float newy = boxpos.y + boxhalf.y + half.y;
if (pos.y < newy && glm::abs(pos.y - newy) < boxhalf.y) {
pos.y = newy;
}
@ -158,7 +171,8 @@ static bool calc_collision_neg_y(
auto velB = calc_collsion_velocity_result(*box, hitbox);
float boxdt = box->substepTime > 0.0f ? box->substepTime : ctx.dt;
hitbox.groundVelocity = (box->position - box->prevPosition) / boxdt;
hitbox.groundVelocity =
glm::vec3(box->position - box->prevPosition) / boxdt;
if (vel.y < hitbox.groundVelocity.y) {
vel.y = velA.y;
push_body(*box, 1, velB.y, ctx.wakeSubstep);
@ -185,8 +199,9 @@ static bool calc_collision_neg_y(
scale.z = 1.0f - E * 4.0f;
aabb.scale(scale);
if (const auto obstacle =
chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) {
if (const auto obstacle = chunks.isObstacleAt(
origin, coord.x, coord.y, coord.z, aabb
)) {
float newy = std::floor(coord.y) + half.y + obstacle->max().y;
if (newy >= pos.y) {
@ -203,6 +218,8 @@ static bool calc_collision_neg_y(
static void calc_collisions(
Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const glm::vec3& half,
float stepHeight,
const CollisionContext& ctx
@ -210,32 +227,31 @@ static void calc_collisions(
const auto& chunks = ctx.chunks;
const auto& solids = ctx.solids;
uint wakeSubstep = ctx.wakeSubstep;
auto& pos = hitbox.position;
auto& vel = hitbox.velocity;
stepHeight = calc_step_height(chunks, pos, half, stepHeight);
stepHeight = calc_step_height(chunks, pos, origin, half, stepHeight);
auto prevPos = pos;
calc_collision<0, 1, 2, -1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep
hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
);
calc_collision<0, 1, 2, 1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep
hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
);
float xpos = pos.x;
pos.x = prevPos.x;
calc_collision<2, 1, 0, -1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep
hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
);
calc_collision<2, 1, 0, 1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep
hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
);
pos.x = xpos;
if (calc_collision_neg_y(hitbox, half, ctx)) {
if (calc_collision_neg_y(hitbox, pos, origin, half, ctx)) {
hitbox.grounded = true;
}
@ -249,7 +265,7 @@ static void calc_collisions(
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) {
float z = (pos.z - half.z + E) + iz;
float y = (pos.y + half.y + E) - E;
if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) {
if (auto aabb = chunks.isObstacleAt(origin, x, y, z, boxAABB)) {
float bottom = std::floor(y) + aabb->min().y;
float newy = bottom - half.y - E;
if (pos.y >= newy && pos.y - half.y < bottom) {
@ -261,12 +277,13 @@ static void calc_collisions(
}
}
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue;
}
auto boxhalf = box->getHalfSize();
if (box->position.y > pos.y && box->getAABB().intersects(boxAABB)) {
float newy = box->position.y - boxhalf.y - half.y;
if (boxpos.y > pos.y && box->getAABB(origin).intersects(boxAABB)) {
float newy = boxpos.y - boxhalf.y - half.y;
if (pos.y > newy && glm::abs(pos.y - newy) < 0.5f) {
pos.y = newy;
}
@ -290,7 +307,7 @@ static void calc_collisions(
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) {
float z = (pos.z - half.z) + iz;
float y = (pos.y - half.y + E) + E;
if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) {
if (auto aabb = chunks.isObstacleAt(origin, x, y, z, boxAABB)) {
if (vel.y < 0.0f) {
vel.y = 0.0f;
}
@ -303,13 +320,14 @@ static void calc_collisions(
}
}
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue;
}
auto boxhalf = box->getHalfSize();
if (box->getAABB().intersects(boxAABB)) {
if (box->getAABB(origin).intersects(boxAABB)) {
vel.y = 0.0f;
float newy = box->position.y + boxhalf.y + half.y;
float newy = boxpos.y + boxhalf.y + half.y;
if (std::abs(newy - pos.y) <= stepHeight + E * 4) {
pos.y = newy;
}
@ -318,12 +336,16 @@ static void calc_collisions(
}
}
void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
static void calc_local_substep(
Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const CollisionContext& ctx
) {
const auto& chunks = ctx.chunks;
const auto& solids = ctx.solids;
const auto& gravity = ctx.gravity;
float dt = ctx.dt;
auto& pos = hitbox.position;
auto& vel = hitbox.velocity;
auto initpos = pos;
@ -333,6 +355,8 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
if (hitbox.type == BodyType::DYNAMIC) {
calc_collisions(
hitbox,
pos,
origin,
half,
(hitbox.prevGrounded && gravityScale > 0.0f) ? hitbox.stepHeight
: 0.0f,
@ -361,17 +385,18 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
float x = (pos.x - half.x + E) + ix;
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++){
float z = (pos.z - half.z + E) + iz;
if (chunks.isObstacleAt(x, y, z, boxAABB)){
if (chunks.isObstacleAt(origin, x, y, z, boxAABB)) {
hitbox.grounded = true;
break;
}
}
}
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue;
}
if (box->position.y < pos.y && box->getAABB().intersects(boxAABB)) {
if (boxpos.y < pos.y && box->getAABB(origin).intersects(boxAABB)) {
hitbox.grounded = true;
break;
}
@ -383,3 +408,10 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
}
hitbox.grounded = true;
}
void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
const glm::ivec3 origin = glm::floor(hitbox.position);
glm::vec3 pos = util::to_local(hitbox.position, origin);
calc_local_substep(hitbox, pos, origin, ctx);
hitbox.position = worldvec3(origin) + worldvec3(pos);
}

View file

@ -13,8 +13,9 @@ namespace physics {
) {
float n = static_cast<float>(substeps);
auto accel = gravity * box.gravityScale;
box.position += box.velocity * (dt * n) +
accel * (dt * dt * n * (n + 2.0f) * 0.5f);
box.position += worldvec3(
box.velocity * (dt * n) + accel * (dt * dt * n * (n + 2.0f) * 0.5f)
);
box.velocity += accel * (dt * n);
}

View file

@ -3,8 +3,6 @@
void physics::update_sensors(
Hitbox& hitbox, const std::vector<Sensor*>& sensors
) {
auto aabb = hitbox.getAABB();
for (size_t i = 0; i < sensors.size(); i++) {
auto& sensor = *sensors[i];
if (sensor.entity == hitbox.entity) {
@ -13,12 +11,12 @@ void physics::update_sensors(
bool triggered = false;
switch (sensor.type) {
case SensorType::AABB:
triggered = aabb.intersects(sensor.calculated.aabb);
triggered = hitbox.getAABB(sensor.position)
.intersects(sensor.calculated.aabb);
break;
case SensorType::RADIUS:
triggered = glm::distance2(
hitbox.position, glm::vec3(sensor.calculated.radial))
< sensor.calculated.radial.w;
triggered = glm::distance2(hitbox.position, sensor.position) <
sensor.calculated.radial.w;
break;
}
if (!triggered) {

View file

@ -2,6 +2,7 @@
#include <memory>
#include <cstdint>
#include <glm/fwd.hpp>
using scriptenv = std::shared_ptr<int>;
@ -12,6 +13,9 @@ using integer_t = int64_t;
/// @brief dynamic floating-point type (64 bit floating point)
using number_t = double;
/// @brief position in the world (64 bit floating point components)
using worldvec3 = glm::dvec3;
using uint = unsigned int;
using u64id_t = uint64_t;

View file

@ -52,7 +52,7 @@ voxel& Chunks::require(int32_t x, int32_t y, int32_t z) const {
return blocks_agent::require(*this, x, y, z);
}
const AABB* Chunks::isObstacleAt(float x, float y, float z) const {
const AABB* Chunks::isObstacleAt(double x, double y, double z) const {
int ix = std::floor(x);
int iy = std::floor(y);
int iz = std::floor(z);
@ -211,10 +211,10 @@ void Chunks::set(
}
voxel* Chunks::rayCast(
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxDist,
glm::vec3& end,
worldvec3& end,
glm::ivec3& norm,
glm::ivec3& iend,
const blocks_agent::RaycastSettings& settings
@ -224,12 +224,12 @@ voxel* Chunks::rayCast(
);
}
glm::vec3 Chunks::rayCastToObstacle(
const glm::vec3& start, const glm::vec3& dir, float maxDist
worldvec3 Chunks::rayCastToObstacle(
const worldvec3& start, const glm::vec3& dir, float maxDist
) const {
const float px = start.x;
const float py = start.y;
const float pz = start.z;
const double px = start.x;
const double py = start.y;
const double pz = start.z;
float dx = dir.x;
float dy = dir.y;
@ -286,11 +286,11 @@ glm::vec3 Chunks::rayCastToObstacle(
norm,
distance
) > RayRelation::None) {
return start + (dir * glm::vec3(distance));
return start + worldvec3(dir) * distance;
}
}
} else {
return glm::vec3(px + t * dx, py + t * dy, pz + t * dz);
return worldvec3(px + t * dx, py + t * dy, pz + t * dz);
}
}
}
@ -316,7 +316,7 @@ glm::vec3 Chunks::rayCastToObstacle(
}
}
}
return glm::vec3(px + maxDist * dx, py + maxDist * dy, pz + maxDist * dz);
return worldvec3(px + maxDist * dx, py + maxDist * dy, pz + maxDist * dz);
}
void Chunks::setCenter(int32_t x, int32_t z) {

View file

@ -110,22 +110,22 @@ public:
void setRotation(int32_t x, int32_t y, int32_t z, uint8_t rotation);
voxel* rayCast(
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxLength,
glm::vec3& end,
worldvec3& end,
glm::ivec3& norm,
glm::ivec3& iend,
const blocks_agent::RaycastSettings& settings
) const;
glm::vec3 rayCastToObstacle(
const glm::vec3& start, const glm::vec3& dir, float maxDist
worldvec3 rayCastToObstacle(
const worldvec3& start, const glm::vec3& dir, float maxDist
) const;
const AABB* isObstacleAt(float x, float y, float z) const;
const AABB* isObstacleAt(double x, double y, double z) const;
const AABB* isObstacleAt(const glm::vec3& pos) const {
const AABB* isObstacleAt(const worldvec3& pos) const {
return isObstacleAt(pos.x, pos.y, pos.z);
}

View file

@ -191,7 +191,7 @@ void GlobalChunks::save(Chunk* chunk) {
return;
}
AABB aabb = chunk->getAABB();
auto entities = level.entities->getAllInside(aabb);
auto entities = level.entities->getAllInside(aabb.a, aabb.b);
auto root = dv::object();
root["data"] = level.entities->serialize(entities);
if (!entities.empty()) {
@ -214,6 +214,8 @@ void GlobalChunks::putChunk(std::shared_ptr<Chunk> chunk) {
chunksMap[keyfrom(chunk->x, chunk->z)] = std::move(chunk);
}
std::optional<AABB> GlobalChunks::isObstacleAt(float x, float y, float z, const AABB& aabb) const {
return blocks_agent::is_obstacle_at(*this, x, y, z, aabb);
std::optional<AABB> GlobalChunks::isObstacleAt(
const glm::ivec3& origin, float x, float y, float z, const AABB& aabb
) const {
return blocks_agent::is_obstacle_at(*this, origin, x, y, z, aabb);
}

View file

@ -58,7 +58,9 @@ public:
void putChunk(std::shared_ptr<Chunk> chunk);
std::optional<AABB> isObstacleAt(float x, float y, float z, const AABB& aabb) const;
std::optional<AABB> isObstacleAt(
const glm::ivec3& origin, float x, float y, float z, const AABB& aabb
) const;
inline Chunk* getChunk(int cx, int cz) const {
const auto& found = chunksMap.find(keyfrom(cx, cz));

View file

@ -217,18 +217,18 @@ bool blocks_agent::set(
template <class Storage>
static inline voxel* raycast_blocks(
const Storage& chunks,
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxDist,
glm::vec3& end,
worldvec3& end,
glm::ivec3& norm,
glm::ivec3& iend,
const RaycastSettings& settings
) {
const auto& blocks = chunks.getContentIndices().blocks;
float px = start.x;
float py = start.y;
float pz = start.z;
double px = start.x;
double py = start.y;
double pz = start.z;
float dx = dir.x;
float dy = dir.y;
@ -271,7 +271,7 @@ static inline voxel* raycast_blocks(
(def.selectable || includeNonSelectable) &&
((filter == nullptr || filter->find(def.rt.id) == filter->end()) ==
settings.blocksFilterExcludeMode)) {
end = start + t * dir;
end = start + worldvec3(t * dir);
iend = {ix, iy, iz};
if (!def.rt.solid) {
@ -301,7 +301,7 @@ static inline voxel* raycast_blocks(
hit = true;
distance = boxDistance;
norm = boxNorm;
end = start + (dir * glm::vec3(distance));
end = start + worldvec3(dir) * distance;
}
}
@ -342,17 +342,17 @@ static inline voxel* raycast_blocks(
}
}
iend = {ix, iy, iz};
end = start + t * dir;
end = start + worldvec3(t * dir);
norm = {0, 0, 0};
return nullptr;
}
voxel* blocks_agent::raycast(
const Chunks& chunks,
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxDist,
glm::vec3& end,
worldvec3& end,
glm::ivec3& norm,
glm::ivec3& iend,
const RaycastSettings& settings
@ -362,10 +362,10 @@ voxel* blocks_agent::raycast(
voxel* blocks_agent::raycast(
const GlobalChunks& chunks,
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxDist,
glm::vec3& end,
worldvec3& end,
glm::ivec3& norm,
glm::ivec3& iend,
const RaycastSettings& settings

View file

@ -447,10 +447,10 @@ struct RaycastSettings {
/// @return voxel pointer or nullptr
voxel* raycast(
const Chunks& chunks,
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxDist,
glm::vec3& end,
worldvec3& end,
glm::ivec3& norm,
glm::ivec3& iend,
const RaycastSettings& settings
@ -469,10 +469,10 @@ voxel* raycast(
/// @return voxel pointer or nullptr
voxel* raycast(
const GlobalChunks& chunks,
const glm::vec3& start,
const worldvec3& start,
const glm::vec3& dir,
float maxDist,
glm::vec3& end,
worldvec3& end,
glm::ivec3& norm,
glm::ivec3& iend,
const RaycastSettings& settings
@ -488,14 +488,20 @@ void get_voxels(
template <class Storage>
inline std::optional<AABB> is_obstacle_at(
const Storage& chunks, float x, float y, float z, const AABB& aabb
const Storage& chunks,
const glm::ivec3& origin,
float x,
float y,
float z,
const AABB& aabb
) {
int ix = std::floor(x);
int iy = std::floor(y);
int iz = std::floor(z);
voxel* v = get(chunks, ix, iy, iz);
glm::ivec3 point = origin + glm::ivec3(ix, iy, iz);
voxel* v = get(chunks, point.x, point.y, point.z);
if (v == nullptr) {
if (iy >= CHUNK_H) {
if (point.y >= CHUNK_H) {
return std::nullopt;
} else {
return AABB();
@ -508,10 +514,9 @@ inline std::optional<AABB> is_obstacle_at(
glm::ivec3 offset {};
blockstate state = v->state;
if (state.segment) {
glm::ivec3 point(ix, iy, iz);
auto origin = seek_origin(chunks, point, def, state);
offset = origin - point;
state = hitbox_state(chunks, origin, state);
auto blockOrigin = seek_origin(chunks, point, def, state);
offset = blockOrigin - point;
state = hitbox_state(chunks, blockOrigin, state);
}
const auto& boxes = def.getHitboxes(state);
@ -525,7 +530,9 @@ inline std::optional<AABB> is_obstacle_at(
template <class Storage>
inline std::optional<AABB> is_obstacle_at(const Storage& chunks, float x, float y, float z) {
return is_obstacle_at(chunks, x, y, z, AABB({x, y, z}, {x + 1, y + 1, z + 1}));
return is_obstacle_at(
chunks, {}, x, y, z, AABB({x, y, z}, {x + 1, y + 1, z + 1})
);
}
/// @brief Check block grounding

View file

@ -3,7 +3,9 @@
#include <cmath>
#include <glm/ext.hpp>
Camera::Camera(glm::vec3 position, float fov) : fov(fov), position(position) {
inline constexpr double ORIGIN_STEP = 1024.0;
Camera::Camera(worldvec3 position, float fov) : fov(fov), position(position) {
updateVectors();
}
@ -40,17 +42,24 @@ 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::vec3(position - worldvec3(getOrigin()));
}
glm::mat4 Camera::getView(bool pos) const {
glm::vec3 camera_pos = this->position;
if (!pos) {
camera_pos = glm::vec3(0.0f);
}
if (perspective) {
return glm::lookAt(camera_pos, camera_pos + front, up);
} else {
return glm::lookAt(camera_pos, camera_pos + front, up);
//return glm::translate(glm::mat4(1.0f), camera_pos);
glm::mat4 view = glm::lookAt(glm::vec3(0.0f), front, up);
if (pos) {
view = glm::translate(view, -getLocalPosition());
}
return view;
}
glm::mat4 Camera::getProjView(bool pos) const {

View file

@ -1,5 +1,7 @@
#pragma once
#include "typedefs.hpp"
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
@ -12,7 +14,7 @@ public:
glm::vec3 right {};
glm::vec3 dir {};
glm::vec3 position {};
worldvec3 position {};
float zoom = 1.0f;
glm::mat4 rotation {1.0f};
@ -27,11 +29,16 @@ public:
Camera() {
updateVectors();
}
Camera(glm::vec3 position, float fov);
Camera(worldvec3 position, float fov);
void updateVectors();
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 getView(bool position = true) const;
glm::mat4 getProjView(bool position = true) const;

View file

@ -64,7 +64,7 @@ Level::Level(
chunks->setOnUnload([this](Chunk& chunk) {
events->trigger(LevelEventType::CHUNK_UNLOAD, &chunk);
AABB aabb = chunk.getAABB();
entities->despawn(entities->getAllInside(aabb));
entities->despawn(entities->getAllInside(aabb.a, aabb.b));
});
inventories = std::make_unique<Inventories>(*this);
}

30
test/physics/Hitbox.cpp Normal file
View file

@ -0,0 +1,30 @@
#include <gtest/gtest.h>
#include "physics/Hitbox.hpp"
TEST(Hitbox, AABBRelativeToOrigin) {
for (double coord : {0.0, 1e6, 3e7}) {
worldvec3 position(coord + 0.3, 64.25, -coord - 0.7);
Hitbox hitbox(
1, BodyType::DYNAMIC, position, glm::vec3(0.3f, 0.9f, 0.3f)
);
AABB aabb = hitbox.getAABB(glm::floor(position));
EXPECT_NEAR(aabb.a.x, 0.0f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.a.y, -0.65f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.a.z, 0.0f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.b.x, 0.6f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.b.y, 1.15f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.b.z, 0.6f, 1e-6f) << "at " << coord;
}
}
TEST(Hitbox, SetPosFarFromOrigin) {
worldvec3 position(3e7 + 0.3, 64.25, -3e7 - 0.7);
Hitbox hitbox(1, BodyType::DYNAMIC, {}, glm::vec3(0.3f, 0.9f, 0.3f));
hitbox.setPos(position);
EXPECT_EQ(hitbox.position, position);
EXPECT_EQ(hitbox.prevPosition, position);
hitbox.setPos(position + worldvec3(0.05, 0.0, 0.0));
EXPECT_EQ(hitbox.prevPosition, position);
}

52
test/window/Camera.cpp Normal file
View file

@ -0,0 +1,52 @@
#include <gtest/gtest.h>
#include <cmath>
#include <glm/ext.hpp>
#include "window/Camera.hpp"
TEST(Camera, ViewRotationFarFromOrigin) {
for (float coord : {0.0f, 1e5f, 1e6f, 3e7f}) {
for (bool rotated : {false, true}) {
Camera camera(glm::vec3(coord, 64.0f, coord), 1.0f);
if (rotated) {
camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f);
}
glm::mat4 rotation = camera.getView(false);
glm::mat4 view = camera.getView();
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
ASSERT_TRUE(std::isfinite(view[col][row]))
<< "at " << coord;
}
}
for (int col = 0; col < 3; col++) {
for (int row = 0; row < 3; row++) {
EXPECT_NEAR(rotation[col][row], view[col][row], 1e-5f)
<< "at " << coord << ", rotated " << rotated;
}
}
}
}
}
TEST(Camera, ViewRelativeToOrigin) {
for (double coord : {0.0, 500.3, -1e5 - 0.3, 1e6 + 0.3, 3e7 + 0.3}) {
Camera camera(worldvec3(coord, 64.0, -coord), 1.0f);
camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f);
worldvec3 origin = camera.getOrigin();
worldvec3 local = camera.getLocalPosition();
EXPECT_LE(glm::abs(local.x), 512.0) << "at " << coord;
EXPECT_LE(glm::abs(local.z), 512.0) << "at " << coord;
EXPECT_NEAR(camera.position.x, origin.x + local.x, 1e-4) << coord;
EXPECT_NEAR(camera.position.z, origin.z + local.z, 1e-4) << coord;
worldvec3 point = camera.position + worldvec3(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;
}
}