python
import math
class Quaternion:
def __init__(self, x=0, y=0, z=0, w=1):
self.x = x
self.y = y
self.z = z
self.w = w
def __mul__(self, q):
x1, y1, z1, w1 = self.x, self.y, self.z, self.w
x2, y2, z2, w2 = q.x, q.y, q.z, q.w
x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2
w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
return Quaternion(x, y, z, w)
def conjugate(self):
return Quaternion(-self.x, -self.y, -self.z, self.w)
def normalize(self):
norm = math.sqrt(self.x**2 + self.y**2 + self.z**2 + self.w**2)
self.x /= norm
self.y /= norm
self.z /= norm
self.w /= norm
return self
def rotate(self, v):
qv = Quaternion(v[0], v[1], v[2], 0)
q_inv = self.conjugate()
q_rotated = self * qv * q_inv
return [q_rotated.x, q_rotated.y, q_rotated.z]
def quat_angle_axis(angle, axis):
angle = math.radians(angle)
half_angle = angle / 2
s = math.sin(half_angle)
c = math.cos(half_angle)
return Quaternion(axis[0] * s, axis[1] * s, axis[2] * s, c)
view_angle = 0.3 * 180.0
view_center = [0, 0, -1]
angle = 45.0
q = quat_angle_axis(angle, [1, 0, 0])
view_center = q.rotate(view_center)