probiner

Quaternions

Mar 26th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. def addVec(vecA,vecB,*vecs):
  2. """ Returns the sum of scalars or vectors """
  3. def Run(*args):
  4. r = 0
  5. for i in args:
  6. r += i
  7. return r
  8.  
  9. items = [vecA,vecB]
  10. items.extend(vecs)
  11.  
  12. try: #Check if is iterable
  13. return [Run(*i) for i in zip(*items)]
  14.  
  15. except TypeError, te:
  16. return Run(*items)
  17.  
  18.  
  19.  
  20. def subVec (vecA, vecB):
  21. """ Given 2 vectors subtracts the second to the first """
  22. try:
  23. return [i[0]-i[1] for i in zip(vecA,vecB)]
  24.  
  25. except TypeError, te:
  26. return vecA - vecB
  27.  
  28.  
  29.  
  30. # Quaternions
  31. def normalize(v, tolerance=0.00001):
  32. mag2 = sum(n * n for n in v)
  33. if abs(mag2 - 1.0) > tolerance:
  34. mag = sqrt(mag2)
  35. v = tuple(n / mag for n in v)
  36. return v
  37.  
  38. def q_mult(q1, q2):
  39. w1, x1, y1, z1 = q1
  40. w2, x2, y2, z2 = q2
  41. w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
  42. x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
  43. y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
  44. z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2
  45. return w, x, y, z
  46.  
  47. def q_conjugate(q):
  48. w, x, y, z = q
  49. return (w, -x, -y, -z)
  50.  
  51. def qv_mult(q1, v1):
  52. q2 = (0.0,) + v1
  53. return q_mult(q_mult(q1, q2), q_conjugate(q1))[1:]
  54.  
  55. def axisangle_to_q(v, theta):
  56. v = normalize(v)
  57. x, y, z = v
  58. theta /= 2
  59. w = cos(theta)
  60. x = x * sin(theta)
  61. y = y * sin(theta)
  62. z = z * sin(theta)
  63. return w, x, y, z
  64.  
  65. def q_to_axisangle(q):
  66. w, v = q[0], q[1:]
  67. theta = acos(w) * 2.0
  68. return normalize(v), theta
  69.  
  70. def rotateVectorAxisAngle(vector, axis, angle, center=None):
  71. def Run(vector, axis, angle):
  72. vector = tuple(vector)
  73. axis = tuple (axis)
  74. quat = axisangle_to_q(axis,angle)
  75. return list(qv_mult(quat, vector))
  76.  
  77. if center == None:
  78. return Run(vector, axis, angle)
  79.  
  80. else:
  81. vector = subVec(vector,center)
  82. vector = Run(vector, axis, angle)
  83. return addVec(vector,center)
  84.  
  85. def rotateVectorQuat(vector, quat, center=None):
  86. def Run(vector, quat):
  87. vector = tuple(vector)
  88. return list(qv_mult(quat, vector))
  89.  
  90. if center == None:
  91. return Run(vector,quat)
  92.  
  93. else:
  94. vector = subVec(vector,center)
  95. vector = Run(vector,quat)
  96. return addVec(vector,center)
  97.  
  98. def makeQuat(v,tetha):
  99. return axisangle_to_q(tuple(v), tetha)
Advertisement
Add Comment
Please, Sign In to add comment