From eeff10ed00e43f067da4470a099c5f6a837fa431 Mon Sep 17 00:00:00 2001 From: Markus Winter Date: Tue, 26 Apr 2022 15:33:23 +0200 Subject: [PATCH] Sync quaternion module structure with complex module --- Package.swift | 2 +- Sources/QuaternionModule/Norms.swift | 112 --------- Sources/QuaternionModule/Polar.swift | 222 ++++++++++++++++++ .../Quaternion+AdditiveArithmetic.swift | 41 ++++ ....swift => Quaternion+AlgebraicField.swift} | 77 ++---- .../QuaternionModule/Quaternion+Codable.swift | 25 ++ ...t => Quaternion+ElementaryFunctions.swift} | 4 +- .../Quaternion+Hashable.swift | 72 ++++++ .../Quaternion+IntegerLiteral.swift | 19 ++ .../QuaternionModule/Quaternion+Numeric.swift | 70 ++++++ .../Quaternion+StringConvertible.swift | 28 +++ Sources/QuaternionModule/Quaternion.swift | 156 +----------- Sources/QuaternionModule/Scale.swift | 39 +++ Sources/QuaternionModule/Transformation.swift | 134 +---------- 14 files changed, 537 insertions(+), 464 deletions(-) delete mode 100644 Sources/QuaternionModule/Norms.swift create mode 100644 Sources/QuaternionModule/Polar.swift create mode 100644 Sources/QuaternionModule/Quaternion+AdditiveArithmetic.swift rename Sources/QuaternionModule/{Arithmetic.swift => Quaternion+AlgebraicField.swift} (65%) create mode 100644 Sources/QuaternionModule/Quaternion+Codable.swift rename Sources/QuaternionModule/{ElementaryFunctions.swift => Quaternion+ElementaryFunctions.swift} (98%) create mode 100644 Sources/QuaternionModule/Quaternion+Hashable.swift create mode 100644 Sources/QuaternionModule/Quaternion+IntegerLiteral.swift create mode 100644 Sources/QuaternionModule/Quaternion+Numeric.swift create mode 100644 Sources/QuaternionModule/Quaternion+StringConvertible.swift create mode 100644 Sources/QuaternionModule/Scale.swift diff --git a/Package.swift b/Package.swift index 876b5cf..8b38311 100644 --- a/Package.swift +++ b/Package.swift @@ -47,7 +47,7 @@ let package = Package( .target( name: "QuaternionModule", dependencies: ["RealModule"], - exclude: excludedFilenames + exclude: ["README.md", "Transformation.md"] ), .target( diff --git a/Sources/QuaternionModule/Norms.swift b/Sources/QuaternionModule/Norms.swift deleted file mode 100644 index 31a9693..0000000 --- a/Sources/QuaternionModule/Norms.swift +++ /dev/null @@ -1,112 +0,0 @@ -//===--- Norms.swift ------------------------------------------*- swift -*-===// -// -// This source file is part of the Swift Numerics open source project -// -// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -// Norms and related quantities defined for Quaternion. -// -// The following API are provided by this extension: -// -// var magnitude: RealType // infinity norm -// var length: RealType // Euclidean norm -// var lengthSquared: RealType // Euclidean norm squared -// -// For detailed documentation, consult Norms.md or the inline documentation -// for each operation. -// -// Implementation notes: -// -// `.magnitude` does not bind the Euclidean norm; it binds the infinity norm -// instead. There are two reasons for this choice: -// -// - It's simply faster to compute in general, because it does not require -// a square root. -// -// - There exist finite values `q` for which the Euclidean norm is not -// representable (consider the quaternion with `r`, `x`, `y` and `z` all -// equal to `RealType.greatestFiniteMagnitude`; the Euclidean norm is -// `.sqrt(4) * .greatestFiniteMagnitude`, which overflows). -// -// The infinity norm is unique among the common vector norms in having -// the property that every finite vector has a representable finite norm, -// which makes it the obvious choice to bind `.magnitude`. -extension Quaternion { - - /// The ∞-norm of the value (`max(abs(r), abs(x), abs(y), abs(z))`). - /// - /// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared` - /// properties instead. - /// - /// Edge cases: - /// - - /// - If `q` is not finite, `q.magnitude` is `.infinity`. - /// - If `q` is zero, `q.magnitude` is `0`. - /// - Otherwise, `q.magnitude` is finite and non-zero. - /// - /// See also: - /// - - /// - `.length` - /// - `.lengthSquared` - @_transparent - public var magnitude: RealType { - guard isFinite else { return .infinity } - return max(abs(components.max()), abs(components.min())) - } - - /// The Euclidean norm (a.k.a. 2-norm, `sqrt(r*r + x*x + y*y + z*z)`). - /// - /// This value is highly prone to overflow or underflow. - /// - /// For most use cases, you can use the cheaper `.magnitude` - /// property (which computes the ∞-norm) instead, which always produces - /// a representable result. - /// - /// Edge cases: - /// - - /// If a quaternion is not finite, its `.length` is `infinity`. - /// - /// See also: - /// - - /// - `.magnitude` - /// - `.lengthSquared` - @_transparent - public var length: RealType { - let naive = lengthSquared - guard naive.isNormal else { return carefulLength } - return .sqrt(naive) - } - - // Internal implementation detail of `length`, moving slow path off - // of the inline function. - @usableFromInline - internal var carefulLength: RealType { - guard isFinite else { return .infinity } - guard !magnitude.isZero else { return .zero } - // Unscale the quaternion, calculate its length and rescale the result - return divided(by: magnitude).length * magnitude - } - - /// The squared length `(r*r + x*x + y*y + z*z)`. - /// - /// This value is highly prone to overflow or underflow. - /// - /// For many cases, `.magnitude` can be used instead, which is similarly - /// cheap to compute and always returns a representable value. - /// - /// This property is more efficient to compute than `length`. - /// - /// See also: - /// - - /// - `.length` - /// - `.magnitude` - @_transparent - public var lengthSquared: RealType { - (components * components).sum() - } -} diff --git a/Sources/QuaternionModule/Polar.swift b/Sources/QuaternionModule/Polar.swift new file mode 100644 index 0000000..ae92add --- /dev/null +++ b/Sources/QuaternionModule/Polar.swift @@ -0,0 +1,222 @@ +//===--- Polar.swift ------------------------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// Norms and related quantities defined for Quaternion. +// +// The following API are provided by this extension: +// +// var magnitude: RealType // infinity norm +// var length: RealType // Euclidean norm +// var lengthSquared: RealType // Euclidean norm squared +// +// For detailed documentation, consult Norms.md or the inline documentation +// for each operation. +// +// Implementation notes: +// +// `.magnitude` does not bind the Euclidean norm; it binds the infinity norm +// instead. There are two reasons for this choice: +// +// - It's simply faster to compute in general, because it does not require +// a square root. +// +// - There exist finite values `q` for which the Euclidean norm is not +// representable (consider the quaternion with `r`, `x`, `y` and `z` all +// equal to `RealType.greatestFiniteMagnitude`; the Euclidean norm is +// `.sqrt(4) * .greatestFiniteMagnitude`, which overflows). +// +// The infinity norm is unique among the common vector norms in having +// the property that every finite vector has a representable finite norm, +// which makes it the obvious choice to bind `.magnitude`. +extension Quaternion { + /// The Euclidean norm (a.k.a. 2-norm, `sqrt(r*r + x*x + y*y + z*z)`). + /// + /// This value is highly prone to overflow or underflow. + /// + /// For most use cases, you can use the cheaper `.magnitude` + /// property (which computes the ∞-norm) instead, which always produces + /// a representable result. + /// + /// Edge cases: + /// - + /// If a quaternion is not finite, its `.length` is `infinity`. + /// + /// See also: + /// - + /// - `.magnitude` + /// - `.lengthSquared` + @_transparent + public var length: RealType { + let naive = lengthSquared + guard naive.isNormal else { return carefulLength } + return .sqrt(naive) + } + + // Internal implementation detail of `length`, moving slow path off + // of the inline function. + @usableFromInline + internal var carefulLength: RealType { + guard isFinite else { return .infinity } + guard !magnitude.isZero else { return .zero } + // Unscale the quaternion, calculate its length and rescale the result + return divided(by: magnitude).length * magnitude + } + + /// The squared length `(r*r + x*x + y*y + z*z)`. + /// + /// This value is highly prone to overflow or underflow. + /// + /// For many cases, `.magnitude` can be used instead, which is similarly + /// cheap to compute and always returns a representable value. + /// + /// This property is more efficient to compute than `length`. + /// + /// See also: + /// - + /// - `.length` + /// - `.magnitude` + @_transparent + public var lengthSquared: RealType { + (components * components).sum() + } + + /// The [polar decomposition][wiki]. + /// + /// Returns the length of this quaternion, phase in radians of range *[0, π]* + /// and the rotation axis as SIMD3 vector of unit length. + /// + /// Edge cases: + /// - + /// - If the quaternion is zero, length is `.zero` and angle and axis + /// are `nan`. + /// - If the quaternion is non-finite, length is `.infinity` and angle and + /// axis are `nan`. + /// - For any length other than `.zero` or `.infinity`, if angle is zero, axis + /// is `nan`. + /// + /// See also: + /// - + /// - `.angle` + /// - `.axis` + /// - `.angleAxis` + /// - `.rotationVector` + /// - `init(length:angle:axis:)` + /// - `init(length:phase:axis)` + /// - `init(rotation:)` + /// + /// [wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition + public var polar: (length: RealType, phase: RealType, axis: SIMD3) { + (length, halfAngle, axis) + } + + /// Creates a quaternion specified with [polar coordinates][wiki]. + /// + /// This initializer reads given `length`, `phase` and `axis` values and + /// creates a quaternion of equal rotation properties and specified *length* + /// using the following equation: + /// + /// Q = (cos(phase), axis * sin(phase)) * length + /// + /// - Note: `axis` must be of unit length, or an assertion failure occurs. + /// + /// Edge cases: + /// - + /// - Negative lengths are interpreted as reflecting the point through the origin, i.e.: + /// ``` + /// Quaternion(length: -r, phase: θ, axis: axis) == -Quaternion(length: r, phase: θ, axis: axis) + /// ``` + /// - For any `θ` and any `axis`, even `.infinity` or `.nan`: + /// ``` + /// Quaternion(length: .zero, phase: θ, axis: axis) == .zero + /// ``` + /// - For any `θ` and any `axis`, even `.infinity` or `.nan`: + /// ``` + /// Quaternion(length: .infinity, phase: θ, axis: axis) == .infinity + /// ``` + /// - Otherwise, `θ` must be finite, or a precondition failure occurs. + /// + /// See also: + /// - + /// - `.angle` + /// - `.axis` + /// - `.angleAxis` + /// - `.rotationVector` + /// - `.polar` + /// - `init(length:angle:axis:)` + /// - `init(rotation:)` + /// + /// [wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition + @inlinable + public init(length: RealType, phase: RealType, axis: SIMD3) { + guard !length.isZero, length.isFinite else { + self = Quaternion(length) + return + } + + // Length is finite and non-zero, therefore + // 1. `phase` must be finite or a precondition failure needs to occur; as + // this is not representable. + // 2. `axis` must be of unit length or an assertion failure occurs; while + // "wrong" by definition, it is representable. + precondition( + phase.isFinite, + "Either phase must be finite, or length must be zero or infinite." + ) + assert( + // TODO: Replace with `approximateEquality()` + abs(.sqrt(axis.lengthSquared)-1) < max(.sqrt(axis.lengthSquared), 1)*RealType.ulpOfOne.squareRoot(), + "Given axis must be of unit length." + ) + + self = Quaternion(halfAngle: phase, unitAxis: axis).multiplied(by: length) + } +} + +// MARK: - Operations for working with polar form + +extension Quaternion { + /// The half rotation angle in radians within *[0, π]* range. + /// + /// Edge cases: + /// - + /// If the quaternion is zero or non-finite, halfAngle is `nan`. + @usableFromInline @inline(__always) + internal var halfAngle: RealType { + guard isFinite else { return .nan } + guard imaginary != .zero else { + // A zero quaternion does not encode transformation properties. + // If imaginary is zero, real must be non-zero or nan is returned. + return real.isZero ? .nan : .zero + } + + // If lengthSquared computes without over/underflow, everything is fine + // and the result is correct. If not, we have to do the computation + // carefully and unscale the quaternion first. + let lenSq = imaginary.lengthSquared + guard lenSq.isNormal else { return divided(by: magnitude).halfAngle } + return .atan2(y: .sqrt(lenSq), x: real) + } + + /// Creates a new quaternion from given half rotation angle about given + /// rotation axis. + /// + /// The angle-axis values are transformed using the following equation: + /// + /// Q = (cos(halfAngle), unitAxis * sin(halfAngle)) + /// + /// - Parameters: + /// - halfAngle: The half rotation angle + /// - unitAxis: The rotation axis of unit length + @usableFromInline @inline(__always) + internal init(halfAngle: RealType, unitAxis: SIMD3) { + self.init(real: .cos(halfAngle), imaginary: unitAxis * .sin(halfAngle)) + } +} diff --git a/Sources/QuaternionModule/Quaternion+AdditiveArithmetic.swift b/Sources/QuaternionModule/Quaternion+AdditiveArithmetic.swift new file mode 100644 index 0000000..f8e45b2 --- /dev/null +++ b/Sources/QuaternionModule/Quaternion+AdditiveArithmetic.swift @@ -0,0 +1,41 @@ +//===--- Quaternion+AdditiveArithmetic.swift ------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Quaternion: AdditiveArithmetic { + /// The additive identity, with real and *all* imaginary parts zero, i.e.: + /// `0 + 0i + 0j + 0k` + /// + /// See also: `one`, `i`, `j`, `k`, `infinity` + @_transparent + public static var zero: Quaternion { + Quaternion(from: SIMD4(repeating: 0)) + } + + @_transparent + public static func + (lhs: Quaternion, rhs: Quaternion) -> Quaternion { + Quaternion(from: lhs.components + rhs.components) + } + + @_transparent + public static func - (lhs: Quaternion, rhs: Quaternion) -> Quaternion { + Quaternion(from: lhs.components - rhs.components) + } + + @_transparent + public static func += (lhs: inout Quaternion, rhs: Quaternion) { + lhs = lhs + rhs + } + + @_transparent + public static func -= (lhs: inout Quaternion, rhs: Quaternion) { + lhs = lhs - rhs + } +} diff --git a/Sources/QuaternionModule/Arithmetic.swift b/Sources/QuaternionModule/Quaternion+AlgebraicField.swift similarity index 65% rename from Sources/QuaternionModule/Arithmetic.swift rename to Sources/QuaternionModule/Quaternion+AlgebraicField.swift index 7dc6908..66c633b 100644 --- a/Sources/QuaternionModule/Arithmetic.swift +++ b/Sources/QuaternionModule/Quaternion+AlgebraicField.swift @@ -1,8 +1,8 @@ -//===--- Arithmetic.swift -------------------------------------*- swift -*-===// +//===--- Quaternion+AlgebraicField.swift ----------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -11,61 +11,22 @@ import RealModule -// MARK: - Conformance to Additive Arithmetic -extension Quaternion: AdditiveArithmetic { - @_transparent - public static func + (lhs: Quaternion, rhs: Quaternion) -> Quaternion { - Quaternion(from: lhs.components + rhs.components) - } - - @_transparent - public static func - (lhs: Quaternion, rhs: Quaternion) -> Quaternion { - Quaternion(from: lhs.components - rhs.components) - } - - @_transparent - public static func += (lhs: inout Quaternion, rhs: Quaternion) { - lhs = lhs + rhs - } - - @_transparent - public static func -= (lhs: inout Quaternion, rhs: Quaternion) { - lhs = lhs - rhs - } -} - -// MARK: - Vector space structure -// -// See: https://github.com/apple/swift-numerics/issues/12 -// While the issue addresses complex operations, this applies to quaternions as well. -extension Quaternion { - @usableFromInline @_transparent - internal func multiplied(by scalar: RealType) -> Quaternion { - Quaternion(from: components * scalar) - } - - @usableFromInline @_transparent - internal func divided(by scalar: RealType) -> Quaternion { - Quaternion(from: components / scalar) - } -} - -// MARK: - Multiplicative structure extension Quaternion: AlgebraicField { + /// The multiplicative identity, with real part one and *all* imaginary parts + /// zero, i.e.: `1 + 0i + 0j + 0k` + /// + /// See also: `zero`, `i`, `j`, `k`, `infinity` @_transparent - public static func * (lhs: Quaternion, rhs: Quaternion) -> Quaternion { + public static var one: Quaternion { + Quaternion(from: SIMD4(0,0,0,1)) + } - let rhsX = SIMD4(+rhs.components.w, +rhs.components.z, -rhs.components.y, +rhs.components.x) - let rhsY = SIMD4(-rhs.components.z, +rhs.components.w, +rhs.components.x, +rhs.components.y) - let rhsZ = SIMD4(+rhs.components.y, -rhs.components.x, +rhs.components.w, +rhs.components.z) - let rhsR = SIMD4(-rhs.components.x, -rhs.components.y, -rhs.components.z, +rhs.components.w) - - let x = (lhs.components * rhsX).sum() - let y = (lhs.components * rhsY).sum() - let z = (lhs.components * rhsZ).sum() - let r = (lhs.components * rhsR).sum() - - return Quaternion(from: SIMD4(x,y,z,r)) + /// The [conjugate][conj] of this value. + /// + /// [conj]: https://en.wikipedia.org/wiki/Quaternion#Conjugation,_the_norm,_and_reciprocal + @_transparent + public var conjugate: Quaternion { + Quaternion(from: components * [-1, -1, -1, 1]) } @_transparent @@ -78,11 +39,6 @@ extension Quaternion: AlgebraicField { return lhs * (rhs.conjugate.divided(by: lengthSquared)) } - @_transparent - public static func *= (lhs: inout Quaternion, rhs: Quaternion) { - lhs = lhs * rhs - } - @_transparent public static func /= (lhs: inout Quaternion, rhs: Quaternion) { lhs = lhs / rhs @@ -155,11 +111,10 @@ extension Quaternion: AlgebraicField { /// ``` @inlinable public var reciprocal: Quaternion? { - let recip = 1/self + let recip = Quaternion(1)/self if recip.isNormal || isZero || !isFinite { return recip } return nil } } - diff --git a/Sources/QuaternionModule/Quaternion+Codable.swift b/Sources/QuaternionModule/Quaternion+Codable.swift new file mode 100644 index 0000000..5c43de4 --- /dev/null +++ b/Sources/QuaternionModule/Quaternion+Codable.swift @@ -0,0 +1,25 @@ +//===--- Quaternion+Codable.swift -----------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import RealModule + +// FloatingPoint does not refine Codable, so this is a conditional conformance. +extension Quaternion: Decodable where RealType: Decodable { + public init(from decoder: Decoder) throws { + try self.init(from: SIMD4(from: decoder)) + } +} + +extension Quaternion: Encodable where RealType: Encodable { + public func encode(to encoder: Encoder) throws { + try components.encode(to: encoder) + } +} diff --git a/Sources/QuaternionModule/ElementaryFunctions.swift b/Sources/QuaternionModule/Quaternion+ElementaryFunctions.swift similarity index 98% rename from Sources/QuaternionModule/ElementaryFunctions.swift rename to Sources/QuaternionModule/Quaternion+ElementaryFunctions.swift index 9f3b56a..12d2ccd 100644 --- a/Sources/QuaternionModule/ElementaryFunctions.swift +++ b/Sources/QuaternionModule/Quaternion+ElementaryFunctions.swift @@ -1,8 +1,8 @@ -//===--- ElementaryFunctions.swift ----------------------------*- swift -*-===// +//===--- Quaternion+ElementaryFunctions.swift -----------------*- swift -*-===// // // This source file is part of the Swift.org open source project // -// Copyright (c) 2019-2021 Apple Inc. and the Swift project authors +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information diff --git a/Sources/QuaternionModule/Quaternion+Hashable.swift b/Sources/QuaternionModule/Quaternion+Hashable.swift new file mode 100644 index 0000000..7e7a227 --- /dev/null +++ b/Sources/QuaternionModule/Quaternion+Hashable.swift @@ -0,0 +1,72 @@ +//===--- Quaternion+Hashable.swift ----------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Quaternion: Hashable { + /// Returns a Boolean value indicating whether two values are equal. + /// + /// - Important: + /// Quaternions are frequently used to represent 3D transformations. It's + /// important to be aware that, when used this way, any quaternion and its + /// negation represent the same transformation, but they do not compare + /// equal using `==` because they are not the same quaternion. You can + /// compare quaternions as 3D transformations using `equals(as3DTransform:)`. + @_transparent + public static func == (lhs: Quaternion, rhs: Quaternion) -> Bool { + // Identify all numbers with either component non-finite as a single "point at infinity". + guard lhs.isFinite || rhs.isFinite else { return true } + // For finite numbers, equality is defined componentwise. Cases where + // only one of lhs or rhs is infinite fall through to here as well, but this + // expression correctly returns false for them so we don't need to handle + // them explicitly. + return lhs.components == rhs.components + } + + /// Returns a Boolean value indicating whether the 3D transformation of the + /// two quaternions are equal. + /// + /// Use this method to test for equality of the 3D transformation properties + /// of quaternions; where for any quaternion `q`, its negation represent the + /// same 3D transformation; i.e. `q.equals(as3DTransform: q)` as well as + /// `q.equals(as3DTransform: -q)` are both `true`. + /// + /// - Parameter other: The value to compare. + /// - Returns: True if the 3D transformation of this quaternion equals `other`. + @_transparent + public func equals(as3DTransform other: Quaternion) -> Bool { + // Identify all numbers with either component non-finite as a single "point at infinity". + guard isFinite || other.isFinite else { return true } + // For finite numbers, equality is defined componentwise. Cases where only + // one of lhs or rhs is infinite fall through to here as well, but this + // expression correctly returns false for them so we don't need to handle + // them explicitly. + return components == other.components || components == -other.components + } + + @_transparent + public func hash(into hasher: inout Hasher) { + // There are two equivalence classes to which we owe special attention: + // All zeros should hash to the same value, regardless of sign, and all + // non-finite numbers should hash to the same value, regardless of + // representation. The correct behavior for zero falls out for free from + // the hash behavior of floating-point, but we need to use a + // representative member for any non-finite values. + // For any normal values we use the "canonical transform" representation, + // where real is always non-negative. This allows people who are using + // quaternions as rotations to get the expected semantics out of collections + // (while unfortunately producing some collisions for people who are not, + // but not in too catastrophic of a fashion). + if isFinite { + canonicalizedTransform.components.hash(into: &hasher) + } else { + hasher.combine(RealType.infinity) + } + } +} diff --git a/Sources/QuaternionModule/Quaternion+IntegerLiteral.swift b/Sources/QuaternionModule/Quaternion+IntegerLiteral.swift new file mode 100644 index 0000000..cafc325 --- /dev/null +++ b/Sources/QuaternionModule/Quaternion+IntegerLiteral.swift @@ -0,0 +1,19 @@ +//===--- Quaternion+IntegerLiteral.swift ----------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Quaternion: ExpressibleByIntegerLiteral { + public typealias IntegerLiteralType = RealType.IntegerLiteralType + + @inlinable + public init(integerLiteral value: IntegerLiteralType) { + self.init(RealType(integerLiteral: value)) + } +} diff --git a/Sources/QuaternionModule/Quaternion+Numeric.swift b/Sources/QuaternionModule/Quaternion+Numeric.swift new file mode 100644 index 0000000..ae15608 --- /dev/null +++ b/Sources/QuaternionModule/Quaternion+Numeric.swift @@ -0,0 +1,70 @@ +//===--- Quaternion+Numeric.swift -----------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Quaternion: Numeric { + @_transparent + public static func * (lhs: Quaternion, rhs: Quaternion) -> Quaternion { + + let rhsX = SIMD4(+rhs.components.w, +rhs.components.z, -rhs.components.y, +rhs.components.x) + let rhsY = SIMD4(-rhs.components.z, +rhs.components.w, +rhs.components.x, +rhs.components.y) + let rhsZ = SIMD4(+rhs.components.y, -rhs.components.x, +rhs.components.w, +rhs.components.z) + let rhsR = SIMD4(-rhs.components.x, -rhs.components.y, -rhs.components.z, +rhs.components.w) + + let x = (lhs.components * rhsX).sum() + let y = (lhs.components * rhsY).sum() + let z = (lhs.components * rhsZ).sum() + let r = (lhs.components * rhsR).sum() + + return Quaternion(from: SIMD4(x,y,z,r)) + } + + @_transparent + public static func *= (lhs: inout Quaternion, rhs: Quaternion) { + lhs = lhs * rhs + } + + /// The quaternion with specified real part and zero imaginary part. + /// + /// Equivalent to `Quaternion(RealType(real))`. + @inlinable + public init(_ real: Other) { + self.init(RealType(real)) + } + + /// The quaternion with specified real part and zero imaginary part, + /// if it can be constructed without rounding. + @inlinable + public init?(exactly real: Other) { + guard let real = RealType(exactly: real) else { return nil } + self.init(real) + } + + /// The ∞-norm of the value (`max(abs(r), abs(x), abs(y), abs(z))`). + /// + /// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared` + /// properties instead. + /// + /// Edge cases: + /// - + /// - If `q` is not finite, `q.magnitude` is `.infinity`. + /// - If `q` is zero, `q.magnitude` is `0`. + /// - Otherwise, `q.magnitude` is finite and non-zero. + /// + /// See also: + /// - + /// - `.length` + /// - `.lengthSquared` + @_transparent + public var magnitude: RealType { + guard isFinite else { return .infinity } + return max(abs(components.max()), abs(components.min())) + } +} diff --git a/Sources/QuaternionModule/Quaternion+StringConvertible.swift b/Sources/QuaternionModule/Quaternion+StringConvertible.swift new file mode 100644 index 0000000..fbfa89f --- /dev/null +++ b/Sources/QuaternionModule/Quaternion+StringConvertible.swift @@ -0,0 +1,28 @@ +//===--- Quaternion+StringConvertible.swift -------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Quaternion: CustomStringConvertible { + public var description: String { + guard isFinite else { return "inf" } + return "(\(components.w), \(components.x), \(components.y), \(components.z))" + } +} + +extension Quaternion: CustomDebugStringConvertible { + public var debugDescription: String { + let x = String(reflecting: components.x) + let y = String(reflecting: components.y) + let z = String(reflecting: components.z) + let r = String(reflecting: components.w) + return "Quaternion<\(RealType.self)>(\(r), \(x), \(y), \(z))" + } +} + diff --git a/Sources/QuaternionModule/Quaternion.swift b/Sources/QuaternionModule/Quaternion.swift index 97a5d92..d7b3de9 100644 --- a/Sources/QuaternionModule/Quaternion.swift +++ b/Sources/QuaternionModule/Quaternion.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2019 - 2022 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -87,34 +87,6 @@ extension Quaternion { } } - /// The additive identity, with real and *all* imaginary parts zero. - /// - /// See also: - /// - - /// - .one - /// - .i - /// - .j - /// - .k - /// - .infinity - @_transparent - public static var zero: Quaternion { - Quaternion(from: SIMD4(repeating: 0)) - } - - /// The multiplicative identity, with real part one and *all* imaginary parts zero. - /// - /// See also: - /// - - /// - .zero - /// - .i - /// - .j - /// - .k - /// - .infinity - @_transparent - public static var one: Quaternion { - Quaternion(from: SIMD4(0,0,0,1)) - } - /// The quaternion with the imaginary unit **i** one, i.e. `0 + i + 0j + 0k`. /// /// See also: @@ -171,12 +143,6 @@ extension Quaternion { Quaternion(.infinity) } - /// The conjugate of this quaternion. - @_transparent - public var conjugate: Quaternion { - Quaternion(from: components * [-1, -1, -1, 1]) - } - /// True if this value is finite. /// /// A quaternion is finite if neither component is an infinity or nan. @@ -372,29 +338,6 @@ extension Quaternion { public init(real: RealType, imaginary x: RealType, _ y: RealType, _ z: RealType) { self.init(real: real, imaginary: SIMD3(x, y, z)) } - - /// The quaternion with specified real part and zero imaginary part. - /// - /// Equivalent to `Quaternion(RealType(real))`. - @inlinable - public init(_ real: Other) { - self.init(RealType(real)) - } - - /// The quaternion with specified real part and zero imaginary part, - /// if it can be constructed without rounding. - @inlinable - public init?(exactly real: Other) { - guard let real = RealType(exactly: real) else { return nil } - self.init(real) - } - - public typealias IntegerLiteralType = Int - - @inlinable - public init(integerLiteral value: Int) { - self.init(RealType(value)) - } } extension Quaternion where RealType: BinaryFloatingPoint { @@ -421,100 +364,3 @@ extension Quaternion where RealType: BinaryFloatingPoint { self.init(from: SIMD4(x, y, z, r)) } } - -// MARK: - Conformance to Hashable and Equatable -extension Quaternion: Hashable { - /// Returns a Boolean value indicating whether two values are equal. - /// - /// - Important: - /// Quaternions are frequently used to represent 3D transformations. It's - /// important to be aware that, when used this way, any quaternion and its - /// negation represent the same transformation, but they do not compare - /// equal using `==` because they are not the same quaternion. You can - /// compare quaternions as 3D transformations using `equals(as3DTransform:)`. - @_transparent - public static func == (lhs: Quaternion, rhs: Quaternion) -> Bool { - // Identify all numbers with either component non-finite as a single "point at infinity". - guard lhs.isFinite || rhs.isFinite else { return true } - // For finite numbers, equality is defined componentwise. Cases where - // only one of lhs or rhs is infinite fall through to here as well, but this - // expression correctly returns false for them so we don't need to handle - // them explicitly. - return lhs.components == rhs.components - } - - /// Returns a Boolean value indicating whether the 3D transformation of the - /// two quaternions are equal. - /// - /// Use this method to test for equality of the 3D transformation properties - /// of quaternions; where for any quaternion `q`, its negation represent the - /// same 3D transformation; i.e. `q.equals(as3DTransform: q)` as well as - /// `q.equals(as3DTransform: -q)` are both `true`. - /// - /// - Parameter other: The value to compare. - /// - Returns: True if the 3D transformation of this quaternion equals `other`. - @_transparent - public func equals(as3DTransform other: Quaternion) -> Bool { - // Identify all numbers with either component non-finite as a single "point at infinity". - guard isFinite || other.isFinite else { return true } - // For finite numbers, equality is defined componentwise. Cases where only - // one of lhs or rhs is infinite fall through to here as well, but this - // expression correctly returns false for them so we don't need to handle - // them explicitly. - return components == other.components || components == -other.components - } - - @_transparent - public func hash(into hasher: inout Hasher) { - // There are two equivalence classes to which we owe special attention: - // All zeros should hash to the same value, regardless of sign, and all - // non-finite numbers should hash to the same value, regardless of - // representation. The correct behavior for zero falls out for free from - // the hash behavior of floating-point, but we need to use a - // representative member for any non-finite values. - // For any normal values we use the "canonical transform" representation, - // where real is always non-negative. This allows people who are using - // quaternions as rotations to get the expected semantics out of collections - // (while unfortunately producing some collisions for people who are not, - // but not in too catastrophic of a fashion). - if isFinite { - canonicalizedTransform.components.hash(into: &hasher) - } else { - hasher.combine(RealType.infinity) - } - } -} - -// MARK: - Conformance to Codable -// FloatingPoint does not refine Codable, so this is a conditional conformance. -extension Quaternion: Decodable where RealType: Decodable { - public init(from decoder: Decoder) throws { - try self.init(from: SIMD4(from: decoder)) - } -} - -extension Quaternion: Encodable where RealType: Encodable { - public func encode(to encoder: Encoder) throws { - try components.encode(to: encoder) - } -} - -// MARK: - Formatting -extension Quaternion: CustomStringConvertible { - public var description: String { - guard isFinite else { - return "inf" - } - return "(\(components.w), \(components.x), \(components.y), \(components.z))" - } -} - -extension Quaternion: CustomDebugStringConvertible { - public var debugDescription: String { - let x = String(reflecting: components.x) - let y = String(reflecting: components.y) - let z = String(reflecting: components.z) - let r = String(reflecting: components.w) - return "Quaternion<\(RealType.self)>(\(r), \(x), \(y), \(z))" - } -} diff --git a/Sources/QuaternionModule/Scale.swift b/Sources/QuaternionModule/Scale.swift new file mode 100644 index 0000000..25c1534 --- /dev/null +++ b/Sources/QuaternionModule/Scale.swift @@ -0,0 +1,39 @@ +//===--- Scale.swift ------------------------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2019-2022 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// Policy: deliberately not using the * and / operators for these at the +// moment, because then there's an ambiguity in expressions like 2*p; is +// that Quaternion(2) * p or is it RealType(2) * p? This is especially +// problematic in type inference: suppose we have: +// +// let a: RealType = 1 +// let b = 2*a +// +// what is the type of b? If we don't have a type context, it's ambiguous. +// If we have a Quaternion type context, then b will be inferred to have type +// Quaternion! Obviously, that doesn't help anyone. +// +// TODO: figure out if there's some way to avoid these surprising results +// and turn these into operators if/when we have it. +// (https://github.com/apple/swift-numerics/issues/12) +extension Quaternion { + /// `self` scaled by `scalar`. + @usableFromInline @_transparent + internal func multiplied(by scalar: RealType) -> Quaternion { + Quaternion(from: components * scalar) + } + + /// `self` unscaled by `scalar`. + @usableFromInline @_transparent + internal func divided(by scalar: RealType) -> Quaternion { + Quaternion(from: components / scalar) + } +} diff --git a/Sources/QuaternionModule/Transformation.swift b/Sources/QuaternionModule/Transformation.swift index 4919143..72b7c50 100644 --- a/Sources/QuaternionModule/Transformation.swift +++ b/Sources/QuaternionModule/Transformation.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2020 - 2022 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -123,35 +123,6 @@ extension Quaternion { axis * angle } - /// The [polar decomposition][wiki]. - /// - /// Returns the length of this quaternion, phase in radians of range *[0, π]* - /// and the rotation axis as SIMD3 vector of unit length. - /// - /// Edge cases: - /// - - /// - If the quaternion is zero, length is `.zero` and angle and axis - /// are `nan`. - /// - If the quaternion is non-finite, length is `.infinity` and angle and - /// axis are `nan`. - /// - For any length other than `.zero` or `.infinity`, if angle is zero, axis - /// is `nan`. - /// - /// See also: - /// - - /// - `.angle` - /// - `.axis` - /// - `.angleAxis` - /// - `.rotationVector` - /// - `init(length:angle:axis:)` - /// - `init(length:phase:axis)` - /// - `init(rotation:)` - /// - /// [wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition - public var polar: (length: RealType, phase: RealType, axis: SIMD3) { - (length, halfAngle, axis) - } - /// Creates a unit quaternion specified with [Angle-Axis][wiki] values. /// /// Angle-Axis is a representation of a three-dimensional rotation using two @@ -278,68 +249,6 @@ extension Quaternion { } } - /// Creates a quaternion specified with [polar coordinates][wiki]. - /// - /// This initializer reads given `length`, `phase` and `axis` values and - /// creates a quaternion of equal rotation properties and specified *length* - /// using the following equation: - /// - /// Q = (cos(phase), axis * sin(phase)) * length - /// - /// - Note: `axis` must be of unit length, or an assertion failure occurs. - /// - /// Edge cases: - /// - - /// - Negative lengths are interpreted as reflecting the point through the origin, i.e.: - /// ``` - /// Quaternion(length: -r, phase: θ, axis: axis) == -Quaternion(length: r, phase: θ, axis: axis) - /// ``` - /// - For any `θ` and any `axis`, even `.infinity` or `.nan`: - /// ``` - /// Quaternion(length: .zero, phase: θ, axis: axis) == .zero - /// ``` - /// - For any `θ` and any `axis`, even `.infinity` or `.nan`: - /// ``` - /// Quaternion(length: .infinity, phase: θ, axis: axis) == .infinity - /// ``` - /// - Otherwise, `θ` must be finite, or a precondition failure occurs. - /// - /// See also: - /// - - /// - `.angle` - /// - `.axis` - /// - `.angleAxis` - /// - `.rotationVector` - /// - `.polar` - /// - `init(length:angle:axis:)` - /// - `init(rotation:)` - /// - /// [wiki]: https://en.wikipedia.org/wiki/Polar_decomposition#Quaternion_polar_decomposition - @inlinable - public init(length: RealType, phase: RealType, axis: SIMD3) { - guard !length.isZero, length.isFinite else { - self = Quaternion(length) - return - } - - // Length is finite and non-zero, therefore - // 1. `phase` must be finite or a precondition failure needs to occur; as - // this is not representable. - // 2. `axis` must be of unit length or an assertion failure occurs; while - // "wrong" by definition, it is representable. - precondition( - phase.isFinite, - "Either phase must be finite, or length must be zero or infinite." - ) - assert( - // TODO: Replace with `approximateEquality()` - abs(.sqrt(axis.lengthSquared)-1) < max(.sqrt(axis.lengthSquared), 1)*RealType.ulpOfOne.squareRoot(), - "Given axis must be of unit length." - ) - - self = Quaternion(halfAngle: phase, unitAxis: axis).multiplied(by: length) - } - /// Transforms a vector by this quaternion. /// /// Quaternions are frequently used to represent three-dimensional @@ -406,44 +315,3 @@ extension Quaternion { return act(on: vector/scale) * scale } } - -// MARK: - Operations for working with polar form - -extension Quaternion { - /// The half rotation angle in radians within *[0, π]* range. - /// - /// Edge cases: - /// - - /// If the quaternion is zero or non-finite, halfAngle is `nan`. - @usableFromInline @inline(__always) - internal var halfAngle: RealType { - guard isFinite else { return .nan } - guard imaginary != .zero else { - // A zero quaternion does not encode transformation properties. - // If imaginary is zero, real must be non-zero or nan is returned. - return real.isZero ? .nan : .zero - } - - // If lengthSquared computes without over/underflow, everything is fine - // and the result is correct. If not, we have to do the computation - // carefully and unscale the quaternion first. - let lenSq = imaginary.lengthSquared - guard lenSq.isNormal else { return divided(by: magnitude).halfAngle } - return .atan2(y: .sqrt(lenSq), x: real) - } - - /// Creates a new quaternion from given half rotation angle about given - /// rotation axis. - /// - /// The angle-axis values are transformed using the following equation: - /// - /// Q = (cos(halfAngle), unitAxis * sin(halfAngle)) - /// - /// - Parameters: - /// - halfAngle: The half rotation angle - /// - unitAxis: The rotation axis of unit length - @usableFromInline @inline(__always) - internal init(halfAngle: RealType, unitAxis: SIMD3) { - self.init(real: .cos(halfAngle), imaginary: unitAxis * .sin(halfAngle)) - } -}