BorrowedTorch.Math 0.3.0

Prefix Reserved
dotnet add package BorrowedTorch.Math --version 0.3.0
                    
NuGet\Install-Package BorrowedTorch.Math -Version 0.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BorrowedTorch.Math" Version="0.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BorrowedTorch.Math" Version="0.3.0" />
                    
Directory.Packages.props
<PackageReference Include="BorrowedTorch.Math" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BorrowedTorch.Math --version 0.3.0
                    
#r "nuget: BorrowedTorch.Math, 0.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BorrowedTorch.Math@0.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BorrowedTorch.Math&version=0.3.0
                    
Install as a Cake Addin
#tool nuget:?package=BorrowedTorch.Math&version=0.3.0
                    
Install as a Cake Tool

BorrowedTorchMath

A small, dependency-free set of math helpers for .NET 8 and later: tolerance-aware comparisons, clamping, wrapping, angle conversion, interpolation and remapping, frame-rate independent damping, safe normalization and nearest points on segments, and a guarded look-rotation builder on System.Numerics types.

Everything lives in one static class, BorrowedTorch.Mathematics.MathUtils.

Install

dotnet add package BorrowedTorch.Math

Targets net8.0, so it runs on .NET 8 and later. No package dependencies.

Comparison

Single-precision helpers use an absolute tolerance of 1e-6, double-precision helpers 1e-10. Every comparison method has a float and a double overload.

Method Notes
IsZero(a) Absolute value below the tolerance.
IsOne(a), IsMinusOne(a) Approximately 1 or -1.
AreEqual(a, b), AreNotEqual(a, b) Hybrid tolerance: absolute near zero, relative to the larger magnitude elsewhere, so large values a few ULPs apart still compare equal.
IsLessOrEqual(a, b), IsGreaterOrEqual(a, b) Ordered comparison with the same tolerance on the equality side.

NaN never compares equal to anything, itself included. Two same-signed infinities are equal.

Clamping

ClampToNonNegative(value) for int, float and double. NaN is propagated rather than clamped to zero.

Wrapping

Method Notes
Wrap(value, length) value wrapped into [0, length), so -1 wraps to length - 1. int, float and double.
Fract(value) Fractional part toward minus infinity, in [0, 1): 2.25 gives 0.25, -0.25 gives 0.75. float and double.

length must be positive (and finite, for the floating-point overloads). The results stay inside the half-open range even where the plain formulas leave it. Adding length back to a tiny negative remainder can round up to length itself, and so can value - Floor(value) to 1. In those cases the largest value below the bound is returned. Unlike (value % length + length) % length, the int overload cannot overflow, whatever length is. A NaN or infinite value gives NaN.

var index = MathUtils.Wrap(i - 1, count);           // previous item of a ring, -1 -> count - 1
var angle = MathUtils.Wrap(heading, MathF.Tau);     // into [0, 2π)
var phase = MathUtils.Fract(elapsedSeconds / period);

Conversions

ToDegrees(radians) and ToRadians(degrees) for float and double. The single-precision radians-to-degrees factor is the correctly rounded float nearest 180/π; 180.0f / MathF.PI evaluates one ULP low.

Interpolation and remapping

These helpers are single-precision only.

Method Notes
InverseLerp(min, max, current) Fraction of current between min and max. Unclamped; 0 for a degenerate range.
Remap(current, oldMin, oldMax, newMin, newMax) Maps a value between ranges. Unclamped; newMin for a degenerate source range.
SecondsToDampingCoefficient(convergenceFraction, durationSec) Turns "cover this fraction of the remaining distance in this many seconds" into a damping coefficient.
InverseExpLerpAmount(dampingCoefficient, elapsedSeconds) The lerp amount of an exponential approach after elapsedSeconds, i.e. 1 - exp(-k * dt).

The last two together give frame-rate independent smoothing:

// Reach 95% of the way to the target in 0.18 seconds, whatever the frame rate.
var damping = MathUtils.SecondsToDampingCoefficient(0.95f, 0.18f);

// Each frame:
var amount = MathUtils.InverseExpLerpAmount(damping, elapsedSeconds);
current = float.Lerp(current, target, amount);

convergenceFraction is clamped to [1e-4, 0.9999], since a fraction of exactly 1 would need an infinite coefficient, and durationSec to at least 1e-4, so a zero or negative duration behaves as a near-instant snap rather than producing an infinite or negative coefficient. NaN in either argument propagates.

Vectors

Method Notes
Cross(a, b) 2D cross product (perp-dot) of two Vector2s: positive when b turns counter-clockwise from a.
SafeNormalize(value, fallback = default) Unit Vector2 or Vector3 along value, or fallback when there is no direction to keep.
SafeNormalize(quaternion) Unit Quaternion, or Quaternion.Identity when there is none.
ClosestPointOnSegment(point, a, b, out t) Point of segment a..b nearest point, and how far along it lies (0 at a, 1 at b). Vector2, Vector3.
DistanceSquaredToSegment(point, a, b) Squared distance from point to segment a..b. Vector2, Vector3.

A direction, a quaternion or a segment shorter than 1e-6 counts as none, as a forward does in LookRotation: a value that short, or with a NaN or infinite component, gets the fallback, and a segment that short is the point a, with t 0. Components too large to square in single precision still normalize. NaN in a segment query propagates.

var direction = MathUtils.SafeNormalize(target - position, Vector3.UnitZ);
var distance = MathF.Sqrt(MathUtils.DistanceSquaredToSegment(pointer, start, end));

Orientation

LookRotation(forward, up) builds the unit System.Numerics.Quaternion whose local -Z axis points along forward, with its local +Y axis along the part of up perpendicular to forward. That is the right-handed, "-Z is forward" convention shared by System.Numerics and MonoGame. Neither input needs to be unit length, and even components too large to square in single precision are handled. LookRotation(forward) uses world +Y as the up reference.

It never returns NaN, whatever the input:

  • A forward shorter than 1e-6, or with a NaN or infinite component, returns Quaternion.Identity.
  • An up that is zero, NaN or infinite, or within about 0.8° of the forward axis, cannot define a frame, so world +Y is substituted. When forward itself is (nearly) vertical, world +Z is used looking up and world -Z looking down instead, which gives the default view pitched straight up or down.

The fallback cannot follow yaw, so a camera driven by LookRotation(forward) snaps when pitched within about 0.8° of straight up or down, by the angle between its heading and world -Z; clamp the pitch short of that.

using System.Numerics;
using BorrowedTorch.Mathematics;

var rotation = MathUtils.LookRotation(target - position, Vector3.UnitY);
var facing = Vector3.Transform(-Vector3.UnitZ, rotation); // ≈ Vector3.Normalize(target - position)

MonoGame

MonoGame's vectors and quaternions have the same components as System.Numerics'. From MonoGame 3.8.1 on they convert both ways: ToNumerics() going in, and implicitly coming back. Declare the result's type, since var would keep the System.Numerics one:

Microsoft.Xna.Framework.Vector3 axis = MathUtils.SafeNormalize(way.ToNumerics(), Vector3.UnitY.ToNumerics());

On MonoGame 3.8.0, copy the components: new System.Numerics.Vector3(v.X, v.Y, v.Z) going in, and new Quaternion(q.X, q.Y, q.Z, q.W) coming back.

Building and testing

dotnet test BorrowedTorchMath.sln

Changelog

  • 0.3.0 Targets net8.0 instead of net10.0, so .NET 8 projects can use it too. Added Wrap and Fract, and the vector helpers: Cross, SafeNormalize, ClosestPointOnSegment and DistanceSquaredToSegment.
  • 0.2.1 LookRotation no longer returns NaN for an infinite forward or one too large to square in single precision (beyond about 1.8e19), and honours a very large up instead of replacing it with world +Y. Looking (nearly) straight up now gives the default view pitched up, as looking down already did, rather than that view rolled by 180°.
  • 0.2.0 Added LookRotation.
  • 0.1.0 Renamed the Mathematics class to MathUtils.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on BorrowedTorch.Math:

Package Downloads
BorrowedTorch.Nature

Nature for MonoGame (compute fork), generated and drawn on the GPU: grass, a procedural sky seen through air worked out from wherever the viewer is, from the ground to orbit, with volumetric clouds, and the wind for anything to move in.

BorrowedTorch.FabricSimulator

GPU cloth solver for MonoGame: a compute shader integrates the particles, relaxes the constraints and computes the normals, and the positions never leave the GPU. Verlet integration with Jacobi relaxation, plastic bending so creases stay, long-range attachments, colliders with friction, self-collision through a spatial hash, cuts, rips and tearing under strain, and drag against wind you set every frame. Solver only - you fetch the particles in your own vertex shader and draw the sheet yourself. Requires Windows and the compute-capable MonoGame fork. The solver ships as HLSL and is compiled by your content pipeline.

BorrowedTorch.Camera

Camera functionality.

BorrowedTorch.TransformGizmo

A screen-sized move / rotate / scale gizmo for MonoGame: drawing, picking and dragging, with per-target flags for which modes are offered, whether move and rotate work in world or local space, and which axes rotate turns about.

BorrowedTorch.ShapingFunctions

A collection of 44 shaping (easing) functions for animation, interpolation and signal shaping.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.0 203 11/18/2026
0.2.2 637 10/13/2026