// ReSharper disable InconsistentNaming
namespace Brutal.Numerics;
/// Shape shared by every numerics value: a fixed-width run of identically-typed components.
/* Non-generic, so shape can be asked about without naming a component type. Says nothing about
* vectors or numbers - a matrix, a plane and a rect are component tuples too. */
public interface IComponentTuple
{
/// Gets the stride of one component in bytes.
static abstract int ComponentSize { get; }
/// Gets the number of components.
static abstract int ComponentCount { get; }
}
///
/// The component type.
public interface IComponentTuple : IComponentTuple
{
/// Gets or sets the element at the specified index.
/// The index of the element to get or set.
/// The element at .
///
/// was less than zero or greater than the number
/// of elements.
///
T this[int index] { get; set; }
/// A mutable view over the components.
///
/// Deliberately NOT a readonly member, because it hands out a writable view. The consequence is that
/// calling it on a readonly field or an parameter gets you a span over a
/// defensive COPY, so writes there are silently lost - reach for instead.
///
Span AsSpan();
/// A read-only view over the components, safe in the readonly contexts where would view a copy.
ReadOnlySpan AsReadOnlySpan();
///
/// Copies the vector to the given .The length of the destination span must be at least
/// as long as there are elements in the source vector.
///
/// The destination span which the values are copied into.
///
/// If number of elements in source vector is greater than those available in
/// destination span.
///
void CopyTo(Span destination);
///
/// Attempts to copy the vector to the given . The length of the destination span must
/// be at least as long as there are elements in the source vector.
///
/// The destination span which the values are copied into.
///
/// if the source vector was successfully copied to .
/// if is not large enough to hold the source vector.
///
bool TryCopyTo(Span destination);
}
///
/// The type that implements the interface.
/// The component type.
/* The rung where a component tuple knows its own type, so it can be constructed and compared.
* Everything above this point is layout and says nothing about being a vector. */
public interface IComponentTuple : IComponentTuple, IEquatable, IFormattable
where TSelf : IComponentTuple
{
/// Constructs a value from the leading components of a span.
/// A span of at least components.
static abstract TSelf Create(ReadOnlySpan span);
}
/* ---------------------------------------------------------------------------
* FUNCTION. Reductions collapse lanes, so they are not layout - which is why they moved off
* IComponentTuple. Split where PRESENCE differs rather than per verb: a quaternion has Dot,
* LengthSquared and Length, and deliberately has no Distance, because Euclidean distance is not the
* metric on rotations. Each carries its own result type, since a squared reduction and a square root
* cannot agree on one.
* --------------------------------------------------------------------------- */
/// The dot product.
/// The type that implements the interface.
/// What the reduction returns; wider than the component where the
/// component cannot carry the result.
/* No family in the name: quaternions have a dot product too, and are not vectors. LengthSquared
* lives here rather than beside Length because it is the SELF-dot - the same reduction, so it cannot
* have a different result type. */
public interface IDotProduct
where TSelf : IDotProduct
{
/// The dot product.
static abstract TResult Dot(TSelf a, TSelf b);
/// The squared magnitude, avoiding the square root.
TResult LengthSquared();
}
/// The magnitude: a square root, so its result type is its own.
public interface IMagnitude
where TSelf : IMagnitude
{
/// The magnitude.
TRoot Length();
}
/// Distance between two values, where a Euclidean metric is the right one.
public interface IDistance
where TSelf : IDistance
{
/// The distance between two values.
static abstract TRoot Distance(TSelf a, TSelf b);
/// The squared distance, avoiding the square root.
static abstract TSquared DistanceSquared(TSelf a, TSelf b);
}
/* INumber forces scalar <, <=, > and >= into existence; R^n has no total order, so ours throw.
* The componentwise forms here are the answers that exist - one bool per lane, reduced by the
* caller with Any/All, as every shader language spells it. Only one of the two occupies the
* public slot: the throwing pair is an EXPLICIT implementation of IComparisonOperators, reachable
* only from code that asked for a total order by naming it.
* INHERITING IComparisonOperators is load-bearing: without it, constraining on BOTH this
* interface and INumber makes every comparison CS9342-ambiguous (measured); with it, the
* redeclarations HIDE the scalar pair and the mask form wins. Pinned in ComparisonDispatchTests. */
/// Defines componentwise relational operators, each returning a per-component mask.
/// The type that implements the interface.
/// The boolean vector of matching arity.
public interface IComponentwiseComparison : IComparisonOperators
where TSelf : IComponentwiseComparison
{
/// Compares each pair of components for less-than.
static abstract TMask operator <(TSelf a, TSelf b);
/// Compares each pair of components for less-than-or-equal.
static abstract TMask operator <=(TSelf a, TSelf b);
/// Compares each pair of components for greater-than.
static abstract TMask operator >(TSelf a, TSelf b);
/// Compares each pair of components for greater-than-or-equal.
static abstract TMask operator >=(TSelf a, TSelf b);
}
/// Defines a generic vector type.
/// The type that implements the interface.
/// The component type.
/* Inherits IEqualityOperators so the ==/!= below are REDECLARATIONS that hide it - the same
* CS9342 cure as IComponentwiseComparison, needed the moment any second route brings
* IEqualityOperators into a constraint closure alongside this interface (the bundles do, through
* IComparisonOperators; INumberBase does for any caller naming both). */
public interface IVector : IComponentTuple, IEqualityOperators
where TSelf : IVector
{
/// Gets the zero vector.
static abstract TSelf Zero { get; }
/// Gets the one vector.
static abstract TSelf One { get; }
/// Returns a value that indicates whether each pair of elements in two specified vectors is equal.
/// The first vector to compare.
/// The second vector to compare.
///
/// if and are equal; otherwise,
/// .
///
public static abstract bool operator ==(TSelf left, TSelf right);
/// Returns a value that indicates whether two specified vectors are not equal.
/// The first vector to compare.
/// The second vector to compare.
///
/// if and are not equal; otherwise,
/// .
///
public static abstract bool operator !=(TSelf left, TSelf right);
}
/// Defines a integer vector type.
public interface INumericVector
where TSelf : INumericVector
{
/// Adds two vectors together.
/// The first vector to add.
/// The second vector to add.
/// The summed vector.
public static abstract TSelf operator +(TSelf left, TSelf right);
/// Subtracts the second vector from the first.
/// The first vector.
/// The second vector.
public static abstract TSelf operator -(TSelf left, TSelf right);
/// Returns a new vector whose values are the product of each pair of elements in two specified vectors.
/// The first vector.
/// The second vector.
/// The element-wise product vector.
public static abstract TSelf operator *(TSelf left, TSelf right);
/// Divides the first vector by the second.
/// The first vector.
/// The second vector.
public static abstract TSelf operator /(TSelf left, TSelf right);
/// Multiplies the specified vector by the specified scalar value.
/// The vector.
/// The scalar value.
/// The scaled vector.
public static abstract TSelf operator *(TSelf left, T right);
/// Divides the specified vector by a specified scalar value.
/// The vector.
/// The scalar value.
/// The result of the division.
public static abstract TSelf operator /(TSelf value1, T value2);
/// Multiplies the scalar value by the specified vector.
/// The vector.
/// The scalar value.
/// The scaled vector.
public static abstract TSelf operator *(T left, TSelf right);
/// Negates the specified vector.
/// The vector to negate.
/// The negated vector.
public static abstract TSelf operator -(TSelf value);
}
/// Defines a integer vector type.
public interface IBooleanVector : IVector
where TSelf : IBooleanVector
{
/// OR operation
public static abstract TSelf operator |(TSelf a, TSelf b);
/// AND operation
public static abstract TSelf operator &(TSelf a, TSelf b);
/// Whether any component is true.
bool Any { get; }
/// Whether every component is true.
bool All { get; }
}
/* TResult is what C# promotion gives the component: int for sbyte, byte, short and ushort, and the
* component itself for int, uint, long and ulong. The square roots are TRoot, since a sqrt has no
* integer answer: float for the 4-byte-and-under components, double for the 8-byte ones, whose
* magnitude float cannot hold.
* T is no longer contravariant, because the magnitude returns TRoot and the reductions return
* TResult; variance never applied to the struct implementers anyway. */
/// Defines a integer vector type.
/// The type that implements the interface.
/// The component type.
/// What a reduction returns: the C# promotion of .
/// What a square root returns: float, or double for the 8-byte components.
public interface IIntegerVector
: INumericVector,
IDotProduct,
IMagnitude,
IDistance
where TSelf : IIntegerVector
{
/* The half of IBinaryInteger that means something for a vector. The other ten members are the
* scalar wire-encoding suite and are undefined here - nothing says whether a big-endian int3
* byte-swaps each component, reverses component order, or both - so taking the whole interface
* would mean inventing a contract to satisfy something nothing constrains on. Every integer
* family has all five, so it is a family trait and belongs here rather than in a name of its
* own. */
///
static abstract TSelf PopCount(TSelf value);
///
static abstract TSelf LeadingZeroCount(TSelf value);
///
static abstract TSelf TrailingZeroCount(TSelf value);
///
static abstract TSelf RotateLeft(TSelf value, int rotateAmount);
///
static abstract TSelf RotateRight(TSelf value, int rotateAmount);
}
///
/* Inherits rather than paralleling it: a signed integer vector IS an integer vector, and the two
* were siblings only because neither declared anything to share. Now that the bit-counting members
* live on the base, the difference is exactly Abs. */
public interface ISignedIntegerVector : IIntegerVector
where TSelf : ISignedIntegerVector
{
/// Returns a vector whose elements are the absolute values of each of the specified vector's elements.
/// A vector.
/// The absolute value vector.
public static abstract TSelf Abs(TSelf value);
}
/// Defines a floating vector type.
/* Named for the FAMILY, not for a BCL rung: it carries the family's math, and the rung the concrete
* types reach (IFloatingPointIeee754) is declared on them, not here. "Floating" rather than
* "FloatingPoint" so the four family names share one shape - IIntegerVector, ISignedIntegerVector,
* IBooleanVector, IFloatingVector - and so the only one colliding with a real BCL interface name
* stops doing so. */
public interface IFloatingVector
: INumericVector,
IDotProduct,
IMagnitude,
IDistance
where TSelf : IFloatingVector
{
/// Reflects a vector about a surface normal.
/* Every floating vector has one at every arity, so it is a family trait. It was its own name
* only while arity 4 lacked it - Vector4 has no Reflect, which looked like a rule and was an
* omission. */
static abstract TSelf Reflect(TSelf vector, TSelf normal);
///
/// Thrown when the input vector is a zero vector.
static abstract TSelf Normalize(TSelf value);
///
/// Will return a zero vector if the input vector is a zero vector.
static abstract TSelf NormalizeOrZero(TSelf value);
/* The static algebra surface: exposes the statics that already exist on every floating-point
* vector type, so generic code can call them through the interface (satisfied implicitly).
* Dot, Distance and DistanceSquared are no longer here - they are inherited from the reduction
* interfaces above, which quaternions share and which carry their own result types. */
///
static abstract TSelf Add(TSelf left, TSelf right);
///
static abstract TSelf Subtract(TSelf left, TSelf right);
///
static abstract TSelf Multiply(TSelf left, TSelf right);
///
static abstract TSelf Multiply(TSelf left, T right);
///
static abstract TSelf Multiply(T left, TSelf right);
///
static abstract TSelf Divide(TSelf left, TSelf right);
///
static abstract TSelf Divide(TSelf left, T divisor);
///
static abstract TSelf Negate(TSelf value);
///
static abstract TSelf Abs(TSelf value);
///
static abstract TSelf SquareRoot(TSelf value);
///
static abstract TSelf Min(TSelf a, TSelf b);
///
static abstract TSelf Max(TSelf a, TSelf b);
///
static abstract TSelf Clamp(TSelf value, TSelf min, TSelf max);
///
static abstract TSelf Lerp(TSelf a, TSelf b, T t);
}
/* The arities are SIBLINGS, not a chain. They used to inherit - IVector4 : IVector3 : IVector2 -
* which meant a float4 satisfied `where TSelf : IVector2`, so arity stopped being a proof
* of anything and a two-component constraint silently accepted four. Each one now states its own
* full axis set instead of collecting them on the way down. */
/// Defines a vector2 type.
public interface IVector2 : IVector
where TSelf : IVector2
{
/* The components by name. They are FIELDS on the concrete types, and a field cannot
* implement a property, so each type carries an explicit forwarder - generated, one line
* each. Worth it because X/Y/Z is how the domain spells a component; the indexer stays for
* code that walks them. */
/// Gets or sets the x component.
T X { get; set; }
/// Gets or sets the y component.
T Y { get; set; }
/// Gets the unit x vector.
static abstract TSelf UnitX { get; }
/// Gets the unit y vector.
static abstract TSelf UnitY { get; }
}
/// Defines a vector3 type.
public interface IVector3 : IVector
where TSelf : IVector3
{
/// Gets or sets the x component.
T X { get; set; }
/// Gets or sets the y component.
T Y { get; set; }
/// Gets or sets the z component.
T Z { get; set; }
///
static abstract TSelf UnitX { get; }
///
static abstract TSelf UnitY { get; }
/// Gets the unit z vector.
static abstract TSelf UnitZ { get; }
}
/// Defines a vector4 type.
public interface IVector4 : IVector
where TSelf : IVector4
{
/// Gets or sets the x component.
T X { get; set; }
/// Gets or sets the y component.
T Y { get; set; }
/// Gets or sets the z component.
T Z { get; set; }
/// Gets or sets the w component.
T W { get; set; }
///
static abstract TSelf UnitX { get; }
///
static abstract TSelf UnitY { get; }
///
static abstract TSelf UnitZ { get; }
/// Gets the unit w vector.
static abstract TSelf UnitW { get; }
}
internal class VectorDebugView2(TSelf v)
where TSelf : IVector2, IMagnitude
{
public T X => v[0];
public T Y => v[1];
public TRoot Length => v.Length();
public override string? ToString()
{
return v.ToString();
}
}
internal class VectorDebugView3(TSelf v)
where TSelf : IVector3, IMagnitude
{
public T X => v[0];
public T Y => v[1];
public T Z => v[2];
public TRoot Length => v.Length();
public override string? ToString()
{
return v.ToString();
}
}
internal class VectorDebugView4(TSelf v)
where TSelf : IVector4, IMagnitude
{
public T X => v[0];
public T Y => v[1];
public T Z => v[2];
public T W => v[3];
public TRoot Length => v.Length();
public override string? ToString()
{
return v.ToString();
}
}
/// Defines the cross product.
public interface ICrossProduct
where TSelf : ICrossProduct
{
///
static abstract TSelf Cross(TSelf left, TSelf right);
}
/* ----------------------------------------------------------------------------
* Per-arity floating bundles. Each composes the two axes - the arity interface for layout, the
* family interface for math - and adds only what neither can carry: the transforms, which name a
* matrix or a quaternion the vector itself knows nothing about.
*
* WHY THE TRANSFORMS ARE DECLARED INLINE rather than composed from ITransform
* capability interfaces. CS0695: a generic type cannot inherit two instantiations of one generic
* interface if they MAY unify under substitution, and nothing proves TMatrix4x4 != TQuaternion.
* Probed 2026-08-24, all three cases:
*
* inherit ONE generic instantiation ITransform compiles
* inherit TWO generic instantiations ... TMatrix and ... TQuat CS0695
* inherit TWO CONCRETE instantiations ... float4x4 and ... floatQuat compiles
*
* So the escape hatch is real but useless here: a bundle hardcoding float4x4 cannot serve double3,
* and the differential suites are one generic body over float and double. Every vector needs at
* least two transforms (by matrix and by rotation), so no generic bundle can compose them.
*
* The alternative was measured rather than assumed: attaching the capabilities to the concrete
* types instead works and keeps this file free of members it does not own, but moves the cost to
* every consumer - the arity-4 differential constraint went from one name to ten. Overloads within
* one interface are fine, so the bundle pays once, here.
* ---------------------------------------------------------------------------- */
/// Everything a 2-component floating-point vector can do.
public interface IFloatingVector2
: IVector2,
IFloatingVector,
IComponentwiseComparison
where TSelf : IFloatingVector2
{
///
static abstract TSelf Transform(TSelf position, TMatrix3x2 matrix);
///
static abstract TSelf Transform(TSelf position, TMatrix4x4 matrix);
///
static abstract TSelf Transform(TSelf value, TQuaternion rotation);
///
static abstract TSelf TransformNormal(TSelf normal, TMatrix3x2 matrix);
///
static abstract TSelf TransformNormal(TSelf normal, TMatrix4x4 matrix);
}
/// Everything a 3-component floating-point vector can do.
/// is the result of the matrix3x2 projection.
public interface IFloatingVector3
: IVector3,
IFloatingVector,
ICrossProduct,
IComponentwiseComparison,
IMultiplyOperators
where TSelf : IFloatingVector3
{
/// Static-method twin of the vector * matrix3x2 operator (projects to 2 components).
static abstract TVector2 Multiply(TSelf vector, TMatrix3x2 matrix);
///
static abstract TSelf Transform(TSelf position, TMatrix4x4 matrix);
///
static abstract TSelf Transform(TSelf value, TQuaternion rotation);
///
static abstract TSelf TransformNormal(TSelf normal, TMatrix4x4 matrix);
}
/// Everything a 4-component floating-point vector can do.
/// / are the cross-dimension transform inputs.
public interface IFloatingVector4
: IVector4,
IFloatingVector,
IComponentwiseComparison,
IMultiplyOperators
where TSelf : IFloatingVector4
{
/// Static-method twin of the vector * matrix4x4 operator.
static abstract TSelf Multiply(TSelf vector, TMatrix4x4 matrix);
///
static abstract TSelf Transform(TSelf vector, TMatrix4x4 matrix);
///
static abstract TSelf Transform(TSelf value, TQuaternion rotation);
// cross-dimension: 2/3-component input transformed up to a 4-component result
///
static abstract TSelf Transform(TVector2 position, TMatrix4x4 matrix);
///
static abstract TSelf Transform(TVector2 value, TQuaternion rotation);
///
static abstract TSelf Transform(TVector3 position, TMatrix4x4 matrix);
///
static abstract TSelf Transform(TVector3 value, TQuaternion rotation);
}