Skip to content
This repository was archived by the owner on Feb 25, 2025. It is now read-only.

Commit f2e78f8

Browse files
committed
Add Matrix::LookAt
1 parent 36cfa9e commit f2e78f8

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

impeller/geometry/geometry_unittests.cc

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,52 @@ TEST(GeometryTest, MatrixIsAligned) {
424424
}
425425
}
426426

427+
TEST(GeometryTest, MatrixLookAt) {
428+
{
429+
auto m = Matrix::MakeLookAt(Vector3(0, 0, -1), Vector3(0, 0, 1),
430+
Vector3(0, 1, 0));
431+
auto expected = Matrix{
432+
1, 0, 0, 0, //
433+
0, 1, 0, 0, //
434+
0, 0, 1, 0, //
435+
0, 0, 1, 1, //
436+
};
437+
ASSERT_MATRIX_NEAR(m, expected);
438+
}
439+
440+
// Sideways tilt.
441+
{
442+
auto m = Matrix::MakeLookAt(Vector3(0, 0, -1), Vector3(0, 0, 1),
443+
Vector3(1, 1, 0).Normalize());
444+
445+
// clang-format off
446+
auto expected = Matrix{
447+
k1OverSqrt2, k1OverSqrt2, 0, 0,
448+
-k1OverSqrt2, k1OverSqrt2, 0, 0,
449+
0, 0, 1, 0,
450+
0, 0, 1, 1,
451+
};
452+
// clang-format on
453+
ASSERT_MATRIX_NEAR(m, expected);
454+
}
455+
456+
// Half way between +x and -y, yaw 90
457+
{
458+
auto m = Matrix::MakeLookAt(Vector3(), Vector3(10, -10, 0),
459+
Vector3(0, 0, -1));
460+
461+
// clang-format off
462+
auto expected = Matrix{
463+
-k1OverSqrt2, 0, k1OverSqrt2, 0,
464+
-k1OverSqrt2, 0, -k1OverSqrt2, 0,
465+
0, -1, 0, 0,
466+
0, 0, 0, 1,
467+
};
468+
// clang-format on
469+
ASSERT_MATRIX_NEAR(m, expected);
470+
}
471+
}
472+
427473
TEST(GeometryTest, QuaternionLerp) {
428474
auto q1 = Quaternion{{0.0, 0.0, 1.0}, 0.0};
429475
auto q2 = Quaternion{{0.0, 0.0, 1.0}, kPiOver4};

impeller/geometry/matrix.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,23 @@ struct Matrix {
435435
return MakePerspective(fov_y, static_cast<Scalar>(size.width) / size.height,
436436
z_near, z_far);
437437
}
438+
439+
static constexpr Matrix MakeLookAt(Vector3 position,
440+
Vector3 target,
441+
Vector3 up) {
442+
Vector3 forward = (target - position).Normalize();
443+
Vector3 right = up.Cross(forward);
444+
up = forward.Cross(right);
445+
446+
// clang-format off
447+
return {
448+
right.x, up.x, forward.x, 0.0f,
449+
right.y, up.y, forward.y, 0.0f,
450+
right.z, up.z, forward.z, 0.0f,
451+
-right.Dot(position), -up.Dot(position), -forward.Dot(position), 1.0f
452+
};
453+
// clang-format on
454+
}
438455
};
439456

440457
static_assert(sizeof(struct Matrix) == sizeof(Scalar) * 16,

0 commit comments

Comments
 (0)