using CommunityToolkit.HighPerformance; namespace Brutal.Numerics; /// /// Packing utilities for converting between vector types /// public static class QuaternionPack { /// /// Convert a span of vectors of one type to another using a per-element delegate converter function /// /// Source span of vectors /// Destination span of vectors /// Delegate for converting between source and destination elements /// Source element type /// Destination element type /// Source vector type /// Destination vector type /// /// Source and destination vector types have different element counts, or are different /// length spans /// public static void Pack( ReadOnlySpan source, Span destination, Func elementConverter ) where TSourceQuaternion : unmanaged, IQuaternion where TDestinationQuaternion : unmanaged, IQuaternion where TSourceType : unmanaged where TDestinationElement : unmanaged { if (destination.Length < source.Length) throw new ArgumentException("Destination span is not long enough to hold the converted vectors"); if (TSourceQuaternion.ComponentCount != TDestinationQuaternion.ComponentCount) throw new ArgumentException("Source and destination vector types have different element counts"); var src = source.Cast(); var dst = destination.Cast(); for (var i = 0; i < src.Length; i++) dst[i] = elementConverter(src[i]); } /// /// Convert a source vector (cast as a span of elements) to a destination vector (created from a span of elements) /// using a per-element delegate converter function /// This slightly quirky signature is a workaround to avoid generics hell where you have to explicitly write each type /// /// Source vector /// Destination vector, created from a span of elements /// Per-element conversion delegate /// Element type of input span /// Element type of output vector /// Type of input vector /// Type of output vector public static void Pack( in TSourceQuaternion source, out TDestinationQuaternion destination, Func elementConverter ) where TSourceType : unmanaged where TDestinationType : unmanaged where TSourceQuaternion : unmanaged, IQuaternion where TDestinationQuaternion : unmanaged, IQuaternion { if (TDestinationQuaternion.ComponentCount < TSourceQuaternion.ComponentCount) throw new ArgumentException("Destination vector type has fewer elements than source vector type"); var src = source.AsSpan(); Span dst = stackalloc TDestinationType[TDestinationQuaternion.ComponentCount]; for (var i = 0; i < src.Length; i++) dst[i] = elementConverter(src[i]); destination = TDestinationQuaternion.Create(dst); } }