1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
| using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Animancer; using MemoryPack; using UnityEngine; using UnityEngine.Pool; using Wepie.Core.CircularBuffer;
namespace Character { [MemoryPackable] public partial struct TransformSnapshot { public long timestamp; public Vector3 position; public Quaternion rotation; public Vector3 velocity; public NetworkAnimationData[] animations; }
public class NetworkCharacterView : MonoBehaviour { [field: SerializeField] public CharacterAnimationLibrary characterAnimationLibrary { get; private set; } [field: SerializeField] public Animator animator { get; private set; } [field: SerializeField] public AnimancerComponent animancer { get; private set; } [field: SerializeField] public AnimationCallback animationCallback { get; private set; } [field: SerializeField] public Collider remoteCollider { get; private set; } [field: SerializeField] public CharacterConfig characterConfig { get; private set; }
private HashSet<AnimationClip> reusableClipSet = new HashSet<AnimationClip>();
private bool isLocalPlayer = false;
private CircularBuffer<TransformSnapshot> transformSnapshotBuffer = new CircularBuffer<TransformSnapshot>(16);
private const float InterpBackTime = 0.1f; private const float MaxExtrapolationTime = 0.25f; private const float SnapThreshold = 2.0f;
private Vector3 smoothedPosition; private Quaternion smoothedRotation; private bool initialized = false;
private const float MotionThreshold = 0.05f;
public void Setup(bool isLocalPlayer) { characterAnimationLibrary.Setup(); reusableClipSet = new HashSet<AnimationClip>(); if (isLocalPlayer) { Destroy(remoteCollider); } this.isLocalPlayer = isLocalPlayer; }
[MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnNetworkData(in NetworkCharacterData networkData, bool tickImmediately) { if (isLocalPlayer) return; var snapshot = new TransformSnapshot() { timestamp = networkData.timestamp, position = networkData.position, rotation = networkData.rotation, velocity = networkData.velocity, animations = networkData.animations.Count > 0 ? networkData.animations.ToArray() : Array.Empty<NetworkAnimationData>() }; transformSnapshotBuffer.PushBack(snapshot); }
private void Update() { if (isLocalPlayer) return;
double now = Time.realtimeSinceStartupAsDouble; double renderTimestamp = (now - InterpBackTime) * 1000.0;
if (transformSnapshotBuffer.Count == 0) return;
if (!initialized) { var first = transformSnapshotBuffer[0]; smoothedPosition = first.position; smoothedRotation = first.rotation; transform.position = smoothedPosition; transform.rotation = smoothedRotation; UpdateAnimation(first.animations); initialized = true; }
while (transformSnapshotBuffer.Count >= 2 && transformSnapshotBuffer[1].timestamp <= renderTimestamp) { transformSnapshotBuffer.PopFront(); }
if (transformSnapshotBuffer.Count >= 2) { var from = transformSnapshotBuffer[0]; var to = transformSnapshotBuffer[1]; double t0 = from.timestamp; double t1 = to.timestamp; float t = t1 > t0 ? Mathf.Clamp01((float)((renderTimestamp - t0) / (t1 - t0))) : 0f;
Vector3 interpPos = Vector3.Lerp(from.position, to.position, t); Quaternion interpRot = Quaternion.Slerp(from.rotation, to.rotation, t);
if ((smoothedPosition - interpPos).sqrMagnitude > SnapThreshold * SnapThreshold) smoothedPosition = interpPos; else smoothedPosition = Vector3.Lerp(smoothedPosition, interpPos, 0.5f);
smoothedRotation = Quaternion.Slerp(smoothedRotation, interpRot, 0.5f);
transform.position = smoothedPosition; transform.rotation = smoothedRotation;
bool fromMoving = from.velocity.sqrMagnitude > MotionThreshold * MotionThreshold; bool toIdle = to.velocity.sqrMagnitude <= MotionThreshold * MotionThreshold; if (fromMoving && toIdle && t < 1.0f) { UpdateAnimation(from.animations); } else { UpdateAnimation(to.animations); } } else { var last = transformSnapshotBuffer[0]; float dt = Mathf.Min((float)((renderTimestamp - last.timestamp) * 0.001f), MaxExtrapolationTime); Vector3 extrapolatedPos = last.position + last.velocity * dt; Quaternion extrapolatedRot = last.rotation;
if ((smoothedPosition - extrapolatedPos).sqrMagnitude > SnapThreshold * SnapThreshold) smoothedPosition = extrapolatedPos; else smoothedPosition = Vector3.Lerp(smoothedPosition, extrapolatedPos, 0.5f);
smoothedRotation = Quaternion.Slerp(smoothedRotation, extrapolatedRot, 0.5f);
transform.position = smoothedPosition; transform.rotation = smoothedRotation;
UpdateAnimation(last.animations); } }
private void UpdateAnimation(NetworkAnimationData[] animations) { reusableClipSet.Clear(); foreach (var animationData in animations) { var clip = characterAnimationLibrary.GetClip(animationData.animationId); if (clip != null) reusableClipSet.Add(clip); }
foreach (var animancerState in animancer.States) { if (!animancerState.IsPlaying) continue; bool found = reusableClipSet.Contains(animancerState.Clip); if (!found) { animancerState.Weight = 0; animancerState.Stop(); } }
foreach (var animationData in animations) { var clip = characterAnimationLibrary.GetClip(animationData.animationId); if (clip == null) continue; if (animancer.States.TryGet(clip, out var state)) { if (state.IsPlaying) continue; if (state.Speed == 0) { Debug.LogError("nicoier[角色]:反序列化异常 Animation speed is zero for clip: " + clip.name); state.Speed = 1.0f; }
state.Play(); continue; }
state = animancer.Play(clip); state.LayerIndex = animationData.avatarMaskId; float speed = animationData.speed; if (speed == 0) { Debug.LogError("nicoier[角色]:反序列化异常 Animation speed is zero for clip: " + clip.name); speed = 1.0f; }
state.Speed = speed; state.Weight = animationData.weight; state.Time = animationData.duration; }
Span<float> totalWeights = stackalloc float[animancer.Layers.Count]; foreach (var animancerState in animancer.States) { totalWeights[animancerState.LayerIndex] += animancerState.Weight; }
foreach (var animancerState in animancer.States) { if (!animancerState.IsPlaying) continue; if (animancerState.Weight == 0f) continue;
var totalWeight = totalWeights[animancerState.LayerIndex]; if (totalWeight > 0) { animancerState.Weight /= totalWeights[animancerState.LayerIndex]; } } }
public ArraySegment<NetworkAnimationData> DeSerializeAnimations(NetworkAnimationData[] reusedAnimations) { if (!isLocalPlayer) { throw new InvalidOperationException("nicoier[角色]:Only local player can serialize animations."); }
int count = 0; foreach (var animancerState in animancer.States) { if (animancerState.IsPlaying && animancerState.Weight > 0f && animancerState.Speed > 0f) { ++count; } }
Span<float> totalWeights = stackalloc float[animancer.Layers.Count]; foreach (var animancerState in animancer.States) { totalWeights[animancerState.LayerIndex] += animancerState.Weight; }
ArraySegment<NetworkAnimationData> segment = new ArraySegment<NetworkAnimationData>(reusedAnimations, 0, count); int index = 0;
foreach (var animancerState in animancer.States) { if (!animancerState.IsPlaying) continue; if (animancerState.Weight == 0f) continue;
bool thisLayerGreaterThanOne = totalWeights[animancerState.LayerIndex] > 1.0f; float weight = animancerState.Weight; if (thisLayerGreaterThanOne) { weight = animancerState.Weight / totalWeights[animancerState.LayerIndex]; }
var data = new NetworkAnimationData(); data.animationId = characterAnimationLibrary.GetAnimationId(animancerState.Clip); data.avatarMaskId = animancerState.LayerIndex; data.duration = animancerState.Duration; data.weight = weight; float speed = animancerState.Speed; if (speed == 0) { Debug.LogError("nicoier[角色]: 序列化异常 Animation speed is zero for clip: " + animancerState.Clip.name); speed = 1.0f; }
data.speed = speed; reusedAnimations[index] = data; ++index; }
return segment; }
public void Dispose() { } } }
|