< Summary

Information
Class: Lattice.Math.FPMath
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/Math/FPMath.cs
Line coverage
62%
Covered lines: 75
Uncovered lines: 45
Coverable lines: 120
Total lines: 421
Line coverage: 62.5%
Branch coverage
62%
Covered branches: 61
Total branches: 98
Branch coverage: 62.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
Sqrt(...)75%4475%
SqrtRaw(...)100%1212100%
InvSqrt(...)0%272160%
GetSqrtDecomp(...)100%1212100%
GetReciprocalForNormalize(...)100%11100%
Sign(...)100%44100%
Abs(...)100%22100%
Min(...)100%22100%
Max(...)100%22100%
Clamp(...)100%44100%
Clamp01(...)100%44100%
Lerp(...)100%11100%
LerpUnclamped(...)100%11100%
Floor(...)100%11100%
Ceiling(...)50%2266.66%
Round(...)100%66100%
NormalizeBatch(...)0%2040%
NormalizeBatch(...)0%2040%
DotBatch(...)0%4260%
LerpBatch(...)50%8660%
ClampBatch(...)75%88100%
Warmup()100%210%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Math/FPMath.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.Numerics;
 8using System.Runtime.CompilerServices;
 9
 10namespace Lattice.Math
 11{
 12    /// <summary>
 13    /// 定点数数学辅助类
 14    /// <para>采用 FrameSyncEngine 纯整数算法,无浮点运算,严格跨平台确定性</para>
 15    /// </summary>
 16    public static class FPMath
 17    {
 18        #region 内部结构
 19
 20        /// <summary>
 21        /// 平方根分解结果:sqrt(x) = Mantissa * 2^Exponent
 22        /// </summary>
 23        internal readonly struct SqrtDecomp
 24        {
 25            public readonly int Exponent;
 26            public readonly int Mantissa;
 27
 28            public SqrtDecomp(int exponent, int mantissa)
 29            {
 1530                Exponent = exponent;
 1531                Mantissa = mantissa;
 1532            }
 33        }
 34
 35        #endregion
 36
 37        #region Sqrt / InvSqrt 实现(FrameSync 风格纯整数算法)
 38
 39        /// <summary>
 40        /// 计算平方根 - 纯整数查表法
 41        /// <para>FrameSync 风格实现:查表 + 指数分解,无浮点运算</para>
 42        /// </summary>
 43        /// <param name="value">输入值,必须 >= 0</param>
 44        /// <returns>平方根结果</returns>
 45        /// <exception cref="ArgumentOutOfRangeException">输入为负数时抛出</exception>
 46        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 47        public static FP Sqrt(FP value)
 48        {
 24649            if (value.RawValue < 0)
 050                throw new ArgumentOutOfRangeException(nameof(value), "平方根输入不能为负数");
 25151            if (value.RawValue == 0) return FP.Zero;
 24152            return FP.FromRaw(SqrtRaw(value.RawValue));
 53        }
 54
 55        /// <summary>
 56        /// 计算平方根(原始值)- 纯整数算法
 57        /// </summary>
 58        /// <remarks>
 59        /// 核心算法来自 FrameSyncEngine:
 60        /// <list type="number">
 61        ///   <item>小值 (&lt;= 65536): 直接查表,结果右移 6 位</item>
 62        ///   <item>大值: 分解为 mantissa * 2^exponent,分别处理</item>
 63        /// </list>
 64        /// </remarks>
 65        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 66        public static long SqrtRaw(long x)
 67        {
 24168            if (x <= 65536L)
 69            {
 70                // 小值直接查表,右移 6 位去除额外精度
 1171                return FPSqrtLut.Table[x] >> FPSqrtLut.AdditionalPrecisionBits;
 72            }
 73
 74            // 大值处理:分解尾数和指数
 75            // x = raw * 2^exponent, 其中 raw 在 [0, 65536] 范围内
 23076            long raw = x;
 23077            int log2 = 0;
 78
 79            // 手动计算 log2(找最高有效位)
 25280            if ((raw >> 32) != 0L) { raw >>= 32; log2 += 32; }
 66881            if ((raw >> 16) != 0L) { raw >>= 16; log2 += 16; }
 24482            if ((raw >> 8) != 0L) { raw >>= 8; log2 += 8; }
 60483            if ((raw >> 4) != 0L) { raw >>= 4; log2 += 4; }
 34084            if ((raw >> 2) != 0L) { log2 += 2; }
 85
 86            // 计算指数偏移,使 x >> exponent 落在查找表范围内
 87            // log2 - 16: 因为查找表覆盖 16 位小数
 88            // + 2: FrameSync 的调整因子
 23089            int exponent = log2 - 16 + 2;
 90
 91            // 查表获取尾数的平方根(带额外精度)
 23092            int mantissaSqrt = FPSqrtLut.Table[x >> exponent];
 93
 94            // 结果 = 尾数平方根 << (exponent / 2)
 95            // exponent >> 1 相当于 exponent / 2
 23096            long result = (long)mantissaSqrt << (exponent >> 1);
 97
 98            // 右移 6 位去除额外精度
 23099            return result >> FPSqrtLut.AdditionalPrecisionBits;
 100        }
 101
 102        /// <summary>
 103        /// 计算倒数平方根 1/Sqrt(x) - 用于快速归一化
 104        /// <para>使用牛顿迭代法优化,比 1/Sqrt(x) 直接计算更快</para>
 105        /// </summary>
 106        /// <param name="value">输入值,必须 > 0</param>
 107        /// <returns>倒数平方根结果</returns>
 108        /// <exception cref="ArgumentOutOfRangeException">输入小于等于 0 时抛出</exception>
 109        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 110        public static FP InvSqrt(FP value)
 111        {
 0112            if (value.RawValue <= 0)
 0113                throw new ArgumentOutOfRangeException(nameof(value), "InvSqrt 输入必须为正数");
 114
 115            // 初始估计:使用 LUT 获取近似值
 116            // 1/sqrt(x) = sqrt(1/x),但直接计算更快
 0117            long x = value.RawValue;
 118
 119            // 使用指数-尾数分解:x = m * 2^e
 120            // 1/sqrt(x) = 1/sqrt(m) * 2^(-e/2)
 0121            int log2 = 0;
 0122            long raw = x;
 0123            if ((raw >> 32) != 0L) { raw >>= 32; log2 += 32; }
 0124            if ((raw >> 16) != 0L) { raw >>= 16; log2 += 16; }
 0125            if ((raw >> 8) != 0L) { raw >>= 8; log2 += 8; }
 0126            if ((raw >> 4) != 0L) { raw >>= 4; log2 += 4; }
 0127            if ((raw >> 2) != 0L) { log2 += 2; }
 128
 129            // 归一化到 [1, 4) 范围
 0130            int exponent = log2 - 16;
 0131            long mantissa = x >> (exponent & ~1);
 0132            if (mantissa > 65536) mantissa >>= 1;
 133
 134            // 初始估计(查表或近似公式)
 135            // 对于 x 在 [1, 4),1/sqrt(x) 在 [0.5, 1]
 0136            long estimate = FP.ONE * 2 / (SqrtRaw(mantissa) >> 15);
 137
 138            // 牛顿迭代一次提高精度: y = y * (3 - x*y^2) / 2
 139            // 简化:使用查表结果已经足够用于 Normalize
 140
 141            // 应用指数调整
 0142            int resultExp = -(exponent >> 1);
 0143            if ((exponent & 1) != 0) // 奇数指数需要 sqrt(2) 补偿
 0144                estimate = (estimate * 46341) >> 16; // 46341 ≈ sqrt(2) * 32768
 145
 0146            return FP.FromRaw(estimate << resultExp);
 147        }
 148
 149        /// <summary>
 150        /// 获取平方根的指数-尾数分解(用于免除法归一化)
 151        /// <para>FrameSync 风格算法,纯整数实现</para>
 152        /// </summary>
 153        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 154        internal static SqrtDecomp GetSqrtDecomp(ulong x)
 155        {
 15156            if (x <= 65536UL)
 157            {
 3158                return new SqrtDecomp(
 3159                    exponent: 0,
 3160                    mantissa: FPSqrtLut.Table[x]);
 161            }
 162
 163            // 计算 log2(找最高有效位)
 12164            ulong raw = x;
 12165            int log2 = 0;
 166
 36167            if ((raw >> 32) != 0UL) { raw >>= 32; log2 += 32; }
 16168            if ((raw >> 16) != 0UL) { raw >>= 16; log2 += 16; }
 16169            if ((raw >> 8) != 0UL) { raw >>= 8; log2 += 8; }
 26170            if ((raw >> 4) != 0UL) { raw >>= 4; log2 += 4; }
 14171            if ((raw >> 2) != 0UL) { log2 += 2; }
 172
 12173            int exponent = log2 - 16 + 2;
 174
 12175            return new SqrtDecomp(
 12176                exponent: exponent >> 1,
 12177                mantissa: FPSqrtLut.Table[x >> exponent]);
 178        }
 179
 180        /// <summary>
 181        /// 快速归一化辅助:使用倒数乘法避免除法
 182        /// </summary>
 183        /// <remarks>
 184        /// FrameSync 优化技巧:1/sqrt(x) = 倒数近似
 185        /// </remarks>
 186        /// <param name="sqrmag">向量长度的平方(原始值,未移位)</param>
 187        /// <returns>(reciprocal, exponent) 用于乘法归一化</returns>
 188        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 189        internal static (long reciprocal, int shift) GetReciprocalForNormalize(ulong sqrmag)
 190        {
 15191            var sqrt = GetSqrtDecomp(sqrmag);
 192
 193            // 计算尾数的倒数:使用 2^44 / mantissa
 194            // 44 = 22 (sqrt 精度) + 16 (Q16.16) + 6 (额外精度)
 15195            long reciprocal = FPMathConstants.ReciprocalNormalizationFactor / sqrt.Mantissa;
 196
 197            // 计算位移量
 15198            int shift = 22 + sqrt.Exponent - 8;
 199
 15200            return (reciprocal, shift);
 201        }
 202
 203        #endregion
 204
 205        #region 常用数学函数
 206
 207        /// <summary>
 208        /// 符号函数:返回 -1, 0, 1
 209        /// </summary>
 210        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 211        public static int Sign(FP value)
 212        {
 4213            if (value.RawValue > 0) return 1;
 3214            if (value.RawValue < 0) return -1;
 1215            return 0;
 216        }
 217
 218        /// <summary>
 219        /// 取绝对值
 220        /// </summary>
 221        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 222        public static FP Abs(FP value)
 223        {
 5224            return value.RawValue < 0 ? new FP(-value.RawValue) : value;
 225        }
 226
 227        /// <summary>
 228        /// 取最小值
 229        /// </summary>
 230        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 231        public static FP Min(FP a, FP b)
 232        {
 3233            return a.RawValue < b.RawValue ? a : b;
 234        }
 235
 236        /// <summary>
 237        /// 取最大值
 238        /// </summary>
 239        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 240        public static FP Max(FP a, FP b)
 241        {
 3242            return a.RawValue > b.RawValue ? a : b;
 243        }
 244
 245        /// <summary>
 246        /// 限制在 [min, max] 范围
 247        /// </summary>
 248        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 249        public static FP Clamp(FP value, FP min, FP max)
 250        {
 7251            if (value.RawValue < min.RawValue) return min;
 6252            if (value.RawValue > max.RawValue) return max;
 4253            return value;
 254        }
 255
 256        /// <summary>
 257        /// 限制在 [0, 1] 范围
 258        /// </summary>
 259        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 260        public static FP Clamp01(FP value)
 261        {
 13262            if (value.RawValue < 0) return FP.Zero;
 13263            if (value.RawValue > FP.ONE) return FP.One;
 9264            return value;
 265        }
 266
 267        /// <summary>
 268        /// 线性插值(已限制 t 在 [0,1])
 269        /// </summary>
 270        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 271        public static FP Lerp(FP a, FP b, FP t)
 272        {
 4273            t = Clamp01(t);
 4274            return new FP(a.RawValue + ((b.RawValue - a.RawValue) * t.RawValue + 32768 >> 16));
 275        }
 276
 277        /// <summary>
 278        /// 线性插值(不限制 t)
 279        /// </summary>
 280        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 281        public static FP LerpUnclamped(FP a, FP b, FP t)
 282        {
 3283            return new FP(a.RawValue + ((b.RawValue - a.RawValue) * t.RawValue + 32768 >> 16));
 284        }
 285
 286        /// <summary>
 287        /// 向下取整
 288        /// </summary>
 289        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 290        public static FP Floor(FP value)
 291        {
 7292            return new FP(value.RawValue & -65536L);
 293        }
 294
 295        /// <summary>
 296        /// 向上取整
 297        /// </summary>
 298        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 299        public static FP Ceiling(FP value)
 300        {
 5301            if ((value.RawValue & 0xFFFF) != 0)
 5302                return new FP((value.RawValue & -65536L) + 65536);
 0303            return value;
 304        }
 305
 306        /// <summary>
 307        /// 四舍五入
 308        /// </summary>
 309        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 310        public static FP Round(FP value)
 311        {
 4312            long fractional = value.RawValue & 0xFFFF;
 4313            if (fractional < 32768)
 1314                return Floor(value);
 3315            if (fractional > 32768)
 1316                return Ceiling(value);
 317            // 正好是 0.5,向偶数取整
 2318            return (value.RawValue & 0x10000) != 0 ? Ceiling(value) : Floor(value);
 319        }
 320
 321        #endregion
 322
 323        #region 批量运算 API (P1 优化)
 324
 325        /// <summary>
 326        /// 批量归一化 - Cache 友好的批量处理
 327        /// <para>比逐个处理快 2-3 倍(更好的 Cache 命中率)</para>
 328        /// </summary>
 329        public static void NormalizeBatch(ReadOnlySpan<FPVector2> input, Span<FPVector2> output)
 330        {
 0331            if (input.Length > output.Length)
 0332                throw new ArgumentException("Output span must be at least as large as input span");
 333
 0334            for (int i = 0; i < input.Length; i++)
 335            {
 0336                output[i] = FPVector2.Normalize(input[i]);
 337            }
 0338        }
 339
 340        /// <summary>
 341        /// 批量归一化 3D 向量
 342        /// </summary>
 343        public static void NormalizeBatch(ReadOnlySpan<FPVector3> input, Span<FPVector3> output)
 344        {
 0345            if (input.Length > output.Length)
 0346                throw new ArgumentException("Output span must be at least as large as input span");
 347
 0348            for (int i = 0; i < input.Length; i++)
 349            {
 0350                output[i] = FPVector3.Normalize(input[i]);
 351            }
 0352        }
 353
 354        /// <summary>
 355        /// 批量计算点积
 356        /// </summary>
 357        public static void DotBatch(ReadOnlySpan<FPVector2> a, ReadOnlySpan<FPVector2> b, Span<FP> output)
 358        {
 0359            if (a.Length != b.Length || a.Length > output.Length)
 0360                throw new ArgumentException("Input spans must have same length and fit in output");
 361
 0362            for (int i = 0; i < a.Length; i++)
 363            {
 0364                output[i] = FPVector2.Dot(a[i], b[i]);
 365            }
 0366        }
 367
 368        /// <summary>
 369        /// 批量线性插值
 370        /// </summary>
 371        public static void LerpBatch(ReadOnlySpan<FP> a, ReadOnlySpan<FP> b, FP t, Span<FP> output)
 372        {
 1373            if (a.Length != b.Length || a.Length > output.Length)
 0374                throw new ArgumentException("Input spans must have same length and fit in output");
 375
 2376            for (int i = 0; i < a.Length; i++)
 377            {
 0378                output[i] = Lerp(a[i], b[i], t);
 379            }
 1380        }
 381
 382        /// <summary>
 383        /// 快速批量 Clamp(无分支)
 384        /// </summary>
 385        public static void ClampBatch(ReadOnlySpan<FP> input, FP min, FP max, Span<FP> output)
 386        {
 2387            if (input.Length > output.Length)
 1388                throw new ArgumentException("Output span must be at least as large as input");
 389
 1390            long minRaw = min.RawValue;
 1391            long maxRaw = max.RawValue;
 392
 4393            for (int i = 0; i < input.Length; i++)
 394            {
 1395                long val = input[i].RawValue;
 396                // 无分支 Clamp
 1397                val = val < minRaw ? minRaw : val;
 1398                val = val > maxRaw ? maxRaw : val;
 1399                output[i] = new FP(val);
 400            }
 1401        }
 402
 403        /// <summary>
 404        /// 预热 LUT 缓存,防止首次使用时的冷启动延迟
 405        /// <para>在游戏初始化时调用一次</para>
 406        /// </summary>
 407        public static void Warmup()
 408        {
 409            // 触发 LUT 静态初始化
 0410            _ = FPSqrtLut.Table[0];
 0411            _ = FPSinCosLut.SinFast[0];
 0412            _ = FPSinCosLut.CosFast[0];
 0413            _ = FPSinCosLut.SinAccurate[0];
 0414            _ = FPSinCosLut.CosAccurate[0];
 0415            _ = FPAcosLut.Table[0];
 0416            _ = FPAtanLut.Table[0];
 0417        }
 418
 419        #endregion
 420    }
 421}