Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
BillboardFacing.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
10#pragma once
11
12#include "../../core/Types.hpp"
13#include "../../math/Math.hpp"
14
15#include <glm/gtc/quaternion.hpp>
16
17#include <cmath>
18
20
22struct ViewAxes {
23 glm::vec3 right{1.0f, 0.0f, 0.0f};
24 glm::vec3 up{0.0f, 1.0f, 0.0f};
25 glm::vec3 back{0.0f, 0.0f, 1.0f};
26};
27
35inline ViewAxes viewAxes(const glm::mat4& viewProjection) {
36 const glm::vec3 row0(viewProjection[0][0], viewProjection[1][0], viewProjection[2][0]);
37 const glm::vec3 row1(viewProjection[0][1], viewProjection[1][1], viewProjection[2][1]);
38 ViewAxes axes;
39 if (glm::dot(row0, row0) < 1e-20f || glm::dot(row1, row1) < 1e-20f) return axes;
40 const glm::vec3 right = glm::normalize(row0);
41 const glm::vec3 back = glm::cross(right, glm::normalize(row1));
42 if (glm::dot(back, back) < 1e-12f) return axes;
43 axes.back = glm::normalize(back);
44 axes.right = right;
45 axes.up = glm::cross(axes.back, axes.right);
46 return axes;
47}
48
57inline glm::quat facing(i32 mode, const glm::mat4& viewProjection, const glm::vec4& eye, const glm::vec3& position) {
58 const ViewAxes axes = viewAxes(viewProjection);
59 if (mode != 1) {
60 // Columns are where the card's own +X, +Y and +Z go.
61 return glm::quat_cast(glm::mat3(axes.right, axes.up, axes.back));
62 }
63 // Upright: toward the viewer, flattened onto the ground. Straight overhead there is no such direction, and the view plane's own back,
64 // flattened, is what keeps the card from spinning as the camera passes over it.
65 glm::vec3 toward = eye.w > 0.5f ? glm::vec3(eye) - position : glm::vec3(eye);
66 toward.y = 0.0f;
67 if (glm::dot(toward, toward) < 1e-8f) {
68 toward = glm::vec3(axes.back.x, 0.0f, axes.back.z);
69 if (glm::dot(toward, toward) < 1e-8f) toward = -glm::vec3(axes.up.x, 0.0f, axes.up.z);
70 if (glm::dot(toward, toward) < 1e-8f) return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
71 }
72 const f32 yaw = std::atan2(toward.x, toward.z);
73 return glm::angleAxis(yaw, glm::vec3(0.0f, 1.0f, 0.0f));
74}
75
76} // namespace esengine::billboard
Math utilities and GLM configuration for ESEngine.
Core type definitions and utilities for ESEngine.
ViewAxes viewAxes(const glm::mat4 &viewProjection)
The axes a view looks along.
glm::quat facing(i32 mode, const glm::mat4 &viewProjection, const glm::vec4 &eye, const glm::vec3 &position)
The rotation a card standing at position is drawn with in this view.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
float f32
32-bit floating point
Definition Types.hpp:59
The view's right, up and toward-the-viewer axes in the world, read off its view-projection.