Code examples using quaternion for rotation?

I have to look into quaternions. But can anyone provide with a code example of how to use them?

For example rotating an object around a vector, and transforming an object from one plane to another. I know there are plugins that can handle quaternions (Falcon and Pufferfish has it) but I need to be able to code it myself (RhinoCommon quaternions).

I tried a bit but the results doesn’t make sense to me… What I did was creating a vector from two box corners (see fig below) and created a transform with zero radians rotation. That resulted in a box rotated 180 degrees (the green box below). And the quat.MatrixForm() (output to T) results in a weird flattened surface (red).

I obviously don’t have a clue. :slight_smile:

Fig 1. The code generating the above:

private void RunScript(double w, Vector3d v, ref object Q, ref object trx)
{
    var vec = cp1 - cp0;
    vec.Unitize();
    var quat = new  Rhino.Geometry.Quaternion(rad, vec.X, vec.Y, vec.Z);

    var out_rad = 0.0;
    var out_vec = Vector3d.Unset;
    quat.GetRotation(out out_rad, out out_vec);

    var xform = Rhino.Geometry.Transform.Rotation(out_rad, out_vec, cp0);
    geo.Transform(xform);

    Geo = geo;   
    T = quat.MatrixForm();  
}

Although totally useless, here’s the script:
Quaternion_test.gh (6.4 KB)

< Embarrassed >

// Rolf

1 Like

Don’t know if it’s going to be any help for you, but here’s a VB implementation of Silicon Graphics trackball routine which uses quaternions and has some comments and literature references embedded.

trackball.txt (10.7 KB)

1 Like

Pufferfish does have it but I did it the hard way - before I knew about the rhinocommon quaternions :smiley: (I coded what a quaternion does behind the scenes ala a reference from Daniel Piker, not actually using rhinocommon quaternions). @Dani_Abalde has the cleanest code for the rotation I’ve seen using the Rhinocommon quaternions - we compared with Pufferfish vs his Plane interpolation in Peacock and results are the same. Maybe he will be nice enough to share with you :wink:

1 Like

I always thought that quaternions are only used to convert in between axis angle, euler and rotation matrices. …and interpolating/lerp in between.
However I’m also having trouble understanding quaternions… In case you need a c# implementation:

I found this here:

http://www.technologicalutopia.com/sourcecode/xnageometry/quaternion.cs.htm

2 Likes

@DanielPiker also has a nice Quaternion script that seems to have gone through some Obfuscation :wink: but I bet he can shed some light on the topic as well.

2 Likes

I only can help with this, interpolating two planes:

Quaternion q0 = Quaternion.Zero;
q0.SetRotation(Plane.WorldXY, fromPlane);

Quaternion q1 = Quaternion.Zero;
q1.SetRotation(Plane.WorldXY, toPlane);

Quaternion q2 = Slerp(q0, q1, st);

Plane slerpPlane = Plane.Unset;
q2.GetRotation(out slerpPlane);

And I hope no one asks me why it works xD
I get the slerp from three.js

2 Likes

.Net’s Media3d namespace also has Quaternion.Slerp.

1 Like

Thank you guys, you are wesome, all of you! I wonder if you really are aware of how special this community is?

I’m quite confident that I will find my way through the dark valley of quaternion with the help of all your hints and links. I will not have to dive all the way to the bottom of the swamp, but being able to utilize the concept in practice, and doing all the conversions, seems to lay whithin reach for my level of math. With this help.

Thank you all for all the valuable links, starting from @AlW’s uploaded code examples (I already refactored it to make it “human readable” (…) and @TomTom’s link, @Michael_Pryor’s hint about the Obfuscated Quaternion (to make this challenge a bit more interesting) to @Dani_Abalde’s elegant snippet of how to apply the quaternions for common tasks.

An last but not the least, Slerping is essential, Lerping too, although I didn’t know that before three or four days ago when I still thought that Euler or Spherical coordinate system would solve all the world’s problems. :slight_smile:

Thanks. I will let you know if I come out of this with the hairy end in the euclidian Z+ direction. :slight_smile:

// Rolf

Hi Rolf,

A little late to this quaternion party,
I’m not sure why you say you have to use quaternions, but not what you want to do with them - it seems a strange way round to start to me :thinking:
They do certainly have their uses, but depending on the problem may not be the only or best solution.

Anyway, assuming this is something to do with rotation, to throw another example into the mix, I’ve included below a simple linear interpolation, and also something I did using Quaternions to interpolate smoothly through a sequence of orientations.

If you just want to interpolate between one orientation and another, then you can use Slerp. Equivalently using (and I think perhaps more intuitive), just using RhinoCommon you can convert the rotation to axis and angle form using: http://developer.rhino3d.com/api/RhinoCommon/html/M_Rhino_Geometry_Quaternion_GetRotation_1.htm
then just rotate by multiples of this angle to interpolate.

Here’s an example of this to interpolate between planes P1 and P2 by a factor of t:

Quaternion q = Quaternion.Rotation(P1, P2);
double angle = new double();
Vector3d axis = new Vector3d();
q.GetRotation(out angle, out axis);
Plane OutputPlane = new Plane(P1);
angle = (angle > Math.PI) ? angle - 2 * Math.PI : angle;
OutputPlane.Rotate(t * angle, axis, OutputPlane.Origin);
Vector3d Translation = new Vector3d(P2.Origin - P1.Origin);
OutputPlane.Translate(Translation * t);

However, if you have more than 2 orientations (such as a camera path that has to pass through a number of locations/targets), using Slerp between each one and the next will result in sudden changes of angular velocity.
To avoid this, you can build up quaternion splines by combining slerps, more or less like how you would make a bezier curve using straight lines.
This paper is a nice reference:

As an alternative to that though, I once tried out an idea for generating quaternion splines via stereographic projection from the 3-sphere of unit quaternions to regular 3d space, then using Rhino’s splines in 3d, and projecting back up into quaternion space to get the rotation.
Here’s a gh definition showing this:
QuaternionSpline2.gh (24.4 KB)
It’s an unconventional approach, but seems to work reasonably well.

and here’s the code version of the same thing Michael was referring to:
QuaternionSpline.gh (4.9 KB)

6 Likes

I get a “certificate error” on this from MIT. Is it just me, or is there a general reason?

Edit: Nevermind. I subsequently went just to https://web.mit.edu and then searched for QuaternionReport1.pdf and found it. Thanks for the reference.

I will use it for shoulder simulations. 3 DOF (actually more, but to start with). IK-like problems follows, since I’m also making a UI where you grab the hand and twist the arm around, until it dislocates (due to injuries on the humeral head and glenoid. Mesh surface collisions involved).

So yes, I will need to apply all the math I can force myself into. :slight_smile:

Thank you very much also for the last example. You already guessed why SLERP is of interest in this context.

I will also have to convert (series of) angle and position data into euclidian ditto’s, both World and CPlanes, oriented to the skeletal joints involved (this to be recorded as simulation results).

This is only one example (of several examples) of why Bongo fails to serve my needs - I cannot log, or record, the positions and orientations while in motion (I needed it for another purely “mechanical” project as well but… never mind). Nor can I script-feed Bongo with motion paths. And thus it cannot produce the “research data” (nor log-data for post-op analysis) which I’m after.

But with GH I can.

In short, I will have to make my own IK Solver. (therefore, hints on existing .NET libraries for rigidbody IK chains is also welcome, saving me time… ).

So detailed output data is one reason to why I need access to source code at all times. It follows that cheating isn’t an option. :sweat_smile: (so, it’s not that I dislike existing plugins, no no, I’d love to jump fences, but closed source components just don’t “let me in” so to speak).

Have a good one.

// Rolf

Stumbled upon this, couldn’t resist :

"Quaternions came from Hamilton after his really good work had been done, and though beautifully ingenious, have been an unmixed evil to those who have touched them in any way." ~Lord Kelvin

And why anyone would still consider taking the pain:

// Rolf

4 Likes

Hi! :vulcan_salute:

I’m trying to understand quaternions to do physics things; especially to graphically explain very, very abstract concepts (such as Spin, coupling, orbitals, space-time diagrams, etc.).

But I do not find good material to understand them; most of them are oriented to pure and simple math, or too simplistic (rotation), but I would love to be able to develop a plugin/scrypt in C# (my language), to be able to use them.

It is necessary to decompact physics from the 2nd dimension and bring it to the 3rd dimension.

  • The greatest problem of it, is the incorrect interpretation; given the mathematical difficulty to interpret the Z axis and the moments (rotations, acceleration, etc.).

So in this way, we will not only be able to achieve a better understanding of it, but also bring it closer to those who want to understand it better, and end so much ignorance about it.

And obviously end up with so much healing quantum waves and all that jaz.

I would greatly appreciate your knowledge and experience in the subject, since I am just learning how to program in grasshopper and rhino.

If useful here are some other links on use of Quaternion. I used them quite a lot some years ago for rocket simulation.

2 Likes

Well, after a lot of research:

  • The project ‘got a bit complicated’, because to do/generate what I want/need, I’ll have to start literally from scratch, since I have to extend up to:
  • Sedenions
  • Octonions
  • Dual/Bi quaternions
  • Quaternions themselves.

But Grasshopper doesn’t have these types of data natively, so I’ll have to code a plugin after all.

And since the project is mainly to teach uses, applications, and understanding (not only mathematical, but also geometric) of such algebras (Robotics, physics, theoretical physics, quantum physics, particle physics, and general relativity).

Obviously, extending it to other fields as understanding improves.

  • So the first goal is to create the C# libraries to make it more practical to adapt them to other platforms/programs later, and then integrate them into Grasshopper (to achieve geometric integration and understanding; points, planes, vectors, surfaces, BREP’s, etc).

I would appreciate any help you can provide (especially on the how-to roadmap), since I haven’t finished reading and interpreting the Grasshopper documentation yet (difficult times for working :money_with_wings: : and studying :book: in Argentina :argentina:).

I don’t know if this makes sense, but I’m curious to transform a Voronoi in hyperspace :stuck_out_tongue:

1 Like

In reality (in fact), the algebra of hypercomplex numbers is greatly undervalued and is only reduced to a mere “tool” that facilitates an action (simple action).

Well, from his beginnings with Hamilton, Tate, James C. Maxwell. It had a lot of resistance, which until then (even today, despite the postulate that best describes the universe [relativity]).

The world is thought to be Euclidean (straight) & 2D, It is enough to verify that each method, function, calculus, etc. is thought in terms of x and y, where the z-axis is an unreal or imaginary (magical) thing.

But this is not the case, B. Riemann taught (at the time) that in a sphere a right angle is not 90° in a sphere, and our universe is predominantly “spherical” (in terms of celestial bodies), Assuming that Euclid can only be accepted in 2Ds terms (Plane), but not in 3Ds (Cube) and 3Ds+1t (Sphere by Gravity efects).

Now… Why was quaternion (Hamilton) algebra not adopted as the main mathematical model?

Easy, because at that time, there was no way to put into practice that complex algebra of rotations, translations, forces, etc.

Until Maxwell introduced his treatise on electricity and magnetism (originally written in quaternions). that is where all your knowledge about vectors and their algebra comes from.

Heaviside (who was not a mathematician, scientist, physicist or teacher, just an engineer). He was the first to popularize Maxwell’s work, but in doing so he dismembered quaternions and separated the scalar from the vector, just to maintain the commutative property of multiplication (orthodox stuff)

From there came the great battle of the mathematicians, where vector notation won (losing itself in time until the appearance of quantum and its use by Pauli)

  • Many marveled (like Riemann) at that type of algebra, but the fear of being discredited or treated as crazy by the scientific community (even Einstein), led them to create complex algebraic structures, only to keep the analysis and geometry in 2D, compacting events, effects of 3Ds+1Dt stuffs in 2Ds, making their interpretation impossible (“Knots” in 2Ds are just “Apparent Intersections” in 3Ds and Paths in 3Ds+1Dt). -

The problem of “dimensions” that falls so much mockery on those who use these algebras, is nothing more than the result of the ignorance and lack of understanding of those who do nothing more than repeat the copy-paste of Heaviside (in Maxwell’s time).

Mathematically, a quaternion has 4 “dimensions” because it has 4 components (nothing else).
And that misinterpretation is perpetuated, making others believe that you are talking about metaphysic and quantum healing waves.

But in a single quaternion, you can encode a lot of information, more in a dual quaternion.

All general relativity can be expressed in terms of dual quaternions, including much quantum physics.

But if there is something that a dual quaternion does not describe well (for reasons of symmetries), it is the chirality and irreversibility of time. (which according to all contemporary physics may be possible)

Which we know is not possible, a broken glass (even if you put together all the quanta of energy) will never be “unbreak” (Thermodynamics, arrow of time, etc.).

That brings us to the octotions, which due to their mathematical particularity (non-commutative and non-associative), makes them purely “evolutionary” (there is no going back, or at least to the same “exact” state).

A dual quaternion can be easily mapped into an octonion, so instead of operating dual quaternions (and making something reversible over time), they operate as octonions (becoming irreversible).

In this way, physics would correspond to what is observed in our 3Ds+1Dt plane.

  • And no, we do not leave our universe to an 8-dimensional one. We only describe more complex things or movements in a simpler way.

In this way, 2 octonions can contain; Points, Planes, Volumes, Velocities, rotations, accelerations, trajectories, spins, the inner and outer face of an object (Normal) and be physically correct.

with your current algebra… Can you invert a sphere from the inside out and vice versa, without its BREP being “cut”, while rotating, translating, accelerating, increasing its volume and/or “energy”? (without violating the laws of thermodynamics)

So you don’t know much about “the probability cloud called electron.

  • And all this thanks to (or consequently) “losing” a mathematical property.

Then imagine a:

  • New Voronois 3Ds+1Dt, physically correct.
  • New “vector” databases for iA’s
  • New transformers for iA’s
  • New algorithms for inference and calculations in GPUs
  • New ways of “seeing” physics
  • New 3D physics simulations (which are impossible today)

I don’t want to say that I will do all of this (I don’t know), but when a human discovers that there are more tools (besides the hammer), and above all… understands their use… Amazing things happen.

“In my time”, the cell phone was a fictional thing, only super agent 86 could have that technology, today they are looking at how to limit it to 2-year-olds.

3 Likes

Well, as I told you last time…

This Tuesday I started writing code, last night I did unit tests to what is Quaternions (0k) :clap: :clap: :clap:. (and continue a bit with the DualQuaternions or BiQuaternions)

  • I started the library in Netstandard 2.1, for greater compatibility, as I only use data types and basic mathematical operations Using System and System.Globalization.

  • Everything is in decimal type, but I also created the methods to be able to be cast to other types and from other types (including string).

I chose that type of data because it is the most accurate, since everything would depend on the use they want to give it.

  • I entered a series of constants (with decimal precision) such as Pi, Phi, e, etc. Well, there will be no shortage of geometer or architect who wants to explore its use.

  • Since the .NET Math library only works with double precision, create DMath that works with decimals, then functions like Cos are mapped to decimal, to don’t have problems with data incompatibility within the code.

  • I separated methods (Dot, Normalized, etc) and operators (+ - * /) from operations (Lerp, Slerp, NLerp), so that everything is more orderly, so that always know where to go.

I would like to know above all, what other functionalities would be “necessary”, because then I must integrate it with GH and I do not want to be modifying and compiling the library again.

  • Everything related to points, vectors, lists, planes, etc. I intend to be done and programmed in the specific interface in which it is used (Grasshopper, Unity, etc), that is why there are tools that allow the conversion of double, string, float, etc to decimal and vice versa.

This library is designed to be basic and fortuitous to be implemented in any other interface or program, since the idea is that it allows you to work on the logic, mathematics of this type of “Hyperdimensional” algebra :face_with_raised_eyebrow:

The rest will depend on the use you want to give it in a particular interface.

The plugin that I intend to develop for GH, you know what “orientation” it has :sweat_smile:, but I have no problem adding more functionality to it, because these interfaces can be applied to all sciences (Graphs, iA’s, Engineering, Aerospace, Analysis, etc).

Honestly, it would be beautiful to see my library present in amazing things.

Now... some Pictures
PC / Setup
  • Don’t ask me to make the code suitable for RTX or RX (Cuda, etc) because you will see that even if I want to, I will never be able to test if it works.
  • You don’t know anything about resource optimization and parametric 3D design, until you are in Argentina. :wink:

The Team!
  • The Chairman, SofaMan, BedMan, HungryMan, SleepMan.
  • The same as in any job (all bosses).

The Code

I appreciate any criticism or suggestion.