-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathaljabr.py
1362 lines (1126 loc) · 43.4 KB
/
aljabr.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
:Authors:
Manuel Bastioni,
Marc Flerackers
:Version: 1.0
:Copyright: MakeHuman Team 2001-2011
:License: GPL3
This module contains the most common 3D algebraic operations used in MakeHuman (http://www.makehuman.org/).
These are mostly the vector and matrix operations core to any 3D application. For efficiency and speed, all matrix
operation will be done thru flat arrays. Function with matrices as flat arrays are written with underscore "_", whilst
functions with matrices as list of lists will have the same name without the underscore.
The name is a tribute to *Al-jabr wa'l muqabalah* the most important paper of Mohammed ibn-Musa al-Khuwarizmi (VII - VIII sec d.C.)
The paper was so important that Al-jabr is the root of modern word *algebra* and al-Khuwarizmi is the root of word *algorithm*.
Categories:
Vector Operations
Matrix Operations
Quaternions
Geometric Operations
Various Functions
"""
from math import sqrt, cos, sin, tan, atan2, fabs, acos, pi, exp
from random import random
machine_epsilon = 1.0e-16
degree2rad = pi/180.0
"""
.. note::
A triple of Euler angles can be applied/interpreted in 24 ways, which can
be specified using a 4 character string or encoded 4-tuple:
*Axes 4-string*: e.g. 'sxyz' or 'ryxy'
- first character : rotations are applied to 's'tatic or 'r'otating frame
- remaining characters : successive rotation axis 'x', 'y', or 'z'
*Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)
- inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix.
- parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed
by 'z', or 'z' is followed by 'x'. Otherwise odd (1).
- repetition : first and last axis are same (1) or different (0).
- frame : rotations are applied to static (0) or rotating (1) frame.
"""
_NEXT_AXIS = [1, 2, 0, 1]
_AXES2TUPLE = {
'sxyz': (0, 0, 0, 0), 'sxyx': (0, 0, 1, 0), 'sxzy': (0, 1, 0, 0),
'sxzx': (0, 1, 1, 0), 'syzx': (1, 0, 0, 0), 'syzy': (1, 0, 1, 0),
'syxz': (1, 1, 0, 0), 'syxy': (1, 1, 1, 0), 'szxy': (2, 0, 0, 0),
'szxz': (2, 0, 1, 0), 'szyx': (2, 1, 0, 0), 'szyz': (2, 1, 1, 0),
'rzyx': (0, 0, 0, 1), 'rxyx': (0, 0, 1, 1), 'ryzx': (0, 1, 0, 1),
'rxzx': (0, 1, 1, 1), 'rxzy': (1, 0, 0, 1), 'ryzy': (1, 0, 1, 1),
'rzxy': (1, 1, 0, 1), 'ryxy': (1, 1, 1, 1), 'ryxz': (2, 0, 0, 1),
'rzxz': (2, 0, 1, 1), 'rxyz': (2, 1, 0, 1), 'rzyz': (2, 1, 1, 1)}
#Vector Operations
def vsub(u, v):
"""
This function returns the difference between two vectors of the same dimension. Works also for flat matrices
:param u: the subrahend
:param v: the minuend
:type u: float iterable
:type v: float iterable
:return: The resulting vector, vect1-vect2
:rtype: double array
"""
ret = []
for i in xrange(len(u)):
ret.append(u[i]-v[i])
return ret
def vadd(*vlist):
"""
This function sums several vectors of the same dimension. If for instance one has vectors v1,v2,v3,v4 all four having dimension n, then one can use
vadd(v1,v2,v3,v4). This works for arbitrary number of vectors (with the same dimension), vadd(v1) is also valid. Works also for flat matrices
:param vlist: the sequence without paranthesis, that determines all the vectors to be added together.
:type vlist: a sequence of list of integers of doubles
:return: the sum of vectors to be added
:rtype: double or integer array
"""
returnValue=[]
for i in xrange(len(vlist[0])):
a=0
for j in xrange(len(vlist)):
a=a+vlist[j][i]
returnValue.append(a)
return returnValue
def vmul(vect, s):
"""
This function returns the vector result of multiplying each entries of a vector by a scalar. Works also for flat matrices
:param vect: the vector to be multiplied with the scalar value
:param s: the scalar value
:type vect: double or integer iterable
:type s: double or integer
:return: The resulting vector s(vect1)
:rtype: double iterable
"""
ret=[]
for x in vect:
ret.append(x*s)
return ret
def vdot(u, v):
"""
This function returns the dot product between two vectors of the same dimension
:param u: The first vector
:param v: The second vector
:type u: float or integer iterable
:type v: float or integer iterable
:return: dot-Product of u and v
:rtype: double or integer
"""
a=0
for i in xrange(len(u)):
a=a+u[i]*v[i]
return a
def vlen(v):
"""
This function returns the norm (length) of a vector (as a float).
:rtype: double
:return: euclidean norm of v
:type vect: float or integer iterable
:param vect: The vector
"""
return sqrt(vdot(v,v))
def vnorm(vect):
"""
This function returns a normalized vector ie a unit length
vector pointing in the same direction as the input vector. This performs
essentially the same function as vunit(vect) except that this function
handles potential zero length vectors.
:rtype: double array
:return: normalized form of vect
:type vect: double iterable
:param vect: The vector - in the format [x,y,z]
(or [x,y,z,0] for affine transformations in an homogeneous space).
"""
length = vlen(vect)
# Keep the program from blowing up by providing an acceptable
# value for vectors whose length may be calculated too close to zero.
if length == 0.0:
return len(vect)*[0.0]
# Dividing each element by the length will result in a
# unit normal vector.
#ret = array('d')
ret = []
for x in vect:
ret.append(x/length)
return ret
def vdist(vect1, vect2):
"""
This function returns the euclidean distance (the straight-line distance)
between two vector coordinates.
The distance between two points is the length of the vector joining them.
:rtype: double
:return: euclidean distance between vect1 and vect2 in 3D space
:type vect1: double iterable
:param vect1: The vector - in the format [x,y,z]
(or [x,y,z,0] for affine transformations in an homogeneous space).
:type vect2: double iterable
:param vect2: The vector - in the format [x,y,z]
(or [x,y,z,0] for affine transformations in an homogeneous space).
"""
return vlen(vsub(vect1,vect2))
def vcross(vect1, vect2):
"""
This function returns the cross product of two vectors.
:rtype: double list
:return: cross product M{vect1 S{times} vect2}
:type vect1: double list
:param vect1: The vector - in the format [x,y,z]
(or [x,y,z,0] for affine transformations in an homogeneous space).
:type vect2: double list
:param vect2: The vector - in the format [x,y,z]
(or [x,y,z,0] for affine transformations in an homogeneous space).
"""
return [vect1[1] * vect2[2] - vect1[2] * vect2[1], vect1[2] * vect2[0] - vect1[0] * vect2[2], vect1[0] * vect2[1] - vect1[1] * vect2[0]]
def pseudoGrammSchmidt(v, w):
"""
Given two linearly indeopendent vectors in 3D, this method perform the gramm-schmidt orthogonormalization of the set of vectors.
The output is a vector normal to the first vector and belonging to the plain defined by the two vectors.
See http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process.
:rtype: array of 3 doubles
:return: normal vector to the first input vector and belonging to the plain in which the two input vector generate
:type v: array of 3 doubles
:param v: first input vector
:type w: array of 3 doubles
:param w: first input vector
"""
return vsub(w, vmul(v, vdot(w,v)/vdot(w,w)))
def isPositive(vec, point):
"""
Given a 3D vector and a point in space we want to determine whether the point lies in the direction of the vector or not. In other words, if the vector represent an exis of
another coordinate system (with center still at 0,0,0) and if we project the point onto that axis, we want to determine if the projection is positive with respect to that
axis or not.
:rtype: a bool
:return: true if point lies in the direction of the vector
:type vec: array of 3 doubles
:param vec: a vector in 3D
:type point: array of 3 doubles
:param point: a point in 3d space
"""
return (fabs(acos(vdot(vec,point)/(vlen(vec)*vlen(point)))) <= pi/2)
#Matrix Operations
def mmul(m2, m1):
"""
.. todo::
Still to comment.
"""
return [m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] ,
m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] ,
m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] ,
m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m2[3],
m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6],
m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6],
m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6],
m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m2[7],
m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10],
m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10],
m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10],
m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m2[11],
0.0, 0.0, 0.0, 1.0]
def flatten(M):
"""
For readability it is easier to write matrices as list of list of doubles. In most cases we do this. But for speed and efficiency,
we it is best to have these matrices as an (flattened matrix) array. This function converts a list of list into an array.
:rtype: array
:return: an array object
:type M: double iterable
:param M: Matrix to convert
"""
#N=array('d')
N=[]
for i in xrange(len(M)):
for j in xrange(len(M[0])):
N.append(M[i][j])
return N
def _unFlatten(M,rows,cols):
N = []
#N=array('d')
for i in xrange(rows):
row = []
n=i*cols
for j in xrange(cols):
row.append(M[n+j])
N.append(row)
return N
def zeros(*shape):
"""
This function returns an multidimensional zero-matrix (row-major, list of lists) or zero-vector (list of doubles). For instance: If you want to have a zero-vector of 3-dimensions you type
zeros(3). If you want a 2x3 zero-matrix, we write zeros(2,3).
:rtype: list of double lists
:return: a matrix represented as list of lists. Each entry of the list represents a row of the matrix (if this is a nxm matrix). The representation is a row-major order.
:type shape: sequence of integers (e.g. 2,3 or 2)
:param shape: this represent the dimensions (in integer tuples) of the output matrix (e.g. for 2x3 matrix shape is 2,2)
"""
if len(shape) == 0:
return 0.0
car = shape[0]
cdr = shape[1:]
return [zeros(*cdr) for i in xrange(car)]
def _unitMatrix(n):
"""
This function returns an nxn unit matrix of doubles.
:rtype: array of doubles
:return: an nxn flat unit-matrix, row-major order.
:type n: integer
:param n: the size of the row of the unit-matrix
"""
M=array('d')
for i in xrange(n):
for j in xrange(n):
if (i==j): M.append(1.0)
else: M.append(0.0)
return M
def _transpose(M,rows=0,cols=0):
"""
This function returns the transpose of a flat matrix
:rtype: double array
:return: a matrix that is the transpose of the input matrix (row-major)
:type M: iterable of doubles or integers
:param M: the input flat matrix (row-major) that we want to transpose
:type rows: integer
:param rows: number of rows that M has (as a row-major matrix)
:type cols: integer
:param colss: number of columns that M has (as a row-major matrix)
"""
#ret = array('d')
ret = []
for i in xrange(cols):
for j in xrange(rows):
ret.append(M[i+j*cols])
return ret
def _vmulv(u,v):
"""
This function returns the matrix uv^T (where T here means transpose).
:rtype: array of doubles
:return: flat matrix uv^T (row-major)
:type u: double iterable
:param u: the vector multiplied from left
:type v: double iterable
:param v: the vector multiplied whose adjoint is multiplied from right
"""
#M=array('d')
M=[]
for i in xrange(len(u)):
for j in xrange(len(v)):
M.append(u[i]*v[j])
return M
# Warning: Unfinished!
def _QR(M,n):
"""
.. warning::
**Unfinished!**
QR-Decomposition of a flat singular square matrix using Householder transformations.
:rtype: tuple of array of doubles
:return: a tuple of flat matrices first matrix is an array representing Q, second matrix represents R for the QR-decomposition of M
:type M: array of doubles
:param M: flat square matrix (row-major) that we want to take the QR-decomposition
:type n: integer
:param n: dimension of the square matrix M
"""
A=M[:] #deep copy for a flat iterable. warning [:] does shallow copy for multidimensional iterables
R=n*n*array('d',[0]) #zero matrix
for j in xrange(n):
m=n-j
x=array('d')
e=m*array('d',[0])
e[0]=1.0
for i in xrange(m):
x.append(A[i])
v = vadd(x,vmul(vlen(x),e))
d=vlen(v) #nonzero because A is singular
d=2/(d*d)
P=vsub(unitMatrix(m),vmul(vmulv(v,v),d))
#A=_mmul(P,A,n,n,n)
B=array('d')
#smart matrix matrix multiplication extracting the lower submatrix into B
#i.e. : removing the first row and column of the multiplication of P and A and assigning B to it
# see how Householder Transformation are created in QR-Decomposition!
for i in xrange(m):
m=i*(n-j)
for j2 in xrange(m):
a=0
for k in xrange(m):
a=a+P[m+k]*A[k*m+j2]
if j2==0:
R[j2+j+j*n]=a
else: B.append(a)
A=B
#A= A
#v is not zero because the matrix is singular
#jocapsco: Todo .. finish this...
def _mmul(M,N,rowsM,colsM,colsN):
"""
This is the naive matrix multiplication. There are faster matrix multiplication algorithms (like those by
Strassen (http://en.wikipedia.org/wiki/Strassen_algorithm) or
Coppersmith-Winograd (http://en.wikipedia.org/wiki/Coppersmith-Winograd_algorithm. But fast algorithms will make our
code uneccessarily long and complicated and for small sized matrix (in 3D programming most matrix
operation are limited to 3x3 matrices) the performance improvement is insignifcant.
:rtype: array of doubles
:return: a flat mxp matrix reprenting the product of M and N
:type M: array of doubles
:param M: flat mxn matrix (row-major), that is supposed to be the left-multiplier
:type rowsM: integer
:param rowsM: number of rows of M
:type colsM: integer
:param colsM: number of columns of M = number of rows of N
:type colsN: integer
:param colsN: number of columns of N
"""
#P=array('d')
P=[]
for i in xrange(rowsM):
n=i*colsM
for j in xrange(colsN):
a=0
for k in xrange(colsM):
a=a+M[n+k]*N[k*colsM+j]
P.append(a)
return P
#Quaternions
# Quaternions are of the form (x,y,z,w)
def qmul(q1, q2):
return [q1[1]*q2[2] - q1[2]*q2[1] + q1[0]*q2[3] + q2[0]*q1[3],
q1[2]*q2[0] - q2[2]*q1[0] + q1[1]*q2[3] + q2[1]*q1[3],
q1[0]*q2[1] - q2[0]*q1[1] + q1[2]*q2[3] + q2[2]*q1[3],
q1[3]*q2[3] - q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2]]
def quaternionVectorTransform(q, v):
return [q[3]*q[3]*v[0] + 2*q[1]*q[3]*v[2] - 2*q[2]*q[3]*v[1] + q[0]*q[0]*v[0] + 2*q[1]*q[0]*v[1] + 2*q[2]*q[0]*v[2] - q[2]*q[2]*v[0] - q[1]*q[1]*v[0],
2*q[0]*q[1]*v[0] + q[1]*q[1]*v[1] + 2*q[2]*q[1]*v[2] + 2*q[3]*q[2]*v[0] - q[2]*q[2]*v[1] + q[3]*q[3]*v[1] - 2*q[0]*q[3]*v[2] - q[0]*q[0]*v[1],
2*q[0]*q[2]*v[0] + 2*q[1]*q[2]*v[1] + q[2]*q[2]*v[2] - 2*q[3]*q[1]*v[0] - q[1]*q[1]*v[2] + 2*q[3]*q[0]*v[1] - q[0]*q[0]*v[2] + q[3]*q[3]*v[2]]
def axisAngleToQuaternion(axis, angle):
s = sin(angle/2.0)
qx = axis[0] * s
qy = axis[1] * s
qz = axis[2] * s
qw = cos(angle/2.0)
return (qx, qy, qz, qw)
def quaternionTranslationToDual(q, t):
return [q,
[0.5 * ( t[0] * q[3] + t[1] * q[2] - t[2] * q[1]),
0.5 * (-t[0] * q[2] + t[1] * q[3] + t[2] * q[0]),
0.5 * ( t[0] * q[1] - t[1] * q[0] + t[2] * q[3]),
-0.5 * ( t[0] * q[0] + t[1] * q[1] + t[2] * q[2])]]
# todo: correct to row-major and test validity
def dualToMatrix(d):
# Since the rotation part is a unit quaternion, we don't need to divide I think
#length = vdot(d[0], d[0])
x, y, z, w = d[0]
t1, t2, t3, t0 = d[1]
m = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
m[0][0] = w*w + x*x - y*y - z*z
m[1][0] = 2.0*x*y - 2.0*w*z
m[2][0] = 2.0*x*z + 2.0*w*y
m[0][1] = 2.0*x*y + 2.0*w*z
m[1][1] = w*w + y*y - x*x - z*z
m[2][1] = 2.0*y*z - 2.0*w*x
m[0][2] = 2.0*x*z - 2.0*w*y
m[1][2] = 2.0*y*z + 2.0*w*x
m[2][2] = w*w + z*z - x*x - y*y
m[3][0] = -2.0*t0*x + 2.0*t1*w - 2.0*t2*z + 2.0*t3*y
m[3][1] = -2.0*t0*y + 2.0*t1*z + 2.0*t2*w - 2.0*t3*x
m[3][2] = -2.0*t0*z - 2.0*t1*y + 2.0*t2*x + 2.0*t3*w
m[0][3] = 0.0
m[1][3] = 0.0
m[2][3] = 0.0
m[3][3] = 1.0
#mdiv(m, length)
return m
#Note: Quaternions have to of normalized form
# Quaternions are of the form (x,y,z,w)
def quaternion2Matrix(q):
m = [ [1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0]] # will be a 3x3 euler rotation matrix
m[0][0] = float(q[3]*q[3] + q[0]*q[0] - q[1]*q[1] - q[2]*q[2])
m[0][1] = 2.0*(q[0]*q[1]-q[3]*q[2])
m[0][2] = 2.0*(q[0]*q[2]+q[3]*q[1])
m[1][0] = 2.0*(q[1]*q[0]+q[3]*q[2])
m[1][1] = float(q[3]*q[3]-q[0]*q[0]+q[1]*q[1]-q[2]*q[2])
m[1][2] = 2.0*(q[1]*q[2]-q[3]*q[0])
m[2][0] = 2.0*(q[2]*q[0]-q[3]*q[1])
m[2][1] = 2.0*(q[2]*q[1]+q[3]*q[0])
m[2][2] = float(q[3]*q[3]-q[0]*q[0]-q[1]*q[1]+q[2]*q[2])
return m
def matrix2Quaternion(m):
q = [0.0, 0.0, 0.0, 1.0];
t = 1.0 + m[0][0] + m[1][1] + m[2][2]
r = 0.0;
i = 0;
if (t == 0.0):
return q
elif (t > 0):
r = sqrt(1.0 + m[0][0] + m[1][1] + m[2][2]);
else:
if ((m[0][0] > m[1][1]) and (m[0][0] > m[2][2])):
i = 1
elif (m[1][1] > m[2][2]):
i = 2
else:
i = 3
r = 2 * m[i - 1][i - 1] - m[0][0] - m[1][1] - m[2][2];
sgn = 1 - 2 * (i % 2)
q[(i + 3) % 4] = r / 2.0
q[(sgn + i + 3) % 4] = (m[2][1] - m[1][2]) / (2 * r)
q[(2 * sgn + i + 3) % 4] = (m[0][2] - m[2][0]) / (2 * r)
q[(3 * sgn + i + 3) % 4] = (m[1][0] - m[0][1]) / (2 * r)
return q
def euler2Quaternion(e, axes='sxyz'):
return matrix2Quaternion(_unFlatten(euler2matrix(e, axes),4,4))
def quaternionLerp(q1, q2, alpha):
return vnorm([q1[0] + alpha * (q2[0] - q1[0]),
q1[1] + alpha * (q2[1] - q1[1]),
q1[2] + alpha * (q2[2] - q1[2]),
q1[3] + alpha * (q2[3] - q1[3])])
'''
def quaternionSlerp2(q1, q2, alpha):
dot = vdot(q1, q2)
if dot > 0.1:
return vnorm([q1[0] + alpha * (q2[0] - q1[0]),
q1[1] + alpha * (q2[1] - q1[1]),
q1[2] + alpha * (q2[2] - q1[2]),
q1[3] + alpha * (q2[3] - q1[3])])
dot = max(-1.0, min(dot, 1.0))
theta0 = acos(dot)
theta = theta0 * alpha
q = vnorm([q2[0] - alpha * q1[0],
q2[1] - alpha * q1[1],
q2[2] - alpha * q1[2],
q2[3] - alpha * q1[3]])
return vadd(vmul(q1, cos(theta)), vmul(q, sin(theta)))
'''
def quaternionSlerp(q1, q2, alpha):
cosHalfTheta = q1[3] * q2[3] + q1[0] * q2[0] + q1[1] * q2[1] + q1[2] * q2[2]
if abs(cosHalfTheta) >= 1.0:
return q1
halfTheta = acos(cosHalfTheta)
sinHalfTheta = sqrt(1.0 - cosHalfTheta * cosHalfTheta)
if abs(sinHalfTheta) < 0.001:
return [q1[0] * 0.5 + q2[0] * 0.5,
q1[1] * 0.5 + q2[1] * 0.5,
q1[2] * 0.5 + q2[2] * 0.5,
q1[3] * 0.5 + q2[3] * 0.5]
ratioA = sin((1 - t) * halfTheta) / sinHalfTheta;
ratioB = sin(t * halfTheta) / sinHalfTheta;
return [q1[0] * ratioA + q2[0] * ratioB,
q1[1] * ratioA + q2[1] * ratioB,
q1[2] * ratioA + q2[2] * ratioB,
q1[3] * ratioA + q2[3] * ratioB]
# Axis is normalized, angle is in radians
def axisAngleToEuler(x, y, z, angle):
s = sin(angle)
c = cos(angle)
t = 1-c
if (x*y*t + z*s) > 0.998:
heading = 2.0 * atan2(x*sin(angle/2.0), cos(angle/2.0))
attitude = pi/2.0
bank = 0.0
return heading, attitude, bank
if (x*y*t + z*s) < -0.998:
heading = -2.0*atan2(x*sin(angle/2.0),cos(angle/2.0))
attitude = -pi/2.0
bank = 0.0
return heading, attitude, bank
heading = atan2(y * s- x * z * t , 1.0 - (y*y+ z*z ) * t)
attitude = asin(x * y * t + z * s)
bank = atan2(x * s - y * z * t , 1.0 - (x*x + z*z) * t)
return heading, attitude, bank
"""
Geometric Operations
"""
def mulmatvec3x3(m, vect):
"""
This function returns a 3D vector which consists of the 3D input
vector multiplied by a 3x3 matrix.
:rtype: double iterable
:return: 3D vector
:type m: double iterable
:param m: The matrix to multiply
:type vect: double iterable
:param vect: The vector - in the format[x,y,z]
(or [x,y,z,0] for affine transformations in an homogeneous space)
"""
r = [0.0, 0.0, 0.0]
r[0] = vect[0] * m[0][0] + vect[1] * m[1][0] + vect[2] * m[2][0]
r[1] = vect[0] * m[0][1] + vect[1] * m[1][1] + vect[2] * m[2][1]
r[2] = vect[0] * m[0][2] + vect[1] * m[1][2] + vect[2] * m[2][2]
return r
def makeRotEulerMtx3D(rx, ry, rz):
"""
This function returns a 3x3 euler rotation matrix based on the 3 angles
rx, ry and rz.
:rtype: double iterable
:return: 3x3 euler rotation matrix
:type rx: float
:param rx: The angle of rotation (in radians) around the x-axis
:type ry: float
:param ry: The angle of rotation (in radians) around the x-axis
:type rz: float
:param rz: The angle of rotation (in radians) around the x-axis
"""
SRX = sin(rx)
SRY = sin(ry)
SRZ = sin(rz)
CRX = cos(rx)
CRY = cos(ry)
CRZ = cos(rz)
return [[CRY * CRZ, CRY * SRZ, -SRY], [(CRZ * SRX) * SRY - CRX * SRZ, CRX * CRZ + (SRX * SRY) * SRZ, CRY * SRX], [SRX * SRZ + (CRX * CRZ) * SRY, (CRX * SRY) * SRZ
- CRZ * SRX, CRX * CRY]]
def makeTransform(Rxyz, Txyz):
"""
Makes a flat 4x4 homogenous transform matrix (row-major). Using xyz rotations and position
:rtype: double iterable
:return: 4x4 roto-translation matrix
:type Rxyz: double iterable
:param Rxyz: A list or rotations around X,Y and Z axis, in radians.
:type Txyz: double iterable
:param Txyz: The translation vector along X,Y and Z axis.
"""
sx = sin(Rxyz[0])
sy = sin(Rxyz[1])
sz = sin(Rxyz[2])
cx = cos(Rxyz[0])
cy = cos(Rxyz[1])
cz = cos(Rxyz[2])
return [cy*cz , cy*sz , -sy , Txyz[0],
cz*sx*sy - cx*sz, cx*cz + sx*sy*sz, cy*sx, Txyz[1],
sx*sz + cx*cz*sy, cx*sy*sz - cz*sx, cx*cy, Txyz[2],
0.0 , 0.0 , 0.0 , 1.0]
def makeRotEulerMtx2D(theta, rotAxe):
"""
This function returns a 3x3 euler matrix that rotates a point on
a plane perpendicular to a specified rotational axis.
:rtype: double iterable
:return: 3x3 euler rotation matrix
:type theta: float
:param theta: The angle of rotation (in radians)
:type rotAxe: string
:param rotAxe: The axis of rotation, which can be "X", "Y" or "Z".
"""
if rotAxe == 'X':
Rmtx = makeRotEulerMtx3D(theta, 0, 0)
elif rotAxe == 'Y':
Rmtx = makeRotEulerMtx3D(0, theta, 0)
elif rotAxe == 'Z':
Rmtx = makeRotEulerMtx3D(0, 0, theta)
return Rmtx
def makeRotMatrix(angle, axis):
"""
This function returns a 3x3 transformation matrix that represents a
rotation through the specified angle around the specified axis.
This matrix is presented in Graphics Gems (Glassner, Academic Press, 1990),
and discussed here: http://www.gamedev.net/reference/programming/features/whyquats/
:rtype: double iterable
:return: 3x3 euler matrix
:type angle: float
:param angle: The angle of rotation (rad) around the specified axis
:type axis: double iterable
:param axis: A 3d vector [x,y,z] defining the axis of rotation
(this should already be normalized to avoid strange results)
"""
a = angle
x = axis[0]
y = axis[1]
z = axis[2]
t = 1 - cos(a)
c = cos(a)
s = sin(a)
M11 = (t * x) * x + c
M12 = (t * x) * y + s * z
M13 = (t * x) * z - s * y
M21 = (t * x) * y - s * z
M22 = (t * y) * y + c
M23 = (t * y) * z + s * x
M31 = (t * x) * z + s * y
M32 = (t * y) * z - s * x
M33 = (t * z) * z + c
return [[M11, M12, M13], [M21, M22, M23], [M31, M32, M33]]
def rotMatrix2Matrix4(m):
return [ m[0][0], m[0][1], m[0][2], 0.0,
m[1][0], m[1][1], m[1][2], 0.0,
m[2][0], m[2][1], m[2][2], 0.0,
0.0, 0.0, 0.0, 1.0]
def makeUnit():
return [1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0]
def makeTranslation(x, y, z):
return [1.0, 0.0, 0.0, x,
0.0, 1.0, 0.0, y,
0.0, 0.0, 1.0, z,
0.0, 0.0, 0.0, 1.0]
def getTranslation(m):
"""
get the translation vector of a homogeneous 4x4 row-major transformation matrix
"""
return [m[3], m[7], m[11]]
def makeRotation(axis, angle):
c = cos(angle)
s = sin(angle)
t = 1 - c
x, y, z = axis
return [x*x * t + c, y*x * t - z*s, x*z * t + y*s, 0.0,
x*y * t + z*s, y*y * t + c, y*z * t - x*s, 0.0,
x*z * t - y*s, y*z * t + x*s, z*z * t + c, 0.0,
0.0, 0.0, 0.0, 1.0]
def makeScale(scale):
if type(scale) is float:
scale = [scale,scale,scale]
return [scale[0], 0.0, 0.0, 0.0,
0.0, scale[1], 0.0, 0.0,
0.0, 0.0, scale[2], 0.0,
0.0, 0.0, 0.0, 1.0]
def mtransform(m, v):
return[m[0]*v[0] + m[1]*v[1] + m[2]*v[2] + m[3],
m[4]*v[0] + m[5]*v[1] + m[6]*v[2] + m[7],
m[8]*v[0] + m[9]*v[1] + m[10]*v[2] + m[11]]
def invTransform(m):
"""
A fast way to inverse a homogenous 4x4 flat row-major transformation matix
we use the fact that rotations are orthogonal
.. note::
there shouldnt be scaling in the matrix)
"""
rinv = [m[0], m[4], m[8], 0,
m[1], m[5], m[9], 0,
m[2], m[6], m[10],0,
0.0, 0.0, 0.0, 1.0]
t = mtransform(rinv, [-m[3],-m[7],-m[11]])
return [m[0], m[4], m[8], t[0],
m[1], m[5], m[9], t[1],
m[2], m[6], m[10],t[2],
0.0, 0.0, 0.0, 1.0]
# uses flat row-major 4x4 transformation matrices. Returned angles are in radians
def matrix2euler(m, ):
"""
See: http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
"""
_NEXT_AXIS = [1, 2, 0, 1]
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
i = firstaxis
j = _NEXT_AXIS[i+parity]
k = _NEXT_AXIS[i-parity+1]
if repetition:
sy = sqrt(m[i+4*j]*m[i + 4*j] + m[i+4*k]*m[i+4*k])
if sy > machine_epsilon:
ax = atan2( m[i+4*j], m[i+4*k])
ay = atan2( sy, m[i+4*i])
az = atan2( m[j+4*i], -m[k+4*i])
else:
ax = math.atan2(-m[j+4*k], m[j+4*j])
ay = math.atan2( sy, m[i+4*i])
az = 0.0
else:
cy = math.sqrt(m[i+4*i]*m[i+4*i] + m[j+4*i]*m[j+4*i])
if cy > machine_epsilon:
ax = math.atan2( m[k+4*j], m[k+4*k])
ay = math.atan2(-m[k+4*i], cy)
az = math.atan2( m[j+4*i], m[i+4*i])
else:
ax = math.atan2(-m[j+4*k], m[j+4*j])
ay = math.atan2(-m[k+4*i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return [ax, ay, az]
#angles are radians!, returns flat matrix!
def euler2matrix(rotation, axes='sxyz'):
"""
Return homogeneous rotation matrix from Euler angles and axis sequence.
see: http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
"""
ai, aj, ak = rotation[0], rotation[1], rotation[2]
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes]
i = firstaxis
j = _NEXT_AXIS[i+parity]
k = _NEXT_AXIS[i-parity+1]
if frame:
ai, ak = ak, ai
if parity:
ai, aj, ak = -ai, -aj, -ak
si, sj, sk = sin(ai), sin(aj), sin(ak)
ci, cj, ck = cos(ai), cos(aj), cos(ak)
cc, cs = ci*ck, ci*sk
sc, ss = si*ck, si*sk
m = makeUnit()
if repetition:
m[4*i+i] = cj
m[4*i+j] = sj*si
m[4*i+k] = sj*ci
m[4*j+i] = sj*sk
m[4*j+j] = -cj*ss+cc
m[4*j+k] = -cj*cs-sc
m[4*k+i] = -sj*ck
m[4*k+j] = cj*sc+cs
m[4*k+k] = cj*cc-ss
else:
m[4*i+i] = cj*ck
m[4*i+j] = sj*sc-cs
m[4*i+k] = sj*cc+ss
m[4*j+i] = cj*sk
m[4*j+j] = sj*ss+cc
m[4*j+k] = sj*cs-sc
m[4*k+i] = -sj
m[4*k+j] = cj*si
m[4*k+k] = cj*ci
return m
#converts a matrix (flat, homogenous row-major transformation) to rotation, position
# where rotation is an euler xyz rotation and position is the position in the form [x,y,z]
def makeXYZPos(m):
position = [m[3], m[7], m[11]]
#xyzRot =
pass
def centroid(vertsList):
"""
This function returns the baricenter of a set of coordinate vectors
[[x1,y1,z1],[x2,y2,z2],...,[xn,yn,zn]], returning a coordinate vector
formatted as a double list [double X,double Y, double Z].
This is the sum of all of the vectors divided by the number of vectors.
:rtype: double iterable
:return: the centroid of the convex hull of all the vertices in M(vertsList)
:type vertsList: list of double lists
:param vertsList: each vector in the list is in the format [x,y,z]
(or [x,y,z,0] for affine transformations in an homogeneous space).
"""
nVerts = len(vertsList)
xTot = 0.0
yTot = 0.0
zTot = 0.0
for v in vertsList:
xTot += v[0]
yTot += v[1]
zTot += v[2]
if nVerts != 0:
centrX = xTot / nVerts
centrY = yTot / nVerts
centrZ = zTot / nVerts
else:
print 'Warning: no verts to calc centroid'
return 0
return [centrX, centrY, centrZ]
def rotatePoint(center, vect, rotMatrix):
"""
This function returns the 3D vector coordinates of a
vector rotated around a specified centre point using a
3x3 rotation matrix.
:rtype: Double iterable
:return: Rotated point
:type center: Double iterable
:param center: A 3D vector - in the format[x,y,z] containing the
coordinates of the center of rotation.
:type vect: Double iterable
:param vect: A 3D vector - in the format[x,y,z] containing the
coordinates of the point to be rotated.
:type rotMatrix: Double iterable
:param rotMatrix: A 3x3 rotation matrix.
"""
# subtract rotation point
tv = vsub(vect, center)
# rotate
nv = mulmatvec3x3(rotMatrix, tv)