Ejemplo n.º 1
0
  /**
   * Sets the Quaternion as a rotation from the {@code from} direction to the {@code to} direction.
   *
   * <p><b>Attention:</b> this rotation is not uniquely defined. The selected axis is usually
   * orthogonal to {@code from} and {@code to}, minimizing the rotation angle. This method is robust
   * and can handle small or almost identical vectors.
   *
   * @see #fromAxisAngle(PVector, float)
   */
  public void fromTo(PVector from, PVector to) {
    float fromSqNorm = MathUtils.squaredNorm(from);
    float toSqNorm = MathUtils.squaredNorm(to);
    // Identity Quaternion when one vector is null
    if ((fromSqNorm < 1E-10f) || (toSqNorm < 1E-10f)) {
      this.x = this.y = this.z = 0.0f;
      this.w = 1.0f;
    } else {

      PVector axis = from.cross(to);

      float axisSqNorm = MathUtils.squaredNorm(axis);

      // Aligned vectors, pick any axis, not aligned with from or to
      if (axisSqNorm < 1E-10f) axis = MathUtils.orthogonalVector(from);

      float angle = PApplet.asin(PApplet.sqrt(axisSqNorm / (fromSqNorm * toSqNorm)));

      if (from.dot(to) < 0.0) angle = PI - angle;

      fromAxisAngle(axis, angle);
    }
  }