.netquaternionssystem.numerics

3D Rotation using System.Numerics.Quaternion


Anybody here know how to rotate a vector3 using .net(4.6 and up) System.Numerics.Quaternion?

My maths is pretty poor though and my understanding only really goes as far as: quaternions are 4d "structures" that can produce translation, scaling and rotation in 3d.

So I had a play and cannot get any rotation. Doing what seemed obvious : changing the W component of the Quaternion.(angle) then reading the vector produces scaling ?!? Anyone able to help or point me in the right direction for help?

My current rotation (non-quaternion) code (X-axis example)

Private Sub Xaxis_rotation(ByVal angle As Double)
        Dim Cangle As Double = Cos(angle)
        Dim Sangle As Double = Sin(angle)
        Parallel.For(1, vertcount, Sub(f As Int32)
                                       Verts(f) -= modelcenter
                                       Verts(f).Y = (Verts(f).Y * Cangle) + (Verts(f).Z * Sangle)
                                       Verts(f).Z = (Verts(f).Z / Cangle) - (Verts(f).Y * Sangle)
                                       Verts(f) += modelcenter
                                   End Sub)
    End Sub

[edit]

    Dim rotAxis As Vector3 = Vector3.UnitX
    Dim rotangle As Single =  0.785398 '45 degrees as radians
    Dim q As Quaternion = Quaternion.CreateFromAxisAngle(rotAxis, rotangle)
    Dim aVector As Vector3 = *vector to be rotated*

    'rotate
    Dim resultQ As Quaternion = q * Quaternion.CreateFromAxisAngle(aVector, 0) / q

    aVector.X = resultQ.X
    aVector.Y = resultQ.Y
    aVector.Z = resultQ.Z

q*Quaternion.CreateFromAxisAngle(aVector, 0) / q is my best guess but it does not produce rotation.


Solution

  • A final update on this:

    The code below using Vector3.Transform is faster and appears more accurate than the previous method, defining the resultq Quaternion.

    Public Shared Sub Rotate_point(ByRef Vect As Vector3, CentPoint As Vector3, angles As Vector3)
        Dim Rotator As Quaternion = Quaternion.CreateFromYawPitchRoll(angles.Y, angles.X, angles.Z) 'rotation in radians
        Vect -= CentPoint '---------The point to rotate around.
        Vect = Vector3.Transform(Vect, Rotator)
        Vect += CentPoint
     End Sub