| | | 1 | | // Copyright (c) 2026 Sideline Authors. All rights reserved. |
| | | 2 | | // Licensed under GPL-3.0. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | using Lattice.Core; |
| | | 7 | | |
| | | 8 | | namespace Lattice.ECS.Core |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// 确定性哈希计算 - 跨平台一致 |
| | | 12 | | /// </summary> |
| | | 13 | | public static class DeterministicHash |
| | | 14 | | { |
| | | 15 | | /// <summary>FNV-1a 32位哈希</summary> |
| | | 16 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 17 | | public static int Fnv1a32(ReadOnlySpan<byte> data) |
| | | 18 | | { |
| | | 19 | | const uint FnvPrime = 0x01000193; |
| | | 20 | | const uint FnvOffset = 0x811C9DC5; |
| | | 21 | | |
| | 0 | 22 | | uint hash = FnvOffset; |
| | 0 | 23 | | foreach (byte b in data) |
| | | 24 | | { |
| | 0 | 25 | | hash ^= b; |
| | 0 | 26 | | hash *= FnvPrime; |
| | | 27 | | } |
| | 0 | 28 | | return (int)hash; |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary>FNV-1a 64位哈希</summary> |
| | | 32 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 33 | | public static long Fnv1a64(ReadOnlySpan<byte> data) |
| | | 34 | | { |
| | | 35 | | const ulong FnvPrime = 0x00000100000001B3; |
| | | 36 | | const ulong FnvOffset = 0xCBF29CE484222325; |
| | | 37 | | |
| | 0 | 38 | | ulong hash = FnvOffset; |
| | 0 | 39 | | foreach (byte b in data) |
| | | 40 | | { |
| | 0 | 41 | | hash ^= b; |
| | 0 | 42 | | hash *= FnvPrime; |
| | | 43 | | } |
| | 0 | 44 | | return (long)hash; |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <summary>实体引用哈希</summary> |
| | | 48 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 49 | | public static int GetHashCode(EntityRef entity) |
| | | 50 | | { |
| | 0 | 51 | | return entity.Index * 59209 + entity.Version; |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <summary>组合哈希</summary> |
| | | 55 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 56 | | public static int Combine(int h1, int h2) |
| | | 57 | | { |
| | 0 | 58 | | uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27); |
| | 0 | 59 | | return ((int)rol5 + h1) ^ h2; |
| | | 60 | | } |
| | | 61 | | } |
| | | 62 | | } |