Skip to content

Commit

Permalink
fixed phase progression and unity loop ticker.
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielWillett committed Oct 6, 2024
1 parent 018d250 commit e883341
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 48 deletions.
43 changes: 37 additions & 6 deletions UncreatedWarfare/Layouts/Layout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Uncreated.Warfare.Configuration;
using Uncreated.Warfare.Layouts.Phases;
using Uncreated.Warfare.Layouts.Teams;
using Uncreated.Warfare.Logging;
using Uncreated.Warfare.Util;

namespace Uncreated.Warfare.Layouts;
Expand Down Expand Up @@ -259,7 +261,7 @@ protected internal virtual async UniTask BeginLayoutAsync(CancellationToken toke
await MoveToNextPhase(token);
}

public virtual async UniTask<bool> MoveToNextPhase(CancellationToken token = default)
public virtual async UniTask MoveToNextPhase(CancellationToken token = default)
{
// keep moving to the next phase until one is activated by BeginPhase.
ILayoutPhase newPhase;
Expand All @@ -283,11 +285,27 @@ public virtual async UniTask<bool> MoveToNextPhase(CancellationToken token = def
{
string phaseTypeFormat = Accessor.Formatter.Format(oldPhase.GetType());
Logger.LogDebug("Ending phase: {0}.", phaseTypeFormat);
await oldPhase.EndPhaseAsync(token);
try
{
await oldPhase.EndPhaseAsync(token);
}
catch (Exception ex)
{
if (oldPhase.IsActive)
{
Logger.LogError(ex, "Error ending phase {0}.", phaseTypeFormat);
await _factory.StartNextLayout(CancellationToken.None);
throw new OperationCanceledException();
}

Logger.LogWarning(ex, "Error ending phase {0}.", phaseTypeFormat);
}

if (oldPhase.IsActive)
{
Logger.LogError("Failed to end phase {0}.", phaseTypeFormat);
return false;
await _factory.StartNextLayout(CancellationToken.None);
throw new OperationCanceledException();
}

await UniTask.SwitchToMainThread(token);
Expand All @@ -311,11 +329,24 @@ public virtual async UniTask<bool> MoveToNextPhase(CancellationToken token = def
}

Logger.LogDebug("Starting next phase: {0}.", Accessor.Formatter.Format(newPhase.GetType()));
await newPhase.BeginPhaseAsync(CancellationToken.None);

try
{
await newPhase.BeginPhaseAsync(CancellationToken.None);
}
catch (Exception ex)
{
if (!newPhase.IsActive)
{
Logger.LogError(ex, "Error beginning phase {0}.", Accessor.Formatter.Format(newPhase.GetType()));
await _factory.StartNextLayout(CancellationToken.None);
throw new OperationCanceledException();
}

Logger.LogWarning(ex, "Error beginning phase {0}.", Accessor.Formatter.Format(newPhase.GetType()));
}
}
while (!newPhase.IsActive);

return true;
}

private void CheckEmptyPhases()
Expand Down
17 changes: 9 additions & 8 deletions UncreatedWarfare/Layouts/Phases/Flags/FlagActionPhaseLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ public async UniTask InitializePhaseAsync(CancellationToken token = default)

_zoneStore = ActivatorUtilities.CreateInstance<ZoneStore>(_serviceProvider, [ zoneProviders, false ]);

await _zoneStore.Initialize(token);

// load pathing provider
IConfigurationSection config = Configuration.GetSection("PathingData");
IZonePathingProvider pathingProvider = (IZonePathingProvider)ReflectionUtility.CreateInstanceFixed(_serviceProvider, pathingProviderType, [ _zoneStore, this, config ]);
Expand All @@ -77,17 +79,13 @@ public async UniTask InitializePhaseAsync(CancellationToken token = default)
_logger.LogInformation("Zone path: {{{0}}}.", string.Join(" -> ", _pathingResult.Skip(1).SkipLast(1).Select(zone => zone.Name)));
}

public virtual async UniTask BeginPhaseAsync(CancellationToken token = default)
public virtual UniTask BeginPhaseAsync(CancellationToken token = default)
{
IsActive = true;

if (_pathingResult == null || _zoneStore == null)
{
throw new LayoutConfigurationException(this, "Unable to create zone path.");
}

await UniTask.SwitchToMainThread(token);

// create zones as objects with colliders

List<ActiveZoneCluster> zoneList = new List<ActiveZoneCluster>(_pathingResult.Count);
Expand All @@ -110,12 +108,13 @@ public virtual async UniTask BeginPhaseAsync(CancellationToken token = default)
ActiveZones = new ReadOnlyCollection<ActiveZoneCluster>(new ArraySegment<ActiveZoneCluster>(_zones, 1, _zones.Length - 2));
StartingTeam = _zones[0];
EndingTeam = _zones[^1];
IsActive = true;

return UniTask.CompletedTask;
}

public virtual async UniTask EndPhaseAsync(CancellationToken token = default)
public virtual UniTask EndPhaseAsync(CancellationToken token = default)
{
await UniTask.SwitchToMainThread(token);

// destroy collider objects
foreach (ActiveZoneCluster cluster in ActiveZones)
{
Expand All @@ -125,5 +124,7 @@ public virtual async UniTask EndPhaseAsync(CancellationToken token = default)
_zones = null;
ActiveZones = Array.Empty<ActiveZoneCluster>();
IsActive = false;

return UniTask.CompletedTask;
}
}
2 changes: 1 addition & 1 deletion UncreatedWarfare/Layouts/Phases/LeaderboardPhase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ public override async UniTask BeginPhaseAsync(CancellationToken token = default)
// todo show leaderboard and count-down timer
_ticker = _tickerFactory.CreateTicker(Duration, invokeImmediately: false, queueOnGameThread: true, (_, _, _) =>
{
UniTask.Create(() => _session.MoveToNextPhase(CancellationToken.None));
_ticker?.Dispose();
_ticker = null;
UniTask.Create(() => _session.MoveToNextPhase(CancellationToken.None));
});

await base.BeginPhaseAsync(token);
Expand Down
26 changes: 13 additions & 13 deletions UncreatedWarfare/Layouts/Phases/PreparationPhase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,20 @@ public PreparationPhase(IServiceProvider serviceProvider, IConfiguration config)
}

/// <inheritdoc />
public override async UniTask BeginPhaseAsync(CancellationToken token = default)
public override UniTask BeginPhaseAsync(CancellationToken token = default)
{
await UniTask.SwitchToMainThread(token);

StartBroadcastingStagingUI();

await base.BeginPhaseAsync(token);
return base.BeginPhaseAsync(token);
}

/// <inheritdoc />
public override async UniTask EndPhaseAsync(CancellationToken token = default)
public override UniTask EndPhaseAsync(CancellationToken token = default)
{
await UniTask.SwitchToMainThread(token);

_stagingUi.ClearFromAllPlayers();
_ticker?.Dispose();

await base.EndPhaseAsync(token);
return base.EndPhaseAsync(token);
}

/// <summary>
Expand Down Expand Up @@ -78,16 +74,20 @@ protected void StartBroadcastingStagingUI()
return;

// tick down the UI timer
_ticker = _tickerFactory.CreateTicker(TimeSpan.FromSeconds(1d), invokeImmediately: false, queueOnGameThread: true, (_, timeSinceStart, _) =>
_ticker = _tickerFactory.CreateTicker(TimeSpan.FromSeconds(1d), invokeImmediately: false, state: this, queueOnGameThread: true, static (ticker, timeSinceStart, _) =>
{
if (timeSinceStart >= Duration)
PreparationPhase phase = ticker.State!;
if (timeSinceStart >= phase.Duration)
{
_stagingUi.UpdateForAll(_translationService.SetOf.AllPlayers(), TimeSpan.Zero);
UniTask.Create(() => _session.MoveToNextPhase(CancellationToken.None));
phase._stagingUi.UpdateForAll(phase._translationService.SetOf.AllPlayers(), TimeSpan.Zero);
phase._ticker?.Dispose();
phase._ticker = null;
PreparationPhase phase2 = phase;
UniTask.Create(() => phase2._session.MoveToNextPhase(CancellationToken.None));
}
else
{
_stagingUi.UpdateForAll(_translationService.SetOf.AllPlayers(), Duration - timeSinceStart);
phase._stagingUi.UpdateForAll(phase._translationService.SetOf.AllPlayers(), phase.Duration - timeSinceStart);
}
});
}
Expand Down
3 changes: 2 additions & 1 deletion UncreatedWarfare/Logging/WarfareLoggingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

// ReSharper disable once CheckNamespace
namespace Uncreated.Warfare;

#if false
// this class is mostly copied from https://github.com/dotnet/extensions/blob/v3.1.0/src/Logging/Logging.Abstractions/src/LoggerExtensions.cs
public static class WarfareLoggingExtensions
{
Expand Down Expand Up @@ -422,3 +422,4 @@ private static string MessageFormatterMtd(WarfareFormattedLogValues state, Excep
return state.ToString();
}
}
#endif
13 changes: 12 additions & 1 deletion UncreatedWarfare/Proximity/ColliderProximity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,17 @@ private void SetupCollider()
_collider = boxCollider;
break;

case IAACylinderProximity cylinder:
transform.position = cylinder.Center;

CapsuleCollider capsuleCollider = gameObject.AddComponent<CapsuleCollider>();
capsuleCollider.center = Vector3.zero;
capsuleCollider.radius = cylinder.Radius;
capsuleCollider.height = cylinder.Height;
capsuleCollider.isTrigger = true;

break;

case ISphereProximity sphere:
BoundingSphere sphereInfo = sphere.Sphere;

Expand All @@ -90,8 +101,8 @@ private void SetupCollider()

MeshCollider meshCollider = gameObject.AddComponent<MeshCollider>();
meshCollider.sharedMesh = mesh;
meshCollider.isTrigger = true;
meshCollider.convex = true;
meshCollider.isTrigger = true;

_collider = meshCollider;
break;
Expand Down
Loading

0 comments on commit e883341

Please sign in to comment.