From 51c767affc133abc93f516b4b0883a7249092e7d Mon Sep 17 00:00:00 2001 From: mischa Date: Thu, 17 Oct 2024 10:52:02 +0200 Subject: [PATCH] perf: sqr distance checks --- .../NetworkTransformHybrid2022.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformHybrid2022.cs b/Assets/Mirror/Components/NetworkTransform/NetworkTransformHybrid2022.cs index b0ca02d90..841e3a5dd 100644 --- a/Assets/Mirror/Components/NetworkTransform/NetworkTransformHybrid2022.cs +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformHybrid2022.cs @@ -96,6 +96,10 @@ public class NetworkTransformHybrid2022 : NetworkBehaviour [Range(0.00_01f, 1f)] // disallow 0 division. 1mm to 1m precision is enough range. public float scalePrecision = 0.01f; // 1 cm + // squared values for faster distance checks + float positionPrecisionSqr; + float scalePrecisionSqr; + // selective sync ////////////////////////////////////////////////////// [Header("Selective Sync & interpolation")] public bool syncPosition = true; @@ -127,6 +131,10 @@ protected virtual void OnValidate() // use sendRate instead of syncInterval for now syncInterval = 0; + // cache squared precisions + positionPrecisionSqr = positionPrecision * positionPrecision; + scalePrecisionSqr = scalePrecision * scalePrecision; + // obsolete clientAuthority compatibility: // if it was used, then set the new SyncDirection automatically. // if it wasn't used, then don't touch syncDirection. @@ -181,15 +189,18 @@ protected virtual void ApplySnapshot(TransformSnapshot interpolated) } // check if position / rotation / scale changed since last _full reliable_ sync. + // squared comparisons for performance protected virtual bool Changed(TransformSnapshot current) { - if (syncPosition && Vector3.Distance(last.position, current.position) >= positionPrecision) + // if (syncPosition && Vector3.Distance(last.position, current.position) >= positionPrecision) + if (syncPosition && (current.position - last.position).sqrMagnitude >= positionPrecisionSqr) return true; if (syncRotation && Quaternion.Angle(last.rotation, current.rotation) >= rotationPrecision) return true; - if (syncScale && Vector3.Distance(last.scale, current.scale) >= scalePrecision) + // if (syncScale && Vector3.Distance(last.scale, current.scale) >= scalePrecision) + if (syncScale && (current.scale - last.scale).sqrMagnitude >= scalePrecisionSqr) return true; return false;