Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions com.unity.netcode.gameobjects/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Additional documentation and release notes are available at [Multiplayer Documen

### Fixed

- Issue where a time sync that arrived late could step a client's network time back, so the `NetworkTransform`s it owns sent no state updates until its time caught up again. A late time sync now slows the client's time down instead, and a `NetworkTransform` keeps sending with increasing ticks if the time does step back. (#4263)
- Issue where `NetworkAnimator` logged an error for a trigger-conditioned transition into an Exit node, and a client that joined during that transition, or during one into a sub-state machine, did not synchronize with it. Transitions that pass through Exit, Entry or sub-state machine nodes now resolve to the state they reach, and a late-joining client cross-fades from the matching originating state when several states transition into the same destination. (#4240)
- Fixed a NullReferenceException that would be thrown if a MonoBehaviour derived from NetworkManager defines it's own Awake or OnEnable. (#4237)
- Issue where `NetworkTime` reported a `TickOffset` of almost a whole tick, instead of zero, for some times that land on a tick (for example 0.3 at a tick rate of 10), which put `TickWithPartial` one tick ahead or, in long sessions, `Tick` one tick behind. Times between minus one tick and zero now report tick -1 with a positive `TickOffset`, as other negative times do. (#4227)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4797,11 +4797,16 @@ public void Remove()
/// </summary>
internal void TickUpdate()
{
// TODO FIX: The local NetworkTickSystem can invoke with the same network tick as before
if (CurrentTick <= m_LastTick)
if (CurrentTick == m_LastTick)
{
return;
}
// If the clock stepped back, keep sending with ticks above the last one sent:
// non-authority instances drop any state that is not newer than the last one they received.
if (CurrentTick < m_LastTick)
{
CurrentTick = m_LastTick + 1;
}
if (m_NetworkManager == null || m_NetworkManager.ShutdownInProgress || !m_NetworkManager.IsListening)
{
Remove();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,16 @@ public static NetworkTimeSystem ServerTimeSystem()
/// </summary>
/// <param name="deltaTimeSec">The amount of time to advance. The delta time which passed since Advance was last called.</param>
/// <returns>True if a hard reset of the time system occurred due to large time offset differences. False if normal time advancement occurred</returns>
/// <remarks>
/// A hard reset only moves time forward. When a sync puts the desired time more than <see cref="HardResetThresholdSec"/>
/// behind, time slows down by <see cref="AdjustmentRatio"/> instead.
/// </remarks>
public bool Advance(double deltaTimeSec)
{
return Advance(deltaTimeSec, false);
}

private bool Advance(double deltaTimeSec, bool allowBackwardReset)
{
m_PreviousTimeSec = m_TimeSec;
m_TimeSec += deltaTimeSec;
Expand All @@ -238,15 +247,26 @@ public bool Advance(double deltaTimeSec)
TickLatency = (int)Mathf.Max(2.0f, Mathf.Round(m_TickLatencyAverage));
}

if (Math.Abs(m_DesiredLocalTimeOffset - m_CurrentLocalTimeOffset) > HardResetThresholdSec || Math.Abs(m_DesiredServerTimeOffset - m_CurrentServerTimeOffset) > HardResetThresholdSec)
var localStep = m_DesiredLocalTimeOffset - m_CurrentLocalTimeOffset;
var serverStep = m_DesiredServerTimeOffset - m_CurrentServerTimeOffset;
if (!allowBackwardReset)
{
// A sync that arrives late (a resend, or one read after a long frame) makes the server look further behind
// than it is, so only a forward gap hard-resets.
localStep = Math.Max(localStep, 0.0);
serverStep = Math.Max(serverStep, 0.0);
}

if (Math.Abs(localStep) > HardResetThresholdSec || Math.Abs(serverStep) > HardResetThresholdSec)
{
m_TimeSec += m_DesiredServerTimeOffset;
var serverOffset = m_CurrentServerTimeOffset + serverStep;
m_TimeSec += serverOffset;

m_DesiredLocalTimeOffset -= m_DesiredServerTimeOffset;
m_CurrentLocalTimeOffset = m_DesiredLocalTimeOffset;
m_CurrentLocalTimeOffset += localStep - serverOffset;
m_DesiredLocalTimeOffset -= serverOffset;

m_DesiredServerTimeOffset = 0;
m_CurrentServerTimeOffset = 0;
m_DesiredServerTimeOffset -= serverOffset;

return true;
}
Expand All @@ -265,7 +285,7 @@ public bool Advance(double deltaTimeSec)
public void Reset(double serverTimeSec, double rttSec)
{
Sync(serverTimeSec, rttSec);
Advance(0);
Advance(0, true);
}
internal int SyncCount;
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,5 +185,65 @@ public void ResetTest()

});
}

/// <summary>
/// Validates that a sync putting the desired time more than the hard reset threshold behind, as a late
/// time sync does, slows time down rather than stepping it back.
/// </summary>
[Test]
public void LateSyncSlowsTimeInsteadOfSteppingBack()
{
const double deltaTime = 1.0d / 60.0d;
double receivedServerTime = 2;
var timeSystem = new NetworkTimeSystem(0.05d, 0.05d, 0.2d);
timeSystem.Reset(receivedServerTime, 0.1d);
timeSystem.Sync(receivedServerTime - 0.5d, 0.1d);

var expectedStep = deltaTime * (1.0d - timeSystem.AdjustmentRatio);
for (int i = 0; i < 60; i++)
{
var localTime = timeSystem.LocalTime;
var serverTime = timeSystem.ServerTime;
Assert.IsFalse(timeSystem.Advance(deltaTime), $"A sync behind the current time hard-reset the clock on frame {i}.");
Assert.AreEqual(expectedStep, timeSystem.LocalTime - localTime, 1e-9d, $"Local time did not slow down on frame {i}.");
Assert.AreEqual(expectedStep, timeSystem.ServerTime - serverTime, 1e-9d, $"Server time did not slow down on frame {i}.");
}
}

/// <summary>
/// Validates that a hard reset forward on server time leaves local time where it is when the same sync puts
/// local time behind, as it does when the RTT drops at the same time.
/// </summary>
[Test]
public void ForwardResetDoesNotStepLocalTimeBack()
{
const double deltaTime = 1.0d / 60.0d;
double receivedServerTime = 2;
var timeSystem = new NetworkTimeSystem(0.05d, 0.05d, 0.2d);
timeSystem.Reset(receivedServerTime, 2.0d);
var localTime = timeSystem.LocalTime;

// Server time 0.5s ahead with the half RTT down from 1s to 0.05s puts desired local time 0.45s behind.
receivedServerTime += 0.5d;
timeSystem.Sync(receivedServerTime, 0.1d);

Assert.IsTrue(timeSystem.Advance(deltaTime), "A sync 0.5s ahead did not hard-reset the clock.");
Assert.AreEqual(receivedServerTime + deltaTime - timeSystem.ServerBufferSec, timeSystem.ServerTime, 1e-9d);
Assert.AreEqual(localTime + deltaTime, timeSystem.LocalTime, 1e-9d, "Local time stepped back during the hard reset.");
}

/// <summary>
/// Validates that <see cref="NetworkTimeSystem.Reset"/> still sets the given time when it is earlier than the current one.
/// </summary>
[Test]
public void ResetCanStepTimeBack()
{
var timeSystem = new NetworkTimeSystem(0.05d, 0.05d, 0.2d);
timeSystem.Reset(2.0d, 0.1d);
timeSystem.Reset(1.0d, 0.1d);

Assert.AreEqual(1.0d - timeSystem.ServerBufferSec, timeSystem.ServerTime, 1e-9d);
Assert.AreEqual(1.0d + 0.05d + timeSystem.LocalBufferSec, timeSystem.LocalTime, 1e-9d);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using Unity.Netcode.Components;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;

namespace Unity.Netcode.RuntimeTests
{
/// <summary>
/// Validates that an owner authoritative <see cref="NetworkTransform"/> keeps sending state updates, with ticks
/// that keep increasing, after the owner's clock steps back.
/// </summary>
internal class NetworkTransformClockStepBackTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 1;

// Far enough back to cover several ticks at any tick rate the tests run with.
private const double k_StepBackSeconds = 0.5d;

// Well under the one second between time syncs, which would move the clock forward again.
private const float k_MoveSeconds = 0.3f;

private const int k_MinimumStatesAfterStepBack = 3;

private GameObject m_Prefab;

internal class StateTickRecorder : NetworkTransform
{
public readonly List<int> ReceivedTicks = new List<int>();

protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState)
{
ReceivedTicks.Add(newState.NetworkTick);
base.OnNetworkTransformStateUpdated(ref oldState, ref newState);
}
}

protected override void OnServerAndClientsCreated()
{
m_Prefab = CreateNetworkObjectPrefab("ClockStepBack");
var networkTransform = m_Prefab.AddComponent<StateTickRecorder>();
networkTransform.AuthorityMode = NetworkTransform.AuthorityModes.Owner;
base.OnServerAndClientsCreated();
}

[UnityTest]
public IEnumerator OwnerKeepsSendingAfterClockStepsBack()
{
var host = GetAuthorityNetworkManager();
var client = GetNonAuthorityNetworkManager();
var spawnedInstance = SpawnObject(m_Prefab, client);
yield return WaitForSpawnedOnAllOrTimeOut(spawnedInstance);
AssertOnTimeout($"Timed out waiting for {spawnedInstance.name} to spawn on all instances.");

var networkObjectId = spawnedInstance.GetComponent<NetworkObject>().NetworkObjectId;
var ownerInstance = client.SpawnManager.SpawnedObjects[networkObjectId].gameObject;
var hostInstance = host.SpawnManager.SpawnedObjects[networkObjectId].GetComponent<StateTickRecorder>();

var receivedAtSpawn = hostInstance.ReceivedTicks.Count;
yield return WaitForConditionOrTimeOut(() =>
{
ownerInstance.transform.position += Vector3.right * 0.1f;
return hostInstance.ReceivedTicks.Count > receivedAtSpawn;
});
AssertOnTimeout("Timed out waiting for the first state update from the owner.");

// A time sync just applied leaves about a second before the next one.
var syncCount = client.NetworkTimeSystem.SyncCount;
yield return WaitForConditionOrTimeOut(() =>
{
ownerInstance.transform.position += Vector3.right * 0.1f;
return client.NetworkTimeSystem.SyncCount != syncCount;
});
AssertOnTimeout("Timed out waiting for a time sync.");

var lastTickBeforeStepBack = hostInstance.ReceivedTicks[hostInstance.ReceivedTicks.Count - 1];
var receivedBeforeStepBack = hostInstance.ReceivedTicks.Count;
client.NetworkTimeSystem.Reset(client.ServerTime.Time - k_StepBackSeconds, client.NetworkTimeSystem.LastSyncedRttSec);

var endTime = Time.realtimeSinceStartup + k_MoveSeconds;
while (Time.realtimeSinceStartup < endTime)
{
ownerInstance.transform.position += Vector3.right * 0.1f;
yield return null;
}

var receivedAfterStepBack = hostInstance.ReceivedTicks.Count - receivedBeforeStepBack;
Assert.GreaterOrEqual(receivedAfterStepBack, k_MinimumStatesAfterStepBack,
$"The host received {receivedAfterStepBack} state updates in {k_MoveSeconds}s after the owner's clock stepped back.");

var previousTick = lastTickBeforeStepBack;
for (int i = receivedBeforeStepBack; i < hostInstance.ReceivedTicks.Count; i++)
{
Assert.Greater(hostInstance.ReceivedTicks[i], previousTick, $"State update {i} was sent with tick {hostInstance.ReceivedTicks[i]}, not after tick {previousTick}.");
previousTick = hostInstance.ReceivedTicks[i];
}
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading