/
Matrix3D.py
475 lines (429 loc) · 16.8 KB
/
Matrix3D.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math
# own modules
from Vector3D import Vector3D as Vector3D
from Polygon import Polygon as Polygon
class Matrix3D(object):
def __init__(self, array_data):
assert len(array_data) == 4
assert all((len(row) == 4 for row in array_data))
self.__data = array_data
def __str__(self):
return "\n".join((str(row) for row in self.__data))
def __repr__(self):
return("Matrix3D([%s])" % ", ".join((str(row) for row in self.__data)))
def __eq__(self, other):
return all((self.__data[index] == other[index] for index in range(4)))
def __getitem__(self, key):
if isinstance(key, tuple):
return self.__data[key[0]][key[1]]
else:
return self.__data[key]
def __setitem__(self, key, value):
if isinstance(key, tuple):
self.__data[key[0]][key[1]] = value
else:
raise TypeError("Matrix3D allowes only single value settings")
@classmethod
def identity(cls):
"""
return identity matrix 4x4
"""
return cls([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
])
@classmethod
def zeros(cls):
"""
return identity matrix 4x4
"""
return cls([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
])
def col(self, colnum):
"""
little helper to get column vector of matrix
for column specified by index
"""
return list((row[colnum] for row in self.__data))
def row(self, rownum):
"""
little helper to get column vector of matrix
for column specified by index
"""
return self.__data[rownum]
def transpose(self):
"""
return transposed version of self
| a1 b1 c1 d1 |T | a1 a2 a3 a4 |
| a2 b2 c2 d2 | = | b1 b2 b3 b4 |
| a3 b3 c3 d3 | | c1 c2 c3 c4 |
| a4 b4 c4 d4 | | d1 d2 d3 d4 |
"""
new_data = []
for colnum in range(4):
new_data.append(self.col(colnum))
return Matrix3D(new_data)
def dot(self, other):
"""
return dot product of these to 4x4 matrices
Matrix A : self
Matrix B : other
TODO: find a way to describe this in short terms
| a11 | a12 | a13 | a14 | | b11 | b12 | b13 | b14 | | row[1].col[1] row[1].col[2] ... ... |
| a21 | a22 | a23 | a24 | . | b21 | b22 | b23 | b24 | = | row[2].col[1] row[2].col[2] ... ... |
| a31 | a32 | a33 | a34 | | b31 | b32 | b33 | b34 | | ... ... |
| a41 | a42 | a43 | a44 | | b41 | b42 | b43 | b44 | | |
"""
assert isinstance(other, Matrix3D)
ret_matrix = self.zeros()
for rownum in range(4):
row_vec = Vector3D.from_list(self.row(rownum))
for colnum in range(4):
col_vec = Vector3D.from_list(other.col(colnum))
ret_matrix[rownum][colnum] = row_vec.dot(col_vec)
return ret_matrix
def v_dot(self, vector):
"""
calculate dot product of Matrix3D with inverted(Vector3D)
| a1 | b1 | c1 | d1 | | x | | a1*x + b1*y + c1*z + d1*h |
| a2 | b2 | c2 | d2 | . | y | = | a2*x + b2*y + c2*z + d2*h |
| a3 | b3 | c3 | d3 | | z | | a3*x + b3*y + c3*z + d3*h |
| a4 | b4 | c4 | d4 | | h | | a4*x + b4*y + c4*z + d4*h |
"""
assert isinstance(vector, Vector3D)
ret_data = [0, 0, 0, 0]
for index in range(4):
row_vec = Vector3D.from_list(self.__data[index])
ret_data[index] = row_vec.dot(vector)
return Vector3D.from_list(ret_data)
def det(self):
"""
calculates determinat of matrix
| a1 b1 c1 d1 |
| a2 b2 c2 d2 |
| a3 b3 c3 d3 |
| a4 b4 c4 d4 |
there exists no easy solution for matrices above 3x3,
this implementation uses one possible variant of
laplace development sentence (translated from german)
http://matheguru.com/lineare-algebra/207-determinante.html
used solution also here
http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/teche23.html
"""
data = self.__data
det = 0 \
+ data[0][0] * data[1][1] * data[2][2] * data[3][3] \
+ data[0][0] * data[1][2] * data[2][3] * data[3][1] \
+ data[0][0] * data[1][3] * data[2][1] * data[3][2] \
+ data[0][1] * data[1][0] * data[2][3] * data[3][2] \
+ data[0][1] * data[1][2] * data[2][0] * data[3][3] \
+ data[0][1] * data[1][3] * data[2][2] * data[3][0] \
+ data[0][2] * data[1][0] * data[2][1] * data[3][3] \
+ data[0][2] * data[1][1] * data[2][3] * data[3][0] \
+ data[0][2] * data[1][3] * data[2][0] * data[3][1] \
+ data[0][3] * data[1][0] * data[2][2] * data[3][1] \
+ data[0][3] * data[1][1] * data[2][0] * data[3][2] \
+ data[0][3] * data[1][2] * data[2][1] * data[3][0] \
- data[0][0] * data[1][1] * data[2][3] * data[3][2] \
- data[0][0] * data[1][2] * data[2][1] * data[3][3] \
- data[0][0] * data[1][3] * data[2][2] * data[3][1] \
- data[0][1] * data[1][0] * data[2][2] * data[3][3] \
- data[0][1] * data[1][2] * data[2][3] * data[3][0] \
- data[0][1] * data[1][3] * data[2][0] * data[3][2] \
- data[0][2] * data[1][0] * data[2][3] * data[3][1] \
- data[0][2] * data[1][1] * data[2][0] * data[3][3] \
- data[0][2] * data[1][3] * data[2][1] * data[3][0] \
- data[0][3] * data[1][0] * data[2][1] * data[3][2] \
- data[0][3] * data[1][1] * data[2][2] * data[3][0] \
- data[0][3] * data[1][2] * data[2][0] * data[3][1]
return det
def inverse(self):
"""
for further readings look at
http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
"""
z = self.zeros()
d = self.__data
m00 = d[0][0]
m01 = d[0][1]
m02 = d[0][2]
m03 = d[0][3]
m10 = d[1][0]
m11 = d[1][1]
m12 = d[1][2]
m13 = d[1][3]
m20 = d[2][0]
m21 = d[2][1]
m22 = d[2][2]
m23 = d[2][3]
m30 = d[3][0]
m31 = d[3][1]
m32 = d[3][2]
m33 = d[3][3]
z[0,0] = m12*m23*m31 - m13*m22*m31 + m13*m21*m32 - m11*m23*m32 - m12*m21*m33 + m11*m22*m33
z[0,1] = m03*m22*m31 - m02*m23*m31 - m03*m21*m32 + m01*m23*m32 + m02*m21*m33 - m01*m22*m33
z[0,2] = m02*m13*m31 - m03*m12*m31 + m03*m11*m32 - m01*m13*m32 - m02*m11*m33 + m01*m12*m33
z[0,3] = m03*m12*m21 - m02*m13*m21 - m03*m11*m22 + m01*m13*m22 + m02*m11*m23 - m01*m12*m23
z[1,0] = m13*m22*m30 - m12*m23*m30 - m13*m20*m32 + m10*m23*m32 + m12*m20*m33 - m10*m22*m33
z[1,1] = m02*m23*m30 - m03*m22*m30 + m03*m20*m32 - m00*m23*m32 - m02*m20*m33 + m00*m22*m33
z[1,2] = m03*m12*m30 - m02*m13*m30 - m03*m10*m32 + m00*m13*m32 + m02*m10*m33 - m00*m12*m33
z[1,3] = m02*m13*m20 - m03*m12*m20 + m03*m10*m22 - m00*m13*m22 - m02*m10*m23 + m00*m12*m23
z[2,0] = m11*m23*m30 - m13*m21*m30 + m13*m20*m31 - m10*m23*m31 - m11*m20*m33 + m10*m21*m33
z[2,1] = m03*m21*m30 - m01*m23*m30 - m03*m20*m31 + m00*m23*m31 + m01*m20*m33 - m00*m21*m33
z[2,2] = m01*m13*m30 - m03*m11*m30 + m03*m10*m31 - m00*m13*m31 - m01*m10*m33 + m00*m11*m33
z[2,3] = m03*m11*m20 - m01*m13*m20 - m03*m10*m21 + m00*m13*m21 + m01*m10*m23 - m00*m11*m23
z[3,0] = m12*m21*m30 - m11*m22*m30 - m12*m20*m31 + m10*m22*m31 + m11*m20*m32 - m10*m21*m32
z[3,1] = m01*m22*m30 - m02*m21*m30 + m02*m20*m31 - m00*m22*m31 - m01*m20*m32 + m00*m21*m32
z[3,2] = m02*m11*m30 - m01*m12*m30 - m02*m10*m31 + m00*m12*m31 + m01*m10*m32 - m00*m11*m32
z[3,3] = m01*m12*m20 - m02*m11*m20 + m02*m10*m21 - m00*m12*m21 - m01*m10*m22 + m00*m11*m22
return z.scale(1/self.det())
def scale(self, scalar):
"""
scale matrix by scalar
return new Matrix3D
"""
new_array = []
for row in self.__data:
new_array.append([value * scalar for value in row])
return Matrix3D(new_array)
@classmethod
def get_rot_x_matrix(cls, theta):
"""
return rotation matrix around X-axis
return rotated version of self around X-Axis
theta should be given in radians
http://stackoverflow.com/questions/14607640/rotating-a-vector-in-3d-space
|1 0 0| |x| | x | |x'|
|0 cos θ -sin θ| |y| = |y cos θ - z sin θ| = |y'|
|0 sin θ cos θ| |z| |y sin θ + z cos θ| |z'|
"""
cos = math.cos(theta)
sin = math.sin(theta)
return cls([
[1, 0, 0, 0],
[0, cos, -sin, 0],
[0, sin, cos, 0],
[0, 0, 0, 1]
])
@classmethod
def get_rot_y_matrix(cls, theta):
"""
return rotated version of self around Y-Axis
theta should be given in radians
http://stackoverflow.com/questions/14607640/rotating-a-vector-in-3d-space
| cos θ 0 sin θ| |x| | x cos θ + z sin θ| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin θ 0 cos θ| |z| |-x sin θ + z cos θ| |z'|
"""
cos = math.cos(theta)
sin = math.sin(theta)
# substitute sin with cos, but its not clear if this is faster
# sin² + cos² = 1
# sin = sqrt(1.0 - cos)
return cls([
[ cos, 0, sin, 0],
[ 0, 1, 0, 0],
[-sin, 0, cos, 0],
[ 0, 0, 0, 1]
])
@classmethod
def get_rot_z_matrix(cls, theta):
"""
return rotated version of self around Z-Axis
theta should be given in radians
http://stackoverflow.com/questions/1 4607640/rotating-a-vector-in-3d-space
|cos θ -sin θ 0| |x| |x cos θ - y sin θ| |x'|
|sin θ cos θ 0| |y| = |x sin θ + y cos θ| = |y'|
| 0 0 1| |z| | z | |z'|
"""
cos = math.cos(theta)
sin = math.sin(theta)
return cls([
[cos, -sin, 0, 0],
[sin, cos, 0, 0],
[ 0, 0, 1, 0],
[ 0, 0, 0, 1]
])
@classmethod
def get_rot_align(cls, vector1, vector2):
"""
return rotation matrix to rotate vector1 such that
T(vector1) = vector2
remember order of vectors:
vector1 is the vector to be transformed, not vector 2
so vector1 is aligned with vector2
to do this efficiently, vector1 and vector2 have to be unit vectors
look at this website to get detailed explanation of what is done here
http://www.iquilezles.org/www/articles/noacos/noacos.htm
"""
# make sure, that both vectors are unit vectors
# TODO: Performance Issue
assert isinstance(vector1, Vector3D)
assert isinstance(vector1, Vector3D)
assert vector1.length_sqrd() == 1
assert vector2.length_sqrd() == 1
cross = vector2.cross(vector1)
dot = vector2.dot(vector1)
k = 1.0 / (1.0 + dot)
return cls([
[cross[0] * cross[0] * k + dot , cross[1] * cross[0] * k - cross[2], cross[2] * cross[0] * k + cross[1], 0],
[cross[1] * cross[1] * k + cross[2], cross[1] * cross[1] * k + dot , cross[2] * cross[1] * k - cross[0], 0],
[cross[2] * cross[2] * k - cross[1], cross[1] * cross[2] * k + cross[0], cross[2] * cross[2] * k + dot, 0],
[ 0, 0, 1]
])
@classmethod
def get_shift_matrix(cls, x, y, z):
"""
return transformation matrix to shift vector
| 1 0 0 sx| |x| |x+sx|
| 0 1 0 sy| |y| |y+sy|
| 0 0 1 sz|.|z|=|z+sz|
| 0 0 0 1| |1| | 1|
"""
return cls([
[1, 0, 0, x],
[0, 1, 0, y],
[0, 0, 1, z],
[0, 0, 0, 1]
])
@classmethod
def get_scale_matrix(cls, x, y, z):
"""
return transformation matrix to scale vector
| x 0 0 0|
| 0 y 0 0|
| 0 0 z 0|
| 0 0 0 1|
"""
return cls([
[x, 0, 0, 0],
[0, y, 0, 0],
[0, 0, z, 0],
[0, 0, 0, 1]
])
def get_rectangle_points():
"""basic rectangle vertices"""
points = (
Vector3D(-1, 1, 0, 1),
Vector3D( 1, 1, 0, 1),
Vector3D( 1, -1, 0, 1),
Vector3D(-1, -1, 0, 1),
Vector3D(-1, 1, 0, 1),
)
return points
def get_triangle_points():
"""basic triangle vertices"""
points = (
Vector3D(-1, 0, 0, 1),
Vector3D( 0, 1, 0, 1),
Vector3D( 1, 0, 0, 1),
Vector3D(-1, 0, 0, 1),
)
return points
def get_pyramid_polygons():
polygons = []
# front
face = get_triangle_points()
transform = get_shift_matrix(0, 0, 1).dot(get_rot_x_matrix(-math.pi/4))
face = face.dot(transform)
face = face.dot(get_shift_matrix(0, 0, 1))
polygons.append(Polygon(face))
# back
face = get_triangle_points()
face = face.dot(get_rot_x_matrix(math.pi/4))
face = face.dot(get_shift_matrix(0, 0, -1))
polygons.append(Polygon(face))
# left
face = get_triangle_points()
face = face.dot(get_rot_x_matrix(-math.pi/4))
face = face.dot(get_rot_y_matrix(-math.pi/2))
face = face.dot(get_shift_matrix(1, 0, 0))
polygons.append(Polygon(face))
# right
face = get_triangle_points()
face = face.dot(get_rot_x_matrix(-math.pi/4))
face = face.dot(get_rot_y_matrix(math.pi/2))
face = face.dot(get_shift_matrix(-1, 0, 0))
polygons.append(face)
return polygons
def get_cube_polygons():
# a cube consist of six faces
# left
polygons = []
rec = Polygon(get_rectangle_points())
t = get_shift_matrix(-1, 0, 0).dot(get_rot_y_matrix(math.pi/2))
polygons.append(rec.transform(t))
# right
t = get_shift_matrix(1, 0, 0).dot(get_rot_y_matrix(math.pi/2))
polygons.append(rec.transform(t))
# bottom
t = get_shift_matrix(0, -1, 0).dot(get_rot_x_matrix(math.pi/2))
polygons.append(rec.transform(t))
# top
t = get_shift_matrix(0, 1, 0).dot(get_rot_x_matrix(math.pi/2))
polygons.append(rec.transform(t))
# front
t = get_shift_matrix(0, 0, -1)
polygons.append(rec.transform(t))
# back
t = get_shift_matrix(0, 0, 1)
polygons.append(rec.transform(t))
return polygons
def get_scale_rot_matrix(scale_tuple, aspect_tuple, shift_tuple):
"""
create a affine transformation matrix
scale is of type tuple (200, 200, 1)
shift is of type tuple (0, 0, -10)
degreees of type tuple for everx axis steps in degrees
aspect of type tuple to correct aspect ratios
steps is of type int
rotates around x/y/z in 1 degree steps and precalculates
360 different matrices
"""
aspect_ratio = aspect_tuple[0] / aspect_tuple[1]
scale_matrix = get_scale_matrix(*scale_tuple)
shift_matrix = get_shift_matrix(*shift_tuple)
alt_basis = (
(1, 0, 0, 0),
(0, aspect_ratio, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)
)
# TODO : majke inversion function
alt_basis_inv = np.linalg.inv(alt_basis)
# combine scale and change of basis to one transformation
# static matrix
# TODO : make dot function for matrices
static_transformation = shift_matrix.dot(alt_basis_inv.dot(scale_matrix))
return static_transformation
def get_rot_matrix(static_transformation, degrees, steps):
"""
static_transformation of type Matrix3d, will be applied to every step
degrees of type tuple, for every axis one entry in degrees
steps of type int, how many steps to precalculate
"""
deg2rad = math.pi / 180
transformations = []
for step in range(steps):
factor = step * deg2rad
angle_x = degrees[0] * factor
angle_y = degrees[1] * factor
angle_z = degrees[2] * factor
# this part of tranformation is calculate for every step
transformation = get_rot_z_matrix(angle_z).dot(
get_rot_x_matrix(angle_x).dot(
get_rot_y_matrix(angle_y)))
# combine with static part of transformation,
# which does scaling, shifting and aspect ration correction
# to get affine transformation matrix
transformation = static_transformation.dot(transformation)
transformations.append(transformation)
return transformations