< Summary

Line coverage
77%
Covered lines: 191
Uncovered lines: 57
Coverable lines: 248
Total lines: 1367
Line coverage: 77%
Branch coverage
75%
Covered branches: 117
Total branches: 155
Branch coverage: 75.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: .cctor()100%11100%
File 1: get_Zero()100%11100%
File 1: get_One()100%11100%
File 1: get_Two()100%210%
File 1: get_Half()100%210%
File 1: get_Pi()100%11100%
File 1: get_Pi2()100%11100%
File 1: get_PiHalf()100%11100%
File 1: get__0()100%11100%
File 1: get__1()100%11100%
File 1: get__2()100%11100%
File 1: get__3()100%11100%
File 1: get__4()100%11100%
File 1: get__5()100%11100%
File 1: get__10()100%11100%
File 1: get__100()100%11100%
File 1: get__1000()100%11100%
File 1: get__0_01()100%11100%
File 1: get__0_05()100%210%
File 1: get__0_10()100%11100%
File 1: get__0_25()100%11100%
File 1: get__0_50()100%11100%
File 1: get__0_75()100%11100%
File 1: get__1_50()100%11100%
File 1: .ctor(...)100%11100%
File 1: FromRaw(...)100%11100%
File 1: op_Implicit(...)100%11100%
File 1: op_Implicit(...)100%11100%
File 1: op_Explicit(...)100%44100%
File 1: op_Explicit(...)100%11100%
File 1: FromFloat_UNSAFE(...)100%210%
File 1: FromDouble_UNSAFE(...)100%210%
File 1: ToFloat_UNSAFE()100%210%
File 1: ToDouble_UNSAFE()100%210%
File 1: op_Explicit(...)100%210%
File 1: op_Explicit(...)100%210%
File 1: op_Addition(...)100%11100%
File 1: op_Subtraction(...)100%11100%
File 1: op_UnaryNegation(...)100%11100%
File 1: op_UnaryPlus(...)100%11100%
File 1: op_Multiply(...)100%11100%
File 1: MultiplyFast(...)100%11100%
File 1: MultiplyPrecise(...)62.5%9880%
File 1: op_Division(...)100%66100%
File 1: op_Multiply(...)100%11100%
File 1: op_Multiply(...)100%210%
File 1: op_Division(...)100%22100%
File 1: op_Addition(...)100%11100%
File 1: op_Addition(...)100%210%
File 1: op_Subtraction(...)100%11100%
File 1: op_Subtraction(...)100%210%
File 1: op_Multiply(...)100%210%
File 1: op_Multiply(...)100%210%
File 1: op_Division(...)0%620%
File 1: op_Equality(...)100%11100%
File 1: op_Inequality(...)100%11100%
File 1: op_LessThan(...)100%11100%
File 1: op_GreaterThan(...)100%11100%
File 1: op_LessThanOrEqual(...)100%11100%
File 1: op_GreaterThanOrEqual(...)100%11100%
File 1: CompareTo(...)100%11100%
File 1: Equals(...)100%11100%
File 1: Equals(...)0%620%
File 1: GetHashCode()100%11100%
File 2: Acos(...)75%88100%
File 2: Asin(...)100%210%
File 3: Abs(...)100%44100%
File 3: AbsBranchless(...)100%210%
File 3: Min(...)50%22100%
File 3: MinBranchless(...)100%210%
File 3: Max(...)50%22100%
File 3: MaxBranchless(...)100%210%
File 3: Clamp(...)100%44100%
File 3: ClampBranchless(...)100%210%
File 3: Lerp(...)100%11100%
File 3: Approximately(...)100%11100%
File 3: Approximately(...)100%22100%
File 4: FromString(...)100%2626100%
File 4: FromString_UNSAFE(...)100%210%
File 4: ToString()100%11100%
File 4: ToString(...)100%1212100%
File 4: ToStringInternal(...)91.66%121293.33%
File 4: Pow10(...)27.27%341142.85%
File 5: .cctor()100%11100%
File 5: SinFast(...)83.33%66100%
File 5: CosFast(...)100%210%
File 5: Sin(...)100%11100%
File 5: Cos(...)100%11100%
File 5: SinAccurate(...)0%4260%
File 5: CosAccurate(...)100%210%
File 5: Tan(...)50%6683.33%
File 5: TanAccurate(...)0%4260%
File 5: Atan2(...)100%1818100%
File 5: AtanSmall(...)100%11100%
File 5: AtanTableLookup(...)66.66%66100%
File 5: Deg2Rad(...)100%11100%
File 5: Rad2Deg(...)100%11100%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Math/FP.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4#nullable enable
 5
 6using System;
 7using System.Diagnostics;
 8using System.Runtime.CompilerServices;
 9using System.Runtime.InteropServices;
 10
 11namespace Lattice.Math;
 12
 13/// <summary>
 14/// 定点数 (Q48.16):48位整数 + 16位小数
 15/// </summary>
 16/// <remarks>
 17/// <para>Lattice 定点数系统使用 64 位有符号整数存储,其中:</para>
 18/// <list type="bullet">
 19///   <item>48 位:整数部分(范围约 ±140万亿)</item>
 20///   <item>16 位:小数部分(精度约 0.000015)</item>
 21/// </list>
 22/// <para>安全乘法范围:±32,768(两个操作数都需在此范围内)</para>
 23/// <para>参考:FrameSyncEngine / Photon Quantum 设计</para>
 24/// <para>用途:确定性帧同步,完全替代 float/double</para>
 25/// </remarks>
 26/// <example>
 27/// 基本使用:
 28/// <code>
 29/// // 初始化 LUT(游戏启动时)
 30/// FPLut.InitializeBuiltIn();
 31///
 32/// // 创建定点数
 33/// FP a = 3.5;                    // 隐式转换
 34/// FP b = FP.FromRaw(FP.Raw._1_50);  // 使用原始常量
 35///
 36/// // 数学运算
 37/// FP c = a * b;                // 乘法(四舍五入)
 38/// FP d = FP.Sqrt(c);           // 平方根
 39/// FP e = FP.Sin(a);            // 正弦
 40/// </code>
 41/// </example>
 42[StructLayout(LayoutKind.Explicit, Size = 8)]  // 8 bytes, Explicit for cross-platform consistency
 43public readonly partial struct FP : IEquatable<FP>, IComparable<FP>
 44{
 45    #region 常量定义
 46
 47    /// <summary>小数位数量</summary>
 48    public const int FRACTIONAL_BITS = 16;
 49
 50    /// <summary>比例因子 = 2^16 = 65536</summary>
 51    public const long ONE = 1L << FRACTIONAL_BITS;
 52
 53    /// <summary>乘法舍入常量:0.5 LSB = 2^15</summary>
 54    /// <remarks>
 55    /// 用于乘法四舍五入:(a * b + MulRound) >> 16
 56    /// 相比截断,精度误差减半
 57    /// </remarks>
 58    internal const long MulRound = 1L << (FRACTIONAL_BITS - 1);  // 32768
 59
 60    /// <summary>
 61    /// 安全乘法上限:sqrt(long.MaxValue) ≈ 3,037,000,499
 62    /// 对应真实值约 46,340
 63    /// <para>两个 FP 都 ≤ UseableMax 时,乘法不会溢出 long</para>
 64    /// </summary>
 165    public static readonly FP UseableMax = new(3037000499L);
 66
 67    /// <summary>安全乘法下限(对应真实值约 -46,340)</summary>
 168    public static readonly FP UseableMin = new(-3037000499L);
 69
 70    /// <summary>
 71    /// 最小精度:1/65536 ≈ 0.000015
 72    /// <para>注意:这是 Q48.16 能表示的最小单位,不是 float.Epsilon 的概念</para>
 73    /// </summary>
 174    public static readonly FP Epsilon = new(1L);
 75
 76    /// <summary>
 77    /// 默认近似比较容差(10倍精度,约 0.00015)
 78    /// <para>用于 Approximately 的默认参数</para>
 79    /// </summary>
 180    public static readonly FP EpsilonDefault = new(10L);
 81
 82    /// <summary>零</summary>
 188983    public static FP Zero => new(0);
 84
 85    /// <summary>一</summary>
 12486    public static FP One => new(ONE);
 87
 88    /// <summary>二</summary>
 089    public static FP Two => new(ONE * 2);
 90
 91    /// <summary>一半 (0.5)</summary>
 092    public static FP Half => new(ONE >> 1);
 93
 94    /// <summary>π (3.14159...)</summary>
 1895    public static FP Pi => new(205887L);       // 3.1415863037109375
 96
 97    /// <summary>2π</summary>
 898    public static FP Pi2 => new(411774L);      // 6.283172607421875
 99
 100    /// <summary>π/2</summary>
 1014101    public static FP PiHalf => new(102943L);   // 1.57079315185546875
 102
 103    // 快捷常量命名(参考 Quantum 风格)
 2439104    public static FP _0 => new(0);
 343105    public static FP _1 => new(ONE);
 24470106    public static FP _2 => new(ONE * 2);
 25107    public static FP _3 => new(ONE * 3);
 6108    public static FP _4 => new(ONE * 4);
 16109    public static FP _5 => new(ONE * 5);
 16110    public static FP _10 => new(ONE * 10);
 24204111    public static FP _100 => new(ONE * 100);
 3449112    public static FP _1000 => new(ONE * 1000);
 113
 9114    public static FP _0_01 => new(655);        // 0.01 (655.36 截断)
 0115    public static FP _0_05 => new(3277);       // 0.05 (3276.8 四舍五入)
 24211116    public static FP _0_10 => new(6554);       // 0.1
 3117    public static FP _0_25 => new(16384);      // 0.25 (精确)
 139118    public static FP _0_50 => new(ONE >> 1);   // 0.5
 1119    public static FP _0_75 => new((ONE >> 1) + (ONE >> 2)); // 0.75
 24202120    public static FP _1_50 => new(ONE + (ONE >> 1));        // 1.5
 121
 122    /// <summary>
 123    /// Raw 常量:用于编译期确定的场景
 124    /// <para>命名规范:_整数 或 _整数_小数</para>
 125    /// </summary>
 126    public static class Raw
 127    {
 128        // ==================== 整数常量 ====================
 129        public const long _0 = 0;
 130        public const long _1 = ONE;
 131        public const long _2 = ONE * 2;
 132        public const long _3 = ONE * 3;
 133        public const long _4 = ONE * 4;
 134        public const long _5 = ONE * 5;
 135        public const long _6 = ONE * 6;
 136        public const long _7 = ONE * 7;
 137        public const long _8 = ONE * 8;
 138        public const long _9 = ONE * 9;
 139        public const long _10 = ONE * 10;
 140        public const long _99 = 6488064L;      // 99
 141        public const long _100 = ONE * 100;
 142        public const long _180 = 11796480L;    // 180
 143        public const long _200 = 13107200L;    // 200
 144        public const long _360 = 23592960L;    // 360
 145        public const long _1000 = ONE * 1000;
 146        public const long _10000 = 655360000L; // 10000
 147
 148        // ==================== 小数常量 (0.01 ~ 0.99) ====================
 149        public const long _0_01 = 655L;        // 0.01
 150        public const long _0_016 = 1049L;      // 0.016 ≈ 1/60s (60fps)
 151        public const long _0_02 = 1311L;       // 0.02
 152        public const long _0_03 = 1966L;       // 0.03
 153        public const long _0_04 = 2621L;       // 0.04
 154        public const long _0_05 = 3277L;       // 0.05
 155        public const long _0_10 = 6554L;       // 0.1
 156        public const long _0_20 = 13107L;      // 0.2
 157        public const long _0_25 = 16384L;      // 0.25 (精确)
 158        public const long _0_33 = 21845L;      // 0.33 (1/3 近似)
 159        public const long _0_50 = ONE >> 1;    // 0.5
 160        public const long _0_66 = 43691L;      // 0.66 (2/3 近似)
 161        public const long _0_75 = (ONE >> 1) + (ONE >> 2); // 0.75
 162        public const long _0_99 = 64881L;      // 0.99
 163
 164        // ==================== 大于1的常量 ====================
 165        public const long _1_01 = 66191L;      // 1.01
 166        public const long _1_02 = 66847L;      // 1.02
 167        public const long _1_03 = 67502L;      // 1.03
 168        public const long _1_04 = 68157L;      // 1.04
 169        public const long _1_05 = 68813L;      // 1.05
 170        public const long _1_10 = 72090L;      // 1.10
 171        public const long _1_20 = 78643L;      // 1.20
 172        public const long _1_25 = 81920L;      // 1.25
 173        public const long _1_33 = 87381L;      // 1.33 (4/3 近似)
 174        public const long _1_50 = ONE + (ONE >> 1); // 1.5
 175        public const long _1_75 = 114688L;     // 1.75
 176        public const long _1_99 = 130417L;     // 1.99
 177
 178        // ==================== 角度弧度常量 ====================
 179        public const long _PI = 205887;        // π ≈ 3.14159
 180        public const long _2Pi = 411774;       // 2π
 181        public const long _PiHalf = 102943;    // π/2
 182        public const long _PiInv = 20861L;     // 1/π
 183        public const long _PiOver2Inv = 41722L;// 2/π
 184        public const long Rad_360 = 411775L;   // 2π (360度)
 185        public const long Rad_180 = 205887L;   // π (180度)
 186        public const long Rad_90 = 102944L;    // π/2 (90度)
 187        public const long Rad_45 = 51472L;     // π/4 (45度)
 188        public const long Rad_30 = 34315L;     // π/6 (30度)
 189        public const long Rad_22_50 = 25736L;  // π/8 (22.5度)
 190
 191        // ==================== 角度转换常量 ====================
 192        public const long _Deg2Rad = 1144;      // π/180 ≈ 0.0174533
 193        public const long _Rad2Deg = 3754936;   // 180/π ≈ 57.2958
 194
 195        // ==================== 极小量常量 (EN = Epsilon N) ====================
 196        public const long EN1 = 6554L;         // 0.1
 197        public const long EN2 = 655L;          // 0.01
 198        public const long EN3 = 66L;           // 0.001 (Epsilon)
 199        public const long EN4 = 7L;            // 0.0001
 200        public const long EN5 = 1L;            // 0.000015 (最小精度)
 201
 202        // ==================== 数学常量 ====================
 203        public const long _E = 178145L;        // e ≈ 2.71828
 204        public const long Log2_E = 94548L;     // log2(e)
 205        public const long Log2_10 = 217706L;   // log2(10)
 206
 207        // ==================== 极值常量 ====================
 208        public const long _MaxValue = 3037000499L;  // UseableMax
 209        public const long _MinValue = -3037000499L; // UseableMin
 210        public const long _Epsilon = 1;             // 最小精度
 211        public const long Minus_1 = -65536L;        // -1
 212    }
 213
 214    #endregion
 215
 216    #region 存储与构造
 217
 218    /// <summary>内部原始值 (Q48.16 格式)</summary>
 219    [FieldOffset(0)]
 220    public readonly long RawValue;
 221
 222    /// <summary>
 223    /// 内部构造函数,允许同程序集内的类型创建实例
 224    /// </summary>
 225    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 443831226    internal FP(long raw) => RawValue = raw;
 227
 228    /// <summary>
 229    /// 从原始值构造 FP(安全的公开 API)
 230    /// </summary>
 231    /// <example>
 232    /// FP angle = FP.FromRaw(FP.Raw._PI);
 233    /// </example>
 234    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 72127235    public static FP FromRaw(long raw) => new(raw);
 236
 237    #endregion
 238
 239    #region 类型转换
 240
 241    // ==================== 整数(隐式,确定性安全) ====================
 242
 243    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 6599244    public static implicit operator FP(int value) => new((long)value << FRACTIONAL_BITS);
 245
 246    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1363247    public static implicit operator FP(long value) => new(value << FRACTIONAL_BITS);
 248
 249    /// <summary>
 250    /// 转换为 int(截断小数部分)
 251    /// <para>如果值超出 int 范围(±2,147,483,647),将抛出 OverflowException</para>
 252    /// </summary>
 253    /// <exception cref="OverflowException">当值超出 int 范围时抛出</exception>
 254    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 255    public static explicit operator int(FP value)
 256    {
 153257        long intPart = value.RawValue >> FRACTIONAL_BITS;
 153258        if (intPart > int.MaxValue || intPart < int.MinValue)
 4259            throw new OverflowException($"FP value {intPart} cannot be converted to int (range: {int.MinValue} to {int.M
 149260        return (int)intPart;
 261    }
 262
 263    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 675264    public static explicit operator long(FP value) => value.RawValue >> FRACTIONAL_BITS;
 265
 266    // ==================== 浮点数(显式 UNSAFE,禁止隐式) ====================
 267
 268#if DEBUG
 269    [Obsolete("警告:FromFloat_UNSAFE 只能在编辑器/配置阶段使用!" +
 270              "模拟/运行时使用会导致非确定性。请使用预计算的 Raw 值,如 FP.FromRaw(FP.Raw._1_50)", true)]
 271#endif
 272    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0273    public static FP FromFloat_UNSAFE(float f) => new((long)(f * ONE));
 274
 275#if DEBUG
 276    [Obsolete("警告:FromDouble_UNSAFE 只能在编辑器/配置阶段使用!" +
 277              "模拟/运行时使用会导致非确定性。", true)]
 278#endif
 279    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0280    public static FP FromDouble_UNSAFE(double d) => new((long)(d * ONE));
 281
 282#if DEBUG
 283    [Obsolete("警告:ToFloat_UNSAFE 只能在调试/渲染中使用!" +
 284              "模拟/运行时使用会导致非确定性。", true)]
 285#endif
 286    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0287    public float ToFloat_UNSAFE() => RawValue / (float)ONE;
 288
 289#if DEBUG
 290    [Obsolete("警告:ToDouble_UNSAFE 只能在调试/渲染中使用!", true)]
 291#endif
 292    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0293    public double ToDouble_UNSAFE() => RawValue / (double)ONE;
 294
 295    // 显式运算符(会抛出异常,作为最后一道防线)
 296    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 297    public static explicit operator FP(float value)
 298    {
 0299        throw new InvalidOperationException(
 0300            "禁止隐式从 float 转换为 FP!请使用 FP.FromRaw(FP.Raw.xxx) 或 FP.FromFloat_UNSAFE()(仅在编辑器使用)");
 301    }
 302
 303    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 304    public static explicit operator FP(double value)
 305    {
 0306        throw new InvalidOperationException(
 0307            "禁止隐式从 double 转换为 FP!请使用 FP.FromRaw(FP.Raw.xxx) 或 FP.FromDouble_UNSAFE()(仅在编辑器使用)");
 308    }
 309
 310    #endregion
 311
 312    #region 算术运算
 313
 314    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 56236315    public static FP operator +(FP a, FP b) => new(a.RawValue + b.RawValue);
 316
 317    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 47085318    public static FP operator -(FP a, FP b) => new(a.RawValue - b.RawValue);
 319
 320    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2835321    public static FP operator -(FP a) => new(-a.RawValue);
 322
 323    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 5324    public static FP operator +(FP a) => a;  // 一元正号
 325
 326    /// <summary>
 327    /// 定点数乘法 (a * b / 65536)
 328    /// 使用四舍五入,精度更高
 329    /// </summary>
 330    /// <remarks>
 331    /// 相比截断版本,精度误差减半(约 0.5 LSB)
 332    /// 性能损失:1 次加法(可忽略)
 333    /// </remarks>
 334    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 335    public static FP operator *(FP a, FP b)
 336    {
 77878337        long product = a.RawValue * b.RawValue;
 338
 339#if DEBUG
 340        // 检查舍入溢出(当 product 接近 long.MaxValue/MinValue 时)
 341        // 这种情况在正常使用中极不可能发生(需要数值 > 2^63 / 2^16 ≈ 140万亿)
 342        if (product > long.MaxValue - MulRound || product < long.MinValue + MulRound)
 343        {
 344            Debug.Fail($"FP multiplication overflow: {a.RawValue} * {b.RawValue}. Use MultiplyPrecise for overflow check
 345        }
 346#endif
 347        // 四舍五入:加上 0.5 LSB 后截断
 77878348        return new((product + MulRound) >> FRACTIONAL_BITS);
 349    }
 350
 351    /// <summary>
 352    /// 快速乘法(截断,无舍入开销)
 353    /// </summary>
 354    /// <remarks>
 355    /// 在性能极度敏感且精度要求不高的场景使用
 356    /// 误差:最大 1 LSB(约 0.000015)
 357    /// </remarks>
 358    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 359    public static FP MultiplyFast(FP a, FP b)
 360    {
 20361        return new((a.RawValue * b.RawValue) >> FRACTIONAL_BITS);
 362    }
 363
 364    /// <summary>
 365    /// 高精度乘法(带溢出检测)
 366    /// </summary>
 367    /// <exception cref="OverflowException">乘法溢出时抛出</exception>
 368    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 369    public static FP MultiplyPrecise(FP a, FP b)
 370    {
 6371        long product = a.RawValue * b.RawValue;
 6372        long rounded = product + MulRound;
 373
 374        // 检测舍入溢出
 6375        if ((product > 0 && rounded < product) || (product < 0 && rounded > product))
 0376            throw new OverflowException($"FP multiplication overflow: {a} * {b}");
 377
 6378        return new(rounded >> FRACTIONAL_BITS);
 379    }
 380
 381    /// <summary>
 382    /// 定点数除法 (a * 65536 / b)
 383    /// <para>注意:除零会抛出 <see cref="DivideByZeroException"/></para>
 384    /// </summary>
 385    /// <exception cref="DivideByZeroException">当 b 为零时抛出</exception>
 386    /// <exception cref="OverflowException">当左移操作溢出时抛出</exception>
 387    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 388    public static FP operator /(FP a, FP b)
 389    {
 46860390        if (b.RawValue == 0)
 4391            throw new DivideByZeroException("FP division by zero");
 392
 393        // 检查左移是否会导致溢出:|a| > long.MaxValue >> 16 ≈ 140万亿
 394        // 对于正常游戏数值(通常 < 100万),永远不会触发
 395        const long MAX_SAFE_DIVIDEND = long.MaxValue >> FRACTIONAL_BITS; // ≈ 140,737,488,355,327
 46856396        if (a.RawValue > MAX_SAFE_DIVIDEND || a.RawValue < -MAX_SAFE_DIVIDEND)
 1397            throw new OverflowException($"FP division overflow: dividend {a.RawValue} is too large for division");
 398
 46855399        long result = (a.RawValue << FRACTIONAL_BITS) / b.RawValue;
 46855400        return new(result);
 401    }
 402
 403    // ==================== 与整数的混合运算(优化) ====================
 404
 405    // int 运算符
 406    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 107407    public static FP operator *(FP a, int b) => new(a.RawValue * b);
 408
 409    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0410    public static FP operator *(int a, FP b) => new(b.RawValue * a);
 411
 412    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 413    public static FP operator /(FP a, int b)
 414    {
 64415        if (b == 0)
 3416            throw new DivideByZeroException("FP division by int zero");
 61417        return new(a.RawValue / b);
 418    }
 419
 420    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 5421    public static FP operator +(FP a, int b) => new(a.RawValue + ((long)b << FRACTIONAL_BITS));
 422
 423    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0424    public static FP operator +(int a, FP b) => b + a;
 425
 426    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 11427    public static FP operator -(FP a, int b) => new(a.RawValue - ((long)b << FRACTIONAL_BITS));
 428
 429    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0430    public static FP operator -(int a, FP b) => new(((long)a << FRACTIONAL_BITS) - b.RawValue);
 431
 432    // long 运算符(P1 优化:避免 int 溢出)
 433    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0434    public static FP operator *(FP a, long b) => new(a.RawValue * b);
 435
 436    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0437    public static FP operator *(long a, FP b) => new(b.RawValue * a);
 438
 439    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 440    public static FP operator /(FP a, long b)
 441    {
 0442        if (b == 0)
 0443            throw new DivideByZeroException("FP division by long zero");
 0444        return new(a.RawValue / b);
 445    }
 446
 447    #endregion
 448
 449    #region 比较运算
 450
 451    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 3452    public static bool operator ==(FP a, FP b) => a.RawValue == b.RawValue;
 453
 454    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1107455    public static bool operator !=(FP a, FP b) => a.RawValue != b.RawValue;
 456
 457    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2040458    public static bool operator <(FP a, FP b) => a.RawValue < b.RawValue;
 459
 460    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2216461    public static bool operator >(FP a, FP b) => a.RawValue > b.RawValue;
 462
 463    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 757464    public static bool operator <=(FP a, FP b) => a.RawValue <= b.RawValue;
 465
 466    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 3467    public static bool operator >=(FP a, FP b) => a.RawValue >= b.RawValue;
 468
 469    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 4470    public int CompareTo(FP other) => RawValue.CompareTo(other.RawValue);
 471
 472    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 75473    public bool Equals(FP other) => RawValue == other.RawValue;
 474
 0475    public override bool Equals(object? obj) => obj is FP other && Equals(other);
 476
 1023477    public override int GetHashCode() => RawValue.GetHashCode();
 478
 479    #endregion
 480}

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Math/FP.InverseTrig.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4#nullable enable
 5
 6using System;
 7using System.Runtime.CompilerServices;
 8
 9namespace Lattice.Math;
 10
 11/// <summary>
 12/// FP 反三角函数部分 - 使用 LUT 实现确定性计算
 13/// </summary>
 14public readonly partial struct FP
 15{
 16    #region 反三角函数
 17
 18    /// <summary>
 19    /// 反余弦函数 Acos(x),x ∈ [-1, 1],返回值 ∈ [0, π]
 20    /// <para>使用预生成查找表,纯整数运算</para>
 21    /// </summary>
 22    /// <param name="x">输入值,必须在 [-1, 1] 范围内</param>
 23    /// <returns>反余弦值,范围 [0, π]</returns>
 24    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 25    public static FP Acos(FP x)
 26    {
 27        // 限制在 [-1, 1]
 2628        long clamped = x.RawValue;
 2729        if (clamped < -FP.ONE) clamped = -FP.ONE;
 2730        if (clamped > FP.ONE) clamped = FP.ONE;
 31
 32        // 使用查表:索引 = (x + 1) * 32768,结果在 [0, π]
 2633        int index = (int)((clamped + FP.ONE) * 32768 >> 16);
 2634        if (index < 0) index = 0;
 2635        if (index > 65536) index = 65536;
 36
 37        // 使用预生成 LUT
 2638        return new FP(FPAcosLut.Table[index]);
 39    }
 40
 41    /// <summary>
 42    /// 反正弦函数 Asin(x),x ∈ [-1, 1],返回值 ∈ [-π/2, π/2]
 43    /// <para>利用 Asin(x) = π/2 - Acos(x) 关系</para>
 44    /// </summary>
 45    /// <param name="x">输入值,必须在 [-1, 1] 范围内</param>
 46    /// <returns>反正弦值,范围 [-π/2, π/2]</returns>
 47    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 48    public static FP Asin(FP x)
 49    {
 50        // Asin(x) = π/2 - Acos(x)
 051        return PiHalf - Acos(x);
 52    }
 53
 54    #endregion
 55}

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Math/FP.Math.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4#nullable enable
 5
 6using System;
 7using System.Runtime.CompilerServices;
 8
 9namespace Lattice.Math;
 10
 11/// <summary>
 12/// FP 数学工具方法(部分类分离)
 13/// <para>包含 Abs、Min、Max、Clamp、Lerp、Approximately 等常用数学函数</para>
 14/// <para>提供分支版本和无分支版本(Branchless),适用于不同性能场景</para>
 15/// </summary>
 16/// <remarks>
 17/// <para><b>分支版本 vs 无分支版本:</b></para>
 18/// <list type="bullet">
 19///   <item><b>分支版本(如 <see cref="Abs(FP)"/>):</b>使用条件语句实现,代码可读性好。当数据分布可预测时(如大部分值为正),现代 CPU 的分支预测能提供良好性能。</item>
 20///   <item><b>无分支版本(如 <see cref="AbsBranchless"/>):</b>使用位运算实现,避免分支预测失败惩罚。适合数据分布随机、不可预测的热点代码路径。</item>
 21/// </list>
 22/// <para>性能建议:在性能敏感场景进行基准测试后选择合适版本。</para>
 23/// </remarks>
 24public readonly partial struct FP
 25{
 26    #region 基础数学函数
 27
 28    /// <summary>
 29    /// 绝对值(分支版本)
 30    /// <para>注意:long.MinValue 的绝对值仍是 long.MinValue(溢出),但在 FP 使用范围内不会发生</para>
 31    /// </summary>
 32    /// <param name="a">输入值</param>
 33    /// <returns>绝对值结果</returns>
 34    /// <remarks>
 35    /// 使用条件分支实现,当输入值的符号可预测时性能较好。
 36    /// 对于随机分布的数据,考虑使用 <see cref="AbsBranchless"/>。
 37    /// </remarks>
 38    /// <seealso cref="AbsBranchless"/>
 39    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 40    public static FP Abs(FP a)
 41    {
 2375142        long v = a.RawValue;
 43        // 处理 long.MinValue 的特殊情况(虽然 FP 使用范围内不会发生)
 2375144        if (v == long.MinValue)
 245            return new(long.MaxValue); // 返回最大正数作为近似
 2374946        return new(v < 0 ? -v : v);
 47
 48    }
 49
 50    /// <summary>
 51    /// 绝对值(无分支版本)
 52    /// <para>使用位运算实现,避免分支预测失败惩罚,适合热点代码路径</para>
 53    /// </summary>
 54    /// <param name="a">输入值</param>
 55    /// <returns>绝对值结果</returns>
 56    /// <remarks>
 57    /// <para><b>适用场景:</b>数据分布随机、不可预测(如物理模拟、AI计算),且在紧循环中频繁调用</para>
 58    /// <para><b>性能特性:</b>恒定执行时间,无分支预测风险,但在现代 CPU 上分支预测成功时可能略慢于分支版本</para>
 59    /// <para><b>实现原理:</b>Abs(x) = (x ^ (x &gt;&gt; 63)) - (x &gt;&gt; 63)</para>
 60    /// </remarks>
 61    /// <example>
 62    /// <code>
 63    /// // 在物理引擎的紧循环中使用无分支版本
 64    /// for (int i = 0; i &lt; particles.Count; i++)
 65    /// {
 66    ///     FP velocity = particle.Velocity;
 67    ///     FP damping = FP.AbsBranchless(velocity) * friction;
 68    /// }
 69    /// </code>
 70    /// </example>
 71    /// <seealso cref="Abs(FP)"/>
 72    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 73    public static FP AbsBranchless(FP a)
 74    {
 075        long v = a.RawValue;
 076        long mask = v >> 63;  // 符号位扩展:负数=-1,正数/零=0
 077        return new((v ^ mask) - mask);  // (v ^ -1) - (-1) = ~v + 1 = -v
 78    }
 79
 80    /// <summary>
 81    /// 取两个值中的较小值(分支版本)
 82    /// </summary>
 83    /// <param name="a">第一个值</param>
 84    /// <param name="b">第二个值</param>
 85    /// <returns>较小值</returns>
 86    /// <remarks>
 87    /// 使用条件分支实现,当两个值的大小关系可预测时性能较好。
 88    /// 对于随机分布的数据,考虑使用 <see cref="MinBranchless"/>。
 89    /// </remarks>
 90    /// <seealso cref="MinBranchless"/>
 91    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 92    public static FP Min(FP a, FP b)
 93    {
 194        return a.RawValue < b.RawValue ? a : b;
 95
 96    }
 97
 98    /// <summary>
 99    /// 取两个值中的较小值(无分支版本)
 100    /// <para>使用位运算实现,避免分支预测失败惩罚,适合热点代码路径</para>
 101    /// </summary>
 102    /// <param name="a">第一个值</param>
 103    /// <param name="b">第二个值</param>
 104    /// <returns>较小值</returns>
 105    /// <remarks>
 106    /// <para><b>适用场景:</b>数据分布随机、不可预测(如物理模拟、排序算法),且在紧循环中频繁调用</para>
 107    /// <para><b>性能特性:</b>恒定执行时间,无分支预测风险,但在现代 CPU 上分支预测成功时可能略慢于分支版本</para>
 108    /// <para><b>实现原理:</b>利用差值的符号位作为掩码选择值</para>
 109    /// </remarks>
 110    /// <example>
 111    /// <code>
 112    /// // 在碰撞检测的 AABB 检查中使用
 113    /// FP minX = FP.MinBranchless(a.Min.X, b.Min.X);
 114    /// FP minY = FP.MinBranchless(a.Min.Y, b.Min.Y);
 115    /// </code>
 116    /// </example>
 117    /// <seealso cref="Min(FP, FP)"/>
 118    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 119    public static FP MinBranchless(FP a, FP b)
 120    {
 0121        long diff = a.RawValue - b.RawValue;
 0122        long mask = diff >> 63;  // a < b 时 mask = -1,否则 mask = 0
 0123        return new((a.RawValue & mask) | (b.RawValue & ~mask));  // mask = -1 时选 a,否则选 b
 124    }
 125
 126    /// <summary>
 127    /// 取两个值中的较大值(分支版本)
 128    /// </summary>
 129    /// <param name="a">第一个值</param>
 130    /// <param name="b">第二个值</param>
 131    /// <returns>较大值</returns>
 132    /// <remarks>
 133    /// 使用条件分支实现,当两个值的大小关系可预测时性能较好。
 134    /// 对于随机分布的数据,考虑使用 <see cref="MaxBranchless"/>。
 135    /// </remarks>
 136    /// <seealso cref="MaxBranchless"/>
 137    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 138    public static FP Max(FP a, FP b)
 139    {
 1140        return a.RawValue > b.RawValue ? a : b;
 141
 142    }
 143
 144    /// <summary>
 145    /// 取两个值中的较大值(无分支版本)
 146    /// <para>使用位运算实现,避免分支预测失败惩罚,适合热点代码路径</para>
 147    /// </summary>
 148    /// <param name="a">第一个值</param>
 149    /// <param name="b">第二个值</param>
 150    /// <returns>较大值</returns>
 151    /// <remarks>
 152    /// <para><b>适用场景:</b>数据分布随机、不可预测(如物理模拟、碰撞检测),且在紧循环中频繁调用</para>
 153    /// <para><b>性能特性:</b>恒定执行时间,无分支预测风险,但在现代 CPU 上分支预测成功时可能略慢于分支版本</para>
 154    /// <para><b>实现原理:</b>利用差值的符号位作为掩码选择值</para>
 155    /// </remarks>
 156    /// <example>
 157    /// <code>
 158    /// // 在动画系统中混合多个值
 159    /// FP maxWeight = FP.MaxBranchless(weight1, FP.MaxBranchless(weight2, weight3));
 160    /// </code>
 161    /// </example>
 162    /// <seealso cref="Max(FP, FP)"/>
 163    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 164    public static FP MaxBranchless(FP a, FP b)
 165    {
 0166        long diff = a.RawValue - b.RawValue;
 0167        long mask = diff >> 63;  // a < b 时 mask = -1,否则 mask = 0
 0168        return new((b.RawValue & mask) | (a.RawValue & ~mask));  // mask = -1 时选 b,否则选 a
 169    }
 170
 171    /// <summary>
 172    /// 将值限制在 [min, max] 范围内(分支版本)
 173    /// <para>如果 value &lt; min 返回 min,如果 value &gt; max 返回 max,否则返回 value</para>
 174    /// </summary>
 175    /// <param name="value">要限制的值</param>
 176    /// <param name="min">最小值</param>
 177    /// <param name="max">最大值</param>
 178    /// <returns>限制后的值</returns>
 179    /// <remarks>
 180    /// 使用条件分支实现,当 value 通常已在范围内时性能较好。
 181    /// 对于随机分布的数据,考虑使用 <see cref="ClampBranchless"/>。
 182    /// </remarks>
 183    /// <seealso cref="ClampBranchless"/>
 184    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 185    public static FP Clamp(FP value, FP min, FP max)
 186    {
 24218187        if (value.RawValue < min.RawValue) return min;
 24213188        if (value.RawValue > max.RawValue) return max;
 24207189        return value;
 190
 191    }
 192
 193    /// <summary>
 194    /// 将值限制在 [min, max] 范围内(无分支版本)
 195    /// <para>使用位运算实现,避免分支预测失败惩罚,适合热点代码路径</para>
 196    /// </summary>
 197    /// <param name="value">要限制的值</param>
 198    /// <param name="min">最小值</param>
 199    /// <param name="max">最大值</param>
 200    /// <returns>限制后的值</returns>
 201    /// <remarks>
 202    /// <para><b>适用场景:</b>数据分布随机、不可预测(如输入处理、动画系统),且在紧循环中频繁调用</para>
 203    /// <para><b>性能特性:</b>恒定执行时间,无分支预测风险,但在现代 CPU 上分支预测成功时可能略慢于分支版本</para>
 204    /// <para><b>实现原理:</b>ClampBranchless(v, min, max) = MinBranchless(MaxBranchless(v, min), max)</para>
 205    /// </remarks>
 206    /// <example>
 207    /// <code>
 208    /// // 在输入处理中限制摇杆值
 209    /// FP clampedX = FP.ClampBranchless(input.X, -FP._1, FP._1);
 210    /// FP clampedY = FP.ClampBranchless(input.Y, -FP._1, FP._1);
 211    /// </code>
 212    /// </example>
 213    /// <seealso cref="Clamp(FP, FP, FP)"/>
 214    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 215    public static FP ClampBranchless(FP value, FP min, FP max)
 216    {
 0217        return MinBranchless(MaxBranchless(value, min), max);
 218    }
 219
 220    /// <summary>
 221    /// 线性插值:a + (b - a) * t
 222    /// <para>结果范围取决于 t,不限制 t 的范围</para>
 223    /// </summary>
 224    /// <param name="a">起始值</param>
 225    /// <param name="b">结束值</param>
 226    /// <param name="t">插值系数(0 返回 a,1 返回 b)</param>
 227    /// <returns>插值结果</returns>
 228    /// <example>
 229    /// <code>
 230    /// // 在 100 和 200 之间插值,t=0.5 返回 150
 231    /// FP result = FP.Lerp(FP._100, FP._200, FP._0_50);
 232    /// </code>
 233    /// </example>
 234    /// <seealso cref="FPVector2.Lerp(FPVector2, FPVector2, FP)"/>
 235    /// <seealso cref="FPVector3.Lerp(FPVector3, FPVector3, FP)"/>
 236    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 237    public static FP Lerp(FP a, FP b, FP t)
 238    {
 22207239        return a + (b - a) * t;
 240    }
 241
 242    /// <summary>
 243    /// 近似相等(使用默认容差 EpsilonDefault ≈ 0.00015)
 244    /// <para>用于处理定点数运算累积的微小误差</para>
 245    /// </summary>
 246    /// <param name="a">第一个值</param>
 247    /// <param name="b">第二个值</param>
 248    /// <returns>如果两值之差小于等于默认容差则返回 true</returns>
 249    /// <remarks>
 250    /// 定点数运算会产生微小精度误差,使用此方法而非 == 进行比较。
 251    /// 默认容差适用于大多数场景,需要自定义容差时使用 <see cref="Approximately(FP, FP, FP)"/>。
 252    /// </remarks>
 253    /// <example>
 254    /// <code>
 255    /// // 检查是否到达目标位置(考虑浮点误差)
 256    /// if (FP.Approximately(currentPos, targetPos))
 257    /// {
 258    ///     // 到达目标
 259    /// }
 260    /// </code>
 261    /// </example>
 262    /// <seealso cref="Approximately(FP, FP, FP)"/>
 263    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 264    public static bool Approximately(FP a, FP b)
 265    {
 5266        return Approximately(a, b, EpsilonDefault);
 267    }
 268
 269    /// <summary>
 270    /// 近似相等(自定义容差)
 271    /// <para>用于处理定点数运算累积的微小误差</para>
 272    /// </summary>
 273    /// <param name="a">第一个值</param>
 274    /// <param name="b">第二个值</param>
 275    /// <param name="epsilon">容差值</param>
 276    /// <returns>如果两值之差小于等于 epsilon 则返回 true</returns>
 277    /// <example>
 278    /// <code>
 279    /// // 使用较大容差检查速度是否接近零
 280    /// if (FP.Approximately(velocity, FP._0, (FP)0.01))
 281    /// {
 282    ///     velocity = FP._0; // 完全停止
 283    /// }
 284    /// </code>
 285    /// </example>
 286    /// <seealso cref="Approximately(FP, FP)"/>
 287    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 288    public static bool Approximately(FP a, FP b, FP epsilon)
 289    {
 5290        long diff = a.RawValue - b.RawValue;
 10291        if (diff < 0) diff = -diff;
 5292        return diff <= epsilon.RawValue;
 293    }
 294
 295    #endregion
 296}

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Math/FP.String.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4#nullable enable
 5
 6using System;
 7using System.Runtime.CompilerServices;
 8
 9namespace Lattice.Math;
 10
 11/// <summary>
 12/// 定点数字符串解析与格式化(部分类)
 13/// </summary>
 14/// <remarks>
 15/// <para>本文件包含 FP 结构体的字符串相关方法:</para>
 16/// <list type="bullet">
 17///   <item>FromString - 确定性解析(安全,可用于运行时)</item>
 18///   <item>FromString_UNSAFE - 基于 float.Parse(仅编辑器使用)</item>
 19///   <item>ToString - 格式化输出(纯整数实现)</item>
 20/// </list>
 21/// </remarks>
 22public readonly partial struct FP
 23{
 24    #region 字符串解析
 25
 26    /// <summary>
 27    /// 确定性字符串解析(安全,可用于运行时加载配置)
 28    /// <para>格式:英文数字,如 "123.456" 或 "-10.5"</para>
 29    /// <para>不经过 float,完全确定性</para>
 30    /// </summary>
 31    /// <param name="s">要解析的字符串</param>
 32    /// <returns>解析后的 FP 值</returns>
 33    /// <exception cref="ArgumentException">字符串为空或 null 时抛出</exception>
 34    /// <exception cref="FormatException">字符串格式无效时抛出</exception>
 35    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 36    public static FP FromString(string s)
 37    {
 4338        if (string.IsNullOrEmpty(s))
 539            throw new ArgumentException("String is null or empty", nameof(s));
 40
 41        // 解析符号
 3842        int start = 0;
 3843        bool negative = false;
 3844        if (s[0] == '-')
 45        {
 1146            negative = true;
 1147            start = 1;
 48        }
 2749        else if (s[0] == '+')
 50        {
 151            start = 1;
 52        }
 53
 54        // 分割整数和小数部分
 3855        int dotIndex = s.IndexOf('.', start);
 56
 57        // 解析整数部分
 3858        long integerPart = 0;
 3859        int end = dotIndex >= 0 ? dotIndex : s.Length;
 15460        for (int i = start; i < end; i++)
 61        {
 4862            if (s[i] < '0' || s[i] > '9')
 963                throw new FormatException($"Invalid character '{s[i]}' in FP string");
 3964            integerPart = integerPart * 10 + (s[i] - '0');
 65        }
 66
 67        // 解析小数部分(最多 5 位,超过部分截断)
 2968        long fractionalPart = 0;
 2969        if (dotIndex >= 0 && dotIndex + 1 < s.Length)
 70        {
 2171            int fracStart = dotIndex + 1;
 2172            int fracLength = System.Math.Min(5, s.Length - fracStart);
 73
 2174            long fracValue = 0;
 2175            long divisor = 1;
 14476            for (int i = 0; i < fracLength; i++)
 77            {
 5378                char c = s[fracStart + i];
 5379                if (c < '0' || c > '9')
 280                    throw new FormatException($"Invalid character '{c}' in FP fractional part");
 5181                fracValue = fracValue * 10 + (c - '0');
 5182                divisor *= 10;
 83            }
 84
 85            // 将小数部分转换为定点数:fracValue / divisor * ONE
 1986            fractionalPart = (fracValue * ONE) / divisor;
 87        }
 88
 2789        long result = (integerPart << FRACTIONAL_BITS) + fractionalPart;
 3690        if (negative) result = -result;
 91
 2792        return new(result);
 93    }
 94
 95    /// <summary>
 96    /// 字符串解析(UNSAFE,基于 float.Parse)
 97    /// <para>警告:此方法内部使用 float.Parse,只能在编辑器/配置阶段使用!</para>
 98    /// <para>模拟/运行时使用会导致非确定性。请使用 FromString 或预计算的 Raw 值。</para>
 99    /// </summary>
 100    /// <param name="s">要解析的字符串</param>
 101    /// <returns>解析后的 FP 值</returns>
 102    /// <remarks>
 103    /// 此方法仅在非 DEBUG 构建中可用。DEBUG 构建中标记为 [Obsolete(error: true)]。
 104    /// </remarks>
 105#if DEBUG
 106    [Obsolete("FromString_UNSAFE 内部使用 float.Parse,只能在编辑器使用。生产环境请使用 FromString()", error: true)]
 107#endif
 108    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 109#pragma warning disable RS0030 // 允许 UNSAFE 方法使用被禁止的 API
 0110    public static FP FromString_UNSAFE(string s) => FromFloat_UNSAFE(float.Parse(s));
 111#pragma warning restore RS0030
 112
 113    #endregion
 114
 115    #region 字符串格式化
 116
 117    /// <summary>
 118    /// 默认格式化输出(纯整数实现,确定性)
 119    /// <para>格式:固定4位小数</para>
 120    /// </summary>
 121    /// <returns>格式化后的字符串,如 "123.4560" 或 "-10.5000"</returns>
 122    public override string ToString()
 123    {
 29124        return ToStringInternal(4);
 125    }
 126
 127    /// <summary>
 128    /// 自定义格式输出(纯整数实现,确定性)
 129    /// <para>支持格式:F0-F9(小数位数)</para>
 130    /// </summary>
 131    /// <param name="format">格式字符串,如 "F2" 表示保留2位小数</param>
 132    /// <returns>格式化后的字符串</returns>
 133    /// <example>
 134    /// <code>
 135    /// FP value = FP.FromRaw(FP.Raw._1_50);  // 1.5
 136    /// string s1 = value.ToString("F2");    // "1.50"
 137    /// string s2 = value.ToString("F0");    // "2"(四舍五入)
 138    /// </code>
 139    /// </example>
 140    public string ToString(string format)
 141    {
 15142        int decimalPlaces = 4;
 15143        if (!string.IsNullOrEmpty(format) && format.Length > 1 && format[0] == 'F')
 144        {
 15145            if (int.TryParse(format.Substring(1), out int parsed) && parsed >= 0 && parsed <= 9)
 15146                decimalPlaces = parsed;
 147        }
 15148        return ToStringInternal(decimalPlaces);
 149    }
 150
 151    /// <summary>
 152    /// 纯整数实现的字符串转换(内部方法)
 153    /// <para>将定点数转换为指定小数位数的字符串表示</para>
 154    /// </summary>
 155    /// <param name="decimalPlaces">小数位数(0-9)</param>
 156    /// <returns>格式化后的字符串</returns>
 157    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 158    private string ToStringInternal(int decimalPlaces)
 159    {
 51160        if (RawValue == 0) return "0." + new string('0', decimalPlaces);
 161
 37162        long raw = RawValue;
 37163        bool negative = raw < 0;
 49164        if (negative) raw = -raw;
 165
 166        // 整数部分
 37167        long intPart = raw >> FRACTIONAL_BITS;
 168
 169        // 小数部分(16位)
 37170        long fracPart = raw & (ONE - 1);
 171
 172        // 将小数部分扩展到指定位数
 173        // fracPart / 65536 * 10^decimalPlaces
 37174        long divisor = ONE;
 572175        for (int i = 0; i < decimalPlaces; i++) divisor /= 10;
 48176        if (divisor == 0) divisor = 1; // 防止除零
 177
 37178        long scaledFrac = (fracPart * Pow10(decimalPlaces)) / ONE;
 179
 180        // 格式化
 37181        string intStr = intPart.ToString();
 37182        string fracStr = scaledFrac.ToString().PadLeft(decimalPlaces, '0');
 183
 184        // 截断到指定位数
 37185        if (fracStr.Length > decimalPlaces)
 0186            fracStr = fracStr.Substring(0, decimalPlaces);
 187
 37188        return (negative ? "-" : "") + intStr + "." + fracStr;
 189    }
 190
 191    #endregion
 192
 193    #region 辅助方法
 194
 195    /// <summary>
 196    /// 10的幂次查找表
 197    /// <para>用于字符串格式化时快速计算 10^n</para>
 198    /// </summary>
 199    /// <param name="n">指数(0-9)</param>
 200    /// <returns>10^n 的值</returns>
 201    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 202    private static long Pow10(int n)
 203    {
 37204        return n switch
 37205        {
 0206            0 => 1,
 0207            1 => 10,
 2208            2 => 100,
 0209            3 => 1000,
 24210            4 => 10000,
 0211            5 => 100000,
 11212            6 => 1000000,
 0213            7 => 10000000,
 0214            8 => 100000000,
 0215            9 => 1000000000,
 0216            _ => 10000
 37217        };
 218    }
 219
 220    #endregion
 221}

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Math/FP.Trig.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4#nullable enable
 5
 6using System;
 7using System.Runtime.CompilerServices;
 8
 9namespace Lattice.Math;
 10
 11/// <summary>
 12/// FP 三角函数部分 - 使用 LUT 实现确定性计算
 13/// </summary>
 14public readonly partial struct FP
 15{
 16    #region 常量与辅助
 17
 18    /// <summary>2π 对应的 RawValue</summary>
 119    private static readonly long TWO_PI_RAW = Pi2.RawValue;
 20
 21    #endregion
 22
 23    #region 快速模式 (1024 LUT)
 24
 25    /// <summary>
 26    /// 快速正弦函数(1024 LUT,Cache 友好)
 27    /// <para>精度:~0.35° 步长,适合一般计算</para>
 28    /// <para>速度:比 Accurate 模式快,Cache 命中率高</para>
 29    /// </summary>
 30    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 31    public static FP SinFast(FP angle)
 32    {
 192133        long raw = angle.RawValue;
 34
 35        // 归一化到 [0, 2π)
 218936        if (raw < 0) raw = raw % TWO_PI_RAW + TWO_PI_RAW;
 167037        else if (raw >= TWO_PI_RAW) raw = raw % TWO_PI_RAW;
 38
 39        // 映射到 [0, 1024):raw * 1024 / 2π
 192140        int index = (int)((raw << 10) / TWO_PI_RAW);  // 10 = log2(1024)
 192141        if (index >= FPSinCosLut.FastSize) index = 0;
 42
 192143        return new(FPSinCosLut.SinFast[index]);
 44    }
 45
 46    /// <summary>
 47    /// 快速余弦函数(1024 LUT)
 48    /// <para>Cos(x) = Sin(x + π/2)</para>
 49    /// </summary>
 50    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 51    public static FP CosFast(FP angle)
 52    {
 053        return SinFast(angle + PiHalf);
 54    }
 55
 56    #endregion
 57
 58    #region 标准模式 (1024 LUT)
 59
 60    /// <summary>
 61    /// 标准正弦函数(1024 LUT)
 62    /// <para>默认推荐:平衡精度和性能</para>
 63    /// </summary>
 64    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 65    public static FP Sin(FP angle)
 66    {
 67        // 使用快速模式(当前实现相同,未来可添加插值)
 191568        return SinFast(angle);
 69    }
 70
 71    /// <summary>
 72    /// 标准余弦函数(1024 LUT)
 73    /// </summary>
 74    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 75    public static FP Cos(FP angle)
 76    {
 81277        return Sin(angle + PiHalf);
 78    }
 79
 80    #endregion
 81
 82    #region 高精度模式 (4096 LUT)
 83
 84    /// <summary>
 85    /// 高精度正弦函数(4096 LUT)
 86    /// <para>精度:~0.088° 步长,适合 3D 旋转和物理模拟</para>
 87    /// <para>内存:比 Fast 模式多 24KB,Cache 压力略大</para>
 88    /// </summary>
 89    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 90    public static FP SinAccurate(FP angle)
 91    {
 092        long raw = angle.RawValue;
 93
 94        // 归一化到 [0, 2π)
 095        if (raw < 0) raw = raw % TWO_PI_RAW + TWO_PI_RAW;
 096        else if (raw >= TWO_PI_RAW) raw = raw % TWO_PI_RAW;
 97
 98        // 映射到 [0, 4096):raw * 4096 / 2π
 099        int index = (int)((raw << 12) / TWO_PI_RAW);  // 12 = log2(4096)
 0100        if (index >= FPSinCosLut.AccurateSize) index = 0;
 101
 0102        return new(FPSinCosLut.SinAccurate[index]);
 103    }
 104
 105    /// <summary>
 106    /// 高精度余弦函数(4096 LUT)
 107    /// </summary>
 108    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 109    public static FP CosAccurate(FP angle)
 110    {
 0111        return SinAccurate(angle + PiHalf);
 112    }
 113
 114    #endregion
 115
 116    #region 其他三角函数
 117
 118    /// <summary>
 119    /// 正切函数 Tan(angle) - 使用标准精度
 120    /// <para>Tan(x) = Sin(x) / Cos(x)</para>
 121    /// </summary>
 122    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 123    public static FP Tan(FP angle)
 124    {
 104125        FP sin = Sin(angle);
 104126        FP cos = Cos(angle);
 127
 128        // 当 Cos 接近 0 时处理
 104129        long absCos = cos.RawValue < 0 ? -cos.RawValue : cos.RawValue;
 104130        if (absCos < 10) // 接近零
 131        {
 0132            return sin.RawValue >= 0 ? UseableMax : UseableMin;
 133        }
 134
 104135        return sin / cos;
 136    }
 137
 138    /// <summary>
 139    /// 高精度正切函数 - 使用 4096 LUT
 140    /// </summary>
 141    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 142    public static FP TanAccurate(FP angle)
 143    {
 0144        FP sin = SinAccurate(angle);
 0145        FP cos = CosAccurate(angle);
 146
 0147        long absCos = cos.RawValue < 0 ? -cos.RawValue : cos.RawValue;
 0148        if (absCos < 10)
 149        {
 0150            return sin.RawValue >= 0 ? UseableMax : UseableMin;
 151        }
 152
 0153        return sin / cos;
 154    }
 155
 156    #endregion
 157
 158    #region 反三角函数
 159
 160    /// <summary>
 161    /// 反正切函数 Atan2(y, x),返回角度 [-π, π]
 162    /// <para>用于计算向量角度,如 MathF.Atan2(y, x)</para>
 163    /// </summary>
 164    /// <remarks>
 165    /// 使用象限归约 + 查表,保证确定性
 166    /// </remarks>
 167    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 168    public static FP Atan2(FP y, FP x)
 169    {
 170        // 处理原点和坐标轴上的点
 217171        if (x.RawValue == 0)
 172        {
 8173            if (y.RawValue > 0) return PiHalf;
 6174            if (y.RawValue < 0) return -PiHalf;
 2175            return Zero;
 176        }
 211177        if (y.RawValue == 0)
 178        {
 5179            return x.RawValue > 0 ? Zero : Pi;
 180        }
 181
 206182        FP absY = Abs(y);
 206183        FP absX = Abs(x);
 184
 185        // 使用公式:atan2(y, x) = atan(y/x) (适当调整象限)
 186        // 但为了精度,当 |y| > |x| 时,使用 atan2(y, x) = π/2 - atan(x/y)
 187        FP angle;
 206188        if (absY <= absX)
 189        {
 190            // |y/x| <= 1,直接计算 atan(|y/x|)
 116191            FP ratio = absY / absX;  // [0, 1]
 116192            angle = AtanSmall(ratio);
 193        }
 194        else
 195        {
 196            // |y/x| > 1,使用互补角公式
 90197            FP ratio = absX / absY;  // [0, 1]
 90198            angle = PiHalf - AtanSmall(ratio);
 199        }
 200
 201        // 恢复符号和象限
 202        // 将结果从第一象限 [0, π/2] 映射到正确的象限
 206203        if (x.RawValue < 0)
 204        {
 205            // 第二或第三象限
 3206            angle = y.RawValue > 0 ? Pi - angle : -Pi + angle;
 207        }
 203208        else if (y.RawValue < 0)
 209        {
 210            // 第四象限
 101211            angle = -angle;
 212        }
 213        // 否则第一象限,保持不变
 214
 206215        return angle;
 216    }
 217
 218    /// <summary>
 219    /// 计算 atan(x) 当 x ∈ [0, 1]
 220    /// <para>使用预生成查找表 + 线性插值</para>
 221    /// </summary>
 222    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 223    private static FP AtanSmall(FP x)
 224    {
 225        // 使用预生成的 atan 表
 226        // atan(x) for x in [0, 1], result in [0, π/4]
 206227        return AtanTableLookup(x);
 228    }
 229
 230    /// <summary>Atan 表大小常量</summary>
 231    private const int ATAN_TABLE_SIZE = 256;
 232
 233    /// <summary>
 234    /// 查表 + 线性插值
 235    /// <para>输入 x ∈ [0, 1],输出 atan(x) ∈ [0, π/4]</para>
 236    /// </summary>
 237    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 238    private static FP AtanTableLookup(FP x)
 239    {
 206240        long r = x.RawValue;
 206241        if (r <= 0) return Zero;
 232242        if (r >= ONE) return new FP(FPAtanLut.Table[ATAN_TABLE_SIZE]);
 243
 244        // 映射到表索引
 180245        long idxLong = (r * ATAN_TABLE_SIZE) / ONE;
 180246        int idx = (int)idxLong;
 180247        if (idx >= ATAN_TABLE_SIZE) return new FP(FPAtanLut.Table[ATAN_TABLE_SIZE]);
 248
 249        // 线性插值
 180250        long lower = FPAtanLut.Table[idx];
 180251        long upper = FPAtanLut.Table[idx + 1];
 180252        long frac = (r * ATAN_TABLE_SIZE) % ONE;
 180253        long interpolated = lower + ((upper - lower) * frac) / ONE;
 254
 180255        return new FP(interpolated);
 256    }
 257
 258    #endregion
 259
 260    #region 角度转换
 261
 262    // 180° 对应的 FP 常量(180 * 65536 = 11796480)
 1263    private static readonly FP DEG_180 = new(11796480L);
 264
 265    /// <summary>
 266    /// 角度转弧度(当输入是角度时)
 267    /// <para>例如:Deg2Rad(90) = π/2</para>
 268    /// </summary>
 269    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 270    public static FP Deg2Rad(FP degrees)
 271    {
 272        // radians = degrees * π / 180
 1273        return degrees * Pi / DEG_180;
 274    }
 275
 276    /// <summary>
 277    /// 弧度转角度
 278    /// </summary>
 279    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 280    public static FP Rad2Deg(FP radians)
 281    {
 282        // degrees = radians * 180 / π
 1283        return radians * DEG_180 / Pi;
 284    }
 285
 286    #endregion
 287
 288    #region 使用指南
 289
 290    /*
 291     * 精度选择指南:
 292     *
 293     * 1. Fast 模式 (1024 LUT):
 294     *    - 场景:粒子效果、UI 动画、非关键逻辑
 295     *    - 优势:Cache 命中率高,适合高频调用
 296     *    - 精度:±0.35° 最大误差
 297     *
 298     * 2. 标准模式 (1024 LUT):
 299     *    - 场景:2D 游戏、一般移动计算
 300     *    - 优势:平衡的性能和精度
 301     *    - 精度:±0.35° 最大误差
 302     *
 303     * 3. Accurate 模式 (4096 LUT):
 304     *    - 场景:3D 旋转、物理模拟、长时间积分
 305     *    - 优势:高精度减少误差累积
 306     *    - 精度:±0.088° 最大误差
 307     *
 308     * 内存占用:
 309     * - Fast (1024):Sin + Cos = 16 KB
 310     * - Accurate (4096):Sin + Cos = 64 KB
 311     * - 总计:80 KB(可接受)
 312     */
 313
 314    #endregion
 315}

Methods/Properties

.cctor()
get_Zero()
get_One()
get_Two()
get_Half()
get_Pi()
get_Pi2()
get_PiHalf()
get__0()
get__1()
get__2()
get__3()
get__4()
get__5()
get__10()
get__100()
get__1000()
get__0_01()
get__0_05()
get__0_10()
get__0_25()
get__0_50()
get__0_75()
get__1_50()
.ctor(System.Int64)
FromRaw(System.Int64)
op_Implicit(System.Int32)
op_Implicit(System.Int64)
op_Explicit(Lattice.Math.FP)
op_Explicit(Lattice.Math.FP)
FromFloat_UNSAFE(System.Single)
FromDouble_UNSAFE(System.Double)
ToFloat_UNSAFE()
ToDouble_UNSAFE()
op_Explicit(System.Single)
op_Explicit(System.Double)
op_Addition(Lattice.Math.FP,Lattice.Math.FP)
op_Subtraction(Lattice.Math.FP,Lattice.Math.FP)
op_UnaryNegation(Lattice.Math.FP)
op_UnaryPlus(Lattice.Math.FP)
op_Multiply(Lattice.Math.FP,Lattice.Math.FP)
MultiplyFast(Lattice.Math.FP,Lattice.Math.FP)
MultiplyPrecise(Lattice.Math.FP,Lattice.Math.FP)
op_Division(Lattice.Math.FP,Lattice.Math.FP)
op_Multiply(Lattice.Math.FP,System.Int32)
op_Multiply(System.Int32,Lattice.Math.FP)
op_Division(Lattice.Math.FP,System.Int32)
op_Addition(Lattice.Math.FP,System.Int32)
op_Addition(System.Int32,Lattice.Math.FP)
op_Subtraction(Lattice.Math.FP,System.Int32)
op_Subtraction(System.Int32,Lattice.Math.FP)
op_Multiply(Lattice.Math.FP,System.Int64)
op_Multiply(System.Int64,Lattice.Math.FP)
op_Division(Lattice.Math.FP,System.Int64)
op_Equality(Lattice.Math.FP,Lattice.Math.FP)
op_Inequality(Lattice.Math.FP,Lattice.Math.FP)
op_LessThan(Lattice.Math.FP,Lattice.Math.FP)
op_GreaterThan(Lattice.Math.FP,Lattice.Math.FP)
op_LessThanOrEqual(Lattice.Math.FP,Lattice.Math.FP)
op_GreaterThanOrEqual(Lattice.Math.FP,Lattice.Math.FP)
CompareTo(Lattice.Math.FP)
Equals(Lattice.Math.FP)
Equals(System.Object)
GetHashCode()
Acos(Lattice.Math.FP)
Asin(Lattice.Math.FP)
Abs(Lattice.Math.FP)
AbsBranchless(Lattice.Math.FP)
Min(Lattice.Math.FP,Lattice.Math.FP)
MinBranchless(Lattice.Math.FP,Lattice.Math.FP)
Max(Lattice.Math.FP,Lattice.Math.FP)
MaxBranchless(Lattice.Math.FP,Lattice.Math.FP)
Clamp(Lattice.Math.FP,Lattice.Math.FP,Lattice.Math.FP)
ClampBranchless(Lattice.Math.FP,Lattice.Math.FP,Lattice.Math.FP)
Lerp(Lattice.Math.FP,Lattice.Math.FP,Lattice.Math.FP)
Approximately(Lattice.Math.FP,Lattice.Math.FP)
Approximately(Lattice.Math.FP,Lattice.Math.FP,Lattice.Math.FP)
FromString(System.String)
FromString_UNSAFE(System.String)
ToString()
ToString(System.String)
ToStringInternal(System.Int32)
Pow10(System.Int32)
.cctor()
SinFast(Lattice.Math.FP)
CosFast(Lattice.Math.FP)
Sin(Lattice.Math.FP)
Cos(Lattice.Math.FP)
SinAccurate(Lattice.Math.FP)
CosAccurate(Lattice.Math.FP)
Tan(Lattice.Math.FP)
TanAccurate(Lattice.Math.FP)
Atan2(Lattice.Math.FP,Lattice.Math.FP)
AtanSmall(Lattice.Math.FP)
AtanTableLookup(Lattice.Math.FP)
Deg2Rad(Lattice.Math.FP)
Rad2Deg(Lattice.Math.FP)