Move camera to world space position of player

master
outfrost 2020-05-27 02:26:29 +02:00
parent 73a2f00122
commit abfdbaf74a
5 changed files with 29 additions and 9 deletions

View File

@ -9,9 +9,9 @@ Transform identity() {
.d1 = 0.0f, .d2 = 0.0f, .d3 = 0.0f, .d4 = 1.0f };
}
void multiply(Transform* transform, Transform by) {
GLfloat* a = (GLfloat*) &by;
GLfloat* b = (GLfloat*) transform;
Transform multiply(Transform t1, Transform t2) {
GLfloat* a = (GLfloat*) &t1;
GLfloat* b = (GLfloat*) &t2;
for (size_t row = 0; row < 4; ++row) {
for (size_t col = 0; col < 4; ++col) {
@ -22,13 +22,16 @@ void multiply(Transform* transform, Transform by) {
+ a[(row * 4) + 3] * b[(3 * 4) + col];
}
}
return t2;
}
void translate(Transform* transform, Vector3D vec) {
multiply(transform, (Transform) { .a1 = 1.0f, .a2 = 0.0f, .a3 = 0.0f, .a4 = vec.x,
.b1 = 0.0f, .b2 = 1.0f, .b3 = 0.0f, .b4 = vec.y,
.c1 = 0.0f, .c2 = 0.0f, .c3 = 1.0f, .c4 = vec.z,
.d1 = 0.0f, .d2 = 0.0f, .d3 = 0.0f, .d4 = 1.0f });
*transform = multiply(
(Transform) { .a1 = 1.0f, .a2 = 0.0f, .a3 = 0.0f, .a4 = vec.x,
.b1 = 0.0f, .b2 = 1.0f, .b3 = 0.0f, .b4 = vec.y,
.c1 = 0.0f, .c2 = 0.0f, .c3 = 1.0f, .c4 = vec.z,
.d1 = 0.0f, .d2 = 0.0f, .d3 = 0.0f, .d4 = 1.0f },
*transform);
}
Vector3D translationOf(Transform transform) {

View File

@ -20,6 +20,7 @@ struct Transform {
};
Transform identity();
Transform multiply(Transform t1, Transform t2);
void translate(Transform* transform, Vector3D vec);
Vector3D translationOf(Transform transform);

View File

@ -96,7 +96,7 @@ static void setupCamera() {
static void moveCameraTo(const Scene* anchor) {
glMatrixMode(GL_PROJECTION);
// TODO This needs to account for parent nodes as well
Vector3D pos = translationOf(anchor->transform);
Vector3D pos = translationOf(worldTransform(anchor));
glTranslatef(-pos.x, -pos.y, -pos.z);
}

View File

@ -24,7 +24,7 @@ void insertChildScene(Scene* scene, Scene* newChild) {
}
if (newChild->parent) {
logError(
"Cannot insert scene 0x%p as child of 0x%p, because it is already child of 0x%p",
"Cannot insert Scene 0x%p as child of 0x%p, because it is already child of 0x%p",
newChild,
scene,
newChild->parent);
@ -67,3 +67,18 @@ void reparentScene(Scene* scene, Scene* newParent) {
insertChildScene(newParent, scene);
}
Transform worldTransform(const Scene* scene) {
if (!scene) {
logError("Cannot compute world space Transform of null Scene");
return identity();
}
if (scene->parent) {
return multiply(scene->transform, worldTransform(scene->parent));
}
else {
return scene->transform;
}
}

View File

@ -18,5 +18,6 @@ Scene* currentScene;
Scene* newScene();
void insertChildScene(Scene* scene, Scene* newChild);
void reparentScene(Scene* scene, Scene* newParent);
Transform worldTransform(const Scene* scene);
#endif // SCENE_H_