treeform/vmath

Missing quat and vector functions

abisxir opened this issue · 4 comments

Some functions for quat are missing, like lookRotation:

proc lookRotation(forward, up: Vec3): Quat

or rotation between two vectors:

proc rotationBetweenVectors(a, b: Vec3): Quat

or rotating a vector, by a quat:

proc rotate(v: Vec3, q: Quat): Vec3

There are some implementation I found (not in nim, in java), I can write nim ported versions here, if you think they are good to add to vmath.

For 1 you could use lookAt and then convert that to a quat.

You right I don't have the other two. I would accept a PR if you add them.

quat lookup

Here is how you can get a look at quat, using the matrix look at:

lookAt(vec3(1, 2, 3), vec3(0, 0, 0)).quat

quat fromTwoVectors

I am adding rotation between two vectors as fromTwoVectors, will be in vmath 2.0, rough code here:

proc orthogonal*[T](v: GVec3[T]): GVec3[T] =
  let v = abs(v)
  var other: type(v) =
    if v.x < v.y :
      if v.x < v.z:
        [T(1), 0, 0] # X_AXIS
      else:
        [T(0), 0, 1] # Z_AXIS
    elif v.y < v.z :
      [T(0), 1, 0] # Y_AXIS
    else:
      [T(0), 0, 1] # Z_AXIS
  return cross(v, other)

proc fromTwoVectors*[T](a, b: GVec3[T]): GVec4[T] =
  ## Return a quat that would take `a` and rotate it into `b`.
  let
    u = b.normalize()
    v = a.normalize()
  if (u == -v):
    let q = normalize(orthogonal(u))
    return [q.x, q.y, q.z, 0]

quat * vec

You can already use quat*vec by first creating a matrix:

q.mat4 * a

See vmath 2.0 here: #29

Thanks for solutions, I also found some solutions and added as utility funcs to my project but was not confident to prefer it here.