Skip to content
This repository has been archived by the owner on Oct 20, 2021. It is now read-only.

Commit

Permalink
Worker Abstraction Update (#203)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jamie Brynes authored Jun 27, 2019
1 parent 1da5392 commit 689a835
Show file tree
Hide file tree
Showing 17 changed files with 521 additions and 422 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## Unreleased

### Changed

- Updated the worker connectors following the [refactor in the GDK](https://github.com/spatialos/gdk-for-unity/pull/981). [#203](https://github.com/spatialos/gdk-for-unity-fps-starter-project/pull/203).
- Refactored the simulated player flow to closer align with the worker connector changes mentioned above. [#203](https://github.com/spatialos/gdk-for-unity-fps-starter-project/pull/203)

## `0.2.3` - 2019-06-12

### Changed
Expand Down
2 changes: 1 addition & 1 deletion gdk.pinned
Original file line number Diff line number Diff line change
@@ -1 +1 @@
eae6cf5dcdb72655bde2121614001cdf1dde51bf
84243525d98aff511e7aa1f7703c37347017e386
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,10 @@ MonoBehaviour:
m_Name:
m_EditorClassIdentifier:
MaxConnectionAttempts: 3
DevelopmentAuthToken:
UseExternalIp: 0
TargetFrameRate: 30
mapTemplate: {fileID: 11400000, guid: f62fdf28a64923b4caf60e8249f24ed7, type: 2}
SimulatedPlayerWorkerConnector: {fileID: 1673159791827972, guid: 416b79ec2ab48a14b94f5d11fe45403f,
type: 3}
DefaultSimulatedPlayerCount: 1
DefaultSimulatedPlayerCreationInterval: 5
SimulatedPlayerDevAuthTokenId:
SimulatedPlayerTargetDeployment:
MaxSimulatedPlayerCount: 1
SimulatedPlayerCreationInterval: 5
UseSessionFlow: 0
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public override void Tick()
return;
}

if (!Blackboard.ClientConnector.HasConnected())
if (!Blackboard.ClientConnector.HasConnected)
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public override void StartState()

public override void Tick()
{
if (!Blackboard.ClientConnector.HasConnected())
if (!Blackboard.ClientConnector.HasConnected)
{
return;
}
Expand Down
11 changes: 3 additions & 8 deletions workers/unity/Assets/Fps/Scripts/MetricSendSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Fps
{
public class MetricSendSystem : ComponentSystem
{
private Connection connection;
private WorkerSystem worker;

private DateTime timeOfNextUpdate;
private DateTime timeOfLastUpdate;
Expand All @@ -31,7 +31,7 @@ public class MetricSendSystem : ComponentSystem
protected override void OnCreate()
{
base.OnCreate();
connection = World.GetExistingSystem<WorkerSystem>().Connection;
worker = World.GetExistingSystem<WorkerSystem>();

targetFps = Application.targetFrameRate == -1
? DefaultTargetFrameRate
Expand All @@ -46,19 +46,14 @@ protected override void OnCreate()

protected override void OnUpdate()
{
if (connection == null)
{
return;
}

if (DateTime.Now >= timeOfNextUpdate)
{
CalculateFps();
WorkerMetrics.GaugeMetrics["Dynamic.FPS"] = calculatedFps;
WorkerMetrics.GaugeMetrics["Unity used heap size"] = GC.GetTotalMemory(false);
WorkerMetrics.Load = CalculateLoad();

connection.SendMetrics(WorkerMetrics);
worker.SendMetrics(WorkerMetrics);

timeOfLastUpdate = DateTime.Now;
timeOfNextUpdate = timeOfLastUpdate.AddSeconds(TimeBetweenMetricUpdatesSecs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class AdvancedEntityPipeline : IEntityGameObjectCreator

private readonly IEntityGameObjectCreator fallback;
private readonly string workerIdAttribute;
private readonly Worker worker;
private readonly WorkerInWorld worker;

private readonly Dictionary<EntityId, GameObject> gameObjectsCreated = new Dictionary<EntityId, GameObject>();

Expand All @@ -34,7 +34,7 @@ public class AdvancedEntityPipeline : IEntityGameObjectCreator
typeof(Rigidbody)
};

public AdvancedEntityPipeline(Worker worker, string authPlayer, string nonAuthPlayer,
public AdvancedEntityPipeline(WorkerInWorld worker, string authPlayer, string nonAuthPlayer,
IEntityGameObjectCreator fallback)
{
this.worker = worker;
Expand Down
129 changes: 95 additions & 34 deletions workers/unity/Assets/Fps/Scripts/SetupLogic/ClientWorkerConnector.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Improbable.Gdk.Core;
using UnityEngine;
using Improbable.Gdk.GameObjectCreation;
using Improbable.Gdk.PlayerLifecycle;
using Improbable.Worker.CInterop;
using Improbable.Worker.CInterop.Alpha;
using Unity.Entities;
using UnityEngine;

namespace Fps
{
public class ClientWorkerConnector : WorkerConnectorBase
{
private string deployment;
protected string deployment;

private string playerName;
private bool isReadyToSpawn;
private bool wantsSpawn;
private Action<PlayerCreator.CreatePlayer.ReceivedResponse> onPlayerResponse;
private AdvancedEntityPipeline entityPipeline;

public bool HasConnected => Worker != null;
protected bool UseSessionFlow => !string.IsNullOrEmpty(deployment);

public event Action OnLostPlayerEntity;
Expand All @@ -38,21 +40,11 @@ public void SpawnPlayer(string playerName, Action<PlayerCreator.CreatePlayer.Rec
wantsSpawn = true;
}

public bool HasConnected()
{
return Worker != null;
}

public void DisconnectPlayer()
{
StartCoroutine(PrepareDestroy());
}

protected override string GetWorkerType()
{
return WorkerUtils.UnityClient;
}

protected virtual string GetAuthPlayerPrefabPath()
{
return "Prefabs/UnityClient/Authoritative/Player";
Expand All @@ -63,36 +55,51 @@ protected virtual string GetNonAuthPlayerPrefabPath()
return "Prefabs/UnityClient/NonAuthoritative/Player";
}

protected override AlphaLocatorConfig GetAlphaLocatorConfig(string workerType)
protected override IConnectionHandlerBuilder GetConnectionHandlerBuilder()
{
return UseSessionFlow
? GetAlphaLocatorConfigViaDevAuthFlow(workerType)
: base.GetAlphaLocatorConfig(workerType);
}
var connectionParams = new ConnectionParameters
{
DefaultComponentVtable = new ComponentVtable(),
WorkerType = WorkerUtils.UnityClient
};

var builder = new SpatialOSConnectionHandlerBuilder()
.SetConnectionParameters(connectionParams);

protected override string SelectLoginToken(List<LoginTokenDetails> loginTokens)
{
if (UseSessionFlow)
{
foreach (var loginToken in loginTokens)
{
if (loginToken.DeploymentName == deployment)
{
return loginToken.LoginToken;
}
}
connectionParams.Network.UseExternalIp = true;
builder.SetConnectionFlow(new ChosenDeploymentAlphaLocatorFlow(deployment,
new SessionConnectionFlowInitializer(new CommandLineConnectionFlowInitializer())));
}
else
else if (Application.isEditor)
{
return base.SelectLoginToken(loginTokens);
builder.SetConnectionFlow(new ReceptionistFlow(CreateNewWorkerId(WorkerUtils.UnityClient)));
}
else
{
var initializer = new CommandLineConnectionFlowInitializer();

throw new ArgumentException("Was not able to connect to deployment.");
}
switch (initializer.GetConnectionService())
{
case ConnectionService.Receptionist:
builder.SetConnectionFlow(new ReceptionistFlow(CreateNewWorkerId(WorkerUtils.UnityClient),
initializer));
break;
case ConnectionService.Locator:
connectionParams.Network.UseExternalIp = true;
builder.SetConnectionFlow(new LocatorFlow(initializer));
break;
case ConnectionService.AlphaLocator:
connectionParams.Network.UseExternalIp = true;
builder.SetConnectionFlow(new AlphaLocatorFlow(initializer));
break;
default:
throw new ArgumentOutOfRangeException();
}
}

protected override ConnectionService GetConnectionService()
{
return UseSessionFlow ? ConnectionService.AlphaLocator : base.GetConnectionService();
return builder;
}

protected override void HandleWorkerConnectionEstablished()
Expand Down Expand Up @@ -169,4 +176,58 @@ private void SendRequest()
.RequestPlayerCreation(serializedArgs, onPlayerResponse);
}
}

internal class ChosenDeploymentAlphaLocatorFlow : AlphaLocatorFlow
{
private readonly string targetDeployment;

public ChosenDeploymentAlphaLocatorFlow(string targetDeployment,
IConnectionFlowInitializer<AlphaLocatorFlow> initializer = null) : base(initializer)
{
this.targetDeployment = targetDeployment;
}

protected override string SelectLoginToken(List<LoginTokenDetails> loginTokens)
{
var token = loginTokens.FirstOrDefault(loginToken => loginToken.DeploymentName == targetDeployment);

return token.LoginToken ?? throw new ArgumentException("Was not able to connect to deployment");
}
}

internal class SessionConnectionFlowInitializer : IConnectionFlowInitializer<AlphaLocatorFlow>
{
private IConnectionFlowInitializer<AlphaLocatorFlow> initializer;

public SessionConnectionFlowInitializer(IConnectionFlowInitializer<AlphaLocatorFlow> standaloneInitializer)
{
initializer = standaloneInitializer;
}

public void Initialize(AlphaLocatorFlow flow)
{
if (Application.isEditor)
{
if (PlayerPrefs.HasKey(RuntimeConfigNames.DevAuthTokenKey))
{
flow.DevAuthToken = PlayerPrefs.GetString(RuntimeConfigNames.DevAuthTokenKey);
return;
}

var textAsset = Resources.Load<TextAsset>("DevAuthToken");

if (textAsset == null)
{
throw new MissingReferenceException("Unable to find DevAuthToken.txt in the Resources folder. " +
"You can generate one via SpatialOS > Generate Dev Authentication Token.");
}

flow.DevAuthToken = textAsset.text;
}
else
{
initializer.Initialize(flow);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using System.Collections;
using UnityEngine;
using Improbable.Gdk.Core;
using Improbable.Gdk.GameObjectCreation;
using Improbable.Gdk.Guns;
using Improbable.Gdk.Health;
using Improbable.Gdk.PlayerLifecycle;
using UnityEngine;

namespace Fps
{
Expand All @@ -17,9 +18,22 @@ protected override async void Start()
await AttemptConnect();
}

protected override string GetWorkerType()
protected override IConnectionHandlerBuilder GetConnectionHandlerBuilder()
{
return WorkerUtils.UnityGameLogic;
var builder = new SpatialOSConnectionHandlerBuilder()
.SetConnectionParameters(CreateConnectionParameters(WorkerUtils.UnityGameLogic));

if (Application.isEditor)
{
builder.SetConnectionFlow(new ReceptionistFlow(CreateNewWorkerId(WorkerUtils.UnityGameLogic)));
}
else
{
builder.SetConnectionFlow(new ReceptionistFlow(CreateNewWorkerId(WorkerUtils.UnityGameLogic),
new CommandLineConnectionFlowInitializer()));
}

return builder;
}

protected override void HandleWorkerConnectionEstablished()
Expand Down
Loading

0 comments on commit 689a835

Please sign in to comment.