Restore the stable legacy Unity project

This commit is contained in:
Meta Vens 2026-08-10 14:57:50 +01:00
commit 7006a6b0dd
2070 changed files with 180490 additions and 169303 deletions

View file

@ -1,7 +1,8 @@
using System;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using GameCult.Mesh;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
using TMPro;
using UniRx.Triggers;
using UnityEngine;
@ -18,16 +19,12 @@ public class ActionBarSlot : MonoBehaviour
public ObservablePointerEnterTrigger PointerEnterTrigger;
public ObservablePointerExitTrigger PointerExitTrigger;
private ActionBarBinding binding;
public string ControlPath { get; set; }
public ActionBarBinding Binding
{
get => binding;
set
{
if (ReferenceEquals(binding, value))
return;
binding = value;
if (binding == null)
{
@ -39,99 +36,90 @@ public class ActionBarSlot : MonoBehaviour
}
}
private void OnDestroy()
{
Binding = null;
}
private void Update()
{
Binding?.Update();
}
public SavedActionBarBinding Save()
{
return Binding switch
{
ActionBarConsumableBinding actionBarConsumableBinding => new SavedActionBarConsumableBinding
{
Target = new DatabaseLink<ConsumableItemData>{LinkID = actionBarConsumableBinding.Target.ID}
},
ActionBarGearBinding actionBarGearBinding => new SavedActionBarGearBinding
{
EquipmentIndex = actionBarGearBinding.Entity.Equipment.IndexOf(actionBarGearBinding.Item),
BehaviorIndex = Array.IndexOf(actionBarGearBinding.Item.Behaviors, actionBarGearBinding.Behavior)
},
ActionBarWeaponGroupBinding actionBarWeaponGroupBinding => new SavedActionBarWeaponGroupBinding
{
Group = actionBarWeaponGroupBinding.Group
},
_ => null
};
}
public void Restore(SavedActionBarBinding binding, Entity entity)
{
Binding = binding switch
{
SavedActionBarConsumableBinding savedActionBarConsumableBinding =>
new ActionBarConsumableBinding(
entity,
this,
savedActionBarConsumableBinding.Target.Value),
SavedActionBarGearBinding savedActionBarGearBinding =>
new ActionBarGearBinding(
entity,
this,
entity.Equipment[savedActionBarGearBinding.EquipmentIndex],
entity.Equipment[savedActionBarGearBinding.EquipmentIndex]
.Behaviors[savedActionBarGearBinding.BehaviorIndex] as IActivatedBehavior),
SavedActionBarWeaponGroupBinding savedActionBarWeaponGroupBinding =>
new ActionBarWeaponGroupBinding(entity, this, savedActionBarWeaponGroupBinding.Group),
_ => null
};
}
}
public abstract class ActionBarBinding
{
private static AetheriaClientState s_runtimeState;
public Entity Entity { get; }
private readonly Func<AetheriaControl> _resolveControl;
protected ActionBarSlot Slot { get; }
protected GameSettings Settings { get; }
public abstract void Activate();
public abstract void Deactivate();
public abstract void Update();
protected ActionBarBinding(
Entity entity,
ActionBarSlot slot,
Func<AetheriaControl> resolveControl,
GameSettings settings)
public ActionBarBinding(Entity entity, ActionBarSlot slot)
{
Entity = entity;
Slot = slot;
_resolveControl = resolveControl ?? (() => null);
Settings = settings;
}
protected bool TrySubmit(Action<AetheriaControl> submit, string label)
{
if (submit == null)
return false;
try
{
var control = _resolveControl();
if (control == null)
return false;
submit(control);
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to send Aetheria daemon action-bar {label} operation; operation not submitted: {ex.Message}");
return false;
}
}
protected AetheriaRuntimeCatalogItem FindCatalogItem(ItemInstance item)
{
try
{
s_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-action-bar");
return s_runtimeState.Catalog.Latest()?.FindItem(item, x => x.ItemKey);
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to bind Aetheria runtime catalog for action-bar binding: {ex.Message}");
return null;
}
}
}
public class ActionBarConsumableBinding : ActionBarBinding
{
public AetheriaRuntimeCatalogItem Target { get; }
public ConsumableItemData Target;
public ActionBarConsumableBinding(
Entity entity,
ActionBarSlot slot,
Func<AetheriaControl> resolveControl,
GameSettings settings,
AetheriaRuntimeCatalogItem target) : base(entity, slot, resolveControl, settings)
public ActionBarConsumableBinding(Entity entity, ActionBarSlot slot, ConsumableItemData target) : base(entity, slot)
{
Target = target;
Slot.QuantityRemaining.gameObject.SetActive(true);
Slot.Label.gameObject.SetActive(false);
Slot.Icon.gameObject.SetActive(false);
var data = Target;
if(!string.IsNullOrEmpty(data.Icon))
{
Slot.Label.gameObject.SetActive(false);
Slot.Icon.gameObject.SetActive(true);
Slot.Icon.texture = Resources.Load<Texture2D>(data.Icon.Substring("Assets/Resources/".Length).Split('.').First());
}
else Slot.Icon.gameObject.SetActive(false);
}
public override void Activate()
{
TrySubmit(
operations => operations.ActivateConsumable(TargetItemKey),
"consumable");
Entity.TryActivateConsumable(Target);
}
public override void Deactivate()
@ -140,20 +128,11 @@ public class ActionBarConsumableBinding : ActionBarBinding
public override void Update()
{
Slot.QuantityRemaining.text = $"{Entity.CountItemsInCargo(TargetItemKey)}";
if (string.IsNullOrWhiteSpace(TargetItemKey))
{
Slot.Fill.fillAmount = 0;
return;
}
var instance = Entity.FindActiveConsumable(TargetItemKey);
Slot.QuantityRemaining.text = $"{Entity.CountItemsInCargo(Target.ID)}";
var instance = Entity.FindActiveConsumable(Target);
if (instance == null) Slot.Fill.fillAmount = 0;
else Slot.Fill.fillAmount = instance.RemainingDuration / instance.Duration;
else Slot.Fill.fillAmount = instance.RemainingDuration / instance.Data.Duration;
}
public string TargetItemKey => Target?.ItemKey ?? "";
}
public class ActionBarGearBinding : ActionBarBinding
@ -163,75 +142,31 @@ public class ActionBarGearBinding : ActionBarBinding
public bool Active;
public int EquipmentIndex => Entity?.Equipment?.IndexOf(Item) ?? -1;
public int BehaviorIndex => Item?.Behaviors == null ? -1 : Array.IndexOf(Item.Behaviors, Behavior);
public string TargetItemKey => Item?.EquippableItem?.ItemKey ?? "";
public ActionBarGearBinding(
Entity entity,
ActionBarSlot slot,
Func<AetheriaControl> resolveControl,
GameSettings settings,
EquippedItem item,
IActivatedBehavior behavior) : base(entity, slot, resolveControl, settings)
public ActionBarGearBinding(Entity entity, ActionBarSlot slot, EquippedItem item, IActivatedBehavior behavior) : base(entity, slot)
{
Item = item;
var data = item.EquippableItem.Data.Value as EquippableItemData;
Behavior = behavior;
Slot.QuantityRemaining.gameObject.SetActive(false);
Slot.Icon.gameObject.SetActive(true);
Slot.Label.gameObject.SetActive(false);
Slot.Icon.texture = ResolveIconTexture();
}
private Texture2D ResolveIconTexture()
{
var typedItem = FindCatalogItem(Item.EquippableItem);
if (typedItem != null)
{
var actionBarIcon = LoadActionBarIcon(typedItem.ActionBarIcon);
if (actionBarIcon != null)
return actionBarIcon;
if (Enum.TryParse<WeaponType>(typedItem.WeaponType, out var weaponType))
return Settings.GetIcon(weaponType).texture;
if (Enum.TryParse<HardpointType>(typedItem.HardpointType, out var hardpointType))
return Settings.GetIcon(hardpointType).texture;
}
return Settings.GetIcon(HardpointType.Tool).texture;
}
private static Texture2D LoadActionBarIcon(string path)
{
if (string.IsNullOrWhiteSpace(path))
return null;
const string resourcesPrefix = "Assets/Resources/";
var resourcePath = path.StartsWith(resourcesPrefix, StringComparison.Ordinal)
? path.Substring(resourcesPrefix.Length)
: path;
resourcePath = resourcePath.Split('.').First();
return Resources.Load<Texture2D>(resourcePath);
if (!string.IsNullOrEmpty(Item.Data.ActionBarIcon))
Slot.Icon.texture = Resources.Load<Texture2D>(Item.Data.ActionBarIcon.Substring("Assets/Resources/".Length).Split('.').First());
else if (data is WeaponItemData weaponItemData)
Slot.Icon.texture = ActionGameManager.Instance.Settings.GetIcon(weaponItemData.WeaponType).texture;
else Slot.Icon.texture = ActionGameManager.Instance.Settings.GetIcon(data.HardpointType).texture;
}
public override void Activate()
{
Active = true;
TrySubmit(
operations => operations.SetBehaviorActive(EquipmentIndex, BehaviorIndex, true),
"behavior activation");
Behavior.Activate();
}
public override void Deactivate()
{
Active = false;
TrySubmit(
operations => operations.SetBehaviorActive(EquipmentIndex, BehaviorIndex, false),
"behavior activation");
Behavior.Deactivate();
}
public override void Update()
@ -240,16 +175,12 @@ public class ActionBarGearBinding : ActionBarBinding
}
}
[MessagePackObject]
public class ActionBarWeaponGroupBinding : ActionBarBinding
{
public int Group;
[Key(0)] public int Group;
public ActionBarWeaponGroupBinding(
Entity entity,
ActionBarSlot slot,
Func<AetheriaControl> resolveControl,
GameSettings settings,
int group) : base(entity, slot, resolveControl, settings)
public ActionBarWeaponGroupBinding(Entity entity, ActionBarSlot slot, int group) : base(entity, slot)
{
Group = group;
slot.Label.gameObject.SetActive(true);
@ -259,20 +190,22 @@ public class ActionBarWeaponGroupBinding : ActionBarBinding
public override void Activate()
{
TrySubmit(
operations => operations.SetWeaponGroupActive(Group, true),
"weapon-group");
foreach (var weapon in Entity.WeaponGroups[Group].weapons)
{
weapon.Activate();
}
}
public override void Deactivate()
{
TrySubmit(
operations => operations.SetWeaponGroupActive(Group, false),
"weapon-group");
foreach (var weapon in Entity.WeaponGroups[Group].weapons)
{
weapon.Deactivate();
}
}
public override void Update()
{
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,266 +0,0 @@
using System.Collections.Generic;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
using UnityEngine.Rendering;
public sealed class AetheriaDaemonIndirectRenderer : MonoBehaviour
{
[SerializeField]
private AetheriaDaemonObserver observer;
[SerializeField]
private AetheriaDaemonRenderAssetCatalog assetCatalog;
[SerializeField]
private bool logMissingAssets;
[SerializeField]
private Camera targetCamera;
private MaterialPropertyBlock _properties;
private readonly Dictionary<int, AetheriaDaemonRenderGroupBatch> _batchesByGroupId =
new Dictionary<int, AetheriaDaemonRenderGroupBatch>();
private readonly HashSet<int> _seenGroupIds = new HashSet<int>();
private readonly List<int> _staleGroupIds = new List<int>();
private readonly List<AetheriaRuntimeDaemonRenderGroupDocument> _visibleRenderGroups =
new List<AetheriaRuntimeDaemonRenderGroupDocument>();
private readonly Vector3[] _frustumCorners = new Vector3[8];
private static readonly int MatrixBufferPropertyId =
Shader.PropertyToID(AetheriaDaemonRenderBuffer.MatrixBufferPropertyName);
private static readonly int InstanceCountPropertyId =
Shader.PropertyToID(AetheriaDaemonRenderBuffer.InstanceCountPropertyName);
public int LastDrawnCount { get; private set; }
public bool HasDrawTarget =>
observer != null &&
assetCatalog != null;
private void Reset()
{
observer = GetComponent<AetheriaDaemonObserver>();
}
private void LateUpdate()
{
DrawLatest();
}
public bool DrawLatest()
{
LastDrawnCount = 0;
if (!HasDrawTarget)
{
return false;
}
if (!observer.HasRenderNativeView)
{
return false;
}
_properties ??= new MaterialPropertyBlock();
var drewAny = false;
var index = observer.LastSoaIndex;
var view = observer.LastRenderNativeView;
_seenGroupIds.Clear();
var renderGroups = QueryRenderGroups(index);
foreach (var renderGroup in renderGroups)
{
_seenGroupIds.Add(renderGroup.GroupId);
if (!TryResolveMesh(renderGroup, out var mesh) ||
!TryResolveMaterial(renderGroup, out var material))
{
if (logMissingAssets)
{
Debug.LogWarning(
$"Could not resolve daemon render group {renderGroup.GroupId} " +
$"mesh='{renderGroup.MeshKey}' material='{renderGroup.MaterialKey}'.");
}
continue;
}
if (!_batchesByGroupId.TryGetValue(renderGroup.GroupId, out var batch))
{
batch = new AetheriaDaemonRenderGroupBatch();
_batchesByGroupId.Add(renderGroup.GroupId, batch);
}
if (batch.LastUploadedGeneration != view.Generation)
{
batch.UploadLatest(view, renderGroup, mesh, renderGroup.DefaultScale);
}
if (!batch.HasGpuBuffers)
{
continue;
}
_properties.Clear();
_properties.SetInt(InstanceCountPropertyId, batch.InstanceCount);
_properties.SetBuffer(MatrixBufferPropertyId, batch.MatrixBuffer);
Graphics.DrawMeshInstancedIndirect(
mesh,
renderGroup.SubMeshIndex,
material,
GetDrawBounds(renderGroup),
batch.IndirectArgsBuffer,
0,
_properties,
GetShadowCastingMode(renderGroup),
renderGroup.ReceiveShadows,
renderGroup.Layer,
targetCamera);
LastDrawnCount += batch.InstanceCount;
drewAny = true;
}
ReleaseStaleBatches();
return drewAny;
}
private IReadOnlyList<AetheriaRuntimeDaemonRenderGroupDocument> QueryRenderGroups(
AetheriaRuntimeDaemonSoaViewIndex index)
{
if (!TryGetCameraQueryBounds(out var min, out var max))
{
return index.RenderGroups;
}
AetheriaRuntimeDaemonRenderQueries.QueryRenderGroups(
index,
min.x,
min.y,
min.z,
max.x,
max.y,
max.z,
_visibleRenderGroups);
return _visibleRenderGroups;
}
private bool TryGetCameraQueryBounds(out Vector3 min, out Vector3 max)
{
var camera = targetCamera != null ? targetCamera : Camera.main;
if (camera == null || !camera.enabled)
{
min = default;
max = default;
return false;
}
var near = Mathf.Max(0.0f, camera.nearClipPlane);
var far = Mathf.Max(near, camera.farClipPlane);
_frustumCorners[0] = camera.ViewportToWorldPoint(new Vector3(0, 0, near));
_frustumCorners[1] = camera.ViewportToWorldPoint(new Vector3(1, 0, near));
_frustumCorners[2] = camera.ViewportToWorldPoint(new Vector3(0, 1, near));
_frustumCorners[3] = camera.ViewportToWorldPoint(new Vector3(1, 1, near));
_frustumCorners[4] = camera.ViewportToWorldPoint(new Vector3(0, 0, far));
_frustumCorners[5] = camera.ViewportToWorldPoint(new Vector3(1, 0, far));
_frustumCorners[6] = camera.ViewportToWorldPoint(new Vector3(0, 1, far));
_frustumCorners[7] = camera.ViewportToWorldPoint(new Vector3(1, 1, far));
min = _frustumCorners[0];
max = _frustumCorners[0];
for (var i = 1; i < _frustumCorners.Length; i++)
{
min = Vector3.Min(min, _frustumCorners[i]);
max = Vector3.Max(max, _frustumCorners[i]);
}
return true;
}
private Bounds GetDrawBounds(AetheriaRuntimeDaemonRenderGroupDocument renderGroup)
{
return new Bounds(
new Vector3(
renderGroup.BoundsCenterX,
renderGroup.BoundsCenterY,
renderGroup.BoundsCenterZ),
new Vector3(
renderGroup.BoundsSizeX,
renderGroup.BoundsSizeY,
renderGroup.BoundsSizeZ));
}
private static ShadowCastingMode GetShadowCastingMode(AetheriaRuntimeDaemonRenderGroupDocument renderGroup)
{
switch (renderGroup.ShadowMode)
{
case AetheriaRuntimeDaemonRenderShadowModes.Off:
return ShadowCastingMode.Off;
case AetheriaRuntimeDaemonRenderShadowModes.TwoSided:
return ShadowCastingMode.TwoSided;
case AetheriaRuntimeDaemonRenderShadowModes.ShadowsOnly:
return ShadowCastingMode.ShadowsOnly;
default:
return ShadowCastingMode.On;
}
}
private void OnDisable()
{
foreach (var batch in _batchesByGroupId.Values)
{
batch.Dispose();
}
_batchesByGroupId.Clear();
_seenGroupIds.Clear();
}
private void ReleaseStaleBatches()
{
if (_batchesByGroupId.Count == _seenGroupIds.Count)
{
return;
}
_staleGroupIds.Clear();
foreach (var groupId in _batchesByGroupId.Keys)
{
if (!_seenGroupIds.Contains(groupId))
{
_staleGroupIds.Add(groupId);
}
}
for (var i = 0; i < _staleGroupIds.Count; i++)
{
var groupId = _staleGroupIds[i];
_batchesByGroupId[groupId].Dispose();
_batchesByGroupId.Remove(groupId);
}
_staleGroupIds.Clear();
}
private bool TryResolveMesh(AetheriaRuntimeDaemonRenderGroupDocument renderGroup, out Mesh mesh)
{
if (renderGroup?.MeshAsset != null &&
!string.IsNullOrWhiteSpace(renderGroup.MeshAsset.AssetKey) &&
assetCatalog.TryResolveMesh(renderGroup.MeshAsset, out mesh))
{
return true;
}
mesh = null;
return false;
}
private bool TryResolveMaterial(AetheriaRuntimeDaemonRenderGroupDocument renderGroup, out Material material)
{
if (renderGroup?.MaterialAsset != null &&
!string.IsNullOrWhiteSpace(renderGroup.MaterialAsset.AssetKey) &&
assetCatalog.TryResolveMaterial(renderGroup.MaterialAsset, out material))
{
return true;
}
material = null;
return false;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 66b38a2f45120a041941eae4412f7da1

View file

@ -1,168 +0,0 @@
using System;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
public sealed class AetheriaDaemonObserver : MonoBehaviour
{
[SerializeField]
private bool pollInUpdate = true;
[SerializeField]
private float pollIntervalSeconds = 0.05f;
[SerializeField]
private bool logChanges;
[SerializeField]
private string clientId = "unity-observer";
private readonly AetheriaRuntimeDaemonObservationCursor _cursor = new AetheriaRuntimeDaemonObservationCursor();
private float _nextPollTime;
private AetheriaDaemonSoaMemoryMap _soaMemoryMap;
private AetheriaDaemonRenderNativeView _renderNativeView;
private AetheriaUnityDaemonRenderDocuments _renderDocuments;
public AetheriaRuntimeDaemonRenderView LastRenderView { get; private set; }
public AetheriaRuntimeDaemonObservationResult LastObservation { get; private set; }
public long LastFrameId => _cursor.LastFrameId;
public long LastSoaGeneration => _cursor.LastSoaGeneration;
public bool HasAuthoritativeState => LastRenderView != null && LastRenderView.IsAuthoritative;
public bool HasSoaView => LastRenderView != null && LastRenderView.HasSoaView;
public AetheriaRuntimeDaemonSoaViewIndex LastSoaIndex =>
LastRenderView?.SoaIndex ?? AetheriaRuntimeDaemonSoaViewIndex.Empty;
public AetheriaDaemonSoaMemoryMap LastSoaMemoryMap => _soaMemoryMap;
public AetheriaDaemonRenderNativeView LastRenderNativeView => _renderNativeView;
public bool HasRenderNativeView => _renderNativeView.IsCreated;
public event Action<AetheriaRuntimeDaemonRenderView, AetheriaRuntimeDaemonObservationResult> DaemonRenderViewChanged;
private void Update()
{
if (!pollInUpdate || Time.unscaledTime < _nextPollTime)
{
return;
}
_nextPollTime = Time.unscaledTime + Mathf.Max(0.001f, pollIntervalSeconds);
Poll();
}
public bool Poll()
{
var observed = ReadDaemonRenderView();
if (observed == null)
{
LastObservation = _cursor.Observe(null);
return false;
}
var result = _cursor.Observe(observed);
LastRenderView = observed;
LastObservation = result;
if (result.SoaViewChanged)
{
RemapSoaView(observed);
}
if (result.Changed)
{
DaemonRenderViewChanged?.Invoke(observed, result);
if (logChanges)
{
Debug.Log(
$"Observed Aetheria daemon frame {result.FrameId} " +
$"soa generation {result.SoaGeneration} authoritative={result.IsAuthoritative}");
}
}
return true;
}
public void ResetObservation()
{
_cursor.Reset();
DisposeRenderViewDocuments();
DisposeSoaMemoryMap();
LastRenderView = null;
LastObservation = null;
}
private void OnDisable()
{
DisposeRenderViewDocuments();
DisposeSoaMemoryMap();
}
private AetheriaRuntimeDaemonRenderView ReadDaemonRenderView()
{
try
{
EnsureRenderViewDocuments();
return _renderDocuments?.Current;
}
catch
{
return null;
}
}
private void EnsureRenderViewDocuments()
{
if (_renderDocuments != null)
{
return;
}
var stateBoot = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
if (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists)
{
throw new InvalidOperationException(
$"Aetheria daemon observer requires a readable managed Verse target: {stateBoot.FailureMessage}");
}
_renderDocuments = AetheriaUnityRuntimeClientProvider.DaemonRenderDocuments(stateBoot, clientId);
}
private void RemapSoaView(AetheriaRuntimeDaemonRenderView observed)
{
DisposeSoaMemoryMap();
if (observed == null || !observed.HasSoaView)
{
return;
}
if (AetheriaDaemonSoaMemoryMap.TryOpen(observed.SoaIndex, out var map, out var error))
{
_soaMemoryMap = map;
if (!AetheriaDaemonRenderNativeView.TryCreate(observed.SoaIndex, map, out _renderNativeView))
{
_renderNativeView = default;
if (logChanges)
{
Debug.LogWarning("Mapped Aetheria daemon SoA memory, but no complete render native view was published.");
}
}
return;
}
if (logChanges)
{
Debug.LogWarning($"Could not map Aetheria daemon SoA view read-only: {error}");
}
}
private void DisposeSoaMemoryMap()
{
_renderNativeView = default;
_soaMemoryMap?.Dispose();
_soaMemoryMap = null;
}
private void DisposeRenderViewDocuments()
{
_renderDocuments?.Dispose();
_renderDocuments = null;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 4f5008a2876ee014fb9e442f1f6103e0

View file

@ -1,118 +0,0 @@
using System;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
[CreateAssetMenu(
fileName = "AetheriaDaemonRenderAssetCatalog",
menuName = "Aetheria/Daemon Render Asset Catalog")]
public sealed class AetheriaDaemonRenderAssetCatalog : ScriptableObject
{
[SerializeField]
private MeshEntry[] meshes = Array.Empty<MeshEntry>();
[SerializeField]
private MaterialEntry[] materials = Array.Empty<MaterialEntry>();
[SerializeField]
private TextureEntry[] textures = Array.Empty<TextureEntry>();
public bool TryResolveMesh(string key, out Mesh mesh)
{
mesh = null;
if (string.IsNullOrWhiteSpace(key))
{
return false;
}
for (var i = 0; i < meshes.Length; i++)
{
if (string.Equals(meshes[i].Key, key, StringComparison.Ordinal))
{
mesh = meshes[i].Mesh;
return mesh != null;
}
}
return false;
}
public bool TryResolveMesh(AetheriaRuntimeAssetRef asset, out Mesh mesh)
{
return TryResolveMesh(ResolveLocalKey(asset), out mesh);
}
public bool TryResolveMaterial(string key, out Material material)
{
material = null;
if (string.IsNullOrWhiteSpace(key))
{
return false;
}
for (var i = 0; i < materials.Length; i++)
{
if (string.Equals(materials[i].Key, key, StringComparison.Ordinal))
{
material = materials[i].Material;
return material != null;
}
}
return false;
}
public bool TryResolveMaterial(AetheriaRuntimeAssetRef asset, out Material material)
{
return TryResolveMaterial(ResolveLocalKey(asset), out material);
}
public bool TryResolveTexture(AetheriaRuntimeAssetRef asset, out Texture2D texture)
{
texture = null;
var key = ResolveLocalKey(asset);
if (string.IsNullOrWhiteSpace(key))
{
return false;
}
for (var i = 0; i < textures.Length; i++)
{
if (string.Equals(textures[i].Key, key, StringComparison.Ordinal))
{
texture = textures[i].Texture;
return texture != null;
}
}
return false;
}
private static string ResolveLocalKey(AetheriaRuntimeAssetRef asset)
{
if (asset == null)
return "";
return string.IsNullOrWhiteSpace(asset.AssetKey) ? asset.Uri ?? "" : asset.AssetKey;
}
[Serializable]
private struct MeshEntry
{
public string Key;
public Mesh Mesh;
}
[Serializable]
private struct MaterialEntry
{
public string Key;
public Material Material;
}
[Serializable]
private struct TextureEntry
{
public string Key;
public Texture2D Texture;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 8fa370b1ea2904d40ae295007ac76b48

View file

@ -1,292 +0,0 @@
using GameCult.Aetheria.State.Verse;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
public sealed class AetheriaDaemonRenderBuffer : MonoBehaviour
{
public const string MatrixBufferPropertyName = "_AetheriaObjectToWorld";
public const string InstanceCountPropertyName = "_AetheriaInstanceCount";
private const int MatrixStrideBytes = 64;
private const int DrawMeshInstancedIndirectArgsCount = 5;
[SerializeField]
private AetheriaDaemonObserver observer;
[SerializeField]
private Mesh indirectArgsMesh;
[SerializeField]
private int innerLoopBatchCount = 64;
[SerializeField]
private bool updateInLateUpdate;
private readonly uint[] _indirectArgs = new uint[DrawMeshInstancedIndirectArgsCount];
private NativeArray<float4x4> _nativeMatrices;
private GraphicsBuffer _matrixBuffer;
private GraphicsBuffer _indirectArgsBuffer;
private long _allocatedGeneration = long.MinValue;
private int _allocatedCount;
public GraphicsBuffer MatrixBuffer => _matrixBuffer;
public GraphicsBuffer IndirectArgsBuffer => _indirectArgsBuffer;
public int InstanceCount { get; private set; }
public long LastUploadedFrameId { get; private set; }
public long LastUploadedGeneration { get; private set; }
public bool HasRenderableView => observer != null && observer.HasRenderNativeView;
public bool HasGpuBuffers =>
_matrixBuffer != null &&
_matrixBuffer.IsValid() &&
InstanceCount > 0;
private static readonly int MatrixBufferPropertyId = Shader.PropertyToID(MatrixBufferPropertyName);
private static readonly int InstanceCountPropertyId = Shader.PropertyToID(InstanceCountPropertyName);
private void Reset()
{
observer = GetComponent<AetheriaDaemonObserver>();
}
private void LateUpdate()
{
if (updateInLateUpdate)
{
UploadLatest();
}
}
public bool UploadLatest()
{
return UploadLatest(indirectArgsMesh);
}
public bool UploadLatest(Mesh argsMesh)
{
return UploadLatest(argsMesh, -1);
}
public bool UploadLatest(Mesh argsMesh, int renderGroupId)
{
return UploadLatest(argsMesh, renderGroupId, 0);
}
public bool UploadLatest(Mesh argsMesh, int renderGroupId, int subMeshIndex)
{
if (!HasRenderableView)
{
InstanceCount = 0;
UpdateIndirectArgs(null, 0);
return false;
}
var view = observer.LastRenderNativeView;
EnsureCapacity(view);
if (!_nativeMatrices.IsCreated || _nativeMatrices.Length == 0)
{
InstanceCount = 0;
UpdateIndirectArgs(argsMesh, 0);
return false;
}
var index = observer.LastSoaIndex;
var defaultScale = ResolveDefaultScale(index, renderGroupId);
var renderLod = ResolveRenderLod(index, renderGroupId);
var count = renderGroupId >= 0 && view.HasRenderGroupId
? BuildRenderGroupMatrices(view, renderGroupId, renderLod, defaultScale)
: BuildAllMatrices(view, renderLod, defaultScale);
_matrixBuffer.SetData(_nativeMatrices, 0, 0, count);
InstanceCount = count;
LastUploadedFrameId = view.FrameId;
LastUploadedGeneration = view.Generation;
UpdateIndirectArgs(argsMesh, count, subMeshIndex);
return true;
}
private int BuildAllMatrices(AetheriaDaemonRenderNativeView view, int renderLod, float defaultScale)
{
if (view.HasRenderVisibility || renderLod >= 0)
{
return BuildCompactedMatrices(view, -1, renderLod, defaultScale);
}
var count = math.min(view.Count, _nativeMatrices.Length);
var handle = view.ScheduleBuildRenderMatrices(
_nativeMatrices,
defaultScale,
innerLoopBatchCount);
handle.Complete();
return count;
}
private int BuildRenderGroupMatrices(
AetheriaDaemonRenderNativeView view,
int renderGroupId,
int renderLod,
float defaultScale)
{
return BuildCompactedMatrices(view, renderGroupId, renderLod, defaultScale);
}
private int BuildCompactedMatrices(
AetheriaDaemonRenderNativeView view,
int renderGroupId,
int renderLod,
float defaultScale)
{
using var writtenCount = new NativeArray<int>(1, Allocator.TempJob);
var job = new AetheriaDaemonRenderGroupMatrixJob
{
Position = view.Position,
RotationRadians = view.RotationRadians,
PhysicsBodyRadius = view.PhysicsBodyRadius,
RenderScale = view.RenderScale,
RenderVisibility = view.RenderVisibility,
RenderLod = view.RenderLod,
RenderGroupId = view.RenderGroupId,
Matrices = _nativeMatrices,
WrittenCount = writtenCount,
TargetRenderGroupId = renderGroupId >= 0 ? (uint)renderGroupId : 0,
TargetRenderLod = renderLod,
HasRotation = view.HasRotation,
HasPhysicsRadius = view.HasPhysicsRadius,
HasRenderScale = view.HasRenderScale,
HasRenderVisibility = view.HasRenderVisibility,
HasRenderLod = view.HasRenderLod,
HasRenderGroupFilter = renderGroupId >= 0,
HasRenderLodFilter = renderLod >= 0,
UniformScale = defaultScale
};
job.Schedule().Complete();
return math.clamp(writtenCount[0], 0, _nativeMatrices.Length);
}
private static float ResolveDefaultScale(AetheriaRuntimeDaemonSoaViewIndex index, int renderGroupId)
{
if (index != null &&
renderGroupId >= 0 &&
index.TryGetRenderGroup(renderGroupId, out var renderGroup))
{
return math.max(renderGroup.DefaultScale, 0.0001f);
}
var renderGroups = index?.RenderGroups;
if (renderGroups != null && renderGroups.Count == 1)
{
return math.max(renderGroups[0].DefaultScale, 0.0001f);
}
return 1.0f;
}
private static int ResolveRenderLod(AetheriaRuntimeDaemonSoaViewIndex index, int renderGroupId)
{
if (index != null &&
renderGroupId >= 0 &&
index.TryGetRenderGroup(renderGroupId, out var renderGroup))
{
return renderGroup.Lod;
}
var renderGroups = index?.RenderGroups;
if (renderGroups != null && renderGroups.Count == 1)
{
return renderGroups[0].Lod;
}
return -1;
}
public void ApplyTo(MaterialPropertyBlock properties)
{
if (properties == null)
{
return;
}
properties.SetInt(InstanceCountPropertyId, InstanceCount);
if (HasGpuBuffers)
{
properties.SetBuffer(MatrixBufferPropertyId, _matrixBuffer);
}
}
private void OnDisable()
{
ReleaseBuffers();
InstanceCount = 0;
LastUploadedFrameId = 0;
LastUploadedGeneration = 0;
}
private void EnsureCapacity(AetheriaDaemonRenderNativeView view)
{
var count = math.max(0, view.Count);
if (_nativeMatrices.IsCreated &&
_allocatedGeneration == view.Generation &&
_allocatedCount == count)
{
return;
}
ReleaseBuffers();
_allocatedGeneration = view.Generation;
_allocatedCount = count;
if (count <= 0)
{
return;
}
_nativeMatrices = new NativeArray<float4x4>(
count,
Allocator.Persistent,
NativeArrayOptions.UninitializedMemory);
_matrixBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, count, MatrixStrideBytes);
_indirectArgsBuffer = new GraphicsBuffer(
GraphicsBuffer.Target.IndirectArguments,
DrawMeshInstancedIndirectArgsCount,
sizeof(uint));
}
private void UpdateIndirectArgs(Mesh mesh, int instanceCount)
{
UpdateIndirectArgs(mesh, instanceCount, 0);
}
private void UpdateIndirectArgs(Mesh mesh, int instanceCount, int subMeshIndex)
{
if (_indirectArgsBuffer == null || !_indirectArgsBuffer.IsValid())
{
return;
}
var safeSubMeshIndex = mesh != null
? math.clamp(subMeshIndex, 0, math.max(0, mesh.subMeshCount - 1))
: 0;
_indirectArgs[0] = mesh != null ? mesh.GetIndexCount(safeSubMeshIndex) : 0;
_indirectArgs[1] = (uint)math.max(0, instanceCount);
_indirectArgs[2] = mesh != null ? mesh.GetIndexStart(safeSubMeshIndex) : 0;
_indirectArgs[3] = mesh != null ? mesh.GetBaseVertex(safeSubMeshIndex) : 0;
_indirectArgs[4] = 0;
_indirectArgsBuffer.SetData(_indirectArgs);
}
private void ReleaseBuffers()
{
if (_nativeMatrices.IsCreated)
{
_nativeMatrices.Dispose();
}
_matrixBuffer?.Release();
_matrixBuffer = null;
_indirectArgsBuffer?.Release();
_indirectArgsBuffer = null;
_allocatedGeneration = long.MinValue;
_allocatedCount = 0;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 9cba277ef259bee438796ab4c0f3df64

View file

@ -1,175 +0,0 @@
using System;
using GameCult.Aetheria.State.Verse;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
public sealed class AetheriaDaemonRenderGroupBatch : IDisposable
{
private const int MatrixStrideBytes = 64;
private const int DrawMeshInstancedIndirectArgsCount = 5;
private readonly uint[] _indirectArgs = new uint[DrawMeshInstancedIndirectArgsCount];
private NativeArray<float4x4> _nativeMatrices;
private GraphicsBuffer _matrixBuffer;
private GraphicsBuffer _indirectArgsBuffer;
private int _capacity;
public int GroupId { get; private set; }
public int InstanceCount { get; private set; }
public long LastUploadedFrameId { get; private set; }
public long LastUploadedGeneration { get; private set; }
public GraphicsBuffer MatrixBuffer => _matrixBuffer;
public GraphicsBuffer IndirectArgsBuffer => _indirectArgsBuffer;
public bool HasGpuBuffers =>
_matrixBuffer != null &&
_matrixBuffer.IsValid() &&
_indirectArgsBuffer != null &&
_indirectArgsBuffer.IsValid() &&
InstanceCount > 0;
public bool UploadLatest(
AetheriaDaemonRenderNativeView view,
AetheriaRuntimeDaemonRenderGroupDocument renderGroup,
Mesh mesh,
float uniformScale)
{
if (!view.IsCreated || mesh == null)
{
InstanceCount = 0;
UpdateIndirectArgs(mesh, 0, renderGroup?.SubMeshIndex ?? 0);
return false;
}
var targetCapacity = renderGroup.InstanceCount >= 0
? math.min(renderGroup.InstanceCount, view.Count)
: view.Count;
EnsureCapacity(targetCapacity);
if (!_nativeMatrices.IsCreated || _nativeMatrices.Length == 0)
{
InstanceCount = 0;
UpdateIndirectArgs(mesh, 0, renderGroup.SubMeshIndex);
return false;
}
var count = view.HasRenderGroupId
? BuildRenderGroupMatrices(view, renderGroup.GroupId, renderGroup.Lod, uniformScale)
: BuildAllMatrices(view, renderGroup.Lod, uniformScale);
_matrixBuffer.SetData(_nativeMatrices, 0, 0, count);
GroupId = renderGroup.GroupId;
InstanceCount = count;
LastUploadedFrameId = view.FrameId;
LastUploadedGeneration = view.Generation;
UpdateIndirectArgs(mesh, count, renderGroup.SubMeshIndex);
return count > 0;
}
public void Dispose()
{
if (_nativeMatrices.IsCreated)
{
_nativeMatrices.Dispose();
}
_matrixBuffer?.Release();
_matrixBuffer = null;
_indirectArgsBuffer?.Release();
_indirectArgsBuffer = null;
_capacity = 0;
InstanceCount = 0;
}
private int BuildAllMatrices(AetheriaDaemonRenderNativeView view, int renderLod, float uniformScale)
{
return BuildCompactedMatrices(view, -1, renderLod, uniformScale);
}
private int BuildRenderGroupMatrices(
AetheriaDaemonRenderNativeView view,
int renderGroupId,
int renderLod,
float uniformScale)
{
return BuildCompactedMatrices(view, renderGroupId, renderLod, uniformScale);
}
private int BuildCompactedMatrices(
AetheriaDaemonRenderNativeView view,
int renderGroupId,
int renderLod,
float uniformScale)
{
using var writtenCount = new NativeArray<int>(1, Allocator.TempJob);
var job = new AetheriaDaemonRenderGroupMatrixJob
{
Position = view.Position,
RotationRadians = view.RotationRadians,
PhysicsBodyRadius = view.PhysicsBodyRadius,
RenderScale = view.RenderScale,
RenderVisibility = view.RenderVisibility,
RenderLod = view.RenderLod,
RenderGroupId = view.RenderGroupId,
Matrices = _nativeMatrices,
WrittenCount = writtenCount,
TargetRenderGroupId = renderGroupId >= 0 ? (uint)renderGroupId : 0,
TargetRenderLod = renderLod,
HasRotation = view.HasRotation,
HasPhysicsRadius = view.HasPhysicsRadius,
HasRenderScale = view.HasRenderScale,
HasRenderVisibility = view.HasRenderVisibility,
HasRenderLod = view.HasRenderLod,
HasRenderGroupFilter = renderGroupId >= 0,
HasRenderLodFilter = renderLod >= 0,
UniformScale = uniformScale
};
job.Schedule().Complete();
return math.clamp(writtenCount[0], 0, _nativeMatrices.Length);
}
private void EnsureCapacity(int capacity)
{
capacity = math.max(0, capacity);
if (_nativeMatrices.IsCreated && _capacity == capacity)
{
return;
}
Dispose();
_capacity = capacity;
if (capacity <= 0)
{
return;
}
_nativeMatrices = new NativeArray<float4x4>(
capacity,
Allocator.Persistent,
NativeArrayOptions.UninitializedMemory);
_matrixBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, capacity, MatrixStrideBytes);
_indirectArgsBuffer = new GraphicsBuffer(
GraphicsBuffer.Target.IndirectArguments,
DrawMeshInstancedIndirectArgsCount,
sizeof(uint));
}
private void UpdateIndirectArgs(Mesh mesh, int instanceCount, int subMeshIndex)
{
if (_indirectArgsBuffer == null || !_indirectArgsBuffer.IsValid())
{
return;
}
var safeSubMeshIndex = mesh != null
? math.clamp(subMeshIndex, 0, math.max(0, mesh.subMeshCount - 1))
: 0;
_indirectArgs[0] = mesh != null ? mesh.GetIndexCount(safeSubMeshIndex) : 0;
_indirectArgs[1] = (uint)math.max(0, instanceCount);
_indirectArgs[2] = mesh != null ? mesh.GetIndexStart(safeSubMeshIndex) : 0;
_indirectArgs[3] = mesh != null ? mesh.GetBaseVertex(safeSubMeshIndex) : 0;
_indirectArgs[4] = 0;
_indirectArgsBuffer.SetData(_indirectArgs);
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 0038a222765ff82468c22a516cfcdbc1

View file

@ -1,86 +0,0 @@
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
[BurstCompile]
public struct AetheriaDaemonRenderGroupMatrixJob : IJob
{
[ReadOnly]
public NativeArray<float3> Position;
[ReadOnly]
public NativeArray<float> RotationRadians;
[ReadOnly]
public NativeArray<float> PhysicsBodyRadius;
[ReadOnly]
public NativeArray<float> RenderScale;
[ReadOnly]
public NativeArray<byte> RenderVisibility;
[ReadOnly]
public NativeArray<int> RenderLod;
[ReadOnly]
public NativeArray<uint> RenderGroupId;
[WriteOnly]
public NativeArray<float4x4> Matrices;
public NativeArray<int> WrittenCount;
public uint TargetRenderGroupId;
public int TargetRenderLod;
public bool HasRotation;
public bool HasPhysicsRadius;
public bool HasRenderScale;
public bool HasRenderVisibility;
public bool HasRenderLod;
public bool HasRenderGroupFilter;
public bool HasRenderLodFilter;
public float UniformScale;
public void Execute()
{
var written = 0;
for (var index = 0; index < Position.Length; index++)
{
if (HasRenderGroupFilter && RenderGroupId[index] != TargetRenderGroupId)
{
continue;
}
if (HasRenderVisibility && RenderVisibility[index] == 0)
{
continue;
}
if (HasRenderLodFilter && (!HasRenderLod || RenderLod[index] != TargetRenderLod))
{
continue;
}
if (written >= Matrices.Length)
{
break;
}
var position = Position[index];
var rotation = HasRotation
? quaternion.RotateY(RotationRadians[index])
: quaternion.identity;
var scaleValue = HasRenderScale
? math.max(RenderScale[index], 0.0001f)
: HasPhysicsRadius
? math.max(PhysicsBodyRadius[index] * 2.0f, 0.0001f)
: math.max(UniformScale, 0.0001f);
Matrices[written] = float4x4.TRS(position, rotation, new float3(scaleValue));
written++;
}
WrittenCount[0] = written;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 146aa8d6d00cc1a44b44a5f83d69edea

View file

@ -1,43 +0,0 @@
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
[BurstCompile]
public struct AetheriaDaemonRenderMatrixJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<float3> Position;
[ReadOnly]
public NativeArray<float> RotationRadians;
[ReadOnly]
public NativeArray<float> PhysicsBodyRadius;
[ReadOnly]
public NativeArray<float> RenderScale;
[WriteOnly]
public NativeArray<float4x4> Matrices;
public bool HasRotation;
public bool HasPhysicsRadius;
public bool HasRenderScale;
public float UniformScale;
public void Execute(int index)
{
var position = Position[index];
var rotation = HasRotation
? quaternion.RotateY(RotationRadians[index])
: quaternion.identity;
var scaleValue = HasRenderScale
? math.max(RenderScale[index], 0.0001f)
: HasPhysicsRadius
? math.max(PhysicsBodyRadius[index] * 2.0f, 0.0001f)
: math.max(UniformScale, 0.0001f);
Matrices[index] = float4x4.TRS(position, rotation, new float3(scaleValue));
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: f6b3b3dc2e2a29245a24b772e2cb87b4

View file

@ -1,248 +0,0 @@
using GameCult.Aetheria.State.Verse;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
public struct AetheriaDaemonRenderNativeView
{
public long FrameId;
public long Generation;
public int Count;
public NativeArray<int> EntityIndex;
public NativeArray<float3> Position;
public NativeArray<float> RotationRadians;
public NativeArray<float3> Velocity;
public NativeArray<float> PhysicsBodyRadius;
public NativeArray<float> PhysicsBodyMass;
public NativeArray<float> PhysicsBodyInverseMass;
public NativeArray<float> RenderScale;
public NativeArray<byte> RenderVisibility;
public NativeArray<int> RenderLod;
public NativeArray<uint> RenderGroupId;
public bool IsCreated =>
Count > 0 &&
Position.IsCreated;
public bool HasRotation => RotationRadians.IsCreated;
public bool HasEntityIndex => EntityIndex.IsCreated;
public bool HasVelocity => Velocity.IsCreated;
public bool HasPhysicsRadius => PhysicsBodyRadius.IsCreated;
public bool HasPhysicsMass => PhysicsBodyMass.IsCreated;
public bool HasPhysicsInverseMass => PhysicsBodyInverseMass.IsCreated;
public bool HasRenderScale => RenderScale.IsCreated;
public bool HasRenderVisibility => RenderVisibility.IsCreated;
public bool HasRenderLod => RenderLod.IsCreated;
public bool HasRenderGroupId => RenderGroupId.IsCreated;
public JobHandle ScheduleBuildRenderMatrices(
NativeArray<float4x4> matrices,
float uniformScale = 1.0f,
int innerLoopBatchCount = 64,
JobHandle dependsOn = default)
{
if (!IsCreated)
{
return dependsOn;
}
var count = math.min(Count, matrices.IsCreated ? matrices.Length : 0);
if (count <= 0)
{
return dependsOn;
}
var job = new AetheriaDaemonRenderMatrixJob
{
Position = Position,
RotationRadians = RotationRadians,
PhysicsBodyRadius = PhysicsBodyRadius,
RenderScale = RenderScale,
Matrices = matrices,
HasRotation = HasRotation,
HasPhysicsRadius = HasPhysicsRadius,
HasRenderScale = HasRenderScale,
UniformScale = uniformScale
};
return job.Schedule(count, math.max(1, innerLoopBatchCount), dependsOn);
}
public static bool TryCreate(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,
out AetheriaDaemonRenderNativeView view)
{
view = default;
if (index == null || map == null)
{
return false;
}
if (!map.TryCreateFirstNativeArrayOfKind(
index,
AetheriaRuntimeDaemonSoaColumnKinds.Position,
out view.Position))
{
view = default;
return false;
}
view.Count = view.Position.Length;
TryAssignOptionalIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.EntityIndex, view.Count, out view.EntityIndex);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RotationRadians, view.Count, out view.RotationRadians);
TryAssignOptionalFloat3Column(index, map, AetheriaRuntimeDaemonSoaColumnKinds.Velocity, view.Count, out view.Velocity);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyRadius, view.Count, out view.PhysicsBodyRadius);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyMass, view.Count, out view.PhysicsBodyMass);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyInverseMass, view.Count, out view.PhysicsBodyInverseMass);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderScale, view.Count, out view.RenderScale);
TryAssignOptionalByteColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderVisibility, view.Count, out view.RenderVisibility);
TryAssignOptionalIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderLod, view.Count, out view.RenderLod);
TryAssignOptionalUIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderGroupId, view.Count, out view.RenderGroupId);
view.FrameId = index.View.FrameId;
view.Generation = index.View.Generation;
return true;
}
private static bool TryAssignOptionalFloat3Column(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,
string kind,
int expectedCount,
out NativeArray<float3> array)
{
array = default;
if (!index.TryGetFirstColumnOfKind(kind, out _))
{
return false;
}
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
{
array = default;
return false;
}
if (array.Length == expectedCount)
{
return true;
}
array = default;
return false;
}
private static bool TryAssignOptionalColumn(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,
string kind,
int expectedCount,
out NativeArray<float> array)
{
array = default;
if (!index.TryGetFirstColumnOfKind(kind, out _))
{
return false;
}
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
{
array = default;
return false;
}
if (array.Length == expectedCount)
{
return true;
}
array = default;
return false;
}
private static bool TryAssignOptionalUIntColumn(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,
string kind,
int expectedCount,
out NativeArray<uint> array)
{
array = default;
if (!index.TryGetFirstColumnOfKind(kind, out _))
{
return false;
}
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
{
array = default;
return false;
}
if (array.Length == expectedCount)
{
return true;
}
array = default;
return false;
}
private static bool TryAssignOptionalIntColumn(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,
string kind,
int expectedCount,
out NativeArray<int> array)
{
array = default;
if (!index.TryGetFirstColumnOfKind(kind, out _))
{
return false;
}
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
{
array = default;
return false;
}
if (array.Length == expectedCount)
{
return true;
}
array = default;
return false;
}
private static bool TryAssignOptionalByteColumn(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,
string kind,
int expectedCount,
out NativeArray<byte> array)
{
array = default;
if (!index.TryGetFirstColumnOfKind(kind, out _))
{
return false;
}
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
{
array = default;
return false;
}
if (array.Length == expectedCount)
{
return true;
}
array = default;
return false;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 48740dbd37e79954ca00a3f6bd7ccef1

View file

@ -1,220 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using GameCult.Aetheria.State.Verse;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
public unsafe sealed class AetheriaDaemonSoaMemoryMap : IDisposable
{
private readonly Dictionary<string, MappedBuffer> _buffersById =
new Dictionary<string, MappedBuffer>(StringComparer.Ordinal);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
private readonly List<AtomicSafetyHandle> _safetyHandles = new List<AtomicSafetyHandle>();
#endif
private bool _disposed;
private AetheriaDaemonSoaMemoryMap()
{
}
public static bool TryOpen(
AetheriaRuntimeDaemonSoaViewIndex index,
out AetheriaDaemonSoaMemoryMap map,
out string error)
{
map = null;
error = "";
if (index == null)
{
error = "No daemon SoA view index was provided.";
return false;
}
if (!index.IsValid)
{
error = index.ValidationErrors.Count > 0
? index.ValidationErrors[0]
: "Daemon SoA view index is invalid.";
return false;
}
var opened = new AetheriaDaemonSoaMemoryMap();
try
{
foreach (var buffer in index.View.Buffers)
{
if (!IsMappableReadOnlyBuffer(buffer))
{
continue;
}
opened.OpenBuffer(buffer);
}
map = opened;
return true;
}
catch (Exception exception)
{
opened.Dispose();
error = exception.Message;
return false;
}
}
public bool TryCreateNativeArray<T>(
AetheriaRuntimeDaemonSoaColumnBinding binding,
out NativeArray<T> array)
where T : struct
{
ThrowIfDisposed();
array = default;
if (binding == null ||
!binding.DirectMemoryCompatible ||
!_buffersById.TryGetValue(binding.Buffer.BufferId, out var buffer))
{
return false;
}
var byteOffset = checked((ulong)binding.AbsoluteByteOffset);
var byteLength = checked((ulong)Math.Max(0, binding.ByteLength));
if (byteOffset + byteLength > buffer.ByteLength)
{
return false;
}
var pointer = buffer.Pointer + byteOffset;
array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(
pointer,
binding.Column.ElementCount,
Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var safetyHandle = AtomicSafetyHandle.Create();
_safetyHandles.Add(safetyHandle);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, safetyHandle);
#endif
return true;
}
public bool TryCreateFirstNativeArrayOfKind<T>(
AetheriaRuntimeDaemonSoaViewIndex index,
string kind,
out NativeArray<T> array)
where T : struct
{
ThrowIfDisposed();
array = default;
if (index == null || !index.TryGetFirstColumnOfKind(kind, out var binding))
{
return false;
}
return TryCreateNativeArray(binding, out array);
}
public void Dispose()
{
if (_disposed)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
for (var i = 0; i < _safetyHandles.Count; i++)
{
AtomicSafetyHandle.Release(_safetyHandles[i]);
}
_safetyHandles.Clear();
#endif
foreach (var buffer in _buffersById.Values)
{
buffer.Dispose();
}
_buffersById.Clear();
_disposed = true;
}
private void OpenBuffer(AetheriaRuntimeDaemonSoaBufferDocument buffer)
{
if (string.IsNullOrWhiteSpace(buffer.BufferId) ||
_buffersById.ContainsKey(buffer.BufferId))
{
return;
}
var byteLength = checked((ulong)(buffer.ByteOffset + buffer.ByteLength));
var memoryMappedFile = MemoryMappedFile.OpenExisting(
buffer.Location,
MemoryMappedFileRights.Read);
var accessor = memoryMappedFile.CreateViewAccessor(0, (long)byteLength, MemoryMappedFileAccess.Read);
byte* pointer = null;
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
_buffersById.Add(
buffer.BufferId,
new MappedBuffer(memoryMappedFile, accessor, pointer, byteLength));
}
private static bool IsMappableReadOnlyBuffer(AetheriaRuntimeDaemonSoaBufferDocument buffer)
{
return buffer != null &&
!buffer.ObserverWritable &&
!string.IsNullOrWhiteSpace(buffer.Location) &&
string.Equals(buffer.Backend, AetheriaRuntimeDaemonSoaBackends.MemoryMappedFile, StringComparison.Ordinal);
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(AetheriaDaemonSoaMemoryMap));
}
}
private sealed class MappedBuffer : IDisposable
{
private readonly MemoryMappedFile _memoryMappedFile;
private readonly MemoryMappedViewAccessor _accessor;
private bool _disposed;
public MappedBuffer(
MemoryMappedFile memoryMappedFile,
MemoryMappedViewAccessor accessor,
byte* pointer,
ulong byteLength)
{
_memoryMappedFile = memoryMappedFile;
_accessor = accessor;
Pointer = pointer;
ByteLength = byteLength;
}
public byte* Pointer { get; }
public ulong ByteLength { get; }
public void Dispose()
{
if (_disposed)
{
return;
}
_accessor.SafeMemoryMappedViewHandle.ReleasePointer();
_accessor.Dispose();
_memoryMappedFile.Dispose();
_disposed = true;
}
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: d8988c7d796df504dab64fd2c64eb868

View file

@ -1,95 +0,0 @@
using System;
using GameCult.Aetheria.State.Verse;
using GameCult.Eve.PluginFields;
using GameCult.Eve.UnityScene.Fields;
using UnityEngine;
using UnityEngine.UI;
public sealed class AetheriaRenderSplatLayerRenderer : MonoBehaviour
{
[SerializeField] private EveFieldsSplatLayerRenderer renderer;
[SerializeField] private AetheriaRenderSplatLayerBinding[] bindings =
{
Binding(EveFieldsSplatLayerKeys.GravityHeight, "_AetheriaGravityHeight"),
Binding(EveFieldsSplatLayerKeys.FogTint, "_NebulaTint"),
Binding(EveFieldsSplatLayerKeys.FogSurfaceHeight, "_NebulaSurfaceHeight", 0.5f),
Binding(EveFieldsSplatLayerKeys.FogPatchHeight, "_NebulaPatchHeight", 0.5f),
Binding(EveFieldsSplatLayerKeys.FogPatch, "_NebulaPatch", 0.5f),
Binding(EveFieldsSplatLayerKeys.Influence, "_AetheriaInfluence")
};
public bool TryGetTexture(string layerKey, out RenderTexture texture)
{
ResolveRenderer();
if (renderer != null) return renderer.TryGetTexture(layerKey, out texture);
texture = null;
return false;
}
public void Render(EveFieldsSplatsDocument document, int width, int height)
{
if (document == null) return;
ResolveRenderer();
if (renderer == null) return;
var targets = new EveFieldsSplatLayerTarget[bindings?.Length ?? 0];
for (var index = 0; index < targets.Length; index++) targets[index] = bindings[index]?.CreateTarget();
renderer.Render(document, targets, width, height);
for (var index = 0; index < targets.Length; index++)
{
var binding = bindings[index];
var target = targets[index];
if (binding == null || target?.TargetTexture == null) continue;
binding.TargetTexture = target.TargetTexture;
ApplyBinding(binding, target.TargetTexture);
}
}
private void ResolveRenderer()
{
if (renderer != null) return;
renderer = GetComponent<EveFieldsSplatLayerRenderer>();
if (renderer == null) renderer = gameObject.AddComponent<EveFieldsSplatLayerRenderer>();
}
private static AetheriaRenderSplatLayerBinding Binding(string layerKey, string globalTextureName, float scale = 1f) =>
new AetheriaRenderSplatLayerBinding { LayerKey = layerKey, GlobalTextureName = globalTextureName, WidthScale = scale, HeightScale = scale };
private static void ApplyBinding(AetheriaRenderSplatLayerBinding binding, RenderTexture texture)
{
if (binding.Display != null)
{
var material = binding.Display.material;
if (material != null && !string.IsNullOrWhiteSpace(binding.MaterialTextureProperty)) material.SetTexture(binding.MaterialTextureProperty, texture);
else binding.Display.material.mainTexture = texture;
}
if (!string.IsNullOrWhiteSpace(binding.GlobalTextureName)) Shader.SetGlobalTexture(binding.GlobalTextureName, texture);
}
}
[Serializable]
public sealed class AetheriaRenderSplatLayerBinding
{
public bool Enabled = true;
public string LayerKey = "";
public Image Display;
public string MaterialTextureProperty = "_DetailTex";
public string GlobalTextureName = "";
public string GraphicsFormatOverride = "";
public float WidthScale = 1f;
public float HeightScale = 1f;
public bool UseMipMaps;
public FilterMode FilterMode = FilterMode.Bilinear;
[NonSerialized] public RenderTexture TargetTexture;
public EveFieldsSplatLayerTarget CreateTarget() => new EveFieldsSplatLayerTarget
{
Enabled = Enabled,
LayerKey = LayerKey,
GraphicsFormatOverride = GraphicsFormatOverride,
WidthScale = WidthScale,
HeightScale = HeightScale,
UseMipMaps = UseMipMaps,
FilterMode = FilterMode,
TargetTexture = TargetTexture
};
}

View file

@ -1,6 +0,0 @@
using GameCult.Eve.UnityScene.Fields;
// Existing scenes retain this MonoScript GUID while EveUnity owns projection.
public sealed class AetheriaRenderSplatRasterizer : EveFieldsSplatRasterizer
{
}

View file

@ -1,13 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
public sealed class AetheriaUnityActionBarBinding
{
public string ControlPath { get; set; } = "";
public string Kind { get; set; } = "";
public string ItemKey { get; set; } = "";
public int EquipmentIndex { get; set; } = -1;
public int BehaviorIndex { get; set; } = -1;
public int WeaponGroup { get; set; } = -1;
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: af36b057bd1c2ba46adad018b02fd568

View file

@ -1,273 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
public sealed class AetheriaUnityActionBarPresentation
{
private IReadOnlyList<ActionBarSlot> _slots = Array.Empty<ActionBarSlot>();
private AetheriaRuntimeCatalogSnapshot _catalog;
private GameSettings _settings;
private Func<Entity> _resolveEntity = () => null;
private Func<AetheriaControl> _resolveControl = () => null;
private IReadOnlyList<AetheriaUnityActionBarBinding> _localBindings =
Array.Empty<AetheriaUnityActionBarBinding>();
public void Bind(
IReadOnlyList<ActionBarSlot> slots,
AetheriaRuntimeCatalogSnapshot catalog,
GameSettings settings,
Func<Entity> resolveEntity,
Func<AetheriaControl> resolveControl)
{
_slots = slots ?? Array.Empty<ActionBarSlot>();
_catalog = catalog;
_settings = settings;
_resolveEntity = resolveEntity ?? (() => null);
_resolveControl = resolveControl ?? (() => null);
}
public int SlotCount => _slots?.Count ?? 0;
public string SlotLabel(int slotIndex)
{
var slot = ResolveSlot(slotIndex);
if (slot == null)
return "";
var controlPath = slot.ControlPath ?? "";
if (string.IsNullOrWhiteSpace(controlPath))
return "Action Bar";
var slashIndex = controlPath.LastIndexOf('/');
return slashIndex >= 0 && slashIndex < controlPath.Length - 1
? controlPath.Substring(slashIndex + 1)
: controlPath;
}
public string BindingLabel(int slotIndex)
{
var slot = ResolveSlot(slotIndex);
return slot?.Binding switch
{
ActionBarWeaponGroupBinding weaponGroup => $"G{weaponGroup.Group + 1}",
ActionBarConsumableBinding consumable => consumable.Target?.Name ?? "Consumable",
ActionBarGearBinding gear => _catalog?.FindItem(gear.Item?.EquippableItem, x => x.ItemKey)?.Name ?? "Gear",
_ => "Empty"
};
}
public bool TryResolveControlPath(int slotIndex, out string controlPath)
{
controlPath = ResolveSlot(slotIndex)?.ControlPath ?? "";
return !string.IsNullOrWhiteSpace(controlPath);
}
public void RequestBinding(ActionBarSlot slot, DragObject dragAction)
{
var entity = _resolveEntity();
if (slot == null || dragAction == null || entity == null)
return;
var binding = CreateBindingCommit(slot, entity, dragAction);
if (binding == null ||
string.IsNullOrWhiteSpace(binding.ControlPath) ||
string.IsNullOrWhiteSpace(binding.Kind))
{
return;
}
SetLocalBinding(binding);
ApplyLocalBindings();
}
public bool RequestWeaponGroupBinding(int slotIndex, int groupIndex)
{
if (groupIndex < 0 || !TryResolveControlPath(slotIndex, out var controlPath))
return false;
SetLocalBinding(new AetheriaUnityActionBarBinding
{
ControlPath = controlPath,
Kind = "weapon_group",
ItemKey = "",
EquipmentIndex = -1,
BehaviorIndex = -1,
WeaponGroup = groupIndex
});
ApplyLocalBindings();
return true;
}
public bool ClearBinding(int slotIndex)
{
if (!TryResolveControlPath(slotIndex, out var controlPath))
return false;
_localBindings = (_localBindings ?? Array.Empty<AetheriaUnityActionBarBinding>())
.Where(binding => !string.Equals(binding?.ControlPath ?? "", controlPath, StringComparison.Ordinal))
.ToArray();
ApplyLocalBindings();
return true;
}
public void ApplyLocalBindings()
{
ApplyBindings(_resolveEntity(), _localBindings);
}
public void ApplyBindings(
Entity entity,
IReadOnlyList<AetheriaUnityActionBarBinding> bindings)
{
if (_slots == null || _slots.Count == 0)
return;
foreach (var slot in _slots)
slot.Binding = null;
if (entity == null || bindings == null || bindings.Count == 0)
return;
var slotsByControlPath = _slots
.Where(slot => !string.IsNullOrWhiteSpace(slot?.ControlPath))
.GroupBy(slot => slot.ControlPath, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.First(), StringComparer.Ordinal);
foreach (var binding in bindings)
{
if (binding == null ||
string.IsNullOrWhiteSpace(binding.ControlPath) ||
!slotsByControlPath.TryGetValue(binding.ControlPath, out var slot))
{
continue;
}
var slotBinding = CreateBinding(slot, entity, binding);
if (slotBinding != null)
slot.Binding = slotBinding;
}
}
public ActionBarBinding CreateBinding(ActionBarSlot slot, Entity entity, DragObject dragAction)
{
var binding = CreateBindingCommit(slot, entity, dragAction);
return binding == null ? null : CreateBinding(slot, entity, binding);
}
private AetheriaUnityActionBarBinding CreateBindingCommit(
ActionBarSlot slot,
Entity entity,
DragObject dragAction)
{
if (slot == null || entity == null || dragAction == null)
return null;
switch (dragAction)
{
case EquippedItemDragObject equippedItemDragAction:
var equippedItem = equippedItemDragAction.EquippedItem;
var trigger = equippedItem?.GetBehavior<IActivatedBehavior>();
var equipmentIndex = equippedItem == null ? -1 : entity.Equipment.IndexOf(equippedItem);
var behaviorIndex = equippedItem?.Behaviors == null ? -1 : Array.IndexOf(equippedItem.Behaviors, trigger);
return trigger == null || equipmentIndex < 0 || behaviorIndex < 0
? null
: new AetheriaUnityActionBarBinding
{
ControlPath = slot.ControlPath ?? "",
Kind = "gear",
ItemKey = equippedItem.EquippableItem?.ItemKey ?? "",
EquipmentIndex = equipmentIndex,
BehaviorIndex = behaviorIndex
};
case ItemInstanceDragObject itemInstanceDragAction:
var consumable = FindConsumable(itemInstanceDragAction.Item);
return consumable == null
? null
: new AetheriaUnityActionBarBinding
{
ControlPath = slot.ControlPath ?? "",
Kind = "consumable",
ItemKey = consumable.ItemKey ?? ""
};
default:
return null;
}
}
private void SetLocalBinding(AetheriaUnityActionBarBinding binding)
{
if (binding == null || string.IsNullOrWhiteSpace(binding.ControlPath))
return;
_localBindings = (_localBindings ?? Array.Empty<AetheriaUnityActionBarBinding>())
.Where(existing => !string.Equals(existing?.ControlPath ?? "", binding.ControlPath, StringComparison.Ordinal))
.Concat(new[] { binding })
.ToArray();
}
private ActionBarBinding CreateBinding(
ActionBarSlot slot,
Entity entity,
AetheriaUnityActionBarBinding binding)
{
if (slot == null || entity == null || binding == null)
return null;
switch (binding.Kind)
{
case "consumable":
var consumable = _catalog?.FindItem(binding.ItemKey ?? "");
return consumable != null &&
string.Equals(consumable.Category, AetheriaRuntimeItemCategories.Consumable, StringComparison.Ordinal)
? new ActionBarConsumableBinding(entity, slot, _resolveControl, _settings, consumable)
: null;
case "gear":
if (binding.EquipmentIndex < 0 || binding.EquipmentIndex >= entity.Equipment.Count)
return null;
var equippedItem = entity.Equipment[binding.EquipmentIndex];
var behaviors = equippedItem?.Behaviors;
if (equippedItem == null ||
!string.Equals(equippedItem.EquippableItem?.ItemKey ?? "", binding.ItemKey ?? "", StringComparison.Ordinal) ||
behaviors == null ||
binding.BehaviorIndex < 0 ||
binding.BehaviorIndex >= behaviors.Length)
{
return null;
}
if (!(behaviors[binding.BehaviorIndex] is IActivatedBehavior activatedBehavior))
return null;
return new ActionBarGearBinding(entity, slot, _resolveControl, _settings, equippedItem, activatedBehavior);
case "weapon_group":
return entity.WeaponGroups != null &&
binding.WeaponGroup >= 0 &&
binding.WeaponGroup < entity.WeaponGroups.Length
? new ActionBarWeaponGroupBinding(entity, slot, _resolveControl, _settings, binding.WeaponGroup)
: null;
default:
return null;
}
}
private AetheriaRuntimeCatalogItem FindConsumable(ItemInstance item)
{
var typedItem = _catalog?.FindItem(item, x => x.ItemKey);
return typedItem != null &&
string.Equals(typedItem.Category, AetheriaRuntimeItemCategories.Consumable, StringComparison.Ordinal)
? typedItem
: null;
}
private ActionBarSlot ResolveSlot(int slotIndex)
{
return _slots != null &&
slotIndex >= 0 &&
slotIndex < _slots.Count
? _slots[slotIndex]
: null;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 0f239f607245e8143805587f4c34fbee

View file

@ -1,40 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityCockpitHudShell
{
public InventoryPanel ShipPanel { get; set; }
public InventoryPanel TargetShipPanel { get; set; }
public SchematicDisplay SchematicDisplay { get; set; }
public SchematicDisplay TargetSchematicDisplay { get; set; }
public PlaceUIElementWorldspace TargetIndicator { get; set; }
public void SetRenderSettings(AetheriaRuntimeDaemonRenderSettings renderSettings)
{
SchematicDisplay?.SetRenderSettings(renderSettings);
TargetSchematicDisplay?.SetRenderSettings(renderSettings);
}
public void UpdatePlayer(Entity currentEntity)
{
ShipPanel?.Display(currentEntity, true);
SchematicDisplay?.ShowShip(currentEntity);
}
public void UpdateTarget(Entity target, Entity currentEntity)
{
if (TargetIndicator != null)
TargetIndicator.gameObject.SetActive(target != null);
if (TargetShipPanel != null)
TargetShipPanel.gameObject.SetActive(target != null);
if (target == null)
return;
TargetShipPanel?.Display(target, true);
TargetSchematicDisplay?.ShowShip(target, currentEntity);
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 027535b4501541f4aa60df9ae50d9eed

View file

@ -1,87 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
using UnityEngine.Rendering;
using float3 = Unity.Mathematics.float3;
public sealed class AetheriaUnityCurrentEntityBinder
{
public ZoneRenderer ZoneRenderer { get; set; }
public Volume DeathPost { get; set; }
public CanvasGroup GameplayUI { get; set; }
public AetheriaUnityCurrentEntityPresentation CurrentEntityPresentation { get; set; }
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
public Func<Entity> GetCurrentEntity { get; set; }
public Func<Entity, Entity> ResolveDockParent { get; set; }
public Action<Entity> SetCurrentEntity { get; set; }
public Func<float3> GetViewDirection { get; set; }
public Action<float3> SetViewDirection { get; set; }
public Func<AetheriaRuntimeZoneRenderDocument> ResolveZoneRender { get; set; }
public Action<IReadOnlyList<AetheriaUnityActionBarBinding>> ApplyActionBarBindings { get; set; }
public Action EnablePlayerInput { get; set; }
public Action DisablePlayerInput { get; set; }
public Action<MusicType> PlayMusic { get; set; }
public Action<Entity> UpdateTargetPanel { get; set; }
public void RestoreBinding(Entity currentEntity)
{
var dockParent = ResolveDockParent?.Invoke(currentEntity);
if (dockParent != null)
{
SetCurrentEntity?.Invoke(currentEntity);
ApplyActionBarBindings?.Invoke(Array.Empty<AetheriaUnityActionBarBinding>());
CurrentEntityPresentation?.BindDocked(
dockParent,
null,
ResolveZoneRender?.Invoke());
return;
}
BindUndocked(
currentEntity);
}
public void ClearBinding()
{
TargetPresentation?.ClearIndicators();
CurrentEntityPresentation?.ClearBinding();
DisablePlayerInput?.Invoke();
Cursor.lockState = CursorLockMode.None;
if (GameplayUI != null)
GameplayUI.gameObject.SetActive(false);
}
private void BindUndocked(Entity entity)
{
if (ZoneRenderer == null ||
!ZoneRenderer.TryGetEntityInstance(entity, out var entityInstance))
{
Debug.LogError($"Attempted to bind to entity {entity?.Name}, but ZoneRenderer has no daemon-indexed instance.");
return;
}
SetCurrentEntity?.Invoke(entity);
if (DeathPost != null)
DeathPost.weight = 0;
if (CultMath.math.length(entity.CultDirection) > .1f)
SetViewDirection?.Invoke((float3)AetheriaMath.ToUnityXZ(entity.CultDirection));
CurrentEntityPresentation?.BindUndocked(
entity,
entityInstance,
Array.Empty<AetheriaUnityActionBarBinding>(),
EnablePlayerInput,
PlayMusic,
SetCurrentEntity,
UpdateTargetPanel,
() => TargetPresentation?.ReconcileVisibleTargetIndicators(GetCurrentEntity?.Invoke()),
ApplyActionBarBindings);
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: c599c7371ae28e249bcf132744d4e547

View file

@ -1,228 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using Cinemachine;
using GameCult.Aetheria.State.Verse;
using UniRx;
using UnityEngine;
public sealed class AetheriaUnityCurrentEntityPresentation
{
private readonly List<IDisposable> _shipSubscriptions = new List<IDisposable>();
private readonly List<IDisposable> _targetSubscriptions = new List<IDisposable>();
private float _hitMarkerTime;
public ZoneRenderer ZoneRenderer { get; set; }
public CinemachineVirtualCamera DockCamera { get; set; }
public CinemachineVirtualCamera FollowCamera { get; set; }
public MenuPanel Menu { get; set; }
public TradeMenu TradeMenu { get; set; }
public CanvasGroup GameplayUI { get; set; }
public InventoryPanel ShipPanel { get; set; }
public InventoryPanel TargetShipPanel { get; set; }
public SchematicDisplay SchematicDisplay { get; set; }
public SchematicDisplay TargetSchematicDisplay { get; set; }
public ImageTargetPresentation TargetImages { get; set; }
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; set; }
public PlaceUIElementWorldspace[] Crosshairs { get; set; } = Array.Empty<PlaceUIElementWorldspace>();
public Prototype LockIndicator { get; set; }
public GameObject HitMarker { get; set; }
public float HitMarkerDuration { get; set; }
public (HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)[] ArticulationGroups { get; private set; } =
Array.Empty<(HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)>();
public (LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)[] LockingIndicators { get; private set; } =
Array.Empty<(LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)>();
public void BindUndocked(
Entity entity,
EntityInstance entityInstance,
IReadOnlyList<AetheriaUnityActionBarBinding> actionBarBindings,
Action enablePlayerInput,
Action<MusicType> playMusic,
Action<Entity> updateCurrentEntity,
Action<Entity> updateTargetPanel,
Action reconcileVisibleTargetIndicators,
Action<IReadOnlyList<AetheriaUnityActionBarBinding>> applyActionBarBindings)
{
if (entity == null || entityInstance == null)
return;
updateCurrentEntity?.Invoke(entity);
ZoneRenderer.PerspectiveEntity = entity;
Menu.gameObject.SetActive(false);
DockCamera.enabled = false;
FollowCamera.enabled = true;
Cursor.lockState = CursorLockMode.Locked;
enablePlayerInput?.Invoke();
GameplayUI.gameObject.SetActive(true);
ShipPanel.Display(entity, true);
SchematicDisplay.ShowShip(entity);
FollowCamera.LookAt = entityInstance.LookAtPoint;
FollowCamera.Follow = entityInstance.transform;
ArticulationGroups = entity.Equipment
.Where(HasArticulatedWeaponBehavior)
.GroupBy(item => entityInstance
.GetBarrel(entity.Hardpoints[item.Position.x, item.Position.y])
.GetComponentInParent<ArticulationPoint>()?.Group ?? -1)
.Select((group, index) =>
{
return (
group.Select(item => entity.Hardpoints[item.Position.x, item.Position.y]).ToArray(),
group.Select(item => entityInstance.GetBarrel(entity.Hardpoints[item.Position.x, item.Position.y])).ToArray(),
Crosshairs[index]
);
}).ToArray();
foreach (var crosshair in Crosshairs)
crosshair.gameObject.SetActive(false);
foreach (var group in ArticulationGroups)
group.crosshair.gameObject.SetActive(true);
_shipSubscriptions.Add(entity.TargetedByCount.Subscribe(count =>
{
playMusic?.Invoke(count > 0 ? MusicType.Combat : MusicType.Overworld);
}));
_shipSubscriptions.Add(entity.Target.Subscribe(target =>
{
ClearTargetSubscriptions();
updateTargetPanel?.Invoke(target);
ConfigureTargetShieldPresentation(target);
if (target != null)
{
_targetSubscriptions.Add(target.IncomingHit.Where(e => e == entity).Subscribe(_ =>
{
HitMarker.SetActive(true);
_hitMarkerTime = HitMarkerDuration;
}));
}
}));
reconcileVisibleTargetIndicators?.Invoke();
LockingIndicators = entity.GetBehaviors<LockWeapon>()
.Select(x =>
{
var indicator = LockIndicator.Instantiate<PlaceUIElementWorldspace>();
return (x, indicator, indicator.GetComponent<Rotate>());
}).ToArray();
applyActionBarBindings?.Invoke(actionBarBindings ?? Array.Empty<AetheriaUnityActionBarBinding>());
}
public bool HasArticulatedWeaponBehavior(EquippedItem item)
{
return AetheriaUnityWeaponPresentationPolicy.HasArticulatedWeaponBehavior(RuntimeCatalog, item);
}
public void BindDocked(
Entity entity,
AetheriaRuntimeCurrentDockingDocument docking,
AetheriaRuntimeZoneRenderDocument zoneRender)
{
if (entity == null)
return;
TradeMenu.Inventory = entity.CargoBays.First();
ZoneRenderer.PerspectiveEntity = entity;
DockCamera.enabled = true;
FollowCamera.enabled = false;
var orbital = entity as OrbitalEntity;
if (orbital == null || !ZoneRenderer.TryGetEntityInstance(orbital, out var orbitalInstance))
{
Debug.LogError($"Attempted to dock at entity {entity.Name}, but ZoneRenderer has no daemon-indexed instance.");
return;
}
DockCamera.Follow = orbitalInstance.transform;
var parentOrbitPlanetBodyKey = ResolveDockParentBodyKey(orbital, docking, zoneRender);
if (ZoneRenderer.TryGetBodyView(parentOrbitPlanetBodyKey, out var parentBodyView))
DockCamera.LookAt = parentBodyView.Body.transform;
else DockCamera.LookAt = ZoneRenderer.ZoneRoot;
Menu.ShowTab(MenuTab.Inventory);
}
private static string ResolveDockParentBodyKey(
OrbitalEntity orbital,
AetheriaRuntimeCurrentDockingDocument docking,
AetheriaRuntimeZoneRenderDocument zoneRender)
{
if (orbital == null)
return "";
var bodyPoses = zoneRender?.BodyPoses ?? Array.Empty<AetheriaRuntimeZoneRenderBodyPose>();
var parentOrbitKey = bodyPoses
.FirstOrDefault(body => body != null &&
string.Equals(body.OrbitKey ?? "", orbital.OrbitKey, StringComparison.Ordinal))
?.ParentOrbitKey ?? docking?.DockParentParentOrbitKey ?? "";
return bodyPoses
.FirstOrDefault(body => body != null &&
string.Equals(body.OrbitKey ?? "", parentOrbitKey, StringComparison.Ordinal))
?.BodyKey ?? docking?.DockParentParentBodyKey ?? "";
}
public void ClearBinding()
{
foreach (var (_, indicator, _) in LockingIndicators)
indicator.GetComponent<Prototype>().ReturnToPool();
LockingIndicators = Array.Empty<(LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)>();
ArticulationGroups = Array.Empty<(HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)>();
foreach (var subscription in _shipSubscriptions)
subscription.Dispose();
_shipSubscriptions.Clear();
ClearTargetSubscriptions();
}
public void Tick(float deltaTime)
{
_hitMarkerTime -= deltaTime;
if (HitMarker.activeSelf && _hitMarkerTime < 0)
HitMarker.SetActive(false);
}
private void ClearTargetSubscriptions()
{
foreach (var subscription in _targetSubscriptions)
subscription.Dispose();
_targetSubscriptions.Clear();
}
private void ConfigureTargetShieldPresentation(Entity target)
{
if (target == null || TargetImages == null)
return;
if (target.Shield != null)
{
TargetImages.TargetShieldsBackground.color = new Color(TargetImages.ShieldColor.r, TargetImages.ShieldColor.g, TargetImages.ShieldColor.b, .4f);
TargetImages.TargetShieldsIcon.color = TargetImages.ShieldColor;
TargetImages.TargetShieldsIcon.sprite = TargetImages.ShieldIcon;
}
else
{
TargetImages.TargetShieldsBackground.color = new Color(TargetImages.NoShieldColor.r, TargetImages.NoShieldColor.g, TargetImages.NoShieldColor.b, .4f);
TargetImages.TargetShieldsIcon.color = TargetImages.NoShieldColor;
TargetImages.TargetShieldsIcon.sprite = TargetImages.NoShieldIcon;
}
}
}
public sealed class ImageTargetPresentation
{
public UnityEngine.UI.Image TargetShieldsBackground { get; set; }
public UnityEngine.UI.Image TargetShieldsIcon { get; set; }
public Color ShieldColor { get; set; }
public Color NoShieldColor { get; set; }
public Sprite ShieldIcon { get; set; }
public Sprite NoShieldIcon { get; set; }
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: f5a7b36e50785fc45ab94ae5a03dd1d6

View file

@ -1,44 +0,0 @@
using System;
using GameCult.Aetheria.State.Verse;
using GameCult.Mesh;
public sealed class AetheriaUnityDaemonRenderDocuments : IDisposable
{
private readonly CultMeshReactiveDocument<AetheriaRuntimeDaemonFrameDocument> _frame;
private readonly CultMeshReactiveDocument<AetheriaRuntimeDaemonSoaViewDocument> _soaView;
private readonly CultMeshReactiveDocument<AetheriaRuntimeZoneRenderDocument> _zoneRender;
private AetheriaUnityDaemonRenderDocuments(AetheriaClientState state)
{
if (state == null)
throw new ArgumentNullException(nameof(state));
_frame = state.DaemonFrame.Reactive();
_soaView = state.DaemonSoaView.Reactive();
_zoneRender = state.ZoneRender.Reactive();
}
public AetheriaRuntimeDaemonRenderView Current =>
TryRead(out var observed) ? observed : null;
public static AetheriaUnityDaemonRenderDocuments Open(AetheriaClientState state)
{
return new AetheriaUnityDaemonRenderDocuments(state);
}
public bool TryRead(out AetheriaRuntimeDaemonRenderView observed)
{
return AetheriaRuntimeDaemonRenderView.TryCreateCurrent(
_frame,
_soaView,
_zoneRender,
out observed);
}
public void Dispose()
{
_frame?.Dispose();
_soaView?.Dispose();
_zoneRender?.Dispose();
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: a5bd499492bebfb439338bc5283f6a23

View file

@ -1,45 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using int2 = Unity.Mathematics.int2;
public abstract class DragObject
{
}
public abstract class ItemDragObject : DragObject
{
protected ItemDragObject(int2 originCellOffset, ItemInstance item)
{
OriginCellOffset = originCellOffset;
Item = item;
}
public ItemInstance Item { get; }
public int2 OriginCellOffset { get; }
}
public class ItemInstanceDragObject : ItemDragObject
{
public ItemInstanceDragObject(ItemInstance item, EquippedCargoBay originInventory, int2 originCellOffset)
: base(originCellOffset, item)
{
OriginInventory = originInventory;
}
public EquippedCargoBay OriginInventory { get; }
}
public class EquippedItemDragObject : ItemDragObject
{
public EquippedItemDragObject(EquippedItem item, Entity originEntity, int2 originCellOffset)
: base(originCellOffset, item.EquippableItem)
{
EquippedItem = item;
OriginEntity = originEntity;
}
public EquippedItem EquippedItem { get; }
public Entity OriginEntity { get; }
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 5f70b0c04a804c349915b07ef0fd9b13

View file

@ -1,37 +0,0 @@
using System;
public sealed class AetheriaUnityDragSession
{
private DragObject _dragObject;
private Action<DragObject> _endDragCallback;
public void Begin(DragObject dragObject)
{
_dragObject = dragObject;
}
public bool TryGetDraggedItem(out ItemDragObject itemDragObject)
{
itemDragObject = _dragObject as ItemDragObject;
return itemDragObject != null;
}
public void RegisterTarget(Action<DragObject> onEndDrag)
{
_endDragCallback = onEndDrag;
}
public void UnregisterTarget()
{
_endDragCallback = null;
}
public bool End()
{
var hadTarget = _endDragCallback != null;
_endDragCallback?.Invoke(_dragObject);
_dragObject = null;
_endDragCallback = null;
return hadTarget;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 6454eeaf62eadb44abbe5d54bf497312

View file

@ -1,161 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using Unity.Mathematics;
public sealed class AetheriaUnityEntityBlueprintMaterializer
{
private readonly AetheriaUnityLoadoutItemFactory _loadoutItemFactory;
public AetheriaUnityEntityBlueprintMaterializer(
AetheriaUnityLoadoutItemFactory loadoutItemFactory)
{
_loadoutItemFactory = loadoutItemFactory ?? throw new ArgumentNullException(nameof(loadoutItemFactory));
}
public EntityConstructionBlueprint MaterializeTemplate(AetheriaRuntimeLoadoutTemplateSnapshot template)
{
if (template == null)
return null;
var blueprint = MaterializeLoadoutEntity(template.RootEntity);
if (blueprint != null && string.IsNullOrWhiteSpace(blueprint.Name))
blueprint.Name = template.Name;
return blueprint;
}
public EntityConstructionBlueprint MaterializeLoadoutEntity(AetheriaRuntimeEntityLoadoutSnapshot entity)
{
if (entity == null)
return null;
var hull = CreateEquippableItem(entity.Hull);
if (hull == null)
return null;
var blueprint = CreateBlueprint(entity.Kind);
if (blueprint is ShipConstructionBlueprint shipBlueprint)
{
shipBlueprint.Direction = new float2(0, 1);
}
blueprint.Name = entity.Name;
blueprint.FactionKey = entity.FactionKey ?? "";
blueprint.Hull = hull;
blueprint.Equipment = CreateEquippableSlots(entity.Equipment);
blueprint.CargoBays = CreateEquippableSlots(entity.CargoBays);
blueprint.DockingBays = CreateEquippableSlots(entity.DockingBays);
blueprint.CargoContents = CreateCargoBayContents(entity.CargoContents);
blueprint.DockingBayContents = CreateCargoBayContents(entity.DockingBayContents);
blueprint.DockingBayAssignments = entity.DockingBayAssignments.ToArray();
blueprint.WeaponGroups = entity.WeaponGroups.Select(group => group.ToArray()).ToArray();
blueprint.Children = entity.Children
.Select(MaterializeLoadoutEntity)
.Where(child => child != null)
.ToArray();
return blueprint;
}
public EntityConstructionBlueprint MaterializeObservedEntity(
AetheriaRuntimeEntitySnapshot entity,
bool isCurrentEntity)
{
if (entity == null)
return null;
var hull = CreateEquippableItem(new AetheriaRuntimeLoadoutItemSnapshot(
entity.HullItemKey,
1,
1,
1,
true,
false));
if (hull == null)
return null;
var blueprint = CreateBlueprint(entity.Kind);
if (blueprint is ShipConstructionBlueprint shipBlueprint)
{
shipBlueprint.Position = new float3((float)entity.PositionX, (float)entity.PositionY, (float)entity.PositionZ);
shipBlueprint.Direction = new float2((float)entity.DirectionX, (float)entity.DirectionY);
shipBlueprint.IsPlayerShip = isCurrentEntity;
}
else if (blueprint is OrbitalEntityConstructionBlueprint orbitalBlueprint)
{
orbitalBlueprint.OrbitKey = entity.OrbitKey ?? "";
orbitalBlueprint.SecurityLevel = (SecurityLevel)entity.SecurityLevel;
orbitalBlueprint.SecurityRadius = (float)entity.SecurityRadius;
}
blueprint.Name = entity.Name ?? "";
blueprint.FactionKey = entity.FactionKey ?? "";
blueprint.Hull = hull;
blueprint.Equipment = CreateEquippableSlots(entity.Equipment);
blueprint.CargoBays = CreateEquippableSlots(entity.CargoBays);
blueprint.DockingBays = CreateEquippableSlots(entity.DockingBays);
blueprint.CargoContents = CreateCargoBayContents(entity.CargoContents);
blueprint.DockingBayContents = CreateCargoBayContents(entity.DockingBayContents);
blueprint.DockingBayAssignments = entity.DockingBayAssignments.ToArray();
blueprint.WeaponGroups = entity.WeaponGroups.Select(group => group.ToArray()).ToArray();
blueprint.Children = Array.Empty<EntityConstructionBlueprint>();
return blueprint;
}
private static EntityConstructionBlueprint CreateBlueprint(string kind)
{
return string.Equals(kind, "orbital", StringComparison.OrdinalIgnoreCase) ||
string.Equals(kind, "station", StringComparison.OrdinalIgnoreCase) ||
string.Equals(kind, "turret", StringComparison.OrdinalIgnoreCase)
? new OrbitalEntityConstructionBlueprint()
: new ShipConstructionBlueprint();
}
private (int2 position, EquippableItem item)[] CreateEquippableSlots(
IReadOnlyList<AetheriaRuntimeLoadoutItemSlotSnapshot> slots)
{
return (slots ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotSnapshot>())
.Select(slot => (position: new int2(slot.X, slot.Y), item: CreateEquippableItem(slot.Item)))
.Where(slot => slot.item != null)
.ToArray();
}
private (int2 position, EquippableItem item)[] CreateEquippableSlots(
IReadOnlyList<AetheriaRuntimeEntityItemSlotSnapshot> slots)
{
return (slots ?? Array.Empty<AetheriaRuntimeEntityItemSlotSnapshot>())
.Select(slot => (position: new int2(slot.X, slot.Y), item: CreateEquippableItem(new AetheriaRuntimeLoadoutItemSnapshot(
slot.ItemKey,
slot.Quality,
slot.Durability,
slot.Quantity,
slot.Enabled,
slot.OverrideShutdown,
slot.Temperature))))
.Where(slot => slot.item != null)
.ToArray();
}
private (int2 position, ItemInstance item)[][] CreateCargoBayContents(
IReadOnlyList<AetheriaRuntimeCargoBayLoadoutSnapshot> bays)
{
return (bays ?? Array.Empty<AetheriaRuntimeCargoBayLoadoutSnapshot>())
.Select(bay => (bay.Items ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotSnapshot>())
.Select(slot => (position: new int2(slot.X, slot.Y), item: _loadoutItemFactory.CreateLoadoutItem(slot.Item)))
.Where(slot => slot.item != null)
.ToArray())
.ToArray();
}
private EquippableItem CreateEquippableItem(AetheriaRuntimeLoadoutItemSnapshot item)
{
var instance = _loadoutItemFactory.CreateLoadoutItem(item) as EquippableItem;
if (instance != null && item.Durability > 0)
instance.Durability = (float)item.Durability;
return instance;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 88f0588c14c7a1d4c87095a96585c957

View file

@ -1,102 +0,0 @@
using System;
using GameCult.Aetheria.State.Verse;
using GameCult.Eve.PluginFields;
using GameCult.Mesh;
public sealed class AetheriaUnityGameViewportDocuments : IDisposable
{
private readonly CultMeshReactiveDocument<AetheriaRuntimeZoneContactsDocument> _contacts;
private readonly CultMeshReactiveDocument<AetheriaRuntimeObjectsViewportDocument> _objectsViewport;
private readonly CultMeshReactiveDocument<EveFieldsSplatsDocument> _renderSplatsViewport;
private AetheriaUnityGameViewportDocuments(
AetheriaClientState state,
AetheriaRuntimeViewportBounds viewport,
bool bindContacts,
bool bindObjects,
bool bindRenderSplats)
{
if (state == null)
throw new ArgumentNullException(nameof(state));
if (viewport == null)
throw new ArgumentNullException(nameof(viewport));
Viewport = viewport;
_contacts = bindContacts ? state.ZoneContacts.Reactive() : null;
_objectsViewport = bindObjects ? state.ObjectsViewport(viewport).Reactive() : null;
_renderSplatsViewport = bindRenderSplats ? state.RenderSplatsViewport(viewport).Reactive() : null;
}
public AetheriaRuntimeViewportBounds Viewport { get; }
public AetheriaRuntimeZoneContactsDocument CurrentContacts => _contacts?.Current;
public AetheriaRuntimeObjectsViewportDocument CurrentObjectsViewport => _objectsViewport?.Current;
public EveFieldsSplatsDocument CurrentRenderSplatsViewport => _renderSplatsViewport?.Current;
public static AetheriaUnityGameViewportDocuments OpenMap(
AetheriaClientState state,
AetheriaRuntimeViewportBounds viewport)
{
return new AetheriaUnityGameViewportDocuments(
state,
viewport,
bindContacts: false,
bindObjects: true,
bindRenderSplats: true);
}
public static AetheriaUnityGameViewportDocuments OpenZonePresentation(
AetheriaClientState state,
AetheriaRuntimeViewportBounds viewport)
{
return new AetheriaUnityGameViewportDocuments(
state,
viewport,
bindContacts: true,
bindObjects: true,
bindRenderSplats: false);
}
public static AetheriaUnityGameViewportDocuments OpenRenderSplats(
AetheriaClientState state,
AetheriaRuntimeViewportBounds viewport)
{
return new AetheriaUnityGameViewportDocuments(
state,
viewport,
bindContacts: false,
bindObjects: false,
bindRenderSplats: true);
}
public bool Matches(AetheriaRuntimeViewportBounds viewport)
{
return SameViewport(Viewport, viewport);
}
public void Dispose()
{
_contacts?.Dispose();
_objectsViewport?.Dispose();
_renderSplatsViewport?.Dispose();
}
public static bool SameViewport(
AetheriaRuntimeViewportBounds left,
AetheriaRuntimeViewportBounds right)
{
if (left == null || right == null)
return false;
return Approximately(left.MinX, right.MinX) &&
Approximately(left.MinY, right.MinY) &&
Approximately(left.MaxX, right.MaxX) &&
Approximately(left.MaxY, right.MaxY);
}
private static bool Approximately(double left, double right)
{
var scale = Math.Max(1.0, Math.Max(Math.Abs(left), Math.Abs(right)));
return Math.Abs(left - right) <= scale * 1e-6;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: e763d94f902249349a0f897ef12bd185

View file

@ -1,141 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using GameCult.Aetheria.State.Verse;
using GameCult.Mesh;
public sealed class AetheriaUnityGameplayBootShell
{
public GameSettings Settings { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public AetheriaUnityCockpitHudShell CockpitHudShell { get; set; }
public Action<string> Log { get; set; }
public AetheriaUnityGameplayBootResult Boot()
{
var stateBoot = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
Log?.Invoke($"Aetheria runtime target: {stateBoot.TargetLabel} via {stateBoot.TargetKind} ({stateBoot.TargetSource})");
Log?.Invoke($"Aetheria runtime id: {stateBoot.RuntimeId}");
Log?.Invoke($"Aetheria runtime state file: {stateBoot.StateFilePath}");
stateBoot = SyncRemoteReplicaBeforeBoot(stateBoot);
if (!stateBoot.SupportsLocalStateFileRead)
{
throw new InvalidOperationException(
$"Aetheria runtime target cannot read the daemon mirror state required for gameplay boot: {stateBoot.FailureMessage}");
}
if (!stateBoot.StateFileExists)
{
throw new InvalidOperationException(
$"Aetheria runtime state file is missing at {stateBoot.StateFilePath}; gameplay requires an authoritative daemon mirror.");
}
var runtimeState = AetheriaUnityRuntimeClientProvider.RuntimeState(stateBoot, stateBoot.RuntimeId);
var runtimeCatalog = runtimeState.Catalog.Latest();
if (runtimeCatalog == null)
throw new InvalidOperationException("Aetheria typed runtime catalog is required before gameplay boot.");
var sectorMap = runtimeState.SectorMap.Latest();
if (sectorMap == null)
throw new InvalidOperationException("Aetheria typed sector map is required before gameplay boot.");
Log?.Invoke($"Aetheria runtime catalog: {runtimeCatalog.Items.Count} items, {runtimeCatalog.Corporations.Count} corporations, {runtimeCatalog.NameFiles.Count} name files");
Log?.Invoke($"Aetheria observed sector-map frame: {sectorMap.FrameId}");
var backgroundSettings = sectorMap.IsTutorial
? Settings.TutorialBackgroundSettings
: Settings.SectorBackgroundSettings;
backgroundSettings.NoisePosition = sectorMap.GenerationSeed == 0 ? 1 : sectorMap.GenerationSeed;
var observedGalaxy = global::Galaxy.ProjectObservedSectorMap(
sectorMap,
backgroundSettings,
runtimeCatalog,
Log);
var itemManager = new ItemManager(
runtimeCatalog,
Settings.GameplaySettings,
message => Log?.Invoke(message));
var loadoutItemFactory = new AetheriaUnityLoadoutItemFactory(itemManager, runtimeCatalog);
ZoneRenderer.SetDroppedPickupItemFactory(loadoutItemFactory.CreateLoadoutItem);
ZoneRenderer.BodySettingsCollections = Settings.BodySettingsCollections;
ZoneRenderer.RenderSettings = ResolveDaemonRenderSettings(runtimeState);
CockpitHudShell.SetRenderSettings(ZoneRenderer.RenderSettings);
if (!AetheriaUnityRuntimeClientProvider.PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap)
ZoneRenderer.ShowAsteroidUI = false;
return new AetheriaUnityGameplayBootResult(
runtimeCatalog,
observedGalaxy,
itemManager,
loadoutItemFactory);
}
private AetheriaRuntimeDaemonRenderSettings ResolveDaemonRenderSettings(AetheriaClientState runtimeState)
{
var frame = runtimeState?.DaemonFrame?.Latest();
if (frame == null)
throw new InvalidOperationException("Aetheria daemon frame is required before gameplay boot; render/game-feel settings are daemon authority.");
Log?.Invoke($"Aetheria render/game-feel settings: daemon frame {frame.FrameId}");
return frame.RenderSettings;
}
private AetheriaRuntimeStateBootReport SyncRemoteReplicaBeforeBoot(AetheriaRuntimeStateBootReport stateBoot)
{
if (!ShouldSyncRemoteReplicaBeforeBoot(stateBoot))
return stateBoot;
Log?.Invoke($"Aetheria remote Verse replica missing; syncing {stateBoot.TargetLabel} from {stateBoot.CultMeshAddress}");
try
{
var target = AetheriaState.At(AetheriaUnityRuntimePaths.GameDataDirectory)
.ClientTarget
.SyncReplica();
AetheriaUnityRuntimePaths.ClearRuntimeStateFilePathCache();
var refreshed = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
Log?.Invoke($"Aetheria remote Verse replica synced: {refreshed.StateFilePath}");
if (!string.IsNullOrWhiteSpace(target.LastReplicaSyncAtUtc))
Log?.Invoke($"Aetheria remote Verse replica sync time: {target.LastReplicaSyncAtUtc}");
return refreshed;
}
catch (Exception ex)
{
AetheriaUnityRuntimePaths.ClearRuntimeStateFilePathCache();
throw new InvalidOperationException(
$"Aetheria remote Verse replica sync failed before gameplay boot: {ex.Message}",
ex);
}
}
private static bool ShouldSyncRemoteReplicaBeforeBoot(AetheriaRuntimeStateBootReport stateBoot)
{
return string.Equals(stateBoot.TargetSource, "client-target", StringComparison.Ordinal)
&& string.Equals(stateBoot.TargetKind, AetheriaRuntimeClientTargetKinds.CultMeshVerse, StringComparison.Ordinal)
&& (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists);
}
}
public readonly struct AetheriaUnityGameplayBootResult
{
public AetheriaUnityGameplayBootResult(
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
Galaxy observedGalaxy,
ItemManager itemManager,
AetheriaUnityLoadoutItemFactory loadoutItemFactory)
{
RuntimeCatalog = runtimeCatalog;
ObservedGalaxy = observedGalaxy;
ItemManager = itemManager;
LoadoutItemFactory = loadoutItemFactory;
}
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; }
public Galaxy ObservedGalaxy { get; }
public ItemManager ItemManager { get; }
public AetheriaUnityLoadoutItemFactory LoadoutItemFactory { get; }
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 70318b35e2014bdfad48683869bfc04d

View file

@ -1,218 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UniRx;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
public sealed class AetheriaUnityGameplayInputShell : IDisposable
{
private readonly List<ActionBarSlot> _actionBarSlots = new List<ActionBarSlot>();
private readonly List<InputAction> _actionBarActions = new List<InputAction>();
private bool _uiHidden;
private int _zoomLevelIndex;
public AetheriaInput Input { get; private set; }
public RuntimePlayerSettings RuntimePlayerSettings { get; set; }
public InputDisplayLayout InputDisplayLayout { get; set; }
public ConfirmationDialog Dialog { get; set; }
public MainMenu MainMenu { get; set; }
public MenuPanel Menu { get; set; }
public MapRenderer MenuMap { get; set; }
public CanvasGroup GameplayUI { get; set; }
public Transform ActionBar { get; set; }
public ActionBarSlot ActionBarSlot { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public AetheriaUnityMenuShell MenuShell { get; set; }
public AetheriaUnityDragSession DragSession { get; set; }
public AetheriaUnityActionBarPresentation ActionBarPresentation { get; set; }
public AetheriaUnityPilotOperationController PilotOperationController { get; set; }
public Func<Entity> ResolveCurrentEntity { get; set; }
public Action<AetheriaInput> SetInput { get; set; }
public IReadOnlyList<ActionBarSlot> ActionBarSlots => _actionBarSlots;
public void Bootstrap()
{
Input = new AetheriaInput();
SetInput?.Invoke(Input);
if (RuntimePlayerSettings?.InputSettings != null)
{
foreach (var binding in RuntimePlayerSettings.InputSettings.InputActionMap)
Input.asset[binding.Key.action].ApplyBindingOverride(binding.Key.binding, binding.Value);
}
if (InputDisplayLayout != null)
InputDisplayLayout.Input = Input.asset;
Dialog?.SetInputGate(
() => Input.Global.Enable(),
() => Input.Global.Disable());
Input.Global.Enable();
_zoomLevelIndex = ZoneRenderer.RenderSettings.ResolveDefaultMinimapZoomIndex();
ZoneRenderer.MinimapDistance = (float)ZoneRenderer.RenderSettings.ResolveMinimapDistance(_zoomLevelIndex);
RegisterGlobalInput();
RegisterPlayerInput();
RegisterActionBarInput();
}
public void EnablePlayerInput()
{
Cursor.lockState = CursorLockMode.Locked;
Input.Player.Enable();
foreach (var action in _actionBarActions)
action.Enable();
}
public void DisablePlayerInput()
{
Cursor.lockState = CursorLockMode.None;
Input.Player.Disable();
foreach (var action in _actionBarActions)
action.Disable();
}
public void Dispose()
{
foreach (var action in _actionBarActions)
action.Dispose();
_actionBarActions.Clear();
_actionBarSlots.Clear();
Input?.Dispose();
Input = null;
}
private void RegisterGlobalInput()
{
Input.Global.ZoneMap.performed += context =>
{
MenuShell.ToggleMenuTab(MenuTab.Map);
var currentEntity = ResolveCurrentEntity?.Invoke();
if (currentEntity == null)
return;
MenuMap.Position = AetheriaMath.ToUnity(currentEntity.CultPositionXZ);
};
Input.Global.Inventory.performed += context => MenuShell.ToggleMenuTab(MenuTab.Inventory);
Input.Global.GalaxyMap.performed += context => MenuShell.ToggleMenuTab(MenuTab.Galaxy);
Input.Global.Interact.performed += context =>
{
if (IsTextInputFocused() || MainMenu.gameObject.activeSelf)
return;
if (ResolveCurrentEntity?.Invoke() == null)
{
Dialog.Clear();
Dialog.Title.text = "Can't undock. You dont have a ship!";
Dialog.Show();
Dialog.MoveToCursor();
return;
}
PilotOperationController.RequestInteract();
};
Input.Global.MainMenu.performed += context =>
{
if (Menu.gameObject.activeSelf)
MenuShell.ToggleMenuTab(Menu.CurrentTab);
else
MenuShell.ToggleFullscreenMenu(MainMenu.gameObject);
};
Input.Global.InputScreen.performed += context => MenuShell.ToggleFullscreenMenu(MenuShell.HelpScreen);
}
private void RegisterPlayerInput()
{
Input.Player.MinimapZoom.performed += context =>
{
_zoomLevelIndex = ZoneRenderer.RenderSettings.ResolveNextMinimapZoomIndex(_zoomLevelIndex);
ZoneRenderer.MinimapDistance = (float)ZoneRenderer.RenderSettings.ResolveMinimapDistance(_zoomLevelIndex);
};
Input.Player.HideUI.performed += context =>
{
_uiHidden = !_uiHidden;
GameplayUI.alpha = _uiHidden ? 0 : 1;
ActionBar.gameObject.SetActive(!_uiHidden);
};
Input.Player.OverrideShutdown.performed += context =>
{
var currentEntity = ResolveCurrentEntity?.Invoke();
if (currentEntity != null)
PilotOperationController.RequestOverrideShutdown(!currentEntity.OverrideShutdown);
};
Input.Player.Ping.performed += context => PilotOperationController.RequestSensorPing();
Input.Player.ToggleHeatsinks.performed += context =>
{
var currentEntity = ResolveCurrentEntity?.Invoke();
if (currentEntity != null)
PilotOperationController.RequestHeatsinksEnabled(!currentEntity.HeatsinksEnabled);
};
Input.Player.ToggleShield.performed += context => PilotOperationController.RequestShieldToggle();
Input.Player.TargetReticle.performed += context => PilotOperationController.RequestTargetReticle();
Input.Player.TargetNearest.performed += context => PilotOperationController.RequestTargetNearest();
Input.Player.TargetNext.performed += context => PilotOperationController.RequestTargetNext();
Input.Player.TargetPrevious.performed += context => PilotOperationController.RequestTargetPrevious();
}
private void RegisterActionBarInput()
{
foreach (var controlPath in (RuntimePlayerSettings?.InputSettings?.ActionBarInputs ?? Enumerable.Empty<string>()).OrderBy(input => input))
CreateActionBarSlot(controlPath);
}
private void CreateActionBarSlot(string controlPath)
{
var action = new InputAction(binding: controlPath);
_actionBarActions.Add(action);
var slot = UnityEngine.Object.Instantiate(ActionBarSlot, ActionBar);
slot.ControlPath = controlPath;
slot.Binding = null;
_actionBarSlots.Add(slot);
action.started += context => slot.Binding?.Activate();
action.canceled += context => slot.Binding?.Deactivate();
var shortName = controlPath.Substring(controlPath.LastIndexOf('/') + 1);
var sprite = Resources.Load<Sprite>($"Sprites/Input/{shortName}");
if (sprite != null)
{
slot.InputIcon.sprite = sprite;
slot.InputLabel.gameObject.SetActive(false);
}
else
{
slot.InputLabel.text = shortName;
slot.InputIcon.gameObject.SetActive(false);
}
slot.PointerEnterTrigger.OnPointerEnterAsObservable().Subscribe(_ =>
{
DragSession.RegisterTarget(dragAction => ActionBarPresentation.RequestBinding(slot, dragAction));
});
slot.PointerExitTrigger.OnPointerExitAsObservable().Subscribe(_ => DragSession.UnregisterTarget());
}
private static bool IsTextInputFocused()
{
return EventSystem.current != null &&
EventSystem.current.currentSelectedGameObject != null &&
EventSystem.current.currentSelectedGameObject.GetComponent<TMP_InputField>() != null;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 055f68d70b7c7634991717c468672f15

View file

@ -1,35 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
public sealed class AetheriaUnityGameplayLoopShell
{
public bool Paused { get; set; }
public Func<Entity> ResolveCurrentEntity { get; set; }
public Func<bool> IsCurrentEntityUndocked { get; set; }
public Action ApplyLatestZoneRender { get; set; }
public AetheriaUnityCurrentEntityPresentation CurrentEntityPresentation { get; set; }
public AetheriaUnityPilotFrameController PilotFrameController { get; set; }
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
public void Tick(float deltaTime, float time)
{
if (Paused)
return;
ApplyLatestZoneRender?.Invoke();
CurrentEntityPresentation?.Tick(deltaTime);
if (IsCurrentEntityUndocked?.Invoke() == true)
PilotFrameController?.Tick(ResolveCurrentEntity?.Invoke(), deltaTime, time);
}
public void LateTick()
{
TargetPresentation?.UpdateTargetIndicators(
ResolveCurrentEntity?.Invoke(),
IsCurrentEntityUndocked?.Invoke() == true,
CurrentEntityPresentation);
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: f4705e6dd36d4d89add3f3751008bf82

View file

@ -1,165 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using Cinemachine;
using GameCult.Aetheria.State.Verse;
using GameCult.Mesh;
using UnityEngine;
using UnityEngine.UI;
public sealed class AetheriaUnityGameplaySceneWiring
{
public ZoneRenderer ZoneRenderer { get; set; }
public CinemachineVirtualCamera DockCamera { get; set; }
public CinemachineVirtualCamera FollowCamera { get; set; }
public MenuPanel Menu { get; set; }
public TradeMenu TradeMenu { get; set; }
public CanvasGroup GameplayUI { get; set; }
public InventoryMenu Inventory { get; set; }
public InventoryPanel ShipPanel { get; set; }
public InventoryPanel TargetShipPanel { get; set; }
public SchematicDisplay SchematicDisplay { get; set; }
public SchematicDisplay TargetSchematicDisplay { get; set; }
public PlaceUIElementWorldspace[] Crosshairs { get; set; } = Array.Empty<PlaceUIElementWorldspace>();
public Prototype LockIndicator { get; set; }
public GameObject HitMarker { get; set; }
public float HitMarkerDuration { get; set; }
public Image TargetShieldsBackground { get; set; }
public Image TargetShieldsIcon { get; set; }
public Color ShieldColor { get; set; }
public Color NoShieldColor { get; set; }
public Sprite ShieldIcon { get; set; }
public Sprite NoShieldIcon { get; set; }
public Prototype HostileTargetIndicator { get; set; }
public Prototype FriendlyTargetIndicator { get; set; }
private AetheriaClientState _targetPresentationState;
private AetheriaClientState TargetPresentationState
{
get
{
_targetPresentationState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-target-presentation");
return _targetPresentationState;
}
}
public PlaceUIElementWorldspace ViewDot { get; set; }
public PlaceUIElementWorldspace TargetIndicator { get; set; }
public Image TargetHitpointsFill { get; set; }
public Image TargetVisibilityFill { get; set; }
public Image VisibilityToTargetFill { get; set; }
public Image TargetShieldsFill { get; set; }
public MainMenu MainMenu { get; set; }
public void ConfigureCurrentEntityPresentation(
AetheriaUnityCurrentEntityPresentation presentation,
AetheriaRuntimeCatalogSnapshot runtimeCatalog)
{
if (presentation == null)
return;
presentation.ZoneRenderer = ZoneRenderer;
presentation.RuntimeCatalog = runtimeCatalog;
presentation.DockCamera = DockCamera;
presentation.FollowCamera = FollowCamera;
presentation.Menu = Menu;
presentation.TradeMenu = TradeMenu;
presentation.GameplayUI = GameplayUI;
presentation.ShipPanel = ShipPanel;
presentation.TargetShipPanel = TargetShipPanel;
presentation.SchematicDisplay = SchematicDisplay;
presentation.TargetSchematicDisplay = TargetSchematicDisplay;
presentation.Crosshairs = Crosshairs;
presentation.LockIndicator = LockIndicator;
presentation.HitMarker = HitMarker;
presentation.HitMarkerDuration = HitMarkerDuration;
presentation.TargetImages = new ImageTargetPresentation
{
TargetShieldsBackground = TargetShieldsBackground,
TargetShieldsIcon = TargetShieldsIcon,
ShieldColor = ShieldColor,
NoShieldColor = NoShieldColor,
ShieldIcon = ShieldIcon,
NoShieldIcon = NoShieldIcon
};
}
public void ConfigureTargetPresentation(
AetheriaUnityTargetPresentation presentation,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
AetheriaUnityPresentationEntityIndex presentationEntityIndex)
{
if (presentation == null)
return;
presentation.ZoneRenderer = ZoneRenderer;
presentation.RuntimeCatalog = runtimeCatalog;
presentation.HostileTargetIndicator = HostileTargetIndicator;
presentation.FriendlyTargetIndicator = FriendlyTargetIndicator;
presentation.ViewDot = ViewDot;
presentation.TargetIndicator = TargetIndicator;
presentation.TargetHitpointsFill = TargetHitpointsFill;
presentation.TargetVisibilityFill = TargetVisibilityFill;
presentation.VisibilityToTargetFill = VisibilityToTargetFill;
presentation.TargetShieldsFill = TargetShieldsFill;
presentation.ResolveEntity = daemonEntityIndex =>
presentationEntityIndex != null &&
presentationEntityIndex.TryGetPresentationEntityByDaemonIndex(daemonEntityIndex, out var entity)
? entity
: null;
presentation.ResolveZoneContacts = ReadZoneContacts;
}
private AetheriaRuntimeZoneContactsDocument ReadZoneContacts()
{
try
{
return TargetPresentationState.ZoneContacts.Latest();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria zone contacts for target presentation: {ex.Message}");
return null;
}
}
public void ConfigureInventoryDragSession(AetheriaUnityDragSession dragSession)
{
Inventory?.SetDragSession(dragSession);
ShipPanel?.SetDragSession(dragSession);
TargetShipPanel?.SetDragSession(dragSession);
}
public void ConfigureActionBarPresentation(
AetheriaUnityActionBarPresentation actionBarPresentation,
AetheriaUnityGameplayInputShell gameplayInputShell,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
GameSettings settings,
Func<Entity> resolveCurrentEntity,
Func<AetheriaControl> resolveActionBarControl)
{
actionBarPresentation?.Bind(
gameplayInputShell?.ActionBarSlots ?? Array.Empty<ActionBarSlot>(),
runtimeCatalog,
settings,
resolveCurrentEntity,
resolveActionBarControl);
Inventory?.SetActionBarPresentation(actionBarPresentation);
}
public void ConfigureRuntimeInputScreenShell(AetheriaUnityMenuShell menuShell)
{
MainMenu?.SetRuntimeInputScreenShell(menuShell.CanOpenRuntimeInputScreen, menuShell.ShowRuntimeInputScreen);
}
public void ConfigurePresentationEntityIndex(AetheriaUnityPresentationEntityIndex presentationEntityIndex)
{
Inventory?.SetPresentationEntityIndex(presentationEntityIndex);
ShipPanel?.SetPresentationEntityIndex(presentationEntityIndex);
TargetShipPanel?.SetPresentationEntityIndex(presentationEntityIndex);
foreach (var localMenu in UnityEngine.Object.FindObjectsByType<LocalMenu>(FindObjectsSortMode.None))
localMenu.SetPresentationEntityIndex(presentationEntityIndex);
}
}

View file

@ -1,63 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityLoadoutItemFactory
{
private readonly ItemManager _itemManager;
private readonly AetheriaRuntimeCatalogSnapshot _catalog;
public AetheriaUnityLoadoutItemFactory(
ItemManager itemManager,
AetheriaRuntimeCatalogSnapshot catalog)
{
_itemManager = itemManager ?? throw new ArgumentNullException(nameof(itemManager));
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
}
public ItemInstance CreateLoadoutItem(AetheriaRuntimeLoadoutItemCommit item)
{
if (item == null)
return null;
return CreateLoadoutItem(
item.ItemKey,
item.Quality,
item.Durability,
Math.Max(1, item.Quantity));
}
public ItemInstance CreateLoadoutItem(AetheriaRuntimeLoadoutItemSnapshot item)
{
if (item == null)
return null;
return CreateLoadoutItem(
item.ItemKey,
item.Quality,
item.Durability,
Math.Max(1, item.Quantity));
}
private ItemInstance CreateLoadoutItem(
string itemKey,
double quality,
double durability,
int quantity)
{
var typedItem = _catalog.FindItem(itemKey ?? "");
if (typedItem == null)
return null;
if (typedItem.Stackable)
return _itemManager.CreateSimpleCommodityInstance(typedItem, Math.Max(1, quantity));
var instance = _itemManager.CreateCraftedInstance(typedItem, (float)quality);
if (instance is EquippableItem equippable && durability > 0)
equippable.Durability = (float)durability;
return instance;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: f14a61accda77214798bd71817fa2dcb

View file

@ -1,129 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
public sealed class AetheriaUnityMenuShell
{
public MainMenu MainMenu { get; set; }
public GameObject HelpScreen { get; set; }
public InputDisplayLayout InputDisplayLayout { get; set; }
public GameObject UiRoot { get; set; }
public MenuPanel Menu { get; set; }
public CanvasGroup GameplayUI { get; set; }
public Func<Entity> ResolveCurrentEntity { get; set; }
public Func<bool> IsCurrentEntityUndocked { get; set; }
public Func<Entity, Entity> ResolveObservedTarget { get; set; }
public Action<bool> SetPaused { get; set; }
public Action EnablePlayerInput { get; set; }
public Action DisablePlayerInput { get; set; }
public Action UpdatePlayerPanel { get; set; }
public Action<Entity> UpdateTargetPanel { get; set; }
private bool _menuShownBeforeFullscreen;
public bool CanOpenRuntimeInputScreen()
{
return ResolveCurrentEntity?.Invoke() != null &&
HelpScreen != null &&
InputDisplayLayout != null;
}
public void ShowRuntimeInputScreen()
{
ShowFullscreenMenu(HelpScreen);
}
public void ToggleFullscreenMenu(GameObject menu)
{
if (IsTextInputFocused() || menu == null || ResolveCurrentEntity?.Invoke() == null)
return;
if (menu.activeSelf)
HideFullscreenMenu(menu);
else
ShowFullscreenMenu(menu);
}
public void ToggleMenuTab(MenuTab tab)
{
if (IsTextInputFocused() || MainMenu == null || Menu == null)
return;
if (MainMenu.gameObject.activeSelf)
return;
if (Menu.gameObject.activeSelf && Menu.CurrentTab == tab)
{
Menu.gameObject.SetActive(false);
if (IsCurrentEntityUndocked?.Invoke() == true)
{
EnablePlayerInput?.Invoke();
RefreshCurrentPanels();
if (GameplayUI != null)
GameplayUI.gameObject.SetActive(true);
}
return;
}
DisablePlayerInput?.Invoke();
Menu.ShowTab(tab);
if (GameplayUI != null)
GameplayUI.gameObject.SetActive(false);
}
private void ShowFullscreenMenu(GameObject menu)
{
if (IsTextInputFocused() || menu == null || ResolveCurrentEntity?.Invoke() == null)
return;
if (MainMenu != null && MainMenu.gameObject != menu)
MainMenu.gameObject.SetActive(false);
if (HelpScreen != null && HelpScreen != menu)
HelpScreen.SetActive(false);
SetPaused?.Invoke(true);
menu.SetActive(true);
if (UiRoot != null)
UiRoot.SetActive(false);
_menuShownBeforeFullscreen = Menu != null && Menu.gameObject.activeSelf;
if (!_menuShownBeforeFullscreen)
DisablePlayerInput?.Invoke();
}
private void HideFullscreenMenu(GameObject menu)
{
if (menu == null || ResolveCurrentEntity?.Invoke() == null)
return;
SetPaused?.Invoke(false);
menu.SetActive(false);
if (UiRoot != null)
UiRoot.SetActive(true);
if (!_menuShownBeforeFullscreen)
{
EnablePlayerInput?.Invoke();
RefreshCurrentPanels();
}
}
private void RefreshCurrentPanels()
{
var currentEntity = ResolveCurrentEntity?.Invoke();
UpdatePlayerPanel?.Invoke();
UpdateTargetPanel?.Invoke(ResolveObservedTarget?.Invoke(currentEntity));
}
private static bool IsTextInputFocused()
{
return EventSystem.current != null &&
EventSystem.current.currentSelectedGameObject != null &&
EventSystem.current.currentSelectedGameObject.GetComponent<TMP_InputField>() != null;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 1a95f06d9ca2ddb47a07fdc47791f5af

View file

@ -1,346 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityObservedEntityRestorer
{
private readonly AetheriaUnityPresentationEntityIndex _entityIndex;
private readonly ItemManager _itemManager;
private readonly Func<AetheriaRuntimeEntitySnapshot, bool, EntityConstructionBlueprint> _createBlueprint;
private readonly Func<AetheriaRuntimeLoadoutItemSnapshot, ItemInstance> _createLoadoutItem;
private readonly Action<string> _logWarning;
public AetheriaUnityObservedEntityRestorer(
AetheriaUnityPresentationEntityIndex entityIndex,
ItemManager itemManager,
Func<AetheriaRuntimeEntitySnapshot, bool, EntityConstructionBlueprint> createBlueprint,
Func<AetheriaRuntimeLoadoutItemSnapshot, ItemInstance> createLoadoutItem,
Action<string> logWarning)
{
_entityIndex = entityIndex ?? throw new ArgumentNullException(nameof(entityIndex));
_itemManager = itemManager ?? throw new ArgumentNullException(nameof(itemManager));
_createBlueprint = createBlueprint ?? throw new ArgumentNullException(nameof(createBlueprint));
_createLoadoutItem = createLoadoutItem ?? throw new ArgumentNullException(nameof(createLoadoutItem));
_logWarning = logWarning ?? (_ => { });
}
public bool TryApplyInPlace(
string lastRunId,
int lastZoneIndex,
string runId,
int zoneIndex,
IReadOnlyList<AetheriaRuntimeEntitySnapshot> entitySnapshots,
string currentEntityKey,
Entity currentEntity,
out Entity reboundCurrentEntity)
{
reboundCurrentEntity = null;
if (!string.Equals(lastRunId, runId, StringComparison.Ordinal) ||
lastZoneIndex != zoneIndex ||
_entityIndex.Count != entitySnapshots.Count)
{
return false;
}
foreach (var snapshot in entitySnapshots)
{
if (!_entityIndex.ContainsRecordKey(snapshot.RecordKey))
return false;
}
ApplyInPlace(entitySnapshots);
if (_entityIndex.TryGetPresentationEntityByRecordKey(currentEntityKey, out var resolvedCurrentEntity) &&
currentEntity != resolvedCurrentEntity)
{
reboundCurrentEntity = resolvedCurrentEntity;
}
return true;
}
public void Replace(
IReadOnlyList<AetheriaRuntimeEntitySnapshot> entitySnapshots,
string currentEntityKey,
Zone zone)
{
var restoredEntities = new Dictionary<string, Entity>();
foreach (var entitySnapshot in entitySnapshots)
{
var blueprint = _createBlueprint(
entitySnapshot,
string.Equals(entitySnapshot.RecordKey, currentEntityKey, StringComparison.Ordinal));
if (blueprint == null)
{
_logWarning($"Typed entity snapshot {entitySnapshot.RecordKey} could not be lowered into a runtime entity.");
continue;
}
var entity = EntityConstructionBlueprintMaterializer.MaterializeObservedFromBlueprint(_itemManager, zone, blueprint);
if (entity == null)
continue;
ApplyPoseAndSimpleRuntimeState(entity, entitySnapshot);
entity.RestoreActiveState(entitySnapshot.IsActive);
restoredEntities[entitySnapshot.RecordKey] = entity;
}
foreach (var entitySnapshot in entitySnapshots)
{
if (!restoredEntities.TryGetValue(entitySnapshot.RecordKey, out var entity))
continue;
entity.HeatsinksEnabled = entitySnapshot.HeatsinksEnabled;
entity.RestoreStatGrids(entitySnapshot.StatGrids);
entity.RestoreThermalExposure((float)entitySnapshot.Heatstroke, (float)entitySnapshot.Hypothermia);
RestoreActiveConsumables(entity, entitySnapshot);
RestoreRuntimeBehaviorState(entity, entitySnapshot, restoredEntities);
}
_entityIndex.Replace(restoredEntities);
}
private void ApplyInPlace(IReadOnlyList<AetheriaRuntimeEntitySnapshot> entitySnapshots)
{
foreach (var entitySnapshot in entitySnapshots)
{
if (!_entityIndex.TryGetPresentationEntityByRecordKey(entitySnapshot.RecordKey, out var entity))
continue;
ApplyPoseAndSimpleRuntimeState(entity, entitySnapshot);
entity.HeatsinksEnabled = entitySnapshot.HeatsinksEnabled;
if (entity.Settings != null)
entity.Settings.ShutdownPerformance = (float)entitySnapshot.ShutdownPerformance;
entity.RestoreThermalExposure((float)entitySnapshot.Heatstroke, (float)entitySnapshot.Hypothermia);
RestoreRuntimeBehaviorState(entity, entitySnapshot, _entityIndex.PresentationEntitiesByRecordKey);
}
_entityIndex.RefreshDaemonIndex();
}
private static void ApplyPoseAndSimpleRuntimeState(Entity entity, AetheriaRuntimeEntitySnapshot entitySnapshot)
{
entity.DaemonRecordKey = entitySnapshot.RecordKey ?? "";
entity.DaemonEntityIndex = entitySnapshot.EntityIndex;
entity.Name = entitySnapshot.Name ?? "";
entity.CultPosition = new CultMath.float3((float)entitySnapshot.PositionX, (float)entitySnapshot.PositionY, (float)entitySnapshot.PositionZ);
entity.CultDirection = new CultMath.float2((float)entitySnapshot.DirectionX, (float)entitySnapshot.DirectionY);
entity.CultVelocity = new CultMath.float2((float)entitySnapshot.VelocityX, (float)entitySnapshot.VelocityY);
entity.OverrideShutdown = entitySnapshot.OverrideShutdown;
entity.TractorPower = (float)entitySnapshot.TractorPower;
}
private void RestoreActiveConsumables(Entity entity, AetheriaRuntimeEntitySnapshot snapshot)
{
var activeEffectIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var activeConsumable in snapshot.ActiveConsumables)
{
if (string.IsNullOrWhiteSpace(activeConsumable.EffectId))
{
_logWarning($"Typed active consumable {activeConsumable.ItemKey} has no daemon effect identity on restored entity {snapshot.RecordKey}.");
continue;
}
activeEffectIds.Add(activeConsumable.EffectId);
var item = _createLoadoutItem(new AetheriaRuntimeLoadoutItemSnapshot(
activeConsumable.ItemKey,
activeConsumable.Quality,
1,
1,
true,
false)) as ConsumableItem;
if (item == null)
{
_logWarning($"Typed active consumable {activeConsumable.ItemKey} could not be lowered for restored entity {snapshot.RecordKey}.");
continue;
}
entity.RestoreActiveConsumable(
activeConsumable.EffectId,
item,
(float)activeConsumable.RemainingDuration,
(float)activeConsumable.Duration);
}
entity.RetainActiveConsumables(activeEffectIds);
}
private static void RestoreRuntimeBehaviorState(
Entity entity,
AetheriaRuntimeEntitySnapshot snapshot,
IReadOnlyDictionary<string, Entity> restoredEntities)
{
foreach (var weaponState in snapshot.WeaponStates)
{
if (!(ResolveRuntimeBehavior(entity, weaponState.OwnerKind, weaponState.OwnerIndex, weaponState.BehaviorIndex) is Weapon weapon))
continue;
if (weapon is LockWeapon lockWeapon)
{
restoredEntities.TryGetValue(weaponState.LockTargetEntityKey, out var lockTarget);
lockWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
weaponState.BurstRemaining,
(float)weaponState.BurstTimer,
(float)weaponState.BurstInterval,
(float)weaponState.CooldownProgress,
weaponState.CoolingDown,
(float)weaponState.LockProgress,
lockTarget);
}
else if (weapon is ChargedWeapon chargedWeapon)
{
chargedWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
weaponState.BurstRemaining,
(float)weaponState.BurstTimer,
(float)weaponState.BurstInterval,
(float)weaponState.CooldownProgress,
weaponState.CoolingDown,
weaponState.Charging,
weaponState.Charged,
(float)weaponState.Charge);
}
else if (weapon is ConstantWeapon constantWeapon)
{
constantWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
(float)weaponState.AmmoIntervalProgress,
(float)weaponState.ReloadProgress,
weaponState.Reloading);
}
else if (weapon is InstantWeapon instantWeapon)
{
instantWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
weaponState.BurstRemaining,
(float)weaponState.BurstTimer,
(float)weaponState.BurstInterval,
(float)weaponState.CooldownProgress,
weaponState.CoolingDown);
}
else
{
weapon.RestoreRuntimeState(weaponState.Firing);
}
}
foreach (var behaviorState in snapshot.BehaviorStates)
{
var behavior = ResolveRuntimeBehavior(entity, behaviorState.OwnerKind, behaviorState.OwnerIndex, behaviorState.BehaviorIndex);
switch (behavior)
{
case Sensor sensor:
sensor.RestoreRuntimeState(
behaviorState.Pinging,
(float)behaviorState.PingCooldown,
(float)behaviorState.PingLerp,
(float)behaviorState.PingRadius);
break;
case Radiator radiator:
radiator.RestoreRuntimeState(
(float)behaviorState.RadiatorTemperature,
(float)behaviorState.Emissivity,
(float)behaviorState.PumpedHeat,
(float)behaviorState.WasteHeat,
(float)behaviorState.EnergyUsage);
break;
case Reactor reactor:
reactor.RestoreRuntimeState(
(float)behaviorState.ReactorDraw,
(float)behaviorState.ReactorLoadRatio);
break;
case Capacitor capacitor:
capacitor.RestoreRuntimeState(
(float)behaviorState.CapacitorCharge,
(float)behaviorState.CapacitorCapacity,
(float)behaviorState.CapacitorEfficiency);
break;
case AetherDrive drive:
drive.RestoreRuntimeState(
new CultMath.float3((float)behaviorState.AetherDriveAxisX, (float)behaviorState.AetherDriveAxisY, (float)behaviorState.AetherDriveAxisZ),
new CultMath.float3((float)behaviorState.AetherDriveThrustX, (float)behaviorState.AetherDriveThrustY, (float)behaviorState.AetherDriveThrustZ),
new CultMath.float3((float)behaviorState.AetherDriveRpmX, (float)behaviorState.AetherDriveRpmY, (float)behaviorState.AetherDriveRpmZ),
(float)behaviorState.AetherDriveMaximumRpm,
new CultMath.float2((float)behaviorState.AetherDriveThrustDirectionX, (float)behaviorState.AetherDriveThrustDirectionY));
break;
case ResourceScanner resourceScanner:
resourceScanner.RestoreRuntimeState(
behaviorState.ResourceScannerTargetBodyKey,
behaviorState.ResourceScannerAsteroidIndex,
(float)behaviorState.ResourceScannerScanTime,
(float)behaviorState.ResourceScannerRange,
(float)behaviorState.ResourceScannerMinimumDensity,
(float)behaviorState.ResourceScannerScanDuration);
break;
case MiningTool miningTool:
miningTool.RestoreRuntimeState(
behaviorState.MiningToolAsteroidBeltKey,
behaviorState.MiningToolAsteroidIndex,
(float)behaviorState.MiningToolRange);
break;
case Thruster thruster:
thruster.RestoreRuntimeState(
(float)behaviorState.ThrusterAxis,
(float)behaviorState.ThrusterThrust);
break;
case Shield shield:
shield.RestoreRuntimeState(
(float)behaviorState.ShieldEfficiency,
(float)behaviorState.ShieldEnergyUsage);
break;
case VelocityLimit velocityLimit:
velocityLimit.RestoreRuntimeState((float)behaviorState.VelocityLimit);
break;
case Thermotoggle thermotoggle:
thermotoggle.TargetTemperature = (float)behaviorState.ThermotoggleTargetTemperature;
break;
case Switch switchBehavior:
switchBehavior.Activated = behaviorState.SwitchActivated;
break;
case Trigger trigger:
trigger.RestoreRuntimeState(behaviorState.TriggerPulled);
break;
case StatModifier statModifier:
statModifier.RestoreRuntimeState(
behaviorState.StatModifierApplied,
behaviorState.StatModifierExecuted);
break;
case TurretController turretController:
turretController.RestoreRuntimeState(
(float)behaviorState.TurretControllerShotSpeed,
behaviorState.TurretControllerPredictShots);
break;
}
}
}
private static Behavior ResolveRuntimeBehavior(Entity entity, string ownerKind, int ownerIndex, int behaviorIndex)
{
var behaviors = ResolveRuntimeBehaviorList(entity, ownerKind, ownerIndex);
return behaviors != null && behaviorIndex >= 0 && behaviorIndex < behaviors.Count
? behaviors[behaviorIndex]
: null;
}
private static IReadOnlyList<Behavior> ResolveRuntimeBehaviorList(Entity entity, string ownerKind, int ownerIndex)
{
if (entity == null || ownerIndex < 0)
return null;
switch (ownerKind)
{
case "equipment":
return ownerIndex < entity.Equipment.Count ? entity.Equipment[ownerIndex].Behaviors : null;
default:
return null;
}
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 0a109bddc65c3d64bb233e11260276d5

View file

@ -1,159 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityObservedFrameApplier
{
private readonly Func<AetheriaDaemonObserver> _resolveObserver;
private readonly Func<int, GalaxyZone> _resolveObservedZone;
private readonly Func<Zone> _getZone;
private readonly Action<Zone> _setZone;
private readonly AetheriaUnityPresentationEntityIndex _entityIndex;
private readonly AetheriaUnityObservedEntityRestorer _entityRestorer;
private readonly AetheriaUnityObservedZoneContextFactory _zoneContextFactory;
private readonly Func<ZoneRenderer> _resolveZoneRenderer;
private readonly Func<Entity> _getCurrentEntity;
private readonly Action<Entity> _restoreCurrentEntityBinding;
private readonly Action<string> _logWarning;
private long _lastAppliedZoneRenderFrameId = -1;
private string _lastAppliedZoneRenderRunId = "";
private int _lastAppliedZoneRenderZoneIndex = -1;
private AetheriaRuntimeZoneRenderDocument _lastZoneRender;
public AetheriaUnityObservedFrameApplier(
Func<AetheriaDaemonObserver> resolveObserver,
Func<int, GalaxyZone> resolveObservedZone,
Func<Zone> getZone,
Action<Zone> setZone,
AetheriaUnityPresentationEntityIndex entityIndex,
AetheriaUnityObservedEntityRestorer entityRestorer,
AetheriaUnityObservedZoneContextFactory zoneContextFactory,
Func<ZoneRenderer> resolveZoneRenderer,
Func<Entity> getCurrentEntity,
Action<Entity> restoreCurrentEntityBinding,
Action<string> logWarning)
{
_resolveObserver = resolveObserver ?? (() => null);
_resolveObservedZone = resolveObservedZone ?? (_ => null);
_getZone = getZone ?? (() => null);
_setZone = setZone ?? (_ => { });
_entityIndex = entityIndex ?? throw new ArgumentNullException(nameof(entityIndex));
_entityRestorer = entityRestorer ?? throw new ArgumentNullException(nameof(entityRestorer));
_zoneContextFactory = zoneContextFactory ?? throw new ArgumentNullException(nameof(zoneContextFactory));
_resolveZoneRenderer = resolveZoneRenderer ?? (() => null);
_getCurrentEntity = getCurrentEntity ?? (() => null);
_restoreCurrentEntityBinding = restoreCurrentEntityBinding ?? (_ => { });
_logWarning = logWarning ?? (_ => { });
}
public bool ApplyLatestZoneRender()
{
var observer = _resolveObserver();
if (observer == null || !observer.HasAuthoritativeState)
{
return false;
}
var render = observer.LastRenderView?.ZoneRender;
if (render == null)
{
return false;
}
return TryRestoreEntityGraphFromZoneRender(render);
}
private bool TryRestoreEntityGraphFromZoneRender(AetheriaRuntimeZoneRenderDocument render)
{
if (render == null || render.ZoneIndex < 0)
{
return false;
}
if (string.IsNullOrWhiteSpace(render.RunId))
{
_logWarning("Aetheria zone-render feed does not identify a run id.");
return false;
}
var runId = render.RunId;
var currentEntityKey = string.IsNullOrWhiteSpace(render.CurrentEntityKey) ? "" : render.CurrentEntityKey;
if (string.IsNullOrWhiteSpace(currentEntityKey))
{
_logWarning($"Aetheria zone-render feed for run {runId} does not identify a current entity.");
return false;
}
var entitySnapshots = render.CreateEntitySnapshots()
.OrderBy(entity => entity.EntityIndex)
.ToArray();
if (entitySnapshots.Length == 0)
{
_logWarning($"Aetheria zone-render feed has no entity snapshots for zone {render.ZoneIndex}.");
return false;
}
var targetZone = _resolveObservedZone(render.ZoneIndex);
if (targetZone == null)
{
_logWarning($"Aetheria zone-render feed references missing zone index {render.ZoneIndex}.");
return false;
}
if (render.FrameId == _lastAppliedZoneRenderFrameId &&
string.Equals(render.RunId, _lastAppliedZoneRenderRunId, StringComparison.Ordinal) &&
render.ZoneIndex == _lastAppliedZoneRenderZoneIndex)
{
return false;
}
var zoneRenderer = _resolveZoneRenderer();
if (_entityRestorer.TryApplyInPlace(
_lastAppliedZoneRenderRunId,
_lastAppliedZoneRenderZoneIndex,
runId,
render.ZoneIndex,
entitySnapshots,
currentEntityKey,
_getCurrentEntity(),
out var reboundCurrentEntity))
{
if (reboundCurrentEntity != null)
_restoreCurrentEntityBinding(reboundCurrentEntity);
zoneRenderer?.ApplyZoneRender(render);
zoneRenderer?.RestoreDroppedPickupsFromZoneRender(render);
_lastAppliedZoneRenderFrameId = render.FrameId;
_lastAppliedZoneRenderRunId = runId;
_lastAppliedZoneRenderZoneIndex = render.ZoneIndex;
_lastZoneRender = render;
return true;
}
if (_getZone()?.GalaxyZone != targetZone)
{
var resolvedZone = _zoneContextFactory.ResolveContext(targetZone, render);
if (resolvedZone == null)
return false;
_setZone(resolvedZone);
}
_entityRestorer.Replace(entitySnapshots, currentEntityKey, _getZone());
zoneRenderer?.LoadDaemonZoneView(_entityIndex.PresentationEntitiesByDaemonIndex, render);
if (_entityIndex.TryGetPresentationEntityByRecordKey(currentEntityKey, out var currentEntity))
_restoreCurrentEntityBinding(currentEntity);
zoneRenderer?.RestoreDroppedPickupsFromZoneRender(render);
_lastAppliedZoneRenderFrameId = render.FrameId;
_lastAppliedZoneRenderRunId = runId;
_lastAppliedZoneRenderZoneIndex = render.ZoneIndex;
_lastZoneRender = render;
return true;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 5f83634c47d54bc4aa34f8c976a660ce

View file

@ -1,198 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
using float2 = Unity.Mathematics.float2;
using float4 = Unity.Mathematics.float4;
public sealed class AetheriaUnityObservedZoneContextFactory
{
private readonly Dictionary<int, Zone> _observedZoneContextsByDaemonIndex = new Dictionary<int, Zone>();
private readonly ItemManager _itemManager;
private readonly PlanetSettings _planetSettings;
private readonly Action<string> _logWarning;
private readonly Action<MusicType> _playMusic;
private readonly Galaxy _observedGalaxy;
public AetheriaUnityObservedZoneContextFactory(
ItemManager itemManager,
PlanetSettings planetSettings,
Galaxy observedGalaxy,
Action<string> logWarning,
Action<MusicType> playMusic)
{
_itemManager = itemManager ?? throw new ArgumentNullException(nameof(itemManager));
_planetSettings = planetSettings ?? throw new ArgumentNullException(nameof(planetSettings));
_observedGalaxy = observedGalaxy;
_logWarning = logWarning ?? (_ => { });
_playMusic = playMusic ?? (_ => { });
}
public Zone ResolveContext(
GalaxyZone galaxyZone,
AetheriaRuntimeZoneRenderDocument render)
{
if (galaxyZone == null)
throw new ArgumentNullException(nameof(galaxyZone));
if (render == null)
{
_logWarning($"Daemon-authoritative zone population suppressed for {galaxyZone.Name}; no zone-render document was provided.");
return null;
}
var zoneIndex = render.ZoneIndex;
if (!_observedZoneContextsByDaemonIndex.TryGetValue(zoneIndex, out var observedZoneContext))
{
if (_observedGalaxy == null)
{
_logWarning($"Daemon-authoritative zone population suppressed for {galaxyZone.Name}; no observed sector projection is available.");
return null;
}
var constructionBlueprint = CreateZoneConstructionBlueprint(render);
observedZoneContext = new Zone(_itemManager, _planetSettings, constructionBlueprint, galaxyZone, _observedGalaxy);
_observedZoneContextsByDaemonIndex[zoneIndex] = observedZoneContext;
}
_playMusic(MusicType.Overworld);
observedZoneContext.Log = s => Debug.Log($"Zone: {s}");
return observedZoneContext;
}
public GalaxyZone ResolveGalaxyZone(int daemonZoneIndex)
{
if (daemonZoneIndex < 0)
return null;
return _observedGalaxy?.Zones?.FirstOrDefault(zone => zone != null && zone.ZoneIndex == daemonZoneIndex);
}
private static ZoneConstructionBlueprint CreateZoneConstructionBlueprint(AetheriaRuntimeZoneRenderDocument render)
{
var blueprint = new ZoneConstructionBlueprint
{
Radius = 2000,
Mass = 10000,
Time = (float)render.SimulationTimeSeconds
};
foreach (var orbit in render.Orbits ?? Array.Empty<AetheriaRuntimeOrbitSnapshotCommit>())
{
if (orbit == null)
continue;
blueprint.Orbits.Add(new OrbitConstructionData
{
OrbitKey = orbit.OrbitKey ?? "",
ParentOrbitKey = orbit.ParentOrbitKey ?? "",
Distance = (float)orbit.Distance,
Phase = (float)orbit.Phase,
FixedPosition = new float2((float)orbit.FixedPositionX, (float)orbit.FixedPositionY)
});
}
foreach (var body in render.Bodies ?? Array.Empty<AetheriaRuntimeBodySnapshotCommit>())
{
if (body == null)
continue;
blueprint.Bodies.Add(CreateBodyConstructionData(body));
}
return blueprint;
}
private static BodyConstructionData CreateBodyConstructionData(AetheriaRuntimeBodySnapshotCommit body)
{
BodyConstructionData data = (body.Kind ?? "").ToLowerInvariant() switch
{
"asteroid_belt" => new AsteroidBeltConstructionData
{
Asteroids = (body.Asteroids ?? Array.Empty<AetheriaRuntimeAsteroidCommit>())
.Where(asteroid => asteroid != null)
.Select(asteroid => new Asteroid
{
Distance = (float)asteroid.Distance,
Phase = (float)asteroid.Phase,
Size = (float)asteroid.Size,
RotationSpeed = (float)asteroid.RotationSpeed
})
.ToArray()
},
"sun" => CreateSunConstructionData(body),
"gas_giant" => CreateGasGiantConstructionData(body),
_ => new PlanetConstructionData()
};
PopulateBodyConstructionData(data, body);
return data;
}
private static GasGiantConstructionData CreateGasGiantConstructionData(AetheriaRuntimeBodySnapshotCommit body)
{
var visual = body.GasGiantVisual ?? new AetheriaRuntimeGasGiantVisualCommit();
return new GasGiantConstructionData
{
FirstOffsetDomainRotationSpeed = (float)visual.FirstOffsetDomainRotationSpeed,
FirstOffsetRotationSpeed = (float)visual.FirstOffsetRotationSpeed,
SecondOffsetDomainRotationSpeed = (float)visual.SecondOffsetDomainRotationSpeed,
SecondOffsetRotationSpeed = (float)visual.SecondOffsetRotationSpeed,
AlbedoRotationSpeed = (float)visual.AlbedoRotationSpeed,
WaveRadiusMultiplier = (float)visual.WaveRadiusMultiplier,
WaveDepthMultiplier = (float)visual.WaveDepthMultiplier,
WaveDepthExponent = (float)visual.WaveDepthExponent,
WaveSpeedMultiplier = (float)visual.WaveSpeedMultiplier,
MaterialOverrides = (visual.MaterialOverrides ?? Array.Empty<string>()).ToList(),
Colors = (visual.Colors ?? Array.Empty<AetheriaRuntimeColorCommit>())
.Where(color => color != null)
.Select(color => new float4((float)color.X, (float)color.Y, (float)color.Z, (float)color.W))
.ToArray()
};
}
private static SunConstructionData CreateSunConstructionData(AetheriaRuntimeBodySnapshotCommit body)
{
var gas = CreateGasGiantConstructionData(body);
var visual = body.SunVisual ?? new AetheriaRuntimeSunVisualCommit();
return new SunConstructionData
{
FirstOffsetDomainRotationSpeed = gas.FirstOffsetDomainRotationSpeed,
FirstOffsetRotationSpeed = gas.FirstOffsetRotationSpeed,
SecondOffsetDomainRotationSpeed = gas.SecondOffsetDomainRotationSpeed,
SecondOffsetRotationSpeed = gas.SecondOffsetRotationSpeed,
AlbedoRotationSpeed = gas.AlbedoRotationSpeed,
WaveRadiusMultiplier = gas.WaveRadiusMultiplier,
WaveDepthMultiplier = gas.WaveDepthMultiplier,
WaveDepthExponent = gas.WaveDepthExponent,
WaveSpeedMultiplier = gas.WaveSpeedMultiplier,
MaterialOverrides = gas.MaterialOverrides,
Colors = gas.Colors,
LightColor = new CultMath.float3((float)visual.LightColorX, (float)visual.LightColorY, (float)visual.LightColorZ),
FogTintColor = new CultMath.float3((float)visual.FogTintColorX, (float)visual.FogTintColorY, (float)visual.FogTintColorZ),
LightRadiusMultiplier = (float)visual.LightRadiusMultiplier
};
}
private static void PopulateBodyConstructionData(
BodyConstructionData data,
AetheriaRuntimeBodySnapshotCommit body)
{
data.BodyKey = body.BodyKey ?? "";
data.Name = body.Name ?? "";
data.OrbitKey = body.OrbitKey ?? "";
data.Mass = (float)body.Mass;
data.BodyRadiusMultiplier = (float)body.BodyRadiusMultiplier;
data.GravityRadiusMultiplier = (float)body.GravityRadiusMultiplier;
data.GravityDepthMultiplier = (float)body.GravityDepthMultiplier;
data.GravityDepthExponent = (float)body.GravityDepthExponent;
data.Resources = (body.Resources ?? Array.Empty<AetheriaRuntimeBodyResourceCommit>())
.Where(resource => resource != null && !string.IsNullOrWhiteSpace(resource.ItemKey))
.ToDictionary(resource => resource.ItemKey, resource => (float)resource.Amount, StringComparer.Ordinal);
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 585768cd246ecc249b1e49ee64a7def9

View file

@ -1,122 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
public sealed class AetheriaUnityPilotCommandSender
{
private const float DaemonMoveCommandIntervalSeconds = 0.05f;
private const float DaemonMoveCommandChangeThreshold = 0.001f;
private const float DaemonLookCommandIntervalSeconds = 0.02f;
private const float DaemonLookCommandChangeThreshold = 0.0001f;
private const float DaemonTractorCommandIntervalSeconds = 0.05f;
private const float DaemonTractorCommandChangeThreshold = 0.001f;
private readonly Func<AetheriaControl> _resolveControl;
private readonly Func<float> _time;
private Vector2 _lastSentDaemonMoveVector;
private Vector3 _lastSentDaemonLookDirection;
private float _lastSentDaemonTractorPower;
private float _nextDaemonMoveCommandTime;
private float _nextDaemonLookCommandTime;
private float _nextDaemonTractorCommandTime;
private bool _hasSentDaemonMoveVector;
private bool _hasSentDaemonLookDirection;
private bool _hasSentDaemonTractorPower;
public AetheriaUnityPilotCommandSender(
Func<AetheriaControl> resolveControl,
Func<float> time)
{
_resolveControl = resolveControl ?? throw new ArgumentNullException(nameof(resolveControl));
_time = time ?? throw new ArgumentNullException(nameof(time));
}
public void RequestMoveVector(Vector2 movement)
{
var changed = !_hasSentDaemonMoveVector ||
(movement - _lastSentDaemonMoveVector).sqrMagnitude >
DaemonMoveCommandChangeThreshold * DaemonMoveCommandChangeThreshold;
if (!changed && _time() < _nextDaemonMoveCommandTime)
{
return;
}
if (TrySubmit(
operations => operations.SetMoveVector(movement.x, movement.y, movement.magnitude),
"movement"))
{
_lastSentDaemonMoveVector = movement;
_hasSentDaemonMoveVector = true;
_nextDaemonMoveCommandTime = _time() + DaemonMoveCommandIntervalSeconds;
}
}
public void RequestLookDirection(Vector3 lookDirection)
{
var changed = !_hasSentDaemonLookDirection ||
(lookDirection - _lastSentDaemonLookDirection).sqrMagnitude >
DaemonLookCommandChangeThreshold * DaemonLookCommandChangeThreshold;
if (!changed && _time() < _nextDaemonLookCommandTime)
{
return;
}
if (TrySubmit(
operations => operations.SetLookDirection(lookDirection.x, lookDirection.y, lookDirection.z),
"look"))
{
_lastSentDaemonLookDirection = lookDirection;
_hasSentDaemonLookDirection = true;
_nextDaemonLookCommandTime = _time() + DaemonLookCommandIntervalSeconds;
}
}
public void RequestTractorPower(float power)
{
var changed = !_hasSentDaemonTractorPower ||
Mathf.Abs(power - _lastSentDaemonTractorPower) >
DaemonTractorCommandChangeThreshold;
if (!changed && _time() < _nextDaemonTractorCommandTime)
{
return;
}
if (TrySubmit(
operations => operations.SetTractorPower(power),
"tractor-power"))
{
_lastSentDaemonTractorPower = power;
_hasSentDaemonTractorPower = true;
_nextDaemonTractorCommandTime = _time() + DaemonTractorCommandIntervalSeconds;
}
}
public bool TrySubmit(
Action<AetheriaControl> submit,
string label)
{
if (submit == null)
{
return false;
}
try
{
var control = _resolveControl();
if (control == null)
return false;
submit(control);
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to send Aetheria daemon pilot {label} operation; operation not submitted: {ex.Message}");
return false;
}
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 2c98d1a89797d6c4ba1034ac4d171e51

View file

@ -1,75 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;
using static Unity.Mathematics.math;
public sealed class AetheriaUnityPilotFrameController
{
private float2 _entityYawPitch;
private readonly Action<float3> _setViewDirection;
public AetheriaUnityPilotFrameController(Action<float3> setViewDirection)
{
_setViewDirection = setViewDirection ?? (_ => { });
}
public ZoneRenderer ZoneRenderer { get; set; }
public AetheriaInput Input { get; set; }
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
public AetheriaUnityPilotCommandSender PilotCommands { get; set; }
public Volume HeatstrokePost { get; set; }
public Volume SevereHeatstrokePost { get; set; }
public float2 Sensitivity { get; set; }
public void Tick(Entity currentEntity, float deltaTime, float timeSeconds)
{
if (currentEntity == null ||
Input == null ||
PilotCommands == null)
{
return;
}
TargetPresentation?.Tick(currentEntity, timeSeconds);
var look = Input.Player.Look.ReadValue<Vector2>();
_entityYawPitch = new float2(
_entityYawPitch.x + look.x * Sensitivity.x,
Mathf.Clamp(_entityYawPitch.y + look.y * Sensitivity.y, -.45f * Mathf.PI, .45f * Mathf.PI));
var viewDirection = (float3)(Quaternion.Euler(
_entityYawPitch.y * Mathf.Rad2Deg,
_entityYawPitch.x * Mathf.Rad2Deg,
0) * Vector3.forward);
_setViewDirection(viewDirection);
PilotCommands.RequestLookDirection(viewDirection);
if (ZoneRenderer != null)
{
var renderSettings = ZoneRenderer.RenderSettings;
if (HeatstrokePost != null)
HeatstrokePost.weight = (float)renderSettings.NormalizeHeatstrokePost(currentEntity.Heatstroke);
if (SevereHeatstrokePost != null)
SevereHeatstrokePost.weight =
(float)renderSettings.ResolveSevereHeatstrokePostWeight(currentEntity.Heatstroke, timeSeconds);
}
if (currentEntity is Ship)
{
var movement = Input.Player.Move.ReadValue<Vector2>();
PilotCommands.RequestMoveVector(movement);
}
var tractorPowerInput = Input.Player.TractorBeam.ReadValue<float>();
PilotCommands.RequestTractorPower(Saturate(
currentEntity.TractorPower +
Mathf.Sign(tractorPowerInput - currentEntity.TractorPower) * deltaTime * 2));
}
private static float Saturate(float value) => Mathf.Clamp01(value);
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 5dfa48356761f45408a1c1a7febd7438

View file

@ -1,114 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using GameCult.Aetheria.State.Verse;
using Unity.Mathematics;
public sealed class AetheriaUnityPilotOperationController
{
private readonly Func<AetheriaUnityPilotCommandSender> _resolvePilotCommands;
private readonly AetheriaUnityPresentationEntityIndex _presentationEntityIndex;
private readonly Func<float3> _resolveViewDirection;
private readonly Func<Entity> _resolveCurrentEntity;
public AetheriaUnityPilotOperationController(
Func<AetheriaUnityPilotCommandSender> resolvePilotCommands,
AetheriaUnityPresentationEntityIndex presentationEntityIndex,
Func<float3> resolveViewDirection,
Func<Entity> resolveCurrentEntity)
{
_resolvePilotCommands = resolvePilotCommands ?? throw new ArgumentNullException(nameof(resolvePilotCommands));
_presentationEntityIndex = presentationEntityIndex ?? throw new ArgumentNullException(nameof(presentationEntityIndex));
_resolveViewDirection = resolveViewDirection ?? (() => default);
_resolveCurrentEntity = resolveCurrentEntity ?? (() => null);
}
public void RequestInteract()
{
Submit(operations => operations.Interact(), "interact");
}
public void RequestTargetSelection(Entity target)
{
if (target == null)
{
Submit(operations => operations.ClearTarget(), "target clear");
return;
}
if (!_presentationEntityIndex.TryGetRecordKeyForPresentationEntity(target, out var targetEntityKey) ||
string.IsNullOrWhiteSpace(targetEntityKey))
{
return;
}
Submit(
operations => operations.SetTarget(targetEntityKey),
"target");
}
public void RequestTargetNearest()
{
Submit(operations => operations.TargetNearest(), "target nearest");
}
public void RequestTargetNext()
{
Submit(operations => operations.TargetNext(), "target next");
}
public void RequestTargetPrevious()
{
Submit(operations => operations.TargetPrevious(), "target previous");
}
public void RequestTargetReticle()
{
var lookDirection = _resolveViewDirection();
Submit(
operations => operations.TargetReticle(lookDirection.x, lookDirection.y, lookDirection.z),
"reticle target");
}
public void RequestOverrideShutdown(bool enabled)
{
Submit(operations => operations.SetOverrideShutdown(enabled), "override-shutdown");
}
public void RequestSensorPing()
{
Submit(operations => operations.SensorPing(), "sensor-ping");
}
public void RequestHeatsinksEnabled(bool enabled)
{
Submit(operations => operations.SetHeatsinksEnabled(enabled), "heatsinks");
}
public void RequestShieldToggle()
{
Submit(operations => operations.ToggleShieldEnabled(), "shield enablement");
}
public void RequestDock()
{
Submit(operations => operations.DockNearest(), "dock");
}
public void RequestUndock()
{
if (_resolveCurrentEntity() == null)
return;
Submit(operations => operations.Undock(), "undock");
}
private void Submit(
Action<AetheriaControl> submit,
string label)
{
_resolvePilotCommands()?.TrySubmit(submit, label);
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 65505a1513191d64fa99fd51d3508383

View file

@ -1,109 +0,0 @@
using System;
using System.Collections.Generic;
public sealed class AetheriaUnityPresentationEntityIndex
{
private readonly Dictionary<string, Entity> _entitiesByRecordKey = new Dictionary<string, Entity>(StringComparer.Ordinal);
private readonly Dictionary<int, Entity> _entitiesByDaemonIndex = new Dictionary<int, Entity>();
public IReadOnlyDictionary<string, Entity> PresentationEntitiesByRecordKey => _entitiesByRecordKey;
public IReadOnlyDictionary<int, Entity> PresentationEntitiesByDaemonIndex => _entitiesByDaemonIndex;
public int Count => _entitiesByRecordKey.Count;
public bool ContainsRecordKey(string recordKey)
{
return !string.IsNullOrWhiteSpace(recordKey) &&
_entitiesByRecordKey.ContainsKey(recordKey);
}
public void Replace(IReadOnlyDictionary<string, Entity> entitiesByRecordKey)
{
_entitiesByRecordKey.Clear();
if (entitiesByRecordKey != null)
{
foreach (var pair in entitiesByRecordKey)
{
if (!string.IsNullOrWhiteSpace(pair.Key) && pair.Value != null)
{
pair.Value.DaemonRecordKey = pair.Key;
_entitiesByRecordKey[pair.Key] = pair.Value;
}
}
}
RebuildDaemonIndex();
}
public void RefreshDaemonIndex()
{
RebuildDaemonIndex();
}
public bool TryGetRecordKeyForPresentationEntity(Entity entity, out string recordKey)
{
recordKey = "";
if (entity == null)
return false;
if (!string.IsNullOrWhiteSpace(entity.DaemonRecordKey) &&
_entitiesByRecordKey.TryGetValue(entity.DaemonRecordKey, out var indexedEntity) &&
ReferenceEquals(indexedEntity, entity))
{
recordKey = entity.DaemonRecordKey;
return true;
}
foreach (var pair in _entitiesByRecordKey)
{
if (ReferenceEquals(pair.Value, entity))
{
recordKey = pair.Key;
return true;
}
}
return false;
}
public bool TryGetPresentationEntityByRecordKey(string recordKey, out Entity entity)
{
entity = null;
return !string.IsNullOrWhiteSpace(recordKey) &&
_entitiesByRecordKey.TryGetValue(recordKey, out entity);
}
public bool TryGetPresentationEntityByDaemonIndex(int daemonEntityIndex, out Entity entity)
{
return _entitiesByDaemonIndex.TryGetValue(daemonEntityIndex, out entity);
}
public bool TryGetPresentationDockingBayByRecordKey(
string parentRecordKey,
int dockingBayIndex,
out EquippedDockingBay dockingBay)
{
dockingBay = null;
if (dockingBayIndex < 0 ||
!TryGetPresentationEntityByRecordKey(parentRecordKey, out var parent) ||
parent?.DockingBays == null ||
dockingBayIndex >= parent.DockingBays.Count)
{
return false;
}
dockingBay = parent.DockingBays[dockingBayIndex];
return dockingBay != null;
}
private void RebuildDaemonIndex()
{
_entitiesByDaemonIndex.Clear();
foreach (var entity in _entitiesByRecordKey.Values)
{
if (entity != null && entity.DaemonEntityIndex >= 0)
_entitiesByDaemonIndex[entity.DaemonEntityIndex] = entity;
}
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 1561fad48f5f1aa43a9070d788f6eaa7

View file

@ -1,168 +0,0 @@
using System;
using GameCult.Aetheria.State.Verse;
using GameCult.Eve.PluginFields;
using UnityEngine;
public sealed class AetheriaUnityRenderSplatViewportSource : MonoBehaviour
{
[SerializeField]
private AetheriaRenderSplatRasterizer rasterizer;
[SerializeField]
private AetheriaRenderSplatLayerRenderer layerRenderer;
[SerializeField]
private string layerKey = AetheriaRuntimeRenderSplatLayerKeys.GravityHeight;
[SerializeField]
private Vector2 position;
[SerializeField]
private Vector2 size = new Vector2(1024, 1024);
[SerializeField]
private float refreshIntervalSeconds = 0.5f;
[SerializeField]
private bool renderInLateUpdate = true;
private float _nextRefreshTime;
private AetheriaUnityGameViewportDocuments _viewportDocuments;
private string _lastWarningMessage = "";
public RenderTexture TargetTexture
{
get
{
if (layerRenderer != null && layerRenderer.TryGetTexture(layerKey, out var texture))
return texture;
return rasterizer != null ? rasterizer.TargetTexture : null;
}
}
public EveFieldsSplatsDocument CurrentDocument =>
_viewportDocuments?.CurrentRenderSplatsViewport;
public bool RenderInLateUpdate
{
get => renderInLateUpdate;
set => renderInLateUpdate = value;
}
private void Reset()
{
rasterizer = GetComponent<AetheriaRenderSplatRasterizer>();
layerRenderer = GetComponent<AetheriaRenderSplatLayerRenderer>();
}
private void LateUpdate()
{
if (renderInLateUpdate)
RenderLatest();
}
private void OnDisable()
{
ClearViewportDocument();
}
public bool RenderLatest()
{
ResolveRenderers();
if (layerRenderer == null && rasterizer == null)
return false;
RefreshDocument(false);
var document = _viewportDocuments?.CurrentRenderSplatsViewport;
if (document == null)
return false;
if (layerRenderer != null)
{
layerRenderer.Render(document, Mathf.RoundToInt(size.x), Mathf.RoundToInt(size.y));
return true;
}
rasterizer.Render(document, Mathf.RoundToInt(size.x), Mathf.RoundToInt(size.y));
return true;
}
private void ResolveRenderers()
{
if (layerRenderer == null)
layerRenderer = GetComponent<AetheriaRenderSplatLayerRenderer>();
if (rasterizer == null)
rasterizer = GetComponent<AetheriaRenderSplatRasterizer>();
if (layerRenderer == null && rasterizer == null)
layerRenderer = gameObject.AddComponent<AetheriaRenderSplatLayerRenderer>();
}
public void SetLayerKey(string value)
{
layerKey = string.IsNullOrWhiteSpace(value)
? AetheriaRuntimeRenderSplatLayerKeys.GravityHeight
: value;
}
public void SetViewport(Vector2 center, Vector2 viewportSize)
{
position = center;
size = viewportSize;
RefreshDocument(true);
}
private void RefreshDocument(bool force)
{
var viewport = ResolveViewportBounds();
if (!force && _viewportDocuments != null && _viewportDocuments.Matches(viewport))
return;
if (!force && Time.unscaledTime < _nextRefreshTime)
return;
_nextRefreshTime = Time.unscaledTime + Mathf.Max(0.02f, refreshIntervalSeconds);
try
{
var nextDocuments = AetheriaUnityRuntimeClientProvider
.RenderSplatViewportDocuments(viewport, "unity-render-splat-viewport");
ClearViewportDocument();
_viewportDocuments = nextDocuments;
_lastWarningMessage = "";
}
catch (Exception ex)
{
ClearViewportDocument();
WarnOnce($"Failed to read daemon render splats from Verse state: {ex.Message}");
}
}
private void WarnOnce(string message)
{
if (string.Equals(_lastWarningMessage, message, StringComparison.Ordinal))
return;
_lastWarningMessage = message;
Debug.LogWarning(message);
}
private AetheriaRuntimeViewportBounds ResolveViewportBounds()
{
var halfSize = size * 0.5f;
return new AetheriaRuntimeViewportBounds
{
MinX = position.x - halfSize.x,
MinY = position.y - halfSize.y,
MaxX = position.x + halfSize.x,
MaxY = position.y + halfSize.y
};
}
private void ClearViewportDocument()
{
_viewportDocuments?.Dispose();
_viewportDocuments = null;
}
}

View file

@ -1,242 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.IO;
using GameCult.Aetheria.State.Verse;
using GameCult.Mesh;
using UnityEngine;
public static class AetheriaUnityRuntimeClientProvider
{
private static readonly Dictionary<string, AetheriaClient> RuntimeClients =
new Dictionary<string, AetheriaClient>(StringComparer.Ordinal);
private static RuntimePlayerSettings _runtimePlayerSettings;
private static bool _playerSettingsLoaded;
public static RuntimePlayerSettings PlayerSettings
{
get
{
_runtimePlayerSettings ??= CreateDefaultPlayerSettings();
RefreshPlayerSettings(_runtimePlayerSettings);
return _runtimePlayerSettings;
}
}
private static AetheriaClient ResolveClient(string stateFilePath, string runtimeId = "")
{
var effectiveRuntimeId = string.IsNullOrWhiteSpace(runtimeId)
? AetheriaRuntimeStateBoundary.DefaultClientRuntimeId
: runtimeId;
var cacheKey = CacheKey(stateFilePath, effectiveRuntimeId);
if (RuntimeClients.TryGetValue(cacheKey, out var runtimeClient))
return runtimeClient;
runtimeClient = AetheriaClient
.OpenAsync(
stateFilePath,
effectiveRuntimeId,
"local",
startServer: false,
pullOnOpen: true)
.GetAwaiter()
.GetResult();
RuntimeClients[cacheKey] = runtimeClient;
return runtimeClient;
}
private static AetheriaClient ResolveClient(AetheriaRuntimeStateBootReport stateBoot, string runtimeId = "")
{
return ResolveClient(
stateBoot.StateFilePath,
string.IsNullOrWhiteSpace(runtimeId) ? stateBoot.RuntimeId : runtimeId);
}
private static AetheriaClient RuntimeClient(string runtimeId = "")
{
return ResolveClient(AetheriaUnityRuntimePaths.RuntimeStateFilePath, runtimeId);
}
private static AetheriaClient RuntimeClient(
AetheriaRuntimeStateBootReport stateBoot,
string runtimeId = "")
{
return ResolveClient(stateBoot, runtimeId);
}
public static AetheriaClientState RuntimeState(string runtimeId = "")
{
return RuntimeClient(runtimeId).State;
}
public static AetheriaClientState RuntimeState(
AetheriaRuntimeStateBootReport stateBoot,
string runtimeId = "")
{
return RuntimeClient(stateBoot, runtimeId).State;
}
public static AetheriaUnityGameViewportDocuments MapViewportDocuments(
AetheriaRuntimeViewportBounds viewport,
string runtimeId = "")
{
return AetheriaUnityGameViewportDocuments.OpenMap(RuntimeState(runtimeId), viewport);
}
public static AetheriaUnityGameViewportDocuments ZonePresentationDocuments(
AetheriaRuntimeViewportBounds viewport,
string runtimeId = "")
{
return AetheriaUnityGameViewportDocuments.OpenZonePresentation(RuntimeState(runtimeId), viewport);
}
public static AetheriaUnityGameViewportDocuments RenderSplatViewportDocuments(
AetheriaRuntimeViewportBounds viewport,
string runtimeId = "")
{
return AetheriaUnityGameViewportDocuments.OpenRenderSplats(RuntimeState(runtimeId), viewport);
}
public static AetheriaUnityDaemonRenderDocuments DaemonRenderDocuments(
AetheriaRuntimeStateBootReport stateBoot,
string runtimeId = "")
{
return AetheriaUnityDaemonRenderDocuments.Open(RuntimeState(stateBoot, runtimeId));
}
public static AetheriaControl Control(string runtimeId = "")
{
return RuntimeClient(runtimeId).Control;
}
public static AetheriaControl Control(
AetheriaRuntimeStateBootReport stateBoot,
string runtimeId = "")
{
return RuntimeClient(stateBoot, runtimeId).Control;
}
public static AetheriaUi Ui(string runtimeId = "")
{
return RuntimeClient(runtimeId).Ui;
}
public static AetheriaUi Ui(
AetheriaRuntimeStateBootReport stateBoot,
string runtimeId = "")
{
return RuntimeClient(stateBoot, runtimeId).Ui;
}
public static CultMeshStateRefResolver EveSurfaceCultMeshStateRefResolver(string runtimeId = "")
{
return RuntimeState(runtimeId).CreateEveSurfaceCultMeshStateRefResolver();
}
public static CultMeshStateRefResolver EveSurfaceCultMeshStateRefResolver(
AetheriaRuntimeStateBootReport stateBoot,
string runtimeId = "")
{
return RuntimeState(stateBoot, runtimeId).CreateEveSurfaceCultMeshStateRefResolver();
}
public static void Dispose()
{
_runtimePlayerSettings = null;
_playerSettingsLoaded = false;
foreach (var client in RuntimeClients.Values)
client.Dispose();
RuntimeClients.Clear();
}
private static string CacheKey(string stateFilePath, string runtimeId)
{
return (stateFilePath ?? "") + "\n" + runtimeId;
}
private static void RefreshPlayerSettings(RuntimePlayerSettings settings)
{
try
{
var stored = RuntimeState().PlayerSettings.Latest();
if (stored == null)
return;
ApplyPlayerSettings(settings, stored);
if (!_playerSettingsLoaded)
{
Debug.Log("Loaded Aetheria Verse player settings from typed state.");
_playerSettingsLoaded = true;
}
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to load Aetheria Verse player settings from typed state; using defaults: {ex}");
}
}
private static RuntimePlayerSettings CreateDefaultPlayerSettings()
{
var settings = new RuntimePlayerSettings();
settings.Name = Environment.UserName;
settings.InputSettings.SetActionBarInputEnabled("<Keyboard>/leftShift", true);
settings.InputSettings.SetActionBarInputEnabled("<Mouse>/leftButton", true);
settings.InputSettings.SetActionBarInputEnabled("<Mouse>/rightButton", true);
settings.InputSettings.SetActionBarInputEnabled("<Mouse>/middleButton", true);
for (var i = 1; i < 6; i++)
settings.InputSettings.SetActionBarInputEnabled($"<Keyboard>/{i}", true);
return settings;
}
private static void ApplyPlayerSettings(
RuntimePlayerSettings settings,
AetheriaRuntimePlayerSettingsDocument stored)
{
if (!string.IsNullOrWhiteSpace(stored.PlayerName))
settings.Name = stored.PlayerName;
settings.TutorialPassed = stored.TutorialPassed;
settings.HashedStoryFiles.Clear();
foreach (var storyFileHash in stored.StoryFileHashes)
{
if (!string.IsNullOrWhiteSpace(storyFileHash.StoryPath))
settings.HashedStoryFiles[storyFileHash.StoryPath] = storyFileHash.Hash;
}
if (Enum.TryParse(stored.TemperatureUnit, out TemperatureUnit temperatureUnit))
settings.GameplaySettings.TemperatureUnit = temperatureUnit;
settings.GameplaySettings.SignificantDigits = Math.Max(0, stored.SignificantDigits);
if (Enum.TryParse(stored.NebulaQuality, out Quality nebulaQuality))
settings.GraphicsSettings.NebulaQuality = nebulaQuality;
settings.GraphicsSettings.ShowAsteroidsInMinimap = stored.ShowAsteroidsInMinimap;
settings.InputSettings.InputActionMap.Clear();
foreach (var binding in stored.BindingOverrides)
{
if (string.IsNullOrWhiteSpace(binding.ActionName) ||
string.IsNullOrWhiteSpace(binding.BindingPath) ||
binding.BindingIndex < 0)
{
continue;
}
settings.InputSettings.SetBindingOverride(binding.ActionName, binding.BindingIndex, binding.BindingPath);
}
settings.InputSettings.ActionBarInputs.Clear();
foreach (var input in stored.ActionBarInputs)
{
if (!string.IsNullOrWhiteSpace(input))
settings.InputSettings.SetActionBarInputEnabled(input, true);
}
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 95ae2790dbb68864a954847834215f2f

View file

@ -1,20 +0,0 @@
using System.IO;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
public static class AetheriaUnityRuntimePaths
{
private static DirectoryInfo _gameDataDirectory;
private static string _runtimeStateFilePath;
public static DirectoryInfo GameDataDirectory =>
_gameDataDirectory ??= new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData");
public static string RuntimeStateFilePath =>
_runtimeStateFilePath ??= AetheriaRuntimeStateBoot.Inspect(GameDataDirectory).StateFilePath;
public static void ClearRuntimeStateFilePathCache()
{
_runtimeStateFilePath = null;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 36e68ebb69d4af84cb7f485e11fd6e6c

View file

@ -1,296 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
using UnityEngine.UI;
using float3 = Unity.Mathematics.float3;
public sealed class AetheriaUnityTargetPresentation
{
private readonly Dictionary<Entity, VisibleTargetIndicator> _visibleHostileIndicators =
new Dictionary<Entity, VisibleTargetIndicator>();
private readonly Dictionary<Entity, VisibleTargetIndicator> _visibleFriendlyIndicators =
new Dictionary<Entity, VisibleTargetIndicator>();
private readonly HashSet<Entity> _observedHostileIndicatorTargets = new HashSet<Entity>();
private readonly HashSet<Entity> _observedFriendlyIndicatorTargets = new HashSet<Entity>();
private readonly List<Entity> _staleIndicatorTargets = new List<Entity>();
public ZoneRenderer ZoneRenderer { get; set; }
public Prototype HostileTargetIndicator { get; set; }
public Prototype FriendlyTargetIndicator { get; set; }
public PlaceUIElementWorldspace ViewDot { get; set; }
public PlaceUIElementWorldspace TargetIndicator { get; set; }
public Image TargetHitpointsFill { get; set; }
public Image TargetVisibilityFill { get; set; }
public Image VisibilityToTargetFill { get; set; }
public Image TargetShieldsFill { get; set; }
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; set; }
public Func<int, Entity> ResolveEntity { get; set; }
public Func<AetheriaRuntimeZoneContactsDocument> ResolveZoneContacts { get; set; }
public Entity Tick(Entity currentEntity, float time)
{
var observedTarget = GetObservedTarget(currentEntity);
ReconcileVisibleTargetIndicators(currentEntity);
UpdateVisibleIndicatorPresentation(
_visibleHostileIndicators,
currentEntity,
observedTarget,
time,
blinkSpottedTargets: true);
UpdateVisibleIndicatorPresentation(
_visibleFriendlyIndicators,
currentEntity,
observedTarget,
time,
blinkSpottedTargets: false);
UpdateTargetStatus(currentEntity, observedTarget);
return observedTarget;
}
public void ReconcileVisibleTargetIndicators(Entity currentEntity)
{
_observedHostileIndicatorTargets.Clear();
_observedFriendlyIndicatorTargets.Clear();
if (currentEntity != null && ZoneRenderer != null)
{
var renderSettings = ZoneRenderer.RenderSettings;
var contacts = GetObservedVisibleContacts(
currentEntity,
renderSettings.TargetDetectionInfoThreshold,
true);
foreach (var contact in contacts)
{
if (ResolveEntity?.Invoke(contact.TargetEntityIndex) is not { } target ||
ReferenceEquals(target, currentEntity))
{
continue;
}
if (contact.Hostile)
_observedHostileIndicatorTargets.Add(target);
else
_observedFriendlyIndicatorTargets.Add(target);
}
}
ReconcileVisibleTargetIndicators(
_visibleHostileIndicators,
_observedHostileIndicatorTargets,
HostileTargetIndicator);
ReconcileVisibleTargetIndicators(
_visibleFriendlyIndicators,
_observedFriendlyIndicatorTargets,
FriendlyTargetIndicator);
}
public void ClearIndicators()
{
ClearIndicators(_visibleHostileIndicators);
ClearIndicators(_visibleFriendlyIndicators);
}
public void UpdateTargetIndicators(
Entity currentEntity,
bool isCurrentEntityObservedUndocked,
AetheriaUnityCurrentEntityPresentation currentEntityPresentation)
{
if (!isCurrentEntityObservedUndocked ||
currentEntity == null ||
ZoneRenderer == null ||
ViewDot == null ||
!ZoneRenderer.TryGetEntityInstance(currentEntity, out var entityInstance))
{
return;
}
var observedTarget = GetObservedTarget(currentEntity);
ViewDot.Target = entityInstance.LookAtPoint.position;
if (observedTarget != null && TargetIndicator != null)
TargetIndicator.Target = observedTarget.Position;
var distance = CultMath.math.length(AetheriaMath.ToCult((float3)ViewDot.Target) - currentEntity.CultPosition);
foreach (var (_, barrels, crosshair) in currentEntityPresentation.ArticulationGroups)
{
var averagePosition = Vector3.zero;
foreach (var barrel in barrels)
averagePosition += barrel.position + barrel.forward * distance;
averagePosition /= barrels.Length;
crosshair.Target = averagePosition;
}
foreach (var (targetLock, indicator, spin) in currentEntityPresentation.LockingIndicators)
{
var showLockingIndicator = targetLock.Lock > .01f &&
observedTarget != null &&
IsObservedHostileContact(currentEntity, observedTarget);
indicator.gameObject.SetActive(showLockingIndicator);
if (!showLockingIndicator)
continue;
var renderSettings = ZoneRenderer.RenderSettings;
indicator.Target = observedTarget.Position;
indicator.NoiseAmplitude = (float)renderSettings.ResolveLockIndicatorNoiseAmplitude(targetLock.Lock);
indicator.NoiseFrequency = (float)renderSettings.ResolveLockIndicatorNoiseFrequency(targetLock.Lock);
spin.Speed = (float)renderSettings.ResolveLockSpinSpeed(targetLock.Lock);
}
}
private void UpdateVisibleIndicatorPresentation(
Dictionary<Entity, VisibleTargetIndicator> indicators,
Entity currentEntity,
Entity observedTarget,
float time,
bool blinkSpottedTargets)
{
if (ZoneRenderer == null)
return;
var renderSettings = ZoneRenderer.RenderSettings;
foreach (var indicator in indicators)
{
indicator.Value.gameObject.SetActive(indicator.Key != observedTarget);
indicator.Value.Place.Target = indicator.Key.Position;
if (!indicator.Key.Active)
{
indicator.Value.Fill.enabled = false;
continue;
}
var infoGathered = GetObservedInfoGathered(indicator.Key, currentEntity);
indicator.Value.Fill.fillAmount = (float)renderSettings.NormalizeDetectionProgress(infoGathered);
indicator.Value.Fill.enabled = !blinkSpottedTargets ||
renderSettings.ResolveTargetSpottedFillEnabled(infoGathered, time);
}
}
private void UpdateTargetStatus(Entity currentEntity, Entity target)
{
if (currentEntity == null || target == null || ZoneRenderer?.RenderSettings == null)
return;
var renderSettings = ZoneRenderer.RenderSettings;
var targetInfoGathered = GetObservedInfoGathered(currentEntity, target);
var visibilityToTarget = GetObservedInfoGathered(target, currentEntity);
TargetVisibilityFill.fillAmount = (float)renderSettings.NormalizeTargetVisibilityFill(targetInfoGathered);
VisibilityToTargetFill.fillAmount = (float)renderSettings.NormalizeVisibilityToTargetFill(visibilityToTarget);
var targetHull = RuntimeCatalog?.FindItem(target.Hull, x => x.ItemKey);
var targetMaxDurability = targetHull?.Durability > 0
? (float)targetHull.Durability
: Math.Max(target.Hull.Durability, 1f);
TargetHitpointsFill.fillAmount =
(float)renderSettings.NormalizeTargetStatusFill(target.Hull.Durability / targetMaxDurability);
TargetShieldsFill.fillAmount = target.Shield == null
? 0
: (float)renderSettings.NormalizeTargetStatusFill(target.Shield.Progress);
}
private void ReconcileVisibleTargetIndicators(
Dictionary<Entity, VisibleTargetIndicator> indicators,
HashSet<Entity> desiredTargets,
Prototype prototype)
{
if (prototype == null)
return;
_staleIndicatorTargets.Clear();
foreach (var indicator in indicators)
{
if (!desiredTargets.Contains(indicator.Key))
_staleIndicatorTargets.Add(indicator.Key);
}
foreach (var staleTarget in _staleIndicatorTargets)
{
indicators[staleTarget].GetComponent<Prototype>().ReturnToPool();
indicators.Remove(staleTarget);
}
foreach (var target in desiredTargets)
{
if (!indicators.ContainsKey(target))
indicators.Add(target, prototype.Instantiate<VisibleTargetIndicator>());
}
}
private static void ClearIndicators(Dictionary<Entity, VisibleTargetIndicator> indicators)
{
foreach (var indicator in indicators.Values)
indicator.GetComponent<Prototype>().ReturnToPool();
indicators.Clear();
}
public Entity GetObservedTarget(Entity observer)
{
if (TryQueryEntityTarget(observer, out var targetEntityIndex))
return ResolveEntity?.Invoke(targetEntityIndex);
return null;
}
private float GetObservedInfoGathered(Entity observer, Entity target)
{
return TryQueryEntityContact(observer, target, out var contact)
? (float)contact.InfoGathered
: 0f;
}
private bool IsObservedHostileContact(Entity observer, Entity target)
{
return TryQueryEntityContact(observer, target, out var contact) && contact.Hostile;
}
private AetheriaRuntimeZoneContactRow[] GetObservedVisibleContacts(
Entity observer,
double minimumInfoGathered,
bool visibleOnly)
{
var contacts = ResolveZoneContacts?.Invoke();
if (observer == null || contacts == null)
return Array.Empty<AetheriaRuntimeZoneContactRow>();
return (contacts.Contacts ?? Array.Empty<AetheriaRuntimeZoneContactRow>())
.Where(contact =>
contact.ObserverEntityIndex == observer.DaemonEntityIndex &&
contact.InfoGathered > minimumInfoGathered &&
(!visibleOnly || contact.Visible))
.ToArray();
}
private bool TryQueryEntityContact(
Entity observer,
Entity target,
out AetheriaRuntimeZoneContactRow contact)
{
contact = default;
if (observer == null || target == null)
return false;
contact = (ResolveZoneContacts?.Invoke()?.Contacts ?? Array.Empty<AetheriaRuntimeZoneContactRow>())
.FirstOrDefault(row =>
row.ObserverEntityIndex == observer.DaemonEntityIndex &&
row.TargetEntityIndex == target.DaemonEntityIndex);
return contact != null;
}
private bool TryQueryEntityTarget(
Entity observer,
out int targetEntityIndex)
{
targetEntityIndex = -1;
if (observer == null)
return false;
targetEntityIndex = (ResolveZoneContacts?.Invoke()?.Targets ?? Array.Empty<AetheriaRuntimeZoneTargetRow>())
.FirstOrDefault(row => row.EntityIndex == observer.DaemonEntityIndex)
?.TargetEntityIndex ?? -1;
return targetEntityIndex >= 0;
}
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 51baf83a22ca0be45abd418061686244

View file

@ -1,36 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using GameCult.Aetheria.State.Verse;
public static class AetheriaUnityWeaponPresentationPolicy
{
private static readonly HashSet<string> ArticulatedWeaponBehaviorKinds = new HashSet<string>(StringComparer.Ordinal)
{
"GuidedWeapon",
"InstantWeapon",
"ConstantWeapon",
"ChargedWeapon",
"AutoWeapon"
};
public static bool HasArticulatedWeaponBehavior(
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
EquippedItem item)
{
var typedItem = runtimeCatalog?.FindItem(item?.EquippableItem, x => x.ItemKey);
if (typedItem?.BehaviorKinds == null)
return false;
foreach (var behaviorKind in typedItem.BehaviorKinds)
{
if (ArticulatedWeaponBehaviorKinds.Contains(behaviorKind))
return true;
}
return false;
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: cf148956af2c4b5780cb1adcdcee0fd1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,11 +1,15 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class ArticulationPoint : MonoBehaviour
{
public Transform Target;
public int Group;
public float YawMin;
public float YawMax;
@ -22,26 +26,26 @@ public class ArticulationPoint : MonoBehaviour
if (Target)
{
var targetLocal = transform.InverseTransformPoint(Target.position);
var yaw = Vector2.SignedAngle(new Vector2(0, 1), new Vector2(targetLocal.x, targetLocal.z));
var pitch = Vector2.SignedAngle(new Vector2(1, 0), new Vector2(targetLocal.z, targetLocal.y));
var targetYaw = Mathf.Clamp(_yaw - yaw, YawMin, YawMax);
var targetPitch = Mathf.Clamp(_pitch - pitch, PitchMin, PitchMax);
var targetYaw = clamp(_yaw - yaw, YawMin, YawMax);
var targetPitch = clamp(_pitch - pitch, PitchMin, PitchMax);
if (Mathf.Abs(targetYaw - _yaw) < Speed * Time.deltaTime)
if (abs(targetYaw - _yaw) < Speed * Time.deltaTime)
_yaw = targetYaw;
else _yaw = _yaw + Mathf.Sign(targetYaw - _yaw) * Speed * Time.deltaTime;
else _yaw = _yaw + sign(targetYaw - _yaw) * Speed * Time.deltaTime;
if (_yaw < -360)
if(_yaw < -360)
_yaw += 360;
if (_yaw > 360)
if(_yaw > 360)
_yaw -= 360;
if (Mathf.Abs(targetPitch - _pitch) < Speed * Time.deltaTime)
if (abs(targetPitch - _pitch) < Speed * Time.deltaTime)
_pitch = targetPitch;
else _pitch = _pitch + Mathf.Sign(targetPitch - _pitch) * Speed * Time.deltaTime;
else _pitch = _pitch + sign(targetPitch - _pitch) * Speed * Time.deltaTime;
transform.localRotation = Quaternion.Euler(_pitch, _yaw, 0);
}
}

View file

@ -1,17 +1,21 @@
using System;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using UniRx;
using UnityEngine;
using cfloat3 = CultMath.float3;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
using Random = UnityEngine.Random;
public class EntityInstance : MonoBehaviour
{
public MeshRenderer MapIcon;
public Transform InfluencePrefab;
public Transform PingPrefab;
public Material InvisibleMaterial;
public static Transform EffectManagerParent;
public ShieldManager Shield;
public HullCollider[] HullColliders;
@ -21,6 +25,7 @@ public class EntityInstance : MonoBehaviour
public WeaponHardpoint[] WeaponHardpoints;
public ArticulationPoint[] ArticulationPoints;
public GameObject DestroyEffect;
public event Action OnFadedOut;
public event Action OnFadedIn;
@ -35,23 +40,30 @@ public class EntityInstance : MonoBehaviour
private bool _fadedElementsVisible = false;
private bool _unfadedElementsVisible = false;
private float _fadeTime;
private bool _destroyed;
private (Transform transform, MeshRenderer meshRenderer) _currentPing;
private float _pingBrightness;
private Sensor _sensor;
private Transform _influenceInstance;
//private List<(GameObject source, EquippedItem item)> _audioSources = new List<(GameObject source, EquippedItem item)>();
// private (Reactor reactor, GameObject sfxSource) _reactor;
// private Dictionary<Radiator, GameObject> _radiatorSfx = new Dictionary<Radiator, GameObject>();
private static Vector2 ToVector2(CultMath.float2 value) => new Vector2(value.x, value.y);
private static Vector2 ToVector2(Unity.Mathematics.float2 value) => new Vector2(value.x, value.y);
private static Dictionary<InstantWeaponData, InstantWeaponEffectManager> _instantWeaponManagers = new Dictionary<InstantWeaponData, InstantWeaponEffectManager>();
private static Dictionary<ConstantWeaponData, ConstantWeaponEffectManager> _constantWeaponManagers = new Dictionary<ConstantWeaponData, ConstantWeaponEffectManager>();
private static cfloat3 ToCult(Vector3 value) => new cfloat3(value.x, value.y, value.z);
public static void ClearWeaponManagers()
{
_instantWeaponManagers.Clear();
_constantWeaponManagers.Clear();
}
public CompassIcon CompassIcon { get; set; }
public Dictionary<HardpointData, Transform[]> Barrels { get; private set; }
public Dictionary<HardpointData, int> BarrelIndices { get; private set; }
public Dictionary<Radiator, MeshRenderer> RadiatorMeshes { get; private set; }
public Transform LookAtPoint { get; private set; }
public int DaemonEntityIndex { get; private set; } = -1;
public Entity Entity { get; private set; }
public ZoneRenderer ZoneRenderer { get; private set; }
public Transform LocalSpace { get; private set; }
@ -149,19 +161,90 @@ public class EntityInstance : MonoBehaviour
LocalSpace.gameObject.name = $"{entity.Name} Sim Space";
LocalSpace.SetParent(transform.parent);
Entity = entity;
DaemonEntityIndex = entity.DaemonEntityIndex;
ZoneRenderer = zoneRenderer;
var typedHull = ZoneRenderer?.FindCatalogItem(entity.Hull);
if (typedHull == null || typedHull.ShapeWidth <= 0 || typedHull.ShapeHeight <= 0 || typedHull.ShapeCells.Count == 0)
{
Debug.LogError($"Cannot bind entity instance for {entity.Name}: missing typed hull shape.");
return;
}
var hullData = entity.ItemManager.GetData(entity.Hull) as HullData;
if(Shield)
Shield.Entity = entity;
foreach (var hullCollider in HullColliders) hullCollider.Entity = entity;
foreach (var item in entity.Equipment)
{
foreach (var behavior in item.Behaviors)
{
if (behavior is Sensor sensor)
{
_sensor = sensor;
sensor.OnPingStart += () =>
{
var pingInstance = Instantiate(PingPrefab);
var pingMesh = pingInstance.GetComponent<MeshRenderer>();
pingInstance.position = entity.Position;
_pingBrightness = pingMesh.material.GetFloat("_Depth");
_currentPing = (pingInstance, pingMesh);
};
sensor.OnPingEnd += OnSensorPingEnd;
}
if (behavior is InstantWeapon instantWeapon)
{
var data = (InstantWeaponData) instantWeapon.Data;
if (!_instantWeaponManagers.ContainsKey(data))
{
var managerPrefab = UnityHelpers.LoadAsset<InstantWeaponEffectManager>(data.EffectPrefab);
if(managerPrefab)
{
_instantWeaponManagers.Add(data, Instantiate(managerPrefab, EffectManagerParent));
}
else Debug.LogError($"No InstantWeaponEffectManager prefab found at path {data.EffectPrefab}");
}
instantWeapon.OnFire += () =>
_instantWeaponManagers[data].Fire(instantWeapon, item, this, entity.Target.Value != null && ZoneRenderer.EntityInstances.ContainsKey(entity.Target.Value) ? ZoneRenderer.EntityInstances[entity.Target.Value] : null);
if (behavior is ChargedWeapon chargedWeapon)
{
var chargeManager = _instantWeaponManagers[data].GetComponent<ChargeEffectManager>();
if (chargeManager)
{
chargedWeapon.OnStartCharging += () => chargeManager.StartCharging(chargedWeapon, item, this);
chargedWeapon.OnStopCharging += () => chargeManager.StopCharging(chargedWeapon);
chargedWeapon.OnCharged += () => chargeManager.Charged(chargedWeapon);
chargedWeapon.OnFailed += () => chargeManager.Failed(chargedWeapon);
}
}
}
if (behavior is ConstantWeapon constantWeapon)
{
var data = (ConstantWeaponData) constantWeapon.Data;
if (!_constantWeaponManagers.ContainsKey(data))
{
var managerPrefab = UnityHelpers.LoadAsset<ConstantWeaponEffectManager>(data.EffectPrefab);
if(managerPrefab)
{
_constantWeaponManagers.Add(data, Instantiate(managerPrefab, EffectManagerParent));
}
else Debug.LogError($"No ConstantWeaponEffectManager prefab found at path {data.EffectPrefab}");
}
constantWeapon.OnStartFiring += () =>
_constantWeaponManagers[data].StartFiring(data, item, this, entity.Target.Value != null ? ZoneRenderer.EntityInstances[entity.Target.Value] : null);
constantWeapon.OnStopFiring += () =>
_constantWeaponManagers[data].StopFiring(item);
}
}
var hp = Entity.Hardpoints[item.Position.x, item.Position.y];
if (hp != null && item.Data.SoundBank != 0)
{
var hardpointTransform = EquipmentHardpoints.FirstOrDefault(x => x.name == hp.Transform);
if (hardpointTransform != null)
{
var hardpointGameObject = hardpointTransform.gameObject;
}
}
}
RadiatorMeshes = new Dictionary<Radiator, MeshRenderer>();
Barrels = new Dictionary<HardpointData, Transform[]>();
BarrelIndices = new Dictionary<HardpointData, int>();
@ -177,7 +260,7 @@ public class EntityInstance : MonoBehaviour
}
}
}
foreach (var hp in Entity.Hardpoints.Cast<HardpointData>().Where(hp => hp != null).Distinct())
foreach (var hp in hullData.Hardpoints)
{
if(hp.Type == HardpointType.Ballistic || hp.Type == HardpointType.Energy || hp.Type == HardpointType.Launcher)
{
@ -190,6 +273,127 @@ public class EntityInstance : MonoBehaviour
}
}
void DamageSchematic(float damage, Shape hitShape)
{
foreach (var v in hitShape.Coordinates)
hitShape[v] = hitShape[v] && hullData.Shape[v];
float hullDamage = 0;
var damagePerCell = damage / hitShape.Coordinates.Length;
foreach (var v in hitShape.Coordinates)
{
var d = damagePerCell;
// Subtract surface damage from armor, passing on the remainder to the item and then to the hull
var prev = entity.Armor[v.x, v.y];
entity.Armor[v.x, v.y] = max(prev - d, 0);
entity.ArmorDamage.OnNext((v, d));
d = max(d - prev, 0);
if (d > 0.1f)
{
var item = entity.GearOccupancy[v.x, v.y];
if (item != null)
{
prev = item.EquippableItem.Durability;
item.EquippableItem.Durability = max(prev - d, 0);
entity.ItemDamage.OnNext((item, d));
d = max(d - prev, 0);
}
}
hullDamage += d;
}
if(hullDamage > .1f)
{
entity.Hull.Durability -= hullDamage;
entity.HullDamage.OnNext(hullDamage);
}
}
foreach (var collider in HullColliders)
{
collider.Splash.Subscribe(splash =>
{
var hitShape = new Shape(hullData.Shape.Width, hullData.Shape.Height);
foreach (var v in hullData.Shape.Coordinates)
{
var localHitDirection = transform.InverseTransformDirection(splash.Direction);
var direction = normalize(float2(localHitDirection.x, localHitDirection.z));
var cellDot = dot(normalize(v - hullData.Shape.CenterOfMass), direction);
if (cellDot < 0) hitShape[v] = true;
}
DamageSchematic(splash.Damage, hitShape);
});
collider.Hit.Subscribe(hit =>
{
Entity.IncomingHit.OnNext(hit.Source);
var hardpointIndex = (int) hit.TexCoord.x - 1;
var hitShape = new Shape(hullData.Shape.Width, hullData.Shape.Height);
// U coordinate between 0-1 indicates a hit that didn't land directly on a hardpoint
// Find the 2D position of the hit scaled to the schematic
float2 hitPos = float2.zero;
if (hardpointIndex < 0 || hardpointIndex >= hullData.Hardpoints.Count)
{
hitPos = float2(hit.TexCoord.x * hullData.Shape.Width, hit.TexCoord.y * hullData.Shape.Height);
// Search all schematic border cells for the cell which is closest to the hit position
var hitCell = int2(-1);
var distance = float.MaxValue;
foreach (var v in hullData.Shape.Coordinates)
{
var cellDist = lengthsq(hitPos - v);
if (cellDist < distance)
{
distance = cellDist;
hitCell = v;
hitPos = v + float2(.5f);
}
}
hitShape[hitCell] = true;
}
else
{
// Collider UV coordinates starting with 1 correspond to hardpoint index
var hardpoint = hullData.Hardpoints[hardpointIndex];
// Obtain the hull coordinates of all cells occupied by the hardpoint
var hardpointCells = hullData.Shape.Inset(hardpoint.Shape, hardpoint.Position);
hitPos = hardpointCells.CenterOfMass;
foreach (var v in hardpointCells.Coordinates)
hitShape[v] = true;
}
for (int i = 0; i < Mathf.RoundToInt(hit.Spread); i++)
{
hitShape = hitShape.Expand();
}
if (hit.Penetration > .5f)
{
// Find the local 2D vector corresponding to the direction of the incoming hit
var localHitDirection = transform.InverseTransformDirection(hit.Direction);
var penetrationVector = normalize(float2(localHitDirection.x, localHitDirection.z));
// TODO: Bresenham's line algorithm
// March a ray through the ship from the hit position
var penetrationPoint = hitPos;
var penetrationDistance = 0f;
while (penetrationDistance < hit.Penetration && hullData.Shape[int2(penetrationPoint)])
{
penetrationDistance += .5f;
hitShape[int2(penetrationPoint)] = true;
penetrationPoint += penetrationVector * .5f;
}
}
DamageSchematic(hit.Damage, hitShape);
});
}
LookAtPoint = new GameObject($"{entity.Name} Look Point").transform;
foreach (var articulationPoint in ArticulationPoints)
@ -197,6 +401,42 @@ public class EntityInstance : MonoBehaviour
articulationPoint.Target = LookAtPoint;
}
_subscriptions.Add(Entity.HullDamage.Subscribe(_ =>
{
if (Entity.Hull.Durability < .01f)
{
if (!this) return;
_destroyed = true;
foreach (var gear in Entity.Equipment)
{
if (gear != Entity.EquippedHull && Random.value < ZoneRenderer.Settings.LootDropProbability)
{
ZoneRenderer.DropItem(
Entity.Position,
Random.onUnitSphere * ZoneRenderer.Settings.LootDropVelocity,
gear.EquippableItem);
}
}
foreach (var cargo in Entity.CargoBays)
{
foreach (var item in cargo.Cargo.Keys)
{
ZoneRenderer.DropItem(
Entity.Position,
Random.onUnitSphere * ZoneRenderer.Settings.LootDropVelocity,
item);
}
}
if (DestroyEffect != null)
{
var t = Instantiate(DestroyEffect).transform;
t.position = transform.position;
}
entity.Zone.Entities.Remove(entity);
}
}));
if (entity is OrbitalEntity orbital && orbital.IsSecureArea)
{
_influenceInstance = Instantiate(InfluencePrefab);
@ -204,6 +444,11 @@ public class EntityInstance : MonoBehaviour
}
}
private void OnSensorPingEnd()
{
Destroy(_currentPing.transform.gameObject);
}
public Transform GetBarrel(HardpointData hardpoint)
{
if (Barrels.ContainsKey(hardpoint))
@ -218,6 +463,11 @@ public class EntityInstance : MonoBehaviour
public virtual void Update()
{
if (_currentPing.transform)
{
_currentPing.transform.localScale = _sensor.PingRadius * Vector3.one;
_currentPing.meshRenderer.material.SetFloat("_Depth", _pingBrightness * _sensor.PingBrightness);
}
if (_fading)
{
if (_fadingIn)
@ -257,31 +507,25 @@ public class EntityInstance : MonoBehaviour
foreach (var x in RadiatorMeshes)
{
x.Value.material.SetFloat("_Emission", (float)ZoneRenderer.RenderSettings.TemperatureEmissionCurve.Evaluate(x.Key.RadiatorTemperature));
x.Value.material.SetFloat("_Emission", Entity.ItemManager.GameplaySettings.TemperatureEmissionCurve.Evaluate(x.Key.RadiatorTemperature));
}
foreach (var x in Barrels)
{
Entity.HardpointTransforms[x.Key] = (
ToCult(x.Value[0].position),
ToCult(x.Value[0].forward));
Entity.HardpointTransforms[x.Key] = (x.Value[0].position, x.Value[0].forward);
}
var entityPosition = (Vector3)AetheriaMath.ToUnity(Entity.CultPosition);
var entityLookDirection = (Vector3)AetheriaMath.ToUnity(Entity.CultLookDirection);
var lookAtDistance = ZoneRenderer != null &&
ZoneRenderer.TryGetDaemonTargetDistance(DaemonEntityIndex, out var daemonTargetDistance)
? Mathf.Max(daemonTargetDistance, (float)ZoneRenderer.RenderSettings.ConvergenceMinimumDistance)
: 10000;
LookAtPoint.position = transform.position + entityLookDirection * lookAtDistance;
LocalSpace.localPosition = transform.position = entityPosition;
LookAtPoint.position = transform.position + (Vector3) Entity.LookDirection *
(Entity.Target.Value != null ? max(Entity.TargetRange,Entity.ItemManager.GameplaySettings.ConvergenceMinimumDistance) : 10000);
LocalSpace.localPosition = transform.position = Entity.Position;
if (_influenceInstance)
_influenceInstance.position = new Vector3(entityPosition.x, 0, entityPosition.z);
_influenceInstance.position = new Vector3(Entity.Position.x, 0, Entity.Position.z);
}
public virtual void OnDestroy()
{
if(_sensor!=null)
_sensor.OnPingEnd -= OnSensorPingEnd;
if (_influenceInstance) Destroy(_influenceInstance.gameObject);
Destroy(LocalSpace.gameObject);
foreach(var x in _subscriptions)

View file

@ -1,29 +1,70 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class FieldDriver : MonoBehaviour
{
public Camera Camera;
public Vector2 Push;
public float2 Push;
public float FrontTwist;
public float RearTwist;
[Inspectable]
public float TestMagnitude;
[Inspectable]
public float FlowSpeed;
[Inspectable]
public float FlowSpeedThrottleExponent;
[Inspectable]
public float WaveThrottleExponent;
public int MaxHits;
[Inspectable]
public ExponentialCurve MagnitudeTimeScaling;
[Inspectable, InspectorHeader("Melee")]
public float MeleeRange;
[Inspectable]
public float MeleeRangeExponent;
[Inspectable]
public float MeleeFlatness;
[Inspectable]
public float MeleeShaping;
[Inspectable]
public float MeleeDuration;
[Inspectable]
public float MeleeAngle;
[Inspectable]
public float MeleeAngleExponent;
[Inspectable, InspectorHeader("Tendril")]
public float TendrilBaseRadius = 3;
[Inspectable]
public float TendrilTipRadius = .1f;
[Inspectable]
public float TendrilExtensionExponent = .75f;
[Inspectable]
public float TendrilExtendBaseAnimationExponent = .5f;
[Inspectable]
public float TendrilBaseDamping = 2;
[Inspectable]
public float TendrilTipRadiusAnimationExponent = 2f;
[Inspectable]
public float TendrilFadeExponent = 2;
// [Inspectable]
// public float GrabScaleAnimationExponent = .5f;
[Inspectable, InspectorHeader("Grab")]
public float GrabExtendTime;
[Inspectable]
public float GrabEnvelopTime;
[Inspectable]
public float GrabPullTime;
[Inspectable]
public RectTransform.Axis RefractionAxis = RectTransform.Axis.Horizontal;
private Material _field;
@ -32,36 +73,57 @@ public class FieldDriver : MonoBehaviour
private float _waveOffset;
private float _meleeTime;
private bool _meleeActive;
private MeshCollider _collider;
private Transform _grabObject;
private Vector3 _grabObjectStartPos;
private Vector3 _grabObjectStartTendrilBasePos;
private Vector3 _grabObjectEndPos;
private Vector3 _grabObjectVelocity;
private float _grabObjectScale;
private float _grabTime;
private GrabPhase _grabPhase;
private Vector3 _tendrilBasePos;
private Vector3 _tendrilBendTarget;
private Vector3 _tendrilTargetPos;
private float _fadePoint;
private enum GrabPhase
{
Extend,
Envelop,
Pull
}
private struct FieldHit
{
public Vector3 Position;
public Vector3 Direction;
public float3 Position;
public float3 Direction;
public float Magnitude;
public float Time;
}
void Start()
{
_collider = GetComponent<MeshCollider>();
_field = GetComponent<MeshRenderer>().material;
var clickableCollider = GetComponent<ClickableCollider>();
if(clickableCollider!=null)
{
clickableCollider.OnClick += (_, _, ray, hit) =>
{
AddHit(hit.Point, ray.direction, TestMagnitude);
AddHit(hit.point, ray.direction, TestMagnitude);
};
}
_hitBuffer = new ComputeBuffer(MaxHits, 32);
}
public void AddHit(Vector3 position, Vector3 direction, float magnitude)
public void AddHit(float3 position, float3 direction, float magnitude)
{
if (_hits.Count >= MaxHits) return;
var hit = new FieldHit
{
Position = Vector3.Scale(transform.InverseTransformPoint(position).normalized, transform.localScale),
Direction = (transform.rotation * direction).normalized,
Position = Vector3.Scale(normalize(transform.InverseTransformPoint(position)), transform.localScale),
Direction = normalize(transform.rotation * direction),
Magnitude = magnitude,
Time = 0
};
@ -77,21 +139,31 @@ public class FieldDriver : MonoBehaviour
_meleeTime = 0;
}
public bool CanGrab => _grabObject == null;
public void GrabObject(Transform t, Vector3 v)
{
_grabPhase = GrabPhase.Extend;
_grabObject = t;
_grabObjectStartPos = t.position;
_grabObjectVelocity = v;
_grabObjectScale = t.localScale.x;
_tendrilBasePos = _grabObjectStartTendrilBasePos = _collider.ClosestPoint(_grabObjectStartPos);
_fadePoint = .999f;
}
void Update()
{
var pushMag = Mathf.Min(Push.magnitude, 1);
var pushMag = min(length(Push), 1);
_waveOffset = Mathf.Repeat(
_waveOffset + Time.deltaTime * FlowSpeed *
Mathf.Pow(Mathf.Max(pushMag, Mathf.Max(Mathf.Abs(FrontTwist), Mathf.Abs(RearTwist))), FlowSpeedThrottleExponent),
1);
_waveOffset = frac(_waveOffset + Time.deltaTime * FlowSpeed * pow(max(pushMag, max(abs(FrontTwist), abs(RearTwist))), FlowSpeedThrottleExponent));
var refractionRotation = Matrix4x4.Rotate(Camera.transform.rotation).inverse;
if (RefractionAxis == RectTransform.Axis.Vertical) refractionRotation =
Matrix4x4.Rotate(Quaternion.Euler(90, 0, 0)) * refractionRotation;
_field.SetFloat("_WaveOffset", _waveOffset * Mathf.PI * 2);
_field.SetFloat("_WaveOffset", _waveOffset * PI * 2);
_field.SetFloat("_Push", pushMag);
_field.SetVector("_PushDirection", new Vector4(-Push.x, 0, -Push.y));
_field.SetFloat("_TwistFront", FrontTwist);
@ -120,8 +192,8 @@ public class FieldDriver : MonoBehaviour
_meleeTime += Time.deltaTime / MeleeDuration;
if (_meleeTime < 1)
{
_field.SetVector("_MeleeDirection", Quaternion.AngleAxis(Mathf.Sign(_meleeTime * 2 - 1) * MeleeAngle * Mathf.Pow(Mathf.Abs(_meleeTime * 2 - 1), MeleeAngleExponent), Vector3.up) * -Vector3.forward);
_field.SetFloat("_MeleeDisplacement", Mathf.Pow(1 - 2 * Mathf.Abs(_meleeTime - .5f), MeleeRangeExponent) * MeleeRange);
_field.SetVector("_MeleeDirection", Quaternion.AngleAxis(sign(_meleeTime*2-1) * MeleeAngle * pow(abs(_meleeTime * 2 - 1), MeleeAngleExponent), Vector3.up) * -Vector3.forward);
_field.SetFloat("_MeleeDisplacement", pow(1 - 2 * abs(_meleeTime - .5f), MeleeRangeExponent) * MeleeRange);
_field.SetFloat("_MeleeShape", MeleeShaping);
_field.SetFloat("_MeleeFlattening", MeleeFlatness);
}
@ -131,6 +203,73 @@ public class FieldDriver : MonoBehaviour
_field.SetFloat("_MeleeDisplacement", 0);
}
}
if(_grabObject != null)
{
_grabTime += Time.deltaTime / _grabPhase switch
{
GrabPhase.Extend => GrabExtendTime,
GrabPhase.Envelop => GrabEnvelopTime,
GrabPhase.Pull => GrabPullTime,
_ => throw new ArgumentOutOfRangeException()
};
if (_grabTime > 1)
{
_grabTime = 0;
if (_grabPhase == GrabPhase.Envelop)
{
_grabObjectEndPos = _grabObject.position;
}
if (_grabPhase == GrabPhase.Pull)
{
Destroy(_grabObject.gameObject);
_grabObject = null;
_field.SetFloat("_TendrilInfluence", 0);
}
else _grabPhase++;
}
if (_grabObject != null)
{
_tendrilBasePos = AetheriaMath.Damp(_tendrilBasePos, _grabObject.position, TendrilBaseDamping, Time.deltaTime);
switch (_grabPhase)
{
case GrabPhase.Extend:
_tendrilBendTarget = _grabObjectStartPos;
_grabObject.position += _grabObjectVelocity * Time.deltaTime;
_tendrilTargetPos = lerp(
lerp(_grabObjectStartTendrilBasePos, _grabObjectStartPos, _grabTime),
lerp(_grabObjectStartPos, _grabObject.position, _grabTime),
pow(_grabTime, TendrilExtensionExponent));
_field.SetFloat("_TendrilInfluence", pow(_grabTime, TendrilExtendBaseAnimationExponent));
_field.SetFloat("_TendrilSize", lerp(TendrilBaseRadius/2,TendrilBaseRadius,pow(_grabTime, TendrilExtendBaseAnimationExponent)));
_field.SetFloat("_TendrilRadius", _grabObjectScale * pow(_grabTime, TendrilTipRadiusAnimationExponent) * TendrilTipRadius);
break;
case GrabPhase.Envelop:
_tendrilBendTarget = _grabObjectStartPos;
_tendrilTargetPos = _grabObject.position += _grabObjectVelocity * Time.deltaTime * (1-_grabTime);
_field.SetFloat("_TendrilInfluence", 1);
_field.SetFloat("_TendrilSize", TendrilBaseRadius);
_field.SetFloat("_TendrilRadius", _grabObjectScale * TendrilTipRadius);
break;
case GrabPhase.Pull:
_tendrilTargetPos = _grabObject.position = lerp(_grabObjectEndPos, transform.position, _grabTime*_grabTime);
_tendrilBendTarget = lerp(_grabObjectStartPos, _grabObjectEndPos, _grabTime*_grabTime);
if (_fadePoint > .99 && transform.InverseTransformPoint(_grabObject.position).sqrMagnitude < 1)
_fadePoint = _grabTime;
_field.SetFloat("_TendrilInfluence", pow(smoothstep(1, _fadePoint, _grabTime), TendrilFadeExponent));
_field.SetFloat("_TendrilSize", TendrilBaseRadius);
_field.SetFloat("_TendrilRadius", _grabObjectScale * TendrilTipRadius);
break;
default:
throw new ArgumentOutOfRangeException();
}
_field.SetVector("_TendrilBase", Vector3.Scale(transform.InverseTransformPoint(_tendrilBasePos).normalized, transform.localScale));
_field.SetVector("_TendrilBend", Vector3.Scale(transform.InverseTransformPoint(_tendrilBendTarget), transform.localScale));
_field.SetVector("_TendrilTarget", Vector3.Scale(transform.InverseTransformPoint(_tendrilTargetPos), transform.localScale));
}
}
}
private float almostIdentity( float x )
@ -143,10 +282,20 @@ public class FieldDriver : MonoBehaviour
return t * t * (3.0f - 2.0f * t);
}
private float SmoothStep(float edge0, float edge1, float x)
private const int GIZMO_STEPS = 16;
private void OnDrawGizmosSelected()
{
var t = Mathf.Clamp01((x - edge0) / (edge1 - edge0));
return t * t * (3.0f - 2.0f * t);
if (_grabObject != null)
{
Vector3 previous = _tendrilBasePos;
for (int i = 1; i <= GIZMO_STEPS; i++)
{
var l = (float)i / GIZMO_STEPS;
var next = AetheriaMath.GetQuadraticSplinePosition(_tendrilBasePos, _tendrilBendTarget, _tendrilTargetPos, l);
Gizmos.DrawLine(previous, next);
previous = next;
}
}
}
private void OnDestroy()

View file

@ -15,6 +15,7 @@ public class GameSettings : ScriptableObject
public string DefaultBossSoundbank = "Boss_Metal";
public string AmbienceSoundBank = "Ambience";
public string StartingHullName = "Longinus";
public float PickupLifetime = 30;
public float LootDropProbability = .25f;
public float LootDropVelocity = 25;
public float HeatstrokePhasingFloor = 0;
@ -85,4 +86,4 @@ public class BodySettingsCollection
{
public float MinimumMass;
public CelestialBodySettings[] BodySettings;
}
}

View file

@ -1,5 +1,7 @@
using System;
using Unity.Mathematics;
using UnityEngine;
using static Unity.Mathematics.math;
using Random = UnityEngine.Random;
public class GridObject : MonoBehaviour
@ -11,8 +13,10 @@ public class GridObject : MonoBehaviour
public float Drag = .1f;
public float LaunchDrag;
private float2 _selfVelocity;
private float _timeOffset;
public Zone Zone { get; set; }
public Vector3 Velocity { get; set; }
private void Start()
@ -23,6 +27,24 @@ public class GridObject : MonoBehaviour
void Update()
{
var t = transform;
t.localRotation = Quaternion.Euler(Mathf.Sin(Time.time - _timeOffset * RotationSpeed) * 90, 0, Mathf.Cos(Time.time - _timeOffset * RotationSpeed) * 90);
t.localRotation = Quaternion.Euler(sin(Time.time - _timeOffset * RotationSpeed) * 90, 0, cos(Time.time - _timeOffset * RotationSpeed) * 90);
if (Zone == null) return;
var position = t.position;
var gridHeight = Zone.GetHeight(position.Flatland()) + GridOffset;
Velocity += Vector3.up * (sign(gridHeight - position.y) * GridAttraction * Time.deltaTime);
Velocity *= max(0, 1 - LaunchDrag * Time.deltaTime);
var normal = Zone.GetNormal(position.Flatland());
var force = new float2(normal.x, normal.z);
var forceMagnitude = lengthsq(force);
if (forceMagnitude > .001f)
{
var fa = 1 / (1 - forceMagnitude) - 1;
_selfVelocity += normalize(force) * Zone.Settings.GravityStrength * fa * Gravity;
}
_selfVelocity *= max(0, 1 - Drag * Time.deltaTime);
t.position = position + (Velocity + new Vector3(_selfVelocity.x, 0, _selfVelocity.y)) * Time.deltaTime;
}
}
}

View file

@ -1,65 +1,65 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UniRx;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using UnityEngine;
using float2 = Unity.Mathematics.float2;
public class HullCollider : MonoBehaviour
{
private Renderer[] _renderers;
public Subject<HullHitEventArgs> Hit = new Subject<HullHitEventArgs>();
public Subject<HullSplashEventArgs> Splash = new Subject<HullSplashEventArgs>();
public Entity Entity { get; set; }
public Bounds YmirBounds => CalculateBounds(transform.position);
public float YmirPlanarRadius => Mathf.Max(YmirBounds.extents.x, YmirBounds.extents.z, 0.001f);
public void RefreshYmirBoundsSource()
public void SendHit(float damage, float penetration, float spread, DamageType damageType, Entity source, Vector2 texCoord, Vector3 direction)
{
_renderers = GetComponentsInChildren<Renderer>();
}
private void Awake()
{
RefreshYmirBoundsSource();
}
private void OnEnable()
{
if (_renderers == null || _renderers.Length == 0)
RefreshYmirBoundsSource();
}
private Bounds CalculateBounds(Vector3 fallbackCenter)
{
if (_renderers == null)
RefreshYmirBoundsSource();
if (_renderers == null || _renderers.Length == 0)
return new Bounds(fallbackCenter, Vector3.one);
var firstRenderer = FirstLiveRenderer();
if (firstRenderer == null)
return new Bounds(fallbackCenter, Vector3.one);
var bounds = firstRenderer.bounds;
for (var i = 0; i < _renderers.Length; i++)
Hit.OnNext(new HullHitEventArgs
{
var renderer = _renderers[i];
if (renderer == null || renderer == firstRenderer)
continue;
bounds.Encapsulate(renderer.bounds);
}
return bounds;
Damage = damage,
Penetration = penetration,
Spread = spread,
DamageType = damageType,
Source = source,
TexCoord = texCoord,
Direction = direction
});
}
private Renderer FirstLiveRenderer()
public void SendSplash(float damage, DamageType damageType, Entity source, Vector3 direction)
{
for (var i = 0; i < _renderers.Length; i++)
Splash.OnNext(new HullSplashEventArgs
{
if (_renderers[i] != null)
return _renderers[i];
}
return null;
Damage = damage,
DamageType = damageType,
Source = source,
Direction = direction
});
}
}
private void OnCollisionEnter(Collision other)
{
Entity.Velocity += ((float3) other.impulse).xz / Time.deltaTime;
}
public class HullHitEventArgs
{
public float Damage;
public float Penetration;
public float Spread;
public DamageType DamageType;
public Entity Source;
public float2 TexCoord;
public float3 Direction;
}
public class HullSplashEventArgs
{
public float Damage;
public DamageType DamageType;
public Entity Source;
public float3 Direction;
}
}

View file

@ -1,8 +1,8 @@
using System;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using static CultMath.math;
using cfloat3 = CultMath.float3;
using static Unity.Mathematics.math;
public class ItemPickup : MonoBehaviour
{
@ -15,28 +15,27 @@ public class ItemPickup : MonoBehaviour
public ItemInstance Item { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public cfloat3 ViewOrigin { get; set; }
public cfloat3 ViewDirection { get; set; }
public float3 ViewOrigin { get; set; }
public float3 ViewDirection { get; set; }
private float _displayTime;
private void Update()
{
var position = transform.position;
var diff = new cfloat3(position.x, position.y, position.z) - ViewOrigin;
var diff = (float3) transform.position - ViewOrigin;
var toThis = normalize(diff);
var viewAngle = acos(dot(toThis, ViewDirection)) * AetheriaMath.Rad2Deg;
var viewAngle = acos(Vector3.Dot(toThis, ViewDirection)) * Mathf.Rad2Deg;
if (length(diff) < LabelDisplayMaxDistance && viewAngle < LabelDisplayAngle)
_displayTime = Time.time;
var targetAlpha = Time.time - _displayTime < LabelPersistDuration ? 1 : 0;
var c = ScanLabel.color;
c.a = c.a + sign(targetAlpha - c.a) * (Time.deltaTime / LabelFadeDuration);
ScanLabel.color = c;
ScanLabelContainer.rotation = Quaternion.LookRotation((Vector3)AetheriaMath.ToUnity(-toThis));
ScanLabelContainer.rotation = Quaternion.LookRotation(-toThis);
}
private void OnDestroy()
{
ZoneRenderer?.DestroyLoot(this);
}
}
}

View file

@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: baa9b1a7f453a7a4aafe9c44c9fba7c3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,109 +0,0 @@
using System;
using System.Collections.Generic;
using UnityEngine;
public sealed class AetheriaYmirPhysicsBridge : MonoBehaviour
{
private static AetheriaYmirPhysicsBridge _instance;
private readonly List<YmirSphereQueryBody> _clickableBodies = new List<YmirSphereQueryBody>();
private readonly Dictionary<string, ClickableCollider> _clickableBodyMap =
new Dictionary<string, ClickableCollider>(StringComparer.Ordinal);
public bool EnableQueries = true;
public static AetheriaYmirPhysicsBridge Instance
{
get
{
if (_instance != null) return _instance;
_instance = FindAnyObjectByType<AetheriaYmirPhysicsBridge>();
if (_instance != null) return _instance;
var bridge = new GameObject("Aetheria Ymir Presentation Query Bridge");
DontDestroyOnLoad(bridge);
_instance = bridge.AddComponent<AetheriaYmirPhysicsBridge>();
return _instance;
}
}
public bool TryCastClickables(
IReadOnlyList<ClickableCollider> clickables,
Ray ray,
float distance,
out AetheriaYmirClickableHit hit)
{
hit = default;
if (!EnableQueries || clickables == null || clickables.Count == 0 || distance <= 0)
return false;
_clickableBodyMap.Clear();
_clickableBodies.Clear();
for (var index = 0; index < clickables.Count; index++)
{
var clickable = clickables[index];
if (clickable == null || !clickable.isActiveAndEnabled) continue;
var bounds = clickable.ClickBounds;
var bodyId = $"eve.clickable.{index}";
_clickableBodyMap[bodyId] = clickable;
_clickableBodies.Add(new YmirSphereQueryBody
{
id = bodyId,
position = ToVec3(bounds.center),
radius = Mathf.Max(0.001f, bounds.extents.magnitude)
});
}
if (_clickableBodies.Count == 0) return false;
YmirSphereCastResult result;
try
{
result = YmirPhysicsQueries.CastSphere(new YmirSphereCastRequest
{
origin = ToVec3(ray.origin),
direction = ToVec3(ray.direction.normalized),
distance = distance,
radius = 0,
bodies = _clickableBodies.ToArray()
});
}
catch (Exception error)
{
Debug.LogWarning($"Ymir clickable presentation query failed: {error.Message}");
return false;
}
foreach (var candidate in result?.hits ?? Array.Empty<YmirSphereCastHit>())
{
if (!_clickableBodyMap.TryGetValue(candidate.bodyId, out var clickable) || clickable == null)
continue;
hit = new AetheriaYmirClickableHit(
clickable,
ToVector3(candidate.point),
ToVector3(candidate.normal).normalized,
candidate.distance);
return true;
}
return false;
}
private static YmirVec3 ToVec3(Vector3 value) => new YmirVec3 { x = value.x, y = value.y, z = value.z };
private static Vector3 ToVector3(YmirVec3 value) => new Vector3(value.x, value.y, value.z);
}
public readonly struct AetheriaYmirClickableHit
{
public AetheriaYmirClickableHit(ClickableCollider clickable, Vector3 point, Vector3 normal, float distance)
{
Clickable = clickable;
Point = point;
Normal = normal;
Distance = distance;
}
public ClickableCollider Clickable { get; }
public Vector3 Point { get; }
public Vector3 Normal { get; }
public float Distance { get; }
}

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 8d2521ff2dd1835498a2c00656d4bff6

View file

@ -1,42 +1,78 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using UnityEngine;
public class ShieldManager : MonoBehaviour
{
public Prototype ShieldPrototype;
public float CollisionHitDuration = 3;
public float LootInteractionCooldown = 0.25f;
public float ShieldCollisionCooldown = 0.1f;
public Entity Entity { get; set; }
private bool IsShieldActive()
private void OnCollisionEnter(Collision other)
{
return Entity?.Shield != null && Entity.Shield.Item.Active.Value;
var otherShield = other.collider.GetComponent<ShieldManager>();
if (!otherShield)
{
var gridObject = other.collider.GetComponent<GridObject>();
if (gridObject)
{
var itemPickup = other.collider.GetComponent<ItemPickup>();
var mine = other.collider.GetComponent<Mine>();
if (itemPickup)
{
if (Entity.CargoBays.Any(c => c.TryStore(itemPickup.Item)))
{
// TODO: Pickup notification!
Destroy(itemPickup.gameObject);
}
else
{
// TODO: Pickup failed notification!
var cp = other.GetContact(0);
gridObject.Velocity += cp.normal * 25;
Debug.Log("Attempted item pickup, but no space in cargo bay!");
}
}
else if (mine)
{
mine.Explode();
}
else
{
Debug.Log("Shield collision occurred with grid object, but other collider isn't a mine or an item pickup!");
}
}
else
Debug.Log("Shield collision occurred, but other collider isn't a shield or a grid object!");
return;
}
var contact = other.GetContact(0);
var normal = normalize(float2(contact.normal.x, contact.normal.z));
var tangent = normal.Rotate(ItemRotation.CounterClockwise);
var v1n = dot(normal, Entity.Velocity);
var v1t = dot(tangent, Entity.Velocity);
var v2n = dot(normal, otherShield.Entity.Velocity);
//var v2t = dot(tangent, otherShield.Entity.Velocity);
var v1np = PostCollisionVelocity(v1n, Entity.Mass, v2n, otherShield.Entity.Mass);
Entity.Velocity = tangent * v1t + normal * v1np;
if(Entity.Shield != null && Entity.Shield.Item.Active.Value) ShowHit(contact.point, CollisionHitDuration);
}
private Bounds ShieldBounds()
private float PostCollisionVelocity(float v1, float m1, float v2, float m2)
{
var renderers = GetComponentsInChildren<Renderer>();
if (renderers.Length == 0)
return new Bounds(transform.position, Vector3.one);
var bounds = renderers[0].bounds;
for (var i = 1; i < renderers.Length; i++)
bounds.Encapsulate(renderers[i].bounds);
return bounds;
}
private static float ShieldPlanarRadius(Bounds bounds)
{
return Mathf.Max(bounds.extents.x, bounds.extents.z, 0.001f);
return (v1 * (m1 - m2) + m2 * v2) / (m1 + m2);
}
public void ShowHit(Vector3 point, float duration)
{
var shield = ShieldPrototype.Instantiate<ShieldAnimation>();
shield.Direction = shield.transform.InverseTransformPoint(point).normalized;
shield.Direction = normalize(shield.transform.InverseTransformPoint(point));
shield.Duration = duration;
}
}

View file

@ -1,4 +1,8 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class ShieldTest : MonoBehaviour
{
@ -8,13 +12,12 @@ public class ShieldTest : MonoBehaviour
// Update is called once per frame
void Update()
{
var previousX = transform.position.x;
_velocity += -Mathf.Sign(transform.position.x) * Acceleration * Time.deltaTime;
_velocity += -sign(transform.position.x) * Acceleration * Time.deltaTime;
transform.position += Vector3.right * (_velocity * Time.deltaTime);
}
if (Mathf.Sign(transform.position.x) != Mathf.Sign(previousX))
{
_velocity = -_velocity;
}
private void OnCollisionEnter(Collision other)
{
_velocity = -_velocity;
}
}

View file

@ -1,7 +1,9 @@
using System;
using System.Collections;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class ShipInstance : EntityInstance
{
@ -47,7 +49,7 @@ public class ShipInstance : EntityInstance
var drive = ship.GetBehavior<AetherDrive>();
if (drive != null)
{
var particles = Instantiate(UnityHelpers.LoadAsset<ParticleSystem>(drive.Particles), transform, false);
var particles = Instantiate(UnityHelpers.LoadAsset<ParticleSystem>(drive.DriveData.Particles), transform, false);
var main = particles.main;
main.customSimulationSpace = LocalSpace;
_aetherDrive = new AetherDriveInstance
@ -60,11 +62,17 @@ public class ShipInstance : EntityInstance
}
_thrusters = ship.GetBehaviors<Thruster>().Select(thruster =>
{
var particles = Instantiate(UnityHelpers.LoadAsset<ParticleSystem>(thruster.ParticlesPrefab), transform, false);
var effectData = (ThrusterData) thruster.Data;
var particles = Instantiate(UnityHelpers.LoadAsset<ParticleSystem>(effectData.ParticlesPrefab), transform, false);
var particlesShape = particles.shape;
var thrusterHardpoint = ThrusterHardpoints
.FirstOrDefault(t => t.name == ship.Hardpoints[thruster.Item.Position.x, thruster.Item.Position.y].Transform);
particlesShape.meshRenderer = thrusterHardpoint?.Emitter;
// if (!string.IsNullOrEmpty(thruster.Item.Data.SoundEffectTrigger) && thrusterHardpoint != null)
// {
// AkSoundEngine.RegisterGameObj(thrusterHardpoint.gameObject);
// AkSoundEngine.PostEvent(thruster.Item.Data.SoundEffectTrigger, thrusterHardpoint.gameObject);
// }
return new ThrusterInstance
{
@ -105,11 +113,11 @@ public class ShipInstance : EntityInstance
base.Update();
TractorBeam.Power = Entity.TractorPower;
TractorBeam.Direction = (Vector3)AetheriaMath.ToUnity(Entity.CultLookDirection);
TractorBeam.Direction = Entity.LookDirection;
if (_aetherDrive != null)
{
var thrust = CultMath.math.length(_aetherDrive.Drive.ThrustDirection);
var thrust = length(_aetherDrive.Drive.ThrustDirection);
var forceOverLifetime = _aetherDrive.Particles.forceOverLifetime;
forceOverLifetime.xMultiplier = _aetherDrive.Drive.ThrustDirection.x * _aetherDrive.BaseForce;
forceOverLifetime.zMultiplier = _aetherDrive.Drive.ThrustDirection.y * _aetherDrive.BaseForce;
@ -121,20 +129,11 @@ public class ShipInstance : EntityInstance
{
var emissionModule = thrusterInstance.System.emission;
var item = thrusterInstance.Thruster.Item.EquippableItem;
var data = Entity.ItemManager.GetData(item);
thrusterInstance.MaxParticleCount = thrusterInstance.System.particleCount;
emissionModule.rateOverTimeMultiplier = thrusterInstance.BaseEmission * thrusterInstance.Thruster.Axis * (item.Durability / GetMaxDurability(item));
emissionModule.rateOverTimeMultiplier = thrusterInstance.BaseEmission * thrusterInstance.Thruster.Axis * (item.Durability / data.Durability);
}
var rotation = Ship.Rotation;
transform.rotation = new Quaternion(rotation.x, rotation.y, rotation.z, rotation.w);
transform.rotation = Ship.Rotation;
}
private float GetMaxDurability(ItemInstance item)
{
var typedItem = ZoneRenderer?.FindCatalogItem(item);
if (typedItem != null && typedItem.Durability > 0)
return (float)typedItem.Durability;
return item is EquippableItem equippable ? Math.Max(equippable.Durability, 1f) : 1f;
}
}
}

View file

@ -0,0 +1,19 @@
using System;
using UnityEngine;
public class TimedDestroy : MonoBehaviour
{
public float Duration;
private float _startTime;
private void Start()
{
_startTime = Time.time;
}
public void Update()
{
if(Time.time - _startTime > Duration) Destroy(gameObject);
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5d5539a23b814254b038a16f32f1d8a9
timeCreated: 1618453298

View file

@ -15,6 +15,19 @@ public class TractorBeam : MonoBehaviour
{
transform.rotation = Quaternion.LookRotation(Direction);
var emission = ParticleSystem.emission;
emission.rateOverTimeMultiplier = Power > .01f ? Power : 0;
if (Power > .01f)
{
var objectFound = false;
foreach (var o in Physics.SphereCastAll(transform.position, Radius, Direction, Distance, 1 << 21))
{
var gridObject = o.collider.GetComponent<GridObject>();
if (gridObject == null) continue;
objectFound = true;
gridObject.Velocity += Vector3.Normalize(transform.position - gridObject.transform.position) * (Traction * Time.deltaTime);
}
emission.rateOverTimeMultiplier = objectFound ? Power : 0;
}
else emission.rateOverTimeMultiplier = 0;
}
}
}

View file

@ -0,0 +1,111 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Unity.Mathematics.math;
public class ConstantLaser : MonoBehaviour
{
public AnimationCurve StartCurve;
public AnimationCurve EndCurve;
public AnimationCurve IntensityCurve;
public float WidthMultiplier = 1;
public float StartDuration;
public float FadeDuration;
public float CycleDuration;
public LineRenderer LineRenderer;
public float Damage { get; set; }
public float Penetration { get; set; }
public float Spread { get; set; }
public DamageType DamageType { get; set; }
public Entity SourceEntity { get; set; }
public float Range { get; set; }
private float _intensity;
private float _stopIntensity;
private bool _starting;
private bool _stopping;
private float _startTime;
private float _cycleStartTime;
private readonly Vector3[] _zeros = {Vector3.zero, Vector3.zero};
private void OnEnable()
{
_stopping = false;
_starting = true;
_startTime = Time.time;
LineRenderer.SetPositions(_zeros);
}
private void Update()
{
if (_stopping)
{
var lerp = (Time.time - _startTime) / FadeDuration;
LineRenderer.widthMultiplier = EndCurve.Evaluate(lerp) * _stopIntensity * WidthMultiplier;
if (lerp > 1)
{
GetComponent<Prototype>().ReturnToPool();
return;
}
}
else
{
var lerp = (Time.time - _startTime) / StartDuration;
if (lerp > 1)
{
if (_starting)
{
_starting = false;
_cycleStartTime = Time.time;
}
_intensity = IntensityCurve.Evaluate((Time.time - _cycleStartTime) / CycleDuration % CycleDuration);
LineRenderer.widthMultiplier = _intensity * WidthMultiplier;
}
else
{
LineRenderer.widthMultiplier = StartCurve.Evaluate(lerp) * WidthMultiplier;
}
}
LineRenderer.SetPosition(0, transform.position);
bool hitFound = false;
foreach (var hit in Physics.RaycastAll(new Ray(transform.position, transform.forward), Range, 1 | (1 << 17)))
{
var shield = hit.collider.GetComponent<ShieldManager>();
if (shield)
{
if (!(shield.Entity.Shield != null && shield.Entity.Shield.Item.Active.Value && shield.Entity.Shield.CanTakeHit(DamageType, Damage))) continue;
if (shield.Entity != SourceEntity)
{
shield.Entity.Shield.TakeHit(DamageType, Damage);
shield.ShowHit(hit.point, sqrt(Damage));
LineRenderer.SetPosition(1, hit.point);
hitFound = true;
break;
}
}
var hull = hit.collider.GetComponent<HullCollider>();
if (hull && !(hull.Entity.Shield != null && hull.Entity.Shield.Item.Active.Value && hull.Entity.Shield.CanTakeHit(DamageType, Damage)))
{
if (hull.Entity != SourceEntity)
{
hull.SendHit(Damage * Time.deltaTime, Penetration, Spread, DamageType, SourceEntity, hit.textureCoord, transform.forward);
LineRenderer.SetPosition(1, hit.point);
hitFound = true;
break;
}
}
}
if(!hitFound)
LineRenderer.SetPosition(1, transform.position + transform.forward * Range);
}
public void Stop()
{
_stopping = true;
_stopIntensity = _intensity;
_startTime = Time.time;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0fdff1d9c6e4a574f987f8cecdb87f36
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 90
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,34 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConstantLaserManager : ConstantWeaponEffectManager
{
public Prototype LaserPrototype;
private Dictionary<EquippedItem, ConstantLaser> _lasers = new Dictionary<EquippedItem, ConstantLaser>();
public override void StartFiring(WeaponData data, EquippedItem item, EntityInstance source, EntityInstance target)
{
var p = LaserPrototype.Instantiate<ConstantLaser>();
p.SourceEntity = source.Entity;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var barrel = source.GetBarrel(hp);
p.Range = item.Evaluate(data.Range);
var t = p.transform;
t.SetParent(barrel);
t.forward = barrel.forward;
t.position = barrel.position;
p.Damage = item.Evaluate(data.Damage);
p.Penetration = item.Evaluate(data.Penetration);
p.Spread = item.Evaluate(data.DamageSpread);
p.DamageType = data.DamageType;
_lasers.Add(item, p);
}
public override void StopFiring(EquippedItem item)
{
_lasers[item].Stop();
_lasers.Remove(item);
}
}

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 0f3c143f0a844f38a109f2de02ce4423
guid: c1a62592df67e114d880374819659914
MonoImporter:
externalObjects: {}
serializedVersion: 2

View file

@ -0,0 +1,87 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Unity.Mathematics.math;
public class ConstantLightning : MonoBehaviour
{
public LightningCompute Lightning;
public float HitRadius;
public AnimationCurve FadeCurve;
public float StartWidth = 1;
public float EndWidth = 1;
public float FadeDuration;
public Transform Barrel { get; set; }
public float Damage { get; set; }
public float Penetration { get; set; }
public float Spread { get; set; }
public DamageType DamageType { get; set; }
public EntityInstance Source { get; set; }
public float Range { get; set; }
private bool _stopping;
private float _startTime;
private void OnEnable()
{
_stopping = false;
Lightning.StartAnimation();
}
private void Update()
{
if (Barrel == null) return;
if (_stopping)
{
var lerp = (Time.time - _startTime) / FadeDuration;
Lightning.StartWidth = FadeCurve.Evaluate(lerp) * StartWidth;
Lightning.EndWidth = FadeCurve.Evaluate(lerp) * EndWidth;
if (lerp > 1)
{
GetComponent<Prototype>().ReturnToPool();
return;
}
}
else
{
Lightning.StartWidth = StartWidth;
Lightning.EndWidth = EndWidth;
}
Lightning.FixedEndpoint = false;
var hits = Physics.SphereCastAll(Barrel.position, HitRadius, Barrel.forward, Range, 1 | (1 << 17));
foreach (var hit in hits)
{
var shield = hit.collider.GetComponent<ShieldManager>();
if (shield && (shield.Entity.Shield != null && shield.Entity.Shield.Item.Active.Value && shield.Entity.Shield.CanTakeHit(DamageType, Damage)))
{
if (shield.Entity == Source.Entity) continue;
shield.Entity.Shield.TakeHit(DamageType, Damage * Time.deltaTime);
shield.ShowHit(hit.point, sqrt(Damage));
}
var hull = hit.collider.GetComponent<HullCollider>();
if (hull && !(hull.Entity.Shield != null && hull.Entity.Shield.Item.Active.Value && hull.Entity.Shield.CanTakeHit(DamageType, Damage)))
{
if (hull.Entity == Source.Entity) continue;
hull.SendHit(Damage * Time.deltaTime, Penetration, Spread, DamageType, Source.Entity, hit.textureCoord, Barrel.forward);
}
Lightning.FixedEndpoint = true;
Lightning.EndPosition = hit.point;
break;
}
if(!Lightning.FixedEndpoint)
Lightning.EndPosition = Barrel.position + Barrel.forward * Range;
Lightning.StartPosition = Barrel.position;
}
public void Stop()
{
_stopping = true;
_startTime = Time.time;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b184352ea3694b8d892f1402b8d51153
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 55
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,32 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
public class ConstantLightningManager : ConstantWeaponEffectManager
{
public Prototype LightningPrototype;
private Dictionary<EquippedItem, ConstantLightning> _bolts = new Dictionary<EquippedItem, ConstantLightning>();
public override void StartFiring(WeaponData data, EquippedItem item, EntityInstance source, EntityInstance target)
{
var p = LightningPrototype.Instantiate<ConstantLightning>();
p.Source = source;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var barrel = source.GetBarrel(hp);
p.Barrel = barrel;
p.Damage = item.Evaluate(data.Damage);
p.Range = item.Evaluate(data.Range);
p.Penetration = item.Evaluate(data.Penetration);
p.Spread = item.Evaluate(data.DamageSpread);
p.DamageType = data.DamageType;
_bolts.Add(item, p);
}
public override void StopFiring(EquippedItem item)
{
_bolts[item].Stop();
_bolts.Remove(item);
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ecabe4f078a147459bba6172582d7bc8
timeCreated: 1612491892

Some files were not shown because too many files have changed in this diff Show more