Debian Codegraph @

src/base/castlevectors_matrix_decompose.inc

raw
1 {%MainUnit castlevectors.pas}
2 {
3 Copyright 2003-2022 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { CastleVectors routines that extract from transformation matrix back
18 the transformation vectors. }
19
20 {$ifdef read_interface}
21
22 { Decompose a matrix that is composition of 3D translation, rotation and scale.
23
24 The returned Rotation is expressed as an axis-angle (first 3 components
25 are axis, last component is an angle in radians),
26 as usual in our engine (see e.g. @link(TCastleTransform.Rotation)). }
27 procedure MatrixDecompose(const Matrix: TMatrix4;
28 out Translation: TVector3; out Rotation: TVector4; out Scale: TVector3);
29
30 { Extract scale from matrix.
31 This performs a subset of MatrixDecompose work. }
32 function ScaleFromMatrix(const Matrix: TMatrix4): TVector3;
33
34 { Extract translation from matrix.
35 This performs a subset of MatrixDecompose work. }
36 function TranslationFromMatrix(const M: TMatrix4): TVector3;
37
38 {$endif read_interface}
39
40 {$ifdef read_implementation}
41
42 procedure MatrixDecompose(const Matrix: TMatrix4;
43 out Translation: TVector3; out Rotation: TVector4; out Scale: TVector3);
44 var
45 I, J: Integer;
46 Column: TVector3;
47 RotationMatrix: TMatrix3;
48 Quaternion: TQuaternion;
49 begin
50 { See
51 https://math.stackexchange.com/questions/237369/given-this-transformation-matrix-how-do-i-decompose-it-into-translation-rotati/1463487#1463487
52 }
53
54 // calculate Translation
55 Translation := Vector3(Matrix.Data[3, 0], Matrix.Data[3, 1], Matrix.Data[3, 2]);
56
57 // calculate Scale
58 for I := 0 to 2 do
59 begin
60 Column := Vector3(Matrix.Data[I, 0], Matrix.Data[I, 1], Matrix.Data[I, 2]);
61 Scale.Data[I] := Column.Length;
62 end;
63
64 // calculate Rotation
65 for I := 0 to 2 do
66 for J := 0 to 2 do
67 RotationMatrix.Data[I, J] := Matrix.Data[I, J] / Scale[I];
68 Quaternion := QuatFromRotationMatrix(RotationMatrix);
69 Rotation := Quaternion.ToAxisAngle;
70 end;
71
72 function ScaleFromMatrix(const Matrix: TMatrix4): TVector3;
73 var
74 I: Integer;
75 Column: TVector3;
76 begin
77 for I := 0 to 2 do
78 begin
79 Column := Vector3(Matrix.Data[I, 0], Matrix.Data[I, 1], Matrix.Data[I, 2]);
80 Result.Data[I] := Column.Length;
81 end;
82 end;
83
84 function TranslationFromMatrix(const M: TMatrix4): TVector3;
85 begin
86 Result := Vector3(M.Data[3, 0], M.Data[3, 1], M.Data[3, 2]);
87 end;
88
89 {$endif read_implementation}