Restore the stable legacy Unity project
This commit is contained in:
parent
56a156ee87
commit
7006a6b0dd
2070 changed files with 180490 additions and 169303 deletions
|
|
@ -3,6 +3,7 @@
|
|||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
|
|
@ -20,20 +21,17 @@ public class ClickRaycaster : MonoBehaviour
|
|||
_clickCatcher = GetComponent<ClickCatcher>();
|
||||
_clickCatcher.OnDown.Subscribe(pointer =>
|
||||
{
|
||||
RaycastHit hit;
|
||||
var ray = RayCamera.ScreenPointToRay(pointer.position);
|
||||
var clickables = new List<ClickableCollider>();
|
||||
foreach (var clickable in ClickableCollider.Active)
|
||||
Physics.Raycast(ray, out hit, 1000, Layers.value);
|
||||
if (hit.collider != null)
|
||||
{
|
||||
if (clickable == null || ((1 << clickable.gameObject.layer) & Layers.value) == 0)
|
||||
continue;
|
||||
|
||||
clickables.Add(clickable);
|
||||
//Debug.Log($"Clicked on gameobject {hit.collider.gameObject}");
|
||||
var clickable = hit.collider.GetComponent<ClickableCollider>();
|
||||
if (clickable != null)
|
||||
clickable.Click(pointer, ray, hit);
|
||||
}
|
||||
|
||||
if (AetheriaYmirPhysicsBridge.Instance.TryCastClickables(clickables, ray, 1000, out var hit))
|
||||
hit.Clickable.Click(pointer, ray, hit);
|
||||
else
|
||||
OnClickMiss?.Invoke(pointer);
|
||||
else OnClickMiss?.Invoke(pointer);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,94 +3,26 @@
|
|||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
public class ClickableCollider : MonoBehaviour
|
||||
{
|
||||
private static readonly List<ClickableCollider> ActiveClickables = new List<ClickableCollider>();
|
||||
public event Action<ClickableCollider, PointerEventData, Ray, RaycastHit> OnClick;
|
||||
|
||||
private Renderer[] _renderers;
|
||||
|
||||
public event Action<ClickableCollider, PointerEventData, Ray, AetheriaYmirClickableHit> OnClick;
|
||||
|
||||
public static IReadOnlyList<ClickableCollider> Active => ActiveClickables;
|
||||
|
||||
public Bounds ClickBounds
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_renderers == null)
|
||||
RefreshYmirBoundsSource();
|
||||
|
||||
if (_renderers == null || _renderers.Length == 0)
|
||||
return new Bounds(transform.position, Vector3.one * 0.5f);
|
||||
|
||||
var firstRenderer = FirstLiveRenderer();
|
||||
if (firstRenderer == null)
|
||||
return new Bounds(transform.position, Vector3.one * 0.5f);
|
||||
|
||||
var bounds = firstRenderer.bounds;
|
||||
for (var i = 0; i < _renderers.Length; i++)
|
||||
{
|
||||
var renderer = _renderers[i];
|
||||
if (renderer == null || renderer == firstRenderer)
|
||||
continue;
|
||||
|
||||
bounds.Encapsulate(renderer.bounds);
|
||||
}
|
||||
|
||||
return bounds;
|
||||
}
|
||||
}
|
||||
|
||||
public void Click(PointerEventData eventData, Ray ray, AetheriaYmirClickableHit hit) => OnClick?.Invoke(this, eventData, ray, hit);
|
||||
public void Click(PointerEventData eventData, Ray ray, RaycastHit raycastHit) => OnClick?.Invoke(this, eventData, ray, raycastHit);
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
OnClick = null;
|
||||
}
|
||||
|
||||
public void RefreshYmirBoundsSource()
|
||||
{
|
||||
_renderers = GetComponentsInChildren<Renderer>();
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
RefreshYmirBoundsSource();
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (_renderers == null || _renderers.Length == 0)
|
||||
RefreshYmirBoundsSource();
|
||||
|
||||
if (!ActiveClickables.Contains(this))
|
||||
ActiveClickables.Add(this);
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
ActiveClickables.Remove(this);
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
var proto = GetComponent<Prototype>();
|
||||
if(proto != null)
|
||||
proto.OnReturnToPool += () => OnClick = null;
|
||||
}
|
||||
|
||||
private Renderer FirstLiveRenderer()
|
||||
{
|
||||
for (var i = 0; i < _renderers.Length; i++)
|
||||
{
|
||||
if (_renderers[i] != null)
|
||||
return _renderers[i];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,143 +1,55 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UI;
|
||||
using UniRx;
|
||||
|
||||
public class ConfirmationDialog : MonoBehaviour
|
||||
public class ConfirmationDialog : PropertiesPanel
|
||||
{
|
||||
public TextMeshProUGUI Title;
|
||||
public RectTransform Content;
|
||||
public Property Property;
|
||||
public InputField InputField;
|
||||
public ClickCatcher CancelClickCatcher;
|
||||
public GameObject ButtonGroup;
|
||||
public Button Cancel;
|
||||
public Button Confirm;
|
||||
public TextMeshProUGUI ConfirmText;
|
||||
public TextMeshProUGUI CancelText;
|
||||
|
||||
|
||||
public bool LockDialog { get; set; }
|
||||
|
||||
private readonly List<GameObject> _entries = new();
|
||||
private readonly List<Action> _refreshers = new();
|
||||
private Action _onCancel;
|
||||
private Action _onConfirm;
|
||||
private Action _enableGlobalInput;
|
||||
private Action _disableGlobalInput;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
Cancel.onClick.AddListener(() => End());
|
||||
Confirm.onClick.AddListener(() => End(true));
|
||||
if (CancelClickCatcher != null)
|
||||
{
|
||||
CancelClickCatcher.OnClick.Subscribe(_ =>
|
||||
CancelClickCatcher.OnClick.Subscribe(data =>
|
||||
{
|
||||
if (!LockDialog)
|
||||
{
|
||||
End();
|
||||
}
|
||||
if (!LockDialog) End();
|
||||
});
|
||||
}
|
||||
|
||||
OnPropertyAdded += go =>
|
||||
{
|
||||
go.SetActive(true);
|
||||
go.transform.SetSiblingIndex(Title.transform.GetSiblingIndex() + 1);
|
||||
};
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
RefreshValues();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
foreach (var entry in _entries)
|
||||
{
|
||||
Destroy(entry);
|
||||
}
|
||||
|
||||
_entries.Clear();
|
||||
_refreshers.Clear();
|
||||
Title.text = "Properties";
|
||||
}
|
||||
|
||||
public Property AddProperty(Func<string> read)
|
||||
{
|
||||
if (read == null)
|
||||
{
|
||||
throw new ArgumentException("Attempted to add confirmation-dialog property with null read function!");
|
||||
}
|
||||
|
||||
var property = Instantiate(Property, Content ?? (RectTransform)transform);
|
||||
_refreshers.Add(() => property.Label.text = read());
|
||||
property.Label.text = read();
|
||||
RegisterEntry(property.gameObject);
|
||||
return property;
|
||||
}
|
||||
|
||||
public Property AddProperty(string text)
|
||||
{
|
||||
var property = Instantiate(Property, Content ?? (RectTransform)transform);
|
||||
property.Label.text = text;
|
||||
RegisterEntry(property.gameObject);
|
||||
return property;
|
||||
}
|
||||
|
||||
public void SetInputGate(Action enableGlobalInput, Action disableGlobalInput)
|
||||
{
|
||||
_enableGlobalInput = enableGlobalInput;
|
||||
_disableGlobalInput = disableGlobalInput;
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<string> read, Action<string> write)
|
||||
{
|
||||
var field = Instantiate(InputField, Content ?? (RectTransform)transform);
|
||||
field.Label.text = name;
|
||||
field.Field.contentType = TMP_InputField.ContentType.Standard;
|
||||
field.Field.onValueChanged.AddListener(write.Invoke);
|
||||
_refreshers.Add(() => SyncField(field.Field, read()));
|
||||
SyncField(field.Field, read());
|
||||
RegisterEntry(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<int> read, Action<int> write)
|
||||
{
|
||||
var field = Instantiate(InputField, Content ?? (RectTransform)transform);
|
||||
field.Label.text = name;
|
||||
field.Field.contentType = TMP_InputField.ContentType.IntegerNumber;
|
||||
field.Field.onValueChanged.AddListener(value =>
|
||||
{
|
||||
if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed))
|
||||
{
|
||||
write(parsed);
|
||||
}
|
||||
});
|
||||
_refreshers.Add(() => SyncField(field.Field, read().ToString(CultureInfo.InvariantCulture)));
|
||||
SyncField(field.Field, read().ToString(CultureInfo.InvariantCulture));
|
||||
RegisterEntry(field.gameObject);
|
||||
}
|
||||
|
||||
|
||||
public void End(bool success = false)
|
||||
{
|
||||
if (success)
|
||||
{
|
||||
_onConfirm?.Invoke();
|
||||
}
|
||||
else
|
||||
{
|
||||
_onCancel?.Invoke();
|
||||
}
|
||||
|
||||
if(success) _onConfirm?.Invoke();
|
||||
else _onCancel?.Invoke();
|
||||
CancelClickCatcher?.gameObject.SetActive(false);
|
||||
gameObject.SetActive(false);
|
||||
_enableGlobalInput?.Invoke();
|
||||
ActionGameManager.Instance?.Input.Global.Enable();
|
||||
}
|
||||
|
||||
public void MoveToCursor()
|
||||
|
|
@ -147,43 +59,19 @@ public class ConfirmationDialog : MonoBehaviour
|
|||
|
||||
public void Show(Action onConfirm = null, Action onCancel = null, string confirmText = "OK", string cancelText = "Cancel")
|
||||
{
|
||||
RefreshValues();
|
||||
gameObject.SetActive(true);
|
||||
|
||||
|
||||
_onConfirm = onConfirm;
|
||||
Confirm.gameObject.SetActive(onConfirm != null);
|
||||
Confirm.gameObject.SetActive(onConfirm!=null);
|
||||
ConfirmText.text = confirmText;
|
||||
|
||||
|
||||
_onCancel = onCancel;
|
||||
Cancel.gameObject.SetActive(onCancel != null);
|
||||
Cancel.gameObject.SetActive(onCancel!=null);
|
||||
CancelText.text = cancelText;
|
||||
|
||||
ButtonGroup.SetActive(onConfirm != null || onCancel != null);
|
||||
|
||||
|
||||
ButtonGroup.SetActive(onConfirm!=null || onCancel!=null);
|
||||
|
||||
CancelClickCatcher?.gameObject.SetActive(true);
|
||||
_disableGlobalInput?.Invoke();
|
||||
}
|
||||
|
||||
private void RegisterEntry(GameObject entry)
|
||||
{
|
||||
_entries.Add(entry);
|
||||
entry.SetActive(true);
|
||||
entry.transform.SetSiblingIndex(Title.transform.GetSiblingIndex() + _entries.Count);
|
||||
}
|
||||
|
||||
private void RefreshValues()
|
||||
{
|
||||
foreach (var refresh in _refreshers)
|
||||
{
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
|
||||
private static void SyncField(TMP_InputField field, string value)
|
||||
{
|
||||
if (!string.Equals(field.text, value, StringComparison.Ordinal))
|
||||
{
|
||||
field.SetTextWithoutNotify(value);
|
||||
}
|
||||
ActionGameManager.Instance?.Input.Global.Disable();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
124
Assets/Scripts/UI/ConsoleController.cs
Normal file
124
Assets/Scripts/UI/ConsoleController.cs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
/// <summary>
|
||||
/// Handles parsing and execution of console commands, as well as collecting log output.
|
||||
/// </summary>
|
||||
using UnityEngine;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEngine.SceneManagement;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
public class ConsoleController
|
||||
{
|
||||
public static Component MessageReceiver;
|
||||
private static ConsoleController _instance;
|
||||
private static Regex _permittedCharacters = new Regex("[^a-zA-Z0-9 -]");
|
||||
private static Dictionary<string, Action<string[]>> _commands = new Dictionary<string, Action<string[]>>();
|
||||
|
||||
private ConsoleController()
|
||||
{
|
||||
}
|
||||
|
||||
public static ConsoleController Instance
|
||||
{
|
||||
get => _instance ?? (_instance = new ConsoleController());
|
||||
}
|
||||
|
||||
public static void ClearCommands()
|
||||
{
|
||||
_commands.Clear();
|
||||
}
|
||||
|
||||
public static void AddCommand(string command, Action<string[]> action)
|
||||
{
|
||||
var lower = command.ToLowerInvariant();
|
||||
if(!_commands.ContainsKey(lower))
|
||||
_commands.Add(lower, action);
|
||||
}
|
||||
|
||||
#region Event declarations
|
||||
// Used to communicate with ConsoleView
|
||||
public delegate void LogChangedHandler(string[] log);
|
||||
public event LogChangedHandler LogChanged;
|
||||
|
||||
public delegate void VisibilityChangedHandler(bool visible);
|
||||
public event VisibilityChangedHandler VisibilityChanged;
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// How many log lines should be retained?
|
||||
/// Note that strings submitted to appendLogLine with embedded newlines will be counted as a single line.
|
||||
/// </summary>
|
||||
private const int ScrollbackSize = 100;
|
||||
|
||||
private readonly Queue<string> _scrollback = new Queue<string>(ScrollbackSize);
|
||||
private readonly List<string> _commandHistory = new List<string>();
|
||||
|
||||
public string[] Log { get; private set; } //Copy of scrollback as an array for easier use by ConsoleView
|
||||
|
||||
public void AppendLogLine(string line) {
|
||||
if (_scrollback.Count >= ScrollbackSize) {
|
||||
_scrollback.Dequeue();
|
||||
}
|
||||
_scrollback.Enqueue(line);
|
||||
|
||||
Log = _scrollback.ToArray();
|
||||
LogChanged?.Invoke(Log);
|
||||
}
|
||||
|
||||
public void RunCommandString(string commandString) {
|
||||
AppendLogLine($"$ {commandString}");
|
||||
|
||||
string[] commandSplit = ParseArguments(commandString);
|
||||
string[] args = {"",""};
|
||||
if (commandSplit.Length < 1) {
|
||||
AppendLogLine($"Unable to process command '{commandString}'");
|
||||
return;
|
||||
|
||||
}
|
||||
if (commandSplit.Length >= 2) {
|
||||
int numArgs = commandSplit.Length - 1;
|
||||
args = new string[numArgs];
|
||||
Array.Copy(commandSplit, 1, args, 0, numArgs);
|
||||
}
|
||||
|
||||
var cmd = commandSplit[0].ToLower();
|
||||
if(_commands.ContainsKey(cmd))
|
||||
_commands[cmd].Invoke(args);
|
||||
else AppendLogLine("Invalid command!");
|
||||
//MessageReceiver.SendMessage(commandSplit[0].ToLower(), args, SendMessageOptions.DontRequireReceiver);
|
||||
_commandHistory.Add(commandString);
|
||||
}
|
||||
|
||||
static string[] ParseArguments(string commandString)
|
||||
{
|
||||
var parmChars = new LinkedList<char>(commandString.ToCharArray());
|
||||
var inQuote = false;
|
||||
var node = parmChars.First;
|
||||
while (node != null)
|
||||
{
|
||||
var next = node.Next;
|
||||
if (node.Value == '"') {
|
||||
inQuote = !inQuote;
|
||||
parmChars.Remove(node);
|
||||
}
|
||||
if (!inQuote && node.Value == ' ') {
|
||||
node.Value = '\n';
|
||||
}
|
||||
node = next;
|
||||
}
|
||||
var parmCharsArr = new char[parmChars.Count];
|
||||
parmChars.CopyTo(parmCharsArr, 0);
|
||||
var args = new string(parmCharsArr).Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries);
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
args[i] = _permittedCharacters.Replace(args[i], "");
|
||||
}
|
||||
return args;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/UI/ConsoleController.cs.meta
Normal file
11
Assets/Scripts/UI/ConsoleController.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 426b2d2dbea4d4d40b069c1ba2f6efb0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
149
Assets/Scripts/UI/ConsoleView.cs
Normal file
149
Assets/Scripts/UI/ConsoleView.cs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
/// <summary>
|
||||
/// Marshals events and data between ConsoleController and uGUI.
|
||||
/// </summary>
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
public class ConsoleView : MonoBehaviour {
|
||||
bool _didShow = false;
|
||||
|
||||
public ActionGameManager GameManager;
|
||||
public GameObject ViewContainer; //Container for console view, should be a child of this GameObject
|
||||
public TextMeshProUGUI LogTextArea;
|
||||
public TextMeshProUGUI InputArea;
|
||||
public ScrollRect Scroll;
|
||||
|
||||
private string _inputString = "";
|
||||
private CursorLockMode _previousCursorLockMode;
|
||||
private bool _playerInputPreviouslyEnabled;
|
||||
|
||||
public string InputString
|
||||
{
|
||||
get => _inputString;
|
||||
set
|
||||
{
|
||||
_inputString = value;
|
||||
InputArea.text = $"> {_inputString}";
|
||||
}
|
||||
}
|
||||
|
||||
//public bool AcceptingInput { get; private set; }
|
||||
|
||||
public bool Visible { get; private set; }
|
||||
|
||||
void Start()
|
||||
{
|
||||
//AcceptingInput = false;
|
||||
//_console = new ConsoleController();
|
||||
Application.logMessageReceived += OnLogCallback;
|
||||
|
||||
SetVisibility(false);
|
||||
|
||||
ConsoleController.Instance.VisibilityChanged += OnVisibilityChanged;
|
||||
ConsoleController.Instance.LogChanged += OnLogChanged;
|
||||
|
||||
Keyboard.current.onTextInput += c =>
|
||||
{
|
||||
if (!Visible || c == '`') return;
|
||||
InputString += c;
|
||||
};
|
||||
InputString = "";
|
||||
|
||||
ConsoleController.AddCommand("echo", Echo);
|
||||
|
||||
// var sizeFitter = GetComponentInChildren<ContentSizeFitter>().on
|
||||
}
|
||||
|
||||
private void OnLogCallback(string condition, string trace, LogType type)
|
||||
{
|
||||
ConsoleController.Instance.AppendLogLine("<color=" + (type == LogType.Error ? "red" : type == LogType.Warning ? "yellow" : "white") + ">" + condition + "</color>");
|
||||
}
|
||||
|
||||
private void OnDestroy() {
|
||||
Application.logMessageReceived -= OnLogCallback;
|
||||
ConsoleController.Instance.VisibilityChanged -= OnVisibilityChanged;
|
||||
ConsoleController.Instance.LogChanged -= OnLogChanged;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
var keyboard = Keyboard.current;
|
||||
//Toggle visibility when tilde key pressed
|
||||
if (keyboard.backquoteKey.wasPressedThisFrame) {
|
||||
ToggleVisibility();
|
||||
}
|
||||
|
||||
if (!Visible) return;
|
||||
|
||||
if(keyboard.deleteKey.wasPressedThisFrame && InputString.Length>0)
|
||||
{
|
||||
InputString = InputString.Substring(0, InputString.Length - 1);
|
||||
}
|
||||
|
||||
if (keyboard.enterKey.wasPressedThisFrame)
|
||||
{
|
||||
if (/*AcceptingInput && */InputString.Length > 0)
|
||||
{
|
||||
//if(_inputString.StartsWith("!") || _inputString.StartsWith("/"))
|
||||
ConsoleController.Instance.RunCommandString(InputString);//.Substring(1));
|
||||
//else ConsoleController.Instance.RunCommandString($"say \"{_inputString}\"");
|
||||
InputString = "";
|
||||
}
|
||||
//AcceptingInput = !AcceptingInput;
|
||||
}
|
||||
}
|
||||
|
||||
void Echo(string[] args)
|
||||
{
|
||||
if(args.Length>0)
|
||||
Debug.Log(args.Aggregate((a,b) => a + " " + b));
|
||||
}
|
||||
|
||||
void ToggleVisibility() {
|
||||
SetVisibility(!ViewContainer.activeSelf);
|
||||
}
|
||||
|
||||
void SetVisibility(bool visible) {
|
||||
ViewContainer.SetActive(visible);
|
||||
Visible = visible;
|
||||
if(visible)
|
||||
{
|
||||
_playerInputPreviouslyEnabled = GameManager.Input.Player.enabled;
|
||||
_previousCursorLockMode = Cursor.lockState;
|
||||
GameManager.Input.Global.Disable();
|
||||
GameManager.DisablePlayerInput();
|
||||
GameManager.Input.UI.Disable();
|
||||
Cursor.lockState = CursorLockMode.None;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(_playerInputPreviouslyEnabled)
|
||||
GameManager.EnablePlayerInput();
|
||||
else GameManager.Input.UI.Enable();
|
||||
GameManager.Input.Global.Enable();
|
||||
Cursor.lockState = _previousCursorLockMode;
|
||||
}
|
||||
}
|
||||
|
||||
void OnVisibilityChanged(bool visible) {
|
||||
SetVisibility(visible);
|
||||
}
|
||||
|
||||
void OnLogChanged(string[] newLog) {
|
||||
LogTextArea.text = string.Join("\n", newLog);
|
||||
// if (AcceptingInput)
|
||||
// LogTextArea.text += "\n\n> " + _inputString;
|
||||
Observable.NextFrame().Subscribe(_ =>
|
||||
{
|
||||
if(Scroll)
|
||||
Scroll.verticalNormalizedPosition = 0;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
11
Assets/Scripts/UI/ConsoleView.cs.meta
Normal file
11
Assets/Scripts/UI/ConsoleView.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 60214997723e68547b9c784ebda51d9a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
142
Assets/Scripts/UI/ContextMenu.cs
Normal file
142
Assets/Scripts/UI/ContextMenu.cs
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UI;
|
||||
using UniRx;
|
||||
|
||||
public class ContextMenu : MonoBehaviour
|
||||
{
|
||||
public Canvas Canvas;
|
||||
public RectTransform Root;
|
||||
public ClickCatcher CancelClickCatcher;
|
||||
public ContextMenuOption OptionPrefab;
|
||||
public ContextMenu DropMenuPrefab;
|
||||
public ContextMenu Parent;
|
||||
public bool ForceDirectionRight;
|
||||
public Vector3 ForcePosition;
|
||||
|
||||
public RectTransform ContentRoot;
|
||||
|
||||
public float OptionHeight;
|
||||
public float PaddingHeight;
|
||||
|
||||
private List<GameObject> _options = new List<GameObject>();
|
||||
private bool _hasDropdown;
|
||||
private bool _dropdownRight;
|
||||
private GameObject _dropdown;
|
||||
private ContextMenuOption _currentDropdown;
|
||||
private IDisposable _backgroundClickSubscription;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (CancelClickCatcher != null)
|
||||
_backgroundClickSubscription = CancelClickCatcher.OnClick.Subscribe(data =>
|
||||
{
|
||||
End();
|
||||
});
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
_backgroundClickSubscription?.Dispose();
|
||||
_backgroundClickSubscription = null;
|
||||
}
|
||||
|
||||
private void End()
|
||||
{
|
||||
if (_dropdown != null)
|
||||
Destroy(_dropdown);
|
||||
CancelClickCatcher.gameObject.SetActive(false);
|
||||
gameObject.SetActive(false);
|
||||
ActionGameManager.Instance?.Input.Global.Enable();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
// Destroy previous options
|
||||
foreach(var option in _options)
|
||||
Destroy(option);
|
||||
_options.Clear();
|
||||
_hasDropdown = false;
|
||||
}
|
||||
|
||||
public void AddOption(string text, Action action, bool enabled = true)
|
||||
{
|
||||
var optionButton = Instantiate(OptionPrefab, ContentRoot);
|
||||
optionButton.Label.text = text;
|
||||
optionButton.Button.onClick.AddListener(() =>
|
||||
{
|
||||
if(Parent!=null)
|
||||
Parent.End();
|
||||
else
|
||||
End();
|
||||
action();
|
||||
});
|
||||
optionButton.Hover.OnEnter += data =>
|
||||
{
|
||||
if (_dropdown != null)
|
||||
Destroy(_dropdown);
|
||||
};
|
||||
optionButton.Arrow.gameObject.SetActive(false);
|
||||
optionButton.Button.interactable = enabled;
|
||||
_options.Add(optionButton.gameObject);
|
||||
}
|
||||
|
||||
public void AddDropdown(string text, IEnumerable<(string text, Action action, bool enabled)> options)
|
||||
{
|
||||
_hasDropdown = true;
|
||||
var optionButton = Instantiate(OptionPrefab, ContentRoot);
|
||||
optionButton.Label.text = text;
|
||||
optionButton.Hover.OnEnter += data =>
|
||||
{
|
||||
if (_currentDropdown != optionButton)
|
||||
{
|
||||
if(_dropdown!=null)
|
||||
Destroy(_dropdown);
|
||||
var drop = Instantiate(DropMenuPrefab, Root);
|
||||
_dropdown = drop.gameObject;
|
||||
foreach (var option in options)
|
||||
drop.AddOption(option.text, option.action, option.enabled);
|
||||
drop.Parent = this;
|
||||
drop.ForceDirectionRight = _dropdownRight;
|
||||
Vector3[] corners = new Vector3[4];
|
||||
((RectTransform) optionButton.transform).GetWorldCorners(corners);
|
||||
drop.ForcePosition = corners[_dropdownRight ? 2 : 1];
|
||||
drop.Show();
|
||||
}
|
||||
};
|
||||
_options.Add(optionButton.gameObject);
|
||||
}
|
||||
|
||||
public void Show()
|
||||
{
|
||||
gameObject.SetActive(true);
|
||||
var rect = transform as RectTransform;
|
||||
var pivot = rect.pivot;
|
||||
var canvas = Parent != null ? Parent.Canvas : Canvas;
|
||||
var mousePosition = Mouse.current.position.ReadValue();
|
||||
if (Parent!=null)
|
||||
pivot.x = ForceDirectionRight ? 0 : 1;
|
||||
else
|
||||
pivot.x = mousePosition.x > Screen.width - rect.sizeDelta.x * canvas.scaleFactor ? 1 : 0;
|
||||
var scaleFactor = canvas.scaleFactor;
|
||||
_dropdownRight = mousePosition.x < Screen.width - rect.sizeDelta.x * scaleFactor * 2;
|
||||
var pos = Parent==null ? mousePosition.y : ForcePosition.y;
|
||||
var space = (PaddingHeight + _options.Count * OptionHeight) * scaleFactor;
|
||||
var deltaY = pos < space ? space - pos : PaddingHeight / 2 * scaleFactor;
|
||||
pivot.y = 1;//pivotTop ? 1 : 0;
|
||||
rect.pivot = pivot;
|
||||
rect.position = (Parent != null ? ForcePosition : (Vector3) mousePosition) + Vector3.up * deltaY;
|
||||
if (Parent==null)
|
||||
CancelClickCatcher.gameObject.SetActive(true);
|
||||
ActionGameManager.Instance?.Input.Global.Disable();
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/UI/ContextMenu.cs.meta
Normal file
11
Assets/Scripts/UI/ContextMenu.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f50aaf220f9a82a4a817fa3164bcd62b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
17
Assets/Scripts/UI/ContextMenuOption.cs
Normal file
17
Assets/Scripts/UI/ContextMenuOption.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
/* 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.Collections;
|
||||
using System.Collections.Generic;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class ContextMenuOption : MonoBehaviour
|
||||
{
|
||||
public TextMeshProUGUI Label;
|
||||
public Image Arrow;
|
||||
public Button Button;
|
||||
public MouseHover Hover;
|
||||
}
|
||||
11
Assets/Scripts/UI/ContextMenuOption.cs.meta
Normal file
11
Assets/Scripts/UI/ContextMenuOption.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 741dca7ca8716dd438516c4f8bafd441
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
88
Assets/Scripts/UI/DropdownMenu.cs
Normal file
88
Assets/Scripts/UI/DropdownMenu.cs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UniRx;
|
||||
|
||||
public class DropdownMenu : MonoBehaviour
|
||||
{
|
||||
public Canvas Canvas;
|
||||
public ClickCatcher CancelClickCatcher;
|
||||
public PropertyButton OptionPrefab;
|
||||
|
||||
public RectTransform ContentRoot;
|
||||
|
||||
public float OptionHeight;
|
||||
public float PaddingHeight;
|
||||
|
||||
private List<GameObject> _options = new List<GameObject>();
|
||||
private IDisposable _backgroundClickSubscription;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (CancelClickCatcher != null)
|
||||
_backgroundClickSubscription = CancelClickCatcher.OnClick.Subscribe(data =>
|
||||
{
|
||||
End();
|
||||
});
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
_backgroundClickSubscription?.Dispose();
|
||||
_backgroundClickSubscription = null;
|
||||
}
|
||||
|
||||
private void End()
|
||||
{
|
||||
CancelClickCatcher.gameObject.SetActive(false);
|
||||
gameObject.SetActive(false);
|
||||
ActionGameManager.Instance?.Input.Global.Enable();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
// Destroy previous options
|
||||
foreach(var option in _options)
|
||||
Destroy(option);
|
||||
_options.Clear();
|
||||
}
|
||||
|
||||
public void AddOption(string text, Action action, bool selected = false, bool enabled = true)
|
||||
{
|
||||
var optionButton = Instantiate(OptionPrefab, ContentRoot);
|
||||
optionButton.Label.text = text;
|
||||
optionButton.Button.onClick.AddListener(() =>
|
||||
{
|
||||
action();
|
||||
End();
|
||||
});
|
||||
optionButton.Button.interactable = enabled;
|
||||
//optionButton.Button..CurrentState = !enabled ? FlatButtonState.Disabled : selected ? FlatButtonState.Selected : FlatButtonState.Unselected;
|
||||
_options.Add(optionButton.gameObject);
|
||||
}
|
||||
|
||||
public void Show(RectTransform parent)
|
||||
{
|
||||
var rect = transform as RectTransform;
|
||||
var pivot = rect.pivot;
|
||||
pivot.x = 0;
|
||||
var scaleFactor = Canvas.scaleFactor;
|
||||
var corners = new Vector3[4];
|
||||
parent.GetWorldCorners(corners);
|
||||
var pivotTop = corners[0].y > (PaddingHeight + _options.Count * OptionHeight) * scaleFactor;
|
||||
pivot.y = pivotTop ? 1 : 0;
|
||||
rect.pivot = pivot;
|
||||
rect.sizeDelta = parent.sizeDelta;
|
||||
rect.position = pivotTop ? corners[0] : corners[1];
|
||||
CancelClickCatcher.gameObject.SetActive(true);
|
||||
ActionGameManager.Instance?.Input.Global.Disable();
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/UI/DropdownMenu.cs.meta
Normal file
11
Assets/Scripts/UI/DropdownMenu.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 848ae49aff071f5458dcc0322b8b84eb
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
112
Assets/Scripts/UI/FieldTester.cs
Normal file
112
Assets/Scripts/UI/FieldTester.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using Random = UnityEngine.Random;
|
||||
|
||||
public class FieldTester : MonoBehaviour
|
||||
{
|
||||
public int PickupCount;
|
||||
public ItemPickup[] PickupPrefabs;
|
||||
public float PickupTravelDistance;
|
||||
public float PickupTravelTimeMin;
|
||||
public float PickupTravelTimeMax;
|
||||
public float PickupSizeMin;
|
||||
public float PickupSizeMax;
|
||||
public float ScaleExponent;
|
||||
public float PickupSpawnDistanceMin;
|
||||
public float PickupSpawnDistanceMax;
|
||||
public Camera Camera;
|
||||
public FieldDriver TestField;
|
||||
public PropertiesPanel Properties;
|
||||
|
||||
private AetheriaInput _input;
|
||||
private bool _forceThrust;
|
||||
private float _throttleDecay = 2;
|
||||
private bool _directionalPush;
|
||||
private float _twistFront;
|
||||
private float _twistRear;
|
||||
|
||||
private List<(float lerp, float time, Transform transform)> _pickups = new List<(float lerp, float time, Transform transform)>();
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_input = new AetheriaInput();
|
||||
_input.Player.Enable();
|
||||
Properties.AddField("Time Scale", () => Time.timeScale, f => Time.timeScale = f, 0, 2);
|
||||
Properties.AddField("FOV", () => Camera.fieldOfView, f => Camera.fieldOfView = f, 15, 45);
|
||||
Properties.AddButton("Melee", () => TestField.Melee());
|
||||
Properties.AddField("Force Thrust", () => _forceThrust, b => _forceThrust = b);
|
||||
Properties.AddField("Directional Push", () => _directionalPush, b => _directionalPush = b);
|
||||
Properties.AddField("Throttle Decay", () => _throttleDecay, f => _throttleDecay = f);
|
||||
Properties.Inspect(TestField, true, true);
|
||||
Properties.AddProperty("Current Hits", () => TestField.HitCount.ToString());
|
||||
Properties.AddProperty("Push X", () => $"{(int)(TestField.Push.x * 100)}%");
|
||||
Properties.AddProperty("Push Y", () => $"{(int)(TestField.Push.y * 100)}%");
|
||||
Properties.AddProperty("Front Twist", () => $"{(int)(TestField.FrontTwist * 100)}%");
|
||||
Properties.AddProperty("Rear Twist", () => $"{(int)(TestField.RearTwist * 100)}%");
|
||||
|
||||
for (int i = 0; i < PickupCount; i++)
|
||||
{
|
||||
var l = (float)i / PickupCount;
|
||||
var pickup = Instantiate(PickupPrefabs[(int)(l * PickupPrefabs.Length)], transform);
|
||||
var i1 = i;
|
||||
var click = pickup.GetComponent<ClickableCollider>();
|
||||
click.OnClick += (collider, data, ray, hit) =>
|
||||
{
|
||||
if (!TestField.CanGrab) return;
|
||||
click.Clear();
|
||||
var p = _pickups[i1];
|
||||
var travelTime = lerp(PickupTravelTimeMin, PickupTravelTimeMax, l);
|
||||
TestField.GrabObject(p.transform, Vector3.forward * (PickupTravelDistance / travelTime));
|
||||
p.transform = null;
|
||||
_pickups[i1] = p;
|
||||
};
|
||||
|
||||
pickup.ScanLabelContainer.gameObject.SetActive(false);
|
||||
pickup.enabled = false;
|
||||
var pickupTransform = pickup.transform;
|
||||
var time = Random.value;
|
||||
var circle = Random.insideUnitCircle.normalized * Random.Range(PickupSpawnDistanceMin,PickupSpawnDistanceMax);
|
||||
pickupTransform.position = new Vector3(circle.x,circle.y, (time-.5f)*PickupTravelDistance);
|
||||
_pickups.Add((l, time, pickupTransform));
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
var move = _forceThrust ? float2(0,1) : (float2)_input.Player.Move.ReadValue<Vector2>();
|
||||
var turn = _input.Player.Turn.ReadValue<float>();
|
||||
if (_directionalPush)
|
||||
{
|
||||
TestField.Push = AetheriaMath.Damp(TestField.Push, move, _throttleDecay, Time.deltaTime);
|
||||
TestField.FrontTwist = AetheriaMath.Damp(TestField.FrontTwist,
|
||||
turn,
|
||||
_throttleDecay, Time.deltaTime);
|
||||
TestField.RearTwist = AetheriaMath.Damp(TestField.RearTwist,
|
||||
turn,
|
||||
_throttleDecay, Time.deltaTime);
|
||||
}
|
||||
else
|
||||
{
|
||||
TestField.Push = AetheriaMath.Damp(TestField.Push, float2(0,move.y), _throttleDecay, Time.deltaTime);
|
||||
TestField.FrontTwist = AetheriaMath.Damp(TestField.FrontTwist,
|
||||
clamp(turn + move.x, -1, 1) * (1+min(move.y,0)),
|
||||
_throttleDecay, Time.deltaTime);
|
||||
TestField.RearTwist = AetheriaMath.Damp(TestField.RearTwist,
|
||||
clamp(turn - move.x, -1, 1) * (1+min(-move.y,0)),
|
||||
_throttleDecay, Time.deltaTime);
|
||||
}
|
||||
|
||||
for (var i = 0; i < _pickups.Count; i++)
|
||||
{
|
||||
var (l, time, t) = _pickups[i];
|
||||
if (t == null) continue;
|
||||
time = frac(time + Time.deltaTime / lerp(PickupTravelTimeMin, PickupTravelTimeMax, l));
|
||||
t.localScale = Vector3.one * lerp(PickupSizeMin, PickupSizeMax, l) * Zone.PowerPulse(time - .5f, ScaleExponent);
|
||||
t.position = new Vector3(t.position.x, t.position.y, (time - .5f) * PickupTravelDistance);
|
||||
_pickups[i] = (l, time, t);
|
||||
}
|
||||
}
|
||||
}
|
||||
3
Assets/Scripts/UI/FieldTester.cs.meta
Normal file
3
Assets/Scripts/UI/FieldTester.cs.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 686a80c9880b431b94a9b0029d39cf1f
|
||||
timeCreated: 1659655755
|
||||
|
|
@ -1,10 +1,7 @@
|
|||
using System;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Mesh;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
|
@ -14,16 +11,6 @@ using static Unity.Mathematics.math;
|
|||
|
||||
public class SchematicDisplay : MonoBehaviour
|
||||
{
|
||||
private static readonly HashSet<string> WeaponBehaviorKinds = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
"GuidedWeapon",
|
||||
"Launcher",
|
||||
"InstantWeapon",
|
||||
"ConstantWeapon",
|
||||
"ChargedWeapon",
|
||||
"AutoWeapon"
|
||||
};
|
||||
|
||||
public GameSettings Settings;
|
||||
public Prototype ListElementPrototype;
|
||||
|
||||
|
|
@ -69,8 +56,6 @@ public class SchematicDisplay : MonoBehaviour
|
|||
private EquippedCargoBay[] _cargoBays;
|
||||
private SchematicDisplayItem[] _schematicItems;
|
||||
private AetherDrive _aetherDrive;
|
||||
private AetheriaRuntimeDaemonRenderSettings? _renderSettings;
|
||||
private AetheriaClientState _runtimeState;
|
||||
|
||||
private bool _enemy;
|
||||
private Entity _player;
|
||||
|
|
@ -89,20 +74,6 @@ public class SchematicDisplay : MonoBehaviour
|
|||
public Weapon Weapon;
|
||||
}
|
||||
|
||||
public void SetRenderSettings(AetheriaRuntimeDaemonRenderSettings renderSettings)
|
||||
{
|
||||
_renderSettings = renderSettings;
|
||||
}
|
||||
|
||||
private AetheriaClientState RuntimeState
|
||||
{
|
||||
get
|
||||
{
|
||||
_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-schematic-display");
|
||||
return _runtimeState;
|
||||
}
|
||||
}
|
||||
|
||||
public void ShowShip(Entity entity, Entity player = null)
|
||||
{
|
||||
_enemy = player != null;
|
||||
|
|
@ -136,7 +107,7 @@ public class SchematicDisplay : MonoBehaviour
|
|||
}
|
||||
|
||||
_schematicItems = entity.Equipment
|
||||
.Where(HasTypedWeaponBehavior)
|
||||
.Where(x => x.Behaviors.Any(b => b.Data is WeaponData))
|
||||
.Select(x => new SchematicDisplayItem
|
||||
{
|
||||
Item = x,
|
||||
|
|
@ -148,100 +119,81 @@ public class SchematicDisplay : MonoBehaviour
|
|||
.ToArray();
|
||||
foreach (var x in _schematicItems)
|
||||
{
|
||||
var typedWeapon = FindTypedWeapon(x.Item.EquippableItem);
|
||||
if (typedWeapon != null)
|
||||
x.ListElement.ShowWeapon(typedWeapon);
|
||||
if(x.Item.Data is WeaponItemData weaponItemData)
|
||||
x.ListElement.ShowWeapon(weaponItemData);
|
||||
//x.ListElement.Label.text = x.Item.EquippableItem.Name;
|
||||
if (!_enemy)
|
||||
{
|
||||
x.ListElement.InfiniteAmmoIcon.gameObject.SetActive(!x.Weapon.UsesAmmo);
|
||||
x.ListElement.AmmoLabel.gameObject.SetActive(x.Weapon.UsesAmmo);
|
||||
x.ListElement.InfiniteAmmoIcon.gameObject.SetActive(x.Weapon.WeaponData.AmmoType == Guid.Empty);
|
||||
x.ListElement.AmmoLabel.gameObject.SetActive(x.Weapon.WeaponData.AmmoType != Guid.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCatalogItem FindTypedWeapon(ItemInstance item)
|
||||
{
|
||||
var typedItem = FindTypedItem(item);
|
||||
return typedItem != null && !string.IsNullOrWhiteSpace(typedItem.WeaponType)
|
||||
? typedItem
|
||||
: null;
|
||||
}
|
||||
|
||||
|
||||
private bool HasTypedWeaponBehavior(EquippedItem item)
|
||||
{
|
||||
var typedItem = FindTypedItem(item.EquippableItem);
|
||||
return typedItem?.BehaviorKinds.Any(WeaponBehaviorKinds.Contains) == true;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (_entity != null)
|
||||
{
|
||||
if (!_enemy)
|
||||
{
|
||||
var hud = CurrentEntityHudStatus();
|
||||
OverrideIcon.SetActive(hud.OverrideShutdown && cos(Time.time * OverrideIconBlinkSpeed) > 0);
|
||||
ShieldIcon.SetActive(hud.ShieldActive);
|
||||
if (hud.RadiatorCount == 1)
|
||||
RadiatorTemperatureLabel.text = FormatTemperature((float)hud.RadiatorTemperatureMinimum);
|
||||
else if (hud.RadiatorCount > 1)
|
||||
OverrideIcon.SetActive(_entity.OverrideShutdown && cos(Time.time * OverrideIconBlinkSpeed) > 0);
|
||||
ShieldIcon.SetActive(_entity.Shield!=null && _entity.Shield.Item.Active.Value);
|
||||
if (_radiators.Length == 1)
|
||||
RadiatorTemperatureLabel.text = $"{((int)(_radiators[0].RadiatorTemperature - 273.15f)).ToString()}°C";
|
||||
else if (_radiators.Length > 1)
|
||||
RadiatorTemperatureLabel.text =
|
||||
$"{FormatTemperature((float)hud.RadiatorTemperatureMinimum)}-" +
|
||||
$"{FormatTemperature((float)hud.RadiatorTemperatureMaximum)}";
|
||||
HeatsinkBackground.color = hud.HeatsinksEnabled ? HeaderElementEnabledColor : HeaderElementDisabledColor;
|
||||
$"{((int)(_radiators.Min(r => r.RadiatorTemperature) - 273.15f)).ToString()}-" +
|
||||
$"{((int)(_radiators.Max(r => r.RadiatorTemperature) - 273.15f)).ToString()}°C";
|
||||
HeatsinkBackground.color = _entity.HeatsinksEnabled ? HeaderElementEnabledColor : HeaderElementDisabledColor;
|
||||
|
||||
if (_heatStorages.Length == 1)
|
||||
HeatStorageTemperatureLabel.text = FormatTemperature(_heatStorages[0].Item.Temperature);
|
||||
HeatStorageTemperatureLabel.text = $"{((int)(_heatStorages[0].Item.Temperature - 273.15f)).ToString()}°C";
|
||||
else if (_heatStorages.Length > 1)
|
||||
HeatStorageTemperatureLabel.text =
|
||||
$"{FormatTemperature(_heatStorages.Min(r => r.Item.Temperature))}-" +
|
||||
$"{FormatTemperature(_heatStorages.Max(r => r.Item.Temperature))}";
|
||||
$"{((int)(_heatStorages.Min(r => r.Item.Temperature) - 273.15f)).ToString()}-" +
|
||||
$"{((int)(_heatStorages.Max(r => r.Item.Temperature) - 273.15f)).ToString()}°C";
|
||||
|
||||
if (_cargoBays.Length == 1)
|
||||
CargoTemperatureLabel.text = FormatTemperature(_cargoBays[0].Temperature);
|
||||
CargoTemperatureLabel.text = $"{((int)(_cargoBays[0].Temperature - 273.15f)).ToString()}°C";
|
||||
else if (_cargoBays.Length > 1)
|
||||
CargoTemperatureLabel.text =
|
||||
$"{FormatTemperature(_cargoBays.Min(r => r.Temperature))}-" +
|
||||
$"{FormatTemperature(_cargoBays.Max(r => r.Temperature))}";
|
||||
$"{((int)(_cargoBays.Min(r => r.Temperature) - 273.15f)).ToString()}-" +
|
||||
$"{((int)(_cargoBays.Max(r => r.Temperature) - 273.15f)).ToString()}°C";
|
||||
|
||||
if(_cockpit != null)
|
||||
{
|
||||
CockpitTemperatureLabel.text = FormatTemperature(_cockpit.Item.Temperature);
|
||||
CockpitTemperatureLabel.text = $"{((int) (_cockpit.Item.Temperature - 273.15f)).ToString()}°C";
|
||||
|
||||
HeatstrokeMeterFill.anchorMax = new Vector2((float)hud.Heatstroke, 1);
|
||||
HypothermiaMeterFill.anchorMax = new Vector2((float)hud.Hypothermia, 1);
|
||||
HeatstrokeLimitFill.anchorMax = new Vector2(
|
||||
(float)(_renderSettings?.NormalizeThermalRisk(_cockpit.Item.Temperature) ?? 0.0),
|
||||
1);
|
||||
HeatstrokeMeterFill.anchorMax = new Vector2(_entity.Heatstroke, 1);
|
||||
HypothermiaMeterFill.anchorMax = new Vector2(_entity.Hypothermia, 1);
|
||||
HeatstrokeLimitFill.anchorMax = new Vector2(unlerp(Settings.GameplaySettings.HypothermiaTemperature, Settings.GameplaySettings.HeatstrokeTemperature, _cockpit.Item.Temperature), 1);
|
||||
}
|
||||
|
||||
SensorCooldownFill.anchorMax = new Vector2((float)hud.SensorCooldown, 1);
|
||||
SensorCooldownFill.anchorMax = new Vector2(_entity.Sensor?.Cooldown ?? 0, 1);
|
||||
|
||||
if (hud.CapacitorCapacity <= 0)
|
||||
if (_capacitors.Length == 0)
|
||||
{
|
||||
EnergyFill.anchorMax = Vector2.up;
|
||||
EnergyLabel.text = FormatValue((float)hud.ReactorDraw);
|
||||
EnergyLabel.text = ActionGameManager.PlayerSettings.Format(_reactor.Draw);
|
||||
}
|
||||
else
|
||||
{
|
||||
var charge = hud.CapacitorCharge;
|
||||
var maxCharge = hud.CapacitorCapacity;
|
||||
EnergyFill.anchorMax = new Vector2((float)(charge / maxCharge), 1);
|
||||
EnergyLabel.text = $"{((int)charge).ToString()}/{((int)maxCharge).ToString()} + ({((int)hud.ReactorDraw).ToString()})";
|
||||
var charge = _capacitors.Sum(x => x.Charge);
|
||||
var maxCharge = _capacitors.Sum(x => x.Capacity);
|
||||
EnergyFill.anchorMax = new Vector2(charge / maxCharge, 1);
|
||||
EnergyLabel.text = $"{((int)charge).ToString()}/{((int)maxCharge).ToString()} + ({((int)_reactor.Draw).ToString()})";
|
||||
}
|
||||
|
||||
if (hud.AetherDriveMaximumRpm > 0)
|
||||
if (_aetherDrive != null)
|
||||
{
|
||||
ForwardRPMLabel.text = FormatValue((float)hud.AetherDriveRpmX);
|
||||
ForwardRPMFill.anchorMax = new Vector2((float)(hud.AetherDriveRpmX / hud.AetherDriveMaximumRpm), 1);
|
||||
ForwardRPMLabel.text = ActionGameManager.PlayerSettings.Format(_aetherDrive.Rpm.x);
|
||||
ForwardRPMFill.anchorMax = new Vector2(_aetherDrive.Rpm.x / _aetherDrive.MaximumRpm, 1);
|
||||
|
||||
StrafeRPMLabel.text = FormatValue((float)hud.AetherDriveRpmY);
|
||||
StrafeRPMFill.anchorMax = new Vector2((float)(hud.AetherDriveRpmY / hud.AetherDriveMaximumRpm), 1);
|
||||
StrafeRPMLabel.text = ActionGameManager.PlayerSettings.Format(_aetherDrive.Rpm.y);
|
||||
StrafeRPMFill.anchorMax = new Vector2(_aetherDrive.Rpm.y / _aetherDrive.MaximumRpm, 1);
|
||||
|
||||
TurnRPMLabel.text = FormatValue((float)hud.AetherDriveRpmZ);
|
||||
TurnRPMFill.anchorMax = new Vector2((float)(hud.AetherDriveRpmZ / hud.AetherDriveMaximumRpm), 1);
|
||||
TurnRPMLabel.text = ActionGameManager.PlayerSettings.Format(_aetherDrive.Rpm.z);
|
||||
TurnRPMFill.anchorMax = new Vector2(_aetherDrive.Rpm.z / _aetherDrive.MaximumRpm, 1);
|
||||
}
|
||||
}
|
||||
// else
|
||||
|
|
@ -249,52 +201,37 @@ public class SchematicDisplay : MonoBehaviour
|
|||
// DistanceLabel.text = $"{(int)length(_entity.Position - _player.Position)}";
|
||||
// }
|
||||
|
||||
if (!_enemy)
|
||||
{
|
||||
var hud = CurrentEntityHudStatus();
|
||||
if(VisibilityLabel)
|
||||
VisibilityLabel.text = ((int)hud.Visibility).ToString();
|
||||
if(VisibilityLabel)
|
||||
VisibilityLabel.text = ((int)_entity.Visibility).ToString();
|
||||
|
||||
if(HullDurabilityFill)
|
||||
{
|
||||
var dur = (float)hud.HullDurabilityRatio;
|
||||
HullDurabilityFill.anchorMax = new Vector2(dur, 1);
|
||||
HullDurabilityLabel.text = $"{FormatValue(dur * 100)}%";
|
||||
}
|
||||
}
|
||||
else
|
||||
if(HullDurabilityFill)
|
||||
{
|
||||
if(VisibilityLabel)
|
||||
VisibilityLabel.text = ((int)_entity.Visibility).ToString();
|
||||
|
||||
if(HullDurabilityFill)
|
||||
{
|
||||
_hull = _entity.Hull;
|
||||
var dur = _hull.Durability / GetMaxDurability(_hull);
|
||||
HullDurabilityFill.anchorMax = new Vector2(dur, 1);
|
||||
HullDurabilityLabel.text = $"{FormatValue(dur * 100)}%";
|
||||
}
|
||||
_hull = _entity.Hull;
|
||||
var hullData = _entity.ItemManager.GetData(_hull);
|
||||
var dur = _hull.Durability / hullData.Durability;
|
||||
HullDurabilityFill.anchorMax = new Vector2(dur, 1);
|
||||
HullDurabilityLabel.text = $"{ActionGameManager.PlayerSettings.Format(dur * 100)}%";
|
||||
}
|
||||
|
||||
foreach (var x in _schematicItems)
|
||||
{
|
||||
if (!_enemy)
|
||||
{
|
||||
var thermalRange = GetThermalRange(x.Item.EquippableItem, x.Item.Temperature);
|
||||
x.ListElement.HeatFill.anchorMax = new Vector2(unlerp(thermalRange.minimum, thermalRange.maximum, x.Item.Temperature), 0);
|
||||
var itemData = _entity.ItemManager.GetData(x.Item.EquippableItem);
|
||||
x.ListElement.HeatFill.anchorMax = new Vector2(unlerp(itemData.MinimumTemperature, itemData.MaximumTemperature, x.Item.Temperature), 0);
|
||||
if (x.Cooldown != null)
|
||||
x.ListElement.CooldownFill.anchorMax = new Vector2(x.Cooldown.Progress, 1);
|
||||
x.ListElement.DurabilityLabel.text = $"{(int)(x.Item.EquippableItem.Durability / GetMaxDurability(x.Item.EquippableItem) * 100)}%";
|
||||
if (x.Weapon.UsesAmmo)
|
||||
x.ListElement.DurabilityLabel.text = $"{(int)(x.Item.EquippableItem.Durability / itemData.Durability * 100)}%";
|
||||
if (x.Weapon.WeaponData.AmmoType != Guid.Empty)
|
||||
{
|
||||
if(x.Weapon.MagazineSize > 1)
|
||||
if(x.Weapon.WeaponData.MagazineSize > 1)
|
||||
x.ListElement.AmmoLabel.text = x.Weapon.Ammo.ToString();
|
||||
else
|
||||
x.ListElement.AmmoLabel.text = _entity.CountItemsInCargo(x.Weapon.AmmoItemKey).ToString();
|
||||
x.ListElement.AmmoLabel.text = _entity.CountItemsInCargo(x.Weapon.WeaponData.AmmoType).ToString();
|
||||
}
|
||||
}
|
||||
|
||||
if (x.Weapon != null)
|
||||
if (x.Weapon.WeaponData != null)
|
||||
{
|
||||
if(x.ListElement.RangeLabel)
|
||||
x.ListElement.RangeLabel.text = ((int) x.Weapon.Range).ToString();
|
||||
|
|
@ -302,97 +239,4 @@ public class SchematicDisplay : MonoBehaviour
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
private (float minimum, float maximum) GetThermalRange(ItemInstance item, float currentTemperature)
|
||||
{
|
||||
var typedItem = FindTypedItem(item);
|
||||
if (typedItem != null && typedItem.MaximumTemperature > typedItem.MinimumTemperature)
|
||||
return ((float)typedItem.MinimumTemperature, (float)typedItem.MaximumTemperature);
|
||||
|
||||
return (currentTemperature, currentTemperature + 1f);
|
||||
}
|
||||
private float GetMaxDurability(ItemInstance item)
|
||||
{
|
||||
var typedItem = FindTypedItem(item);
|
||||
if (typedItem != null && typedItem.Durability > 0)
|
||||
return (float)typedItem.Durability;
|
||||
|
||||
return item is EquippableItem equippable ? Math.Max(equippable.Durability, 1f) : 1f;
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCatalogItem FindTypedItem(ItemInstance item)
|
||||
{
|
||||
return CatalogSnapshot()?.FindItem(item, x => x.ItemKey);
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCatalogSnapshot CatalogSnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.Catalog.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria runtime catalog for schematic display: {ex.Message}");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private AetheriaRuntimePlayerSettingsDocument PlayerSettingsSnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.PlayerSettings.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria player settings for schematic display: {ex.Message}");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCurrentEntityHudStatus CurrentEntityHudStatus()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.CurrentEntity.Latest()?.Hud ?? new AetheriaRuntimeCurrentEntityHudStatus();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria current entity for schematic display: {ex.Message}");
|
||||
}
|
||||
|
||||
return new AetheriaRuntimeCurrentEntityHudStatus();
|
||||
}
|
||||
|
||||
private string FormatValue(float value)
|
||||
{
|
||||
var settings = PlayerSettingsSnapshot();
|
||||
var significantDigits = settings?.SignificantDigits ?? 3;
|
||||
var magnitude = value == 0.0f ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(value))) + 1;
|
||||
var digits = significantDigits - magnitude;
|
||||
if (digits < 0)
|
||||
digits = 0;
|
||||
|
||||
var formatted = value.ToString($"N{digits}", CultureInfo.CurrentCulture);
|
||||
var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
|
||||
var decimalSeparator = Convert.ToChar(separator);
|
||||
return formatted.Contains(separator)
|
||||
? formatted.TrimEnd('0').TrimEnd(decimalSeparator)
|
||||
: formatted;
|
||||
}
|
||||
|
||||
private string FormatTemperature(float value)
|
||||
{
|
||||
var unit = PlayerSettingsSnapshot()?.TemperatureUnit ?? nameof(TemperatureUnit.Celsius);
|
||||
if (string.Equals(unit, nameof(TemperatureUnit.Kelvin), StringComparison.OrdinalIgnoreCase))
|
||||
return $"{FormatValue(value)} K";
|
||||
if (string.Equals(unit, nameof(TemperatureUnit.Fahrenheit), StringComparison.OrdinalIgnoreCase))
|
||||
return $"{FormatValue(value * (9f / 5) - 459.67f)} F";
|
||||
|
||||
return $"{FormatValue(value - 273.15f)} C";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
|
@ -18,74 +17,35 @@ public class SchematicListElement : MonoBehaviour
|
|||
|
||||
private List<Prototype> _iconInstances = new List<Prototype>();
|
||||
|
||||
public void ShowWeapon(AetheriaRuntimeCatalogItem weapon)
|
||||
public void ShowWeapon(WeaponItemData weapon)
|
||||
{
|
||||
if (TryParseWeaponFacets(
|
||||
weapon,
|
||||
out var caliber,
|
||||
out var range,
|
||||
out var type,
|
||||
out var fireTypes,
|
||||
out var modifiers))
|
||||
ShowWeapon(caliber, range, type, fireTypes, modifiers);
|
||||
}
|
||||
|
||||
private void ShowWeapon(
|
||||
WeaponCaliber caliber,
|
||||
WeaponRange range,
|
||||
WeaponType type,
|
||||
WeaponFireType fireTypes,
|
||||
WeaponModifiers modifiers)
|
||||
{
|
||||
foreach (var prototype in _iconInstances) prototype.ReturnToPool();
|
||||
foreach(var prototype in _iconInstances) prototype.ReturnToPool();
|
||||
_iconInstances.Clear();
|
||||
|
||||
var caliberIcon = IconPrototype.Instantiate<Image>();
|
||||
_iconInstances.Add(caliberIcon.GetComponent<Prototype>());
|
||||
caliberIcon.sprite = Settings.GetIcon(caliber);
|
||||
caliberIcon.sprite = Settings.GetIcon(weapon.WeaponCaliber);
|
||||
|
||||
var rangeIcon = IconPrototype.Instantiate<Image>();
|
||||
_iconInstances.Add(rangeIcon.GetComponent<Prototype>());
|
||||
rangeIcon.sprite = Settings.GetIcon(range);
|
||||
rangeIcon.sprite = Settings.GetIcon(weapon.WeaponRange);
|
||||
|
||||
var typeIcon = IconPrototype.Instantiate<Image>();
|
||||
_iconInstances.Add(typeIcon.GetComponent<Prototype>());
|
||||
typeIcon.sprite = Settings.GetIcon(type);
|
||||
typeIcon.sprite = Settings.GetIcon(weapon.WeaponType);
|
||||
|
||||
foreach (var sprite in Settings.GetIcons(fireTypes))
|
||||
foreach (var sprite in Settings.GetIcons(weapon.WeaponFireTypes))
|
||||
{
|
||||
var fireTypeIcon = IconPrototype.Instantiate<Image>();
|
||||
_iconInstances.Add(fireTypeIcon.GetComponent<Prototype>());
|
||||
fireTypeIcon.sprite = sprite;
|
||||
}
|
||||
|
||||
foreach (var sprite in Settings.GetIcons(modifiers))
|
||||
foreach (var sprite in Settings.GetIcons(weapon.WeaponModifiers))
|
||||
{
|
||||
var modifierIcon = IconPrototype.Instantiate<Image>();
|
||||
_iconInstances.Add(modifierIcon.GetComponent<Prototype>());
|
||||
modifierIcon.sprite = sprite;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryParseWeaponFacets(
|
||||
AetheriaRuntimeCatalogItem weapon,
|
||||
out WeaponCaliber caliber,
|
||||
out WeaponRange range,
|
||||
out WeaponType type,
|
||||
out WeaponFireType fireTypes,
|
||||
out WeaponModifiers modifiers)
|
||||
{
|
||||
caliber = default;
|
||||
range = default;
|
||||
type = default;
|
||||
fireTypes = default;
|
||||
modifiers = default;
|
||||
|
||||
return
|
||||
Enum.TryParse(weapon.WeaponCaliber, out caliber) &&
|
||||
Enum.TryParse(weapon.WeaponRange, out range) &&
|
||||
Enum.TryParse(weapon.WeaponType, out type) &&
|
||||
Enum.TryParse(weapon.WeaponFireTypes, out fireTypes) &&
|
||||
Enum.TryParse(weapon.WeaponModifiers, out modifiers);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,85 +1,18 @@
|
|||
using System.Collections.Generic;
|
||||
using JsonKnownTypes;using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class InputLayout
|
||||
{
|
||||
public InputLayoutRow[] Rows;
|
||||
|
||||
public static InputLayout CreateAnsi104()
|
||||
{
|
||||
return new InputLayout
|
||||
{
|
||||
Rows = new InputLayoutRow[]
|
||||
{
|
||||
Row(
|
||||
Key("Esc"), Spacer(1), Key("F1"), Key("F2"), Key("F3"), Key("F4"), Spacer(.5f),
|
||||
Key("F5"), Key("F6"), Key("F7"), Key("F8"), Spacer(.5f),
|
||||
Key("F9"), Key("F10"), Key("F11"), Key("F12"), Spacer(.25f),
|
||||
Key(""), Key(""), Key("")),
|
||||
RowSpacer(.5f),
|
||||
Row(
|
||||
Key("~\n`"), Key("!\n1"), Key("@\n2"), Key("#\n3"), Key("$\n4"), Key("%\n5"), Key("^\n6"),
|
||||
Key("&\n7"), Key("*\n8"), Key("(\n9"), Key(")\n0"), Key("_\n-"), Key("+\n="), Key("Backspace", 2),
|
||||
Spacer(.25f), Key("Insert"), Key("Home"), Key("PgUp"), Spacer(.25f), Key(""), Key("/"), Key("*"), Key("-")),
|
||||
Row(
|
||||
Key("Tab", 1.5f), Key("Q"), Key("W"), Key("E"), Key("R"), Key("T"), Key("Y"), Key("U"), Key("I"), Key("O"), Key("P"),
|
||||
Key("{\n["), Key("}\n]"), Key("|\n\\", 1.5f), Spacer(.25f),
|
||||
Key("Delete"), Key("End"), Key("PgDn"), Spacer(.25f), Key("Home\n7"), Key("Up\n8"), Key("PgUp\n9"), Key("+", 1, 2)),
|
||||
Row(
|
||||
Key("Caps Lock", 1.75f), Key("A"), Key("S"), Key("D"), Key("F"), Key("G"), Key("H"), Key("J"), Key("K"), Key("L"),
|
||||
Key(":\n;"), Key("\"\n'"), Key("Enter", 2.25f), Spacer(3.5f), Key("Left\n4"), Key("5"), Key("Right\n6")),
|
||||
Row(
|
||||
Key("Shift", 2.25f), Key("Z"), Key("X"), Key("C"), Key("V"), Key("B"), Key("N"), Key("M"),
|
||||
Key("<\n,"), Key(">\n."), Key("?\n/"), Key("Shift", 2.75f), Spacer(1.25f), Key("Up"), Spacer(1.25f),
|
||||
Key("End\n1"), Key("Down\n2"), Key("PgDn\n3"), Key("Enter", 1, 2)),
|
||||
Row(
|
||||
Key("Ctrl", 1.25f), Key("", 1.25f), Key("Alt", 1.25f), Key("Spacebar", 6.25f), Key("Alt", 1.25f),
|
||||
Key("", 1.25f), Key("", 1.25f), Key("Ctrl", 1.25f), Spacer(.25f),
|
||||
Key("Left"), Key("Down"), Key("Right"), Spacer(.25f), Key("Ins\n0", 2), Key("Del\n."))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static InputLayoutRowSpacer RowSpacer(float height)
|
||||
{
|
||||
return new InputLayoutRowSpacer {Height = height};
|
||||
}
|
||||
|
||||
private static InputLayoutKeyRow Row(params InputLayoutColumn[] columns)
|
||||
{
|
||||
return new InputLayoutKeyRow {Columns = columns};
|
||||
}
|
||||
|
||||
private static InputLayoutColumnSpacer Spacer(float width)
|
||||
{
|
||||
return new InputLayoutColumnSpacer {Width = width};
|
||||
}
|
||||
|
||||
private static InputLayoutKey Key(string label, float width = 1f, int height = 1)
|
||||
{
|
||||
InputLayoutKey key;
|
||||
var trimmedLabel = label.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmedLabel))
|
||||
{
|
||||
var labels = trimmedLabel.Split('\n');
|
||||
key = height != 1 ? new InputLayoutMultiRowKey {Height = height} : new InputLayoutBindableKey();
|
||||
((InputLayoutBindableKey) key).MainLabel = labels.Length == 2 ? labels[1] : trimmedLabel;
|
||||
((InputLayoutBindableKey) key).AltLabel = labels.Length == 2 ? labels[0] : "";
|
||||
}
|
||||
else
|
||||
{
|
||||
key = new InputLayoutKey();
|
||||
}
|
||||
|
||||
key.Width = width;
|
||||
return key;
|
||||
}
|
||||
[Key(0), JsonProperty("rows")] public InputLayoutRow[] Rows;
|
||||
|
||||
public IEnumerable<InputLayoutBindableKey> GetBindableKeys()
|
||||
{
|
||||
foreach (var row in Rows)
|
||||
{
|
||||
if (!(row is InputLayoutKeyRow keyRow)) continue;
|
||||
|
||||
|
||||
foreach (var column in keyRow.Columns)
|
||||
{
|
||||
if (column is InputLayoutBindableKey bindableKey)
|
||||
|
|
@ -91,33 +24,51 @@ public class InputLayout
|
|||
}
|
||||
}
|
||||
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<InputLayoutRow>)),
|
||||
MessagePackObject,
|
||||
Union(0, typeof(InputLayoutRowSpacer)),
|
||||
Union(1, typeof(InputLayoutKeyRow))
|
||||
]
|
||||
public abstract class InputLayoutRow { }
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class InputLayoutRowSpacer : InputLayoutRow
|
||||
{
|
||||
public float Height;
|
||||
[Key(0), JsonProperty("height")] public float Height;
|
||||
}
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class InputLayoutKeyRow : InputLayoutRow
|
||||
{
|
||||
public InputLayoutColumn[] Columns;
|
||||
[Key(0), JsonProperty("columns")] public InputLayoutColumn[] Columns;
|
||||
}
|
||||
|
||||
[JsonConverter(typeof(JsonKnownTypesConverter<InputLayoutColumn>)),
|
||||
MessagePackObject,
|
||||
Union(0, typeof(InputLayoutColumnSpacer)),
|
||||
Union(1, typeof(InputLayoutKey)),
|
||||
Union(2, typeof(InputLayoutBindableKey)),
|
||||
Union(3, typeof(InputLayoutMultiRowKey))
|
||||
]
|
||||
public abstract class InputLayoutColumn
|
||||
{
|
||||
public float Width;
|
||||
[Key(0), JsonProperty("width")] public float Width;
|
||||
}
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class InputLayoutColumnSpacer : InputLayoutColumn { }
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class InputLayoutKey : InputLayoutColumn { }
|
||||
|
||||
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public class InputLayoutBindableKey : InputLayoutKey, IBindableButton
|
||||
{
|
||||
public string MainLabel;
|
||||
public string AltLabel;
|
||||
public string ShortPath;
|
||||
[Key(1), JsonProperty("mainLabel")] public string MainLabel;
|
||||
[Key(2), JsonProperty("altLabel")] public string AltLabel;
|
||||
[Key(3), JsonProperty("path")] public string ShortPath;
|
||||
|
||||
[IgnoreMember]
|
||||
public string InputSystemPath
|
||||
{
|
||||
get
|
||||
|
|
@ -133,7 +84,7 @@ public class InputLayoutBindableKey : InputLayoutKey, IBindableButton
|
|||
|
||||
public class InputLayoutMultiRowKey : InputLayoutBindableKey
|
||||
{
|
||||
public int Height;
|
||||
[Key(4), JsonProperty("height")] public int Height;
|
||||
}
|
||||
|
||||
public class InputLayoutMouseButton : IBindableButton
|
||||
|
|
@ -149,4 +100,4 @@ public class InputLayoutMouseButton : IBindableButton
|
|||
public interface IBindableButton
|
||||
{
|
||||
public string InputSystemPath { get; set; }
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,64 +1,38 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.EveRuntime;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Eve.Surface;
|
||||
using GameCult.Mesh;
|
||||
using UnityEngine;
|
||||
using UniRx;
|
||||
using UniRx.Triggers;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine.UIElements;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class InventoryMenu : MonoBehaviour
|
||||
{
|
||||
public InventoryPanel[] InventoryPanels;
|
||||
public PropertiesPanel PropertiesPanel;
|
||||
public ActionGameManager GameManager;
|
||||
public RectTransform DragParent;
|
||||
public ConfirmationDialog Dialog;
|
||||
// public ClickCatcher Background;
|
||||
|
||||
private EquippedItem _selectedEquippedItem;
|
||||
private AetheriaRuntimeCurrentEntityDocument _shipSettingsCurrentEntity;
|
||||
private UIDocument _shipSettingsSurfaceDocument;
|
||||
private UIDocument _cargoItemDetailsSurfaceDocument;
|
||||
private UIDocument _equippedItemDetailsSurfaceDocument;
|
||||
private AetheriaUnityActionBarPresentation _actionBarPresentation;
|
||||
private AetheriaUnityPresentationEntityIndex _presentationEntityIndex;
|
||||
private AetheriaClientState _runtimeState;
|
||||
private readonly AetheriaEveUnitySurfaceChrome _shipSettingsSurfaceChrome = PanelChrome(360f, 420f);
|
||||
private readonly AetheriaEveUnitySurfaceChrome _cargoItemDetailsSurfaceChrome = PanelChrome(420f, 520f);
|
||||
private readonly AetheriaEveUnitySurfaceChrome _equippedItemDetailsSurfaceChrome = PanelChrome(460f, 560f);
|
||||
private int _currentPanel = -1;
|
||||
|
||||
private int2 _selectedPosition;
|
||||
private InventoryPanel _selectedPanel;
|
||||
private ItemInstance _selectedItem;
|
||||
private ItemData _selectedItemData;
|
||||
// private List<IDisposable> _backgroundSubscriptions;
|
||||
|
||||
// private ItemInstance _dragItem;
|
||||
// private Transform[] _dragCells;
|
||||
// private Vector2[] _dragOffsets;
|
||||
|
||||
public void SetDragSession(AetheriaUnityDragSession dragSession)
|
||||
{
|
||||
if (InventoryPanels == null)
|
||||
return;
|
||||
|
||||
foreach (var panel in InventoryPanels)
|
||||
panel?.SetDragSession(dragSession);
|
||||
}
|
||||
|
||||
public void SetActionBarPresentation(AetheriaUnityActionBarPresentation actionBarPresentation)
|
||||
{
|
||||
_actionBarPresentation = actionBarPresentation;
|
||||
}
|
||||
|
||||
public void SetPresentationEntityIndex(AetheriaUnityPresentationEntityIndex presentationEntityIndex)
|
||||
{
|
||||
_presentationEntityIndex = presentationEntityIndex;
|
||||
}
|
||||
|
||||
private AetheriaClientState RuntimeState => _runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-inventory-menu");
|
||||
// private int2 _dragCellOffset;
|
||||
// private ItemRotation _originalRotation;
|
||||
// //private Shape _previousFakeOccupancy;
|
||||
|
|
@ -84,557 +58,145 @@ public class InventoryMenu : MonoBehaviour
|
|||
// {
|
||||
// _destroyItem = false;
|
||||
// });
|
||||
var hasCurrentEntity = TryResolveCurrentEntity(out var currentEntity);
|
||||
var cargo = TryResolveCurrentDockingBay(out var dockingBay)
|
||||
? dockingBay
|
||||
: currentEntity?.CargoBays.FirstOrDefault();
|
||||
var cargo = GameManager.DockingBay ?? GameManager.CurrentEntity.CargoBays.FirstOrDefault();
|
||||
if (cargo!=null)
|
||||
InventoryPanels[0].Display(cargo);
|
||||
else InventoryPanels[0].Clear();
|
||||
if(hasCurrentEntity)
|
||||
InventoryPanels[1].Display(currentEntity);
|
||||
if(GameManager.CurrentEntity != null)
|
||||
InventoryPanels[1].Display(GameManager.CurrentEntity);
|
||||
else InventoryPanels[1].Clear();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
HideCurrentShipSettingsSurface();
|
||||
HideCargoItemDetailsSurface();
|
||||
HideEquippedItemDetailsSurface();
|
||||
// Background.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
PropertiesPanel.GameManager = GameManager;
|
||||
foreach (var panel in InventoryPanels)
|
||||
{
|
||||
panel.OnClickAsObservable().Subscribe(e =>
|
||||
{
|
||||
if (e.data is InventoryCargoEventData cargoEvent)
|
||||
{
|
||||
var item = cargoEvent.CargoBay.Occupancy[cargoEvent.Position.x, cargoEvent.Position.y];
|
||||
if(item!=null)
|
||||
{
|
||||
if (e.clickCount == 2)
|
||||
{
|
||||
var otherPanel = panel == InventoryPanels[0] ? InventoryPanels[1] : InventoryPanels[0];
|
||||
if (otherPanel.CanDropItem(item))
|
||||
{
|
||||
otherPanel.DropItem(item);
|
||||
// TODO: SFX: Equip
|
||||
cargoEvent.CargoBay.Remove(item);
|
||||
panel.RefreshCells();
|
||||
otherPanel.RefreshCells();
|
||||
}
|
||||
// else
|
||||
// TODO: SFX: Fail
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_selectedPanel != null)
|
||||
{
|
||||
if (_selectedPanel.CellInstances.ContainsKey(_selectedPosition))
|
||||
{
|
||||
foreach (var v in _selectedItemData.Shape.Coordinates)
|
||||
{
|
||||
var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition;
|
||||
_selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2);
|
||||
}
|
||||
}
|
||||
}
|
||||
_selectedPanel = panel;
|
||||
_selectedPosition = cargoEvent.Position;
|
||||
PropertiesPanel.Inspect(item);
|
||||
_selectedPanel = panel;
|
||||
_selectedPosition = cargoEvent.CargoBay.Cargo[item];
|
||||
_selectedItem = item;
|
||||
_selectedItemData = item.Data.Value;
|
||||
foreach (var v in _selectedItemData.Shape.Coordinates)
|
||||
{
|
||||
var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition;
|
||||
_selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2, true);
|
||||
}
|
||||
// TODO: SFX: Success
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (e.data is InventoryEntityEventData entityEvent)
|
||||
{
|
||||
var item = entityEvent.Entity.GearOccupancy[entityEvent.Position.x, entityEvent.Position.y];
|
||||
if (item != null)
|
||||
{
|
||||
if (e.clickCount == 2)
|
||||
{
|
||||
var otherPanel = panel == InventoryPanels[0] ? InventoryPanels[1] : InventoryPanels[0];
|
||||
if (otherPanel.CanDropItem(item.EquippableItem))
|
||||
{
|
||||
if (!entityEvent.Entity.Active)
|
||||
{
|
||||
if (entityEvent.Entity.TryUnequip(item) != null)
|
||||
{
|
||||
otherPanel.DropItem(item.EquippableItem);
|
||||
// TODO: SFX: Unequip
|
||||
panel.RefreshCells();
|
||||
otherPanel.RefreshCells();
|
||||
}
|
||||
// else
|
||||
// TODO: SFX: Fail
|
||||
}
|
||||
// else
|
||||
// TODO: SFX: Fail
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_selectedPanel != null)
|
||||
{
|
||||
if (_selectedPanel.CellInstances.ContainsKey(_selectedPosition))
|
||||
{
|
||||
foreach (var v in _selectedItemData.Shape.Coordinates)
|
||||
{
|
||||
var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition;
|
||||
_selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PropertiesPanel.Inspect(item);
|
||||
_selectedPanel = panel;
|
||||
_selectedPosition = item.Position;
|
||||
_selectedItem = item.EquippableItem;
|
||||
_selectedItemData = GameManager.ItemManager.GetData(item.EquippableItem);
|
||||
foreach (var v in _selectedItemData.Shape.Coordinates)
|
||||
{
|
||||
var v2 = _selectedItemData.Shape.Rotate(v, _selectedItem.Rotation) + _selectedPosition;
|
||||
_selectedPanel.CellInstances[v2].Icon.color = _selectedPanel.GetColor(v2, true);
|
||||
}
|
||||
// TODO: SFX: Success
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
panel.OnBackgroundClick.Subscribe(data =>
|
||||
{
|
||||
if (!TryReadCurrentEntity(out var currentEntity)) return;
|
||||
|
||||
RenderCurrentShipSettingsSurface(currentEntity);
|
||||
if (GameManager.CurrentEntity == null) return; // Only show ship settings if there's a ship, duh!
|
||||
|
||||
PropertiesPanel.Clear();
|
||||
PropertiesPanel.AddField("Shutdown Threshold",
|
||||
() => GameManager.CurrentEntity.Settings.ShutdownPerformance,
|
||||
f => GameManager.CurrentEntity.Settings.ShutdownPerformance = f,
|
||||
0,
|
||||
1);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderCurrentShipSettingsSurface(AetheriaRuntimeCurrentEntityDocument currentEntity)
|
||||
{
|
||||
if (currentEntity == null || string.IsNullOrWhiteSpace(currentEntity.EntityKey))
|
||||
return;
|
||||
|
||||
HideCargoItemDetailsSurface();
|
||||
HideEquippedItemDetailsSurface();
|
||||
ClearSelectedItemSelection();
|
||||
_shipSettingsCurrentEntity = currentEntity;
|
||||
|
||||
_shipSettingsSurfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
|
||||
transform,
|
||||
_shipSettingsSurfaceDocument,
|
||||
"Aetheria Inventory Ship Settings Surface",
|
||||
AetheriaRuntimeShipSettingsSurfaceBuilder.Build(
|
||||
currentEntity?.Entity?.DisplayName ?? "",
|
||||
(float)(currentEntity?.ShutdownPerformance ?? 0),
|
||||
FormatValue),
|
||||
HandleCurrentShipSettingsSurfaceCommand,
|
||||
_shipSettingsSurfaceChrome);
|
||||
}
|
||||
|
||||
private void HandleCurrentShipSettingsSurfaceCommand(EveSurfaceCommandRequest request)
|
||||
{
|
||||
var currentEntity = _shipSettingsCurrentEntity;
|
||||
if (currentEntity == null ||
|
||||
string.IsNullOrWhiteSpace(currentEntity.EntityKey) ||
|
||||
!TryReadCurrentEntity(out var latestCurrentEntity) ||
|
||||
!string.Equals(latestCurrentEntity.EntityKey, currentEntity.EntityKey, StringComparison.Ordinal))
|
||||
{
|
||||
HideCurrentShipSettingsSurface();
|
||||
return;
|
||||
}
|
||||
|
||||
_shipSettingsCurrentEntity = latestCurrentEntity;
|
||||
|
||||
if (!AetheriaRuntimeShipSettingsSurfaceCommands.TryRead(request, out var command))
|
||||
{
|
||||
Debug.LogWarning($"Unknown inventory ship settings command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (command.Kind)
|
||||
{
|
||||
case AetheriaRuntimeShipSettingsCommandKind.DecrementShutdownThreshold:
|
||||
case AetheriaRuntimeShipSettingsCommandKind.IncrementShutdownThreshold:
|
||||
case AetheriaRuntimeShipSettingsCommandKind.ResetShutdownThreshold:
|
||||
RequestEntityShutdownPerformance(
|
||||
latestCurrentEntity.EntityKey,
|
||||
AetheriaRuntimeShipSettingsSurfaceCommands.ResolveShutdownPerformance(
|
||||
command.Kind,
|
||||
(float)latestCurrentEntity.ShutdownPerformance,
|
||||
ResolveDefaultShutdownPerformance()));
|
||||
return;
|
||||
case AetheriaRuntimeShipSettingsCommandKind.Close:
|
||||
HideCurrentShipSettingsSurface();
|
||||
return;
|
||||
default:
|
||||
Debug.LogWarning($"Unknown inventory ship settings command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void HideCurrentShipSettingsSurface()
|
||||
{
|
||||
_shipSettingsCurrentEntity = null;
|
||||
if (_shipSettingsSurfaceDocument == null)
|
||||
return;
|
||||
|
||||
AetheriaEveUnitySurfaceHost.Hide(_shipSettingsSurfaceDocument);
|
||||
}
|
||||
|
||||
private void RenderCargoItemDetailsSurface(ItemInstance item)
|
||||
{
|
||||
var typedItem = FindTypedInventoryItem(item);
|
||||
if (item == null || typedItem == null)
|
||||
return;
|
||||
|
||||
HideEquippedItemDetailsSurface();
|
||||
|
||||
_cargoItemDetailsSurfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
|
||||
transform,
|
||||
_cargoItemDetailsSurfaceDocument,
|
||||
"Aetheria Inventory Cargo Item Details Surface",
|
||||
AetheriaRuntimeCargoItemDetailsSurfaceBuilder.Build(
|
||||
typedItem,
|
||||
ComposeCargoItemObservation(item),
|
||||
ResolveManufacturerName(typedItem),
|
||||
item is EquippableItem equippableItem ? FormatItemTier(typedItem, equippableItem) : "",
|
||||
FormatValue,
|
||||
FormatTemperature),
|
||||
HandleCargoItemDetailsSurfaceCommand,
|
||||
_cargoItemDetailsSurfaceChrome,
|
||||
sortingOrder: 1001);
|
||||
}
|
||||
|
||||
private void HandleCargoItemDetailsSurfaceCommand(EveSurfaceCommandRequest request)
|
||||
{
|
||||
if (!AetheriaRuntimeCargoItemDetailsSurfaceCommands.TryRead(request, out var command))
|
||||
{
|
||||
Debug.LogWarning($"Unknown inventory cargo item details command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.Kind == AetheriaRuntimeCargoItemDetailsCommandKind.Close)
|
||||
{
|
||||
HideCargoItemDetailsSurface();
|
||||
ClearSelectedItemSelection();
|
||||
return;
|
||||
}
|
||||
|
||||
Debug.LogWarning($"Unknown inventory cargo item details command: {request?.Command}");
|
||||
}
|
||||
|
||||
private void HideCargoItemDetailsSurface()
|
||||
{
|
||||
if (_cargoItemDetailsSurfaceDocument == null)
|
||||
return;
|
||||
|
||||
AetheriaEveUnitySurfaceHost.Hide(_cargoItemDetailsSurfaceDocument);
|
||||
}
|
||||
|
||||
private void RenderEquippedItemDetailsSurface(EquippedItem item)
|
||||
{
|
||||
var typedItem = FindTypedInventoryItem(item?.EquippableItem);
|
||||
if (item?.EquippableItem == null || typedItem == null)
|
||||
return;
|
||||
|
||||
_equippedItemDetailsSurfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
|
||||
transform,
|
||||
_equippedItemDetailsSurfaceDocument,
|
||||
"Aetheria Inventory Equipped Item Details Surface",
|
||||
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.Build(
|
||||
typedItem,
|
||||
ComposeEquippedItemObservation(item),
|
||||
BuildEquippedItemTitle(item, typedItem),
|
||||
ResolveManufacturerName(typedItem),
|
||||
FormatValue,
|
||||
FormatTemperature,
|
||||
ComposeEquippedItemTemperatureControls(item).ToArray(),
|
||||
item.GetBehavior<Weapon>() != null
|
||||
? ComposeEquippedItemWeaponGroupControls(item).ToArray()
|
||||
: Array.Empty<AetheriaRuntimeEquippedItemControl>()),
|
||||
HandleEquippedItemDetailsSurfaceCommand,
|
||||
_equippedItemDetailsSurfaceChrome,
|
||||
sortingOrder: 1002);
|
||||
}
|
||||
|
||||
private void HandleEquippedItemDetailsSurfaceCommand(EveSurfaceCommandRequest request)
|
||||
{
|
||||
var item = _selectedEquippedItem;
|
||||
if (item?.EquippableItem == null)
|
||||
{
|
||||
HideEquippedItemDetailsSurface();
|
||||
ClearSelectedItemSelection();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!AetheriaRuntimeEquippedItemDetailsSurfaceCommands.TryRead(request, out var command))
|
||||
{
|
||||
Debug.LogWarning($"Unknown inventory equipped item details command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (command.Kind)
|
||||
{
|
||||
case AetheriaRuntimeEquippedItemDetailsCommandKind.Close:
|
||||
HideEquippedItemDetailsSurface();
|
||||
ClearSelectedItemSelection();
|
||||
return;
|
||||
case AetheriaRuntimeEquippedItemDetailsCommandKind.ToggleOverrideShutdown:
|
||||
RequestEquippedItemOverrideShutdown(item, !item.EquippableItem.OverrideShutdown);
|
||||
return;
|
||||
case AetheriaRuntimeEquippedItemDetailsCommandKind.SetTargetTemperature:
|
||||
if (command.BehaviorIndex >= 0 &&
|
||||
command.BehaviorIndex < (item.Behaviors?.Length ?? 0) &&
|
||||
item.Behaviors[command.BehaviorIndex] is Thermotoggle thermotoggle &&
|
||||
thermotoggle.Adjustable)
|
||||
{
|
||||
RequestThermotoggleTargetTemperature(item, command.BehaviorIndex, command.TargetTemperature);
|
||||
return;
|
||||
}
|
||||
|
||||
Debug.LogWarning("Unable to apply equipped-item target temperature command.");
|
||||
RenderEquippedItemDetailsSurface(item);
|
||||
return;
|
||||
case AetheriaRuntimeEquippedItemDetailsCommandKind.ToggleWeaponGroup:
|
||||
if (command.GroupIndex >= 0)
|
||||
{
|
||||
var assigned = !IsWeaponGroupAssigned(item, command.GroupIndex);
|
||||
RequestWeaponGroupMembership(item, command.GroupIndex, assigned);
|
||||
return;
|
||||
}
|
||||
|
||||
Debug.LogWarning("Unable to submit equipped-item weapon group membership request.");
|
||||
return;
|
||||
default:
|
||||
Debug.LogWarning($"Unknown inventory equipped item details command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void HideEquippedItemDetailsSurface()
|
||||
{
|
||||
if (_equippedItemDetailsSurfaceDocument == null)
|
||||
return;
|
||||
|
||||
AetheriaEveUnitySurfaceHost.Hide(_equippedItemDetailsSurfaceDocument);
|
||||
}
|
||||
|
||||
private static AetheriaEveUnitySurfaceChrome PanelChrome(float width, float maxWidth)
|
||||
{
|
||||
return new AetheriaEveUnitySurfaceChrome
|
||||
{
|
||||
RootAlignItems = Align.FlexStart,
|
||||
RootJustifyContent = Justify.FlexStart,
|
||||
RootPaddingTop = 0f,
|
||||
Width = width,
|
||||
MinWidth = 0f,
|
||||
MaxWidth = maxWidth,
|
||||
PaddingLeft = 18f,
|
||||
PaddingRight = 18f,
|
||||
PaddingTop = 18f,
|
||||
PaddingBottom = 18f
|
||||
};
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeEquippedItemObservation ComposeEquippedItemObservation(EquippedItem item)
|
||||
{
|
||||
var equippableItem = item?.EquippableItem;
|
||||
return new AetheriaRuntimeEquippedItemObservation(
|
||||
equippableItem?.ItemKey ?? "",
|
||||
equippableItem?.Quality ?? 1,
|
||||
equippableItem?.Durability ?? 1,
|
||||
item?.Temperature ?? 0,
|
||||
equippableItem != null && equippableItem.OverrideShutdown);
|
||||
}
|
||||
|
||||
private IEnumerable<AetheriaRuntimeEquippedItemTemperatureControl> ComposeEquippedItemTemperatureControls(
|
||||
EquippedItem item)
|
||||
{
|
||||
for (var i = 0; i < (item.Behaviors?.Length ?? 0); i++)
|
||||
{
|
||||
if (item.Behaviors[i] is not Thermotoggle thermotoggle || !thermotoggle.Adjustable)
|
||||
continue;
|
||||
|
||||
yield return new AetheriaRuntimeEquippedItemTemperatureControl(
|
||||
$"{AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.SurfaceId}.controls.thermotoggle.{i}.input",
|
||||
$"Target Temperature {i + 1}",
|
||||
thermotoggle.TargetTemperature.ToString(CultureInfo.InvariantCulture),
|
||||
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.Payload(
|
||||
("behaviorIndex", i.ToString(CultureInfo.InvariantCulture))));
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<AetheriaRuntimeEquippedItemControl> ComposeEquippedItemWeaponGroupControls(
|
||||
EquippedItem item)
|
||||
{
|
||||
return Enumerable.Range(0, item.Entity?.WeaponGroups?.Length ?? 0)
|
||||
.Select(groupIndex => new AetheriaRuntimeEquippedItemControl(
|
||||
$"{AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.SurfaceId}.weapon_groups.{groupIndex}",
|
||||
IsWeaponGroupAssigned(item, groupIndex) ? $"G{groupIndex + 1} On" : $"G{groupIndex + 1} Off",
|
||||
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.ToggleWeaponGroup,
|
||||
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.Payload(
|
||||
("group", groupIndex.ToString(CultureInfo.InvariantCulture)))));
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeCargoItemObservation ComposeCargoItemObservation(ItemInstance item)
|
||||
{
|
||||
var equippableItem = item as EquippableItem;
|
||||
return new AetheriaRuntimeCargoItemObservation(
|
||||
item?.ItemKey ?? "",
|
||||
item is SimpleCommodity simpleCommodity ? simpleCommodity.Quantity : 0,
|
||||
equippableItem != null,
|
||||
equippableItem?.Quality ?? 1,
|
||||
equippableItem?.Durability ?? 1,
|
||||
0,
|
||||
equippableItem != null && equippableItem.OverrideShutdown);
|
||||
}
|
||||
|
||||
private string BuildEquippedItemTitle(EquippedItem item, AetheriaRuntimeCatalogItem typedItem)
|
||||
{
|
||||
return $"{typedItem?.Name ?? "Unknown Item"} ({FormatItemTier(typedItem, item.EquippableItem)})";
|
||||
}
|
||||
|
||||
private string FormatItemTier(AetheriaRuntimeCatalogItem typedItem, EquippableItem item)
|
||||
{
|
||||
var tradeValue = AetheriaRuntimeDaemonTradeItemQueries.TradeItemValue(
|
||||
typedItem,
|
||||
ToRuntimeLoadoutItem(item),
|
||||
CatalogSnapshot()?.TradeValueSettings);
|
||||
return tradeValue.HasTier
|
||||
? $"{tradeValue.TierName}{new string('+', tradeValue.Upgrades)}"
|
||||
: "";
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeLoadoutItemCommit ToRuntimeLoadoutItem(EquippableItem item)
|
||||
{
|
||||
return AetheriaRuntimeDaemonItemStatQueries.ItemCommit(
|
||||
item?.ItemKey ?? "",
|
||||
item?.Quality ?? 1,
|
||||
item?.Durability ?? 1,
|
||||
enabled: true,
|
||||
overrideShutdown: item != null && item.OverrideShutdown);
|
||||
}
|
||||
|
||||
private static bool IsWeaponGroupAssigned(EquippedItem item, int groupIndex)
|
||||
{
|
||||
return item?.Entity?.WeaponGroups != null &&
|
||||
groupIndex >= 0 &&
|
||||
groupIndex < item.Entity.WeaponGroups.Length &&
|
||||
item.Entity.WeaponGroups[groupIndex].items.Contains(item);
|
||||
}
|
||||
|
||||
private void ClearSelectedItemSelection()
|
||||
{
|
||||
_selectedEquippedItem = null;
|
||||
}
|
||||
|
||||
private void RequestEntityShutdownPerformance(string targetEntityKey, float shutdownPerformance)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(targetEntityKey))
|
||||
return;
|
||||
|
||||
TrySubmitOperation(
|
||||
operations => operations.SetShutdownPerformance(targetEntityKey, shutdownPerformance),
|
||||
"entity shutdown-performance");
|
||||
}
|
||||
|
||||
private void RequestEquippedItemOverrideShutdown(EquippedItem item, bool enabled)
|
||||
{
|
||||
if (!TryResolveEquippedItem(item, out var targetEntityKey, out var equipmentIndex) ||
|
||||
item?.EquippableItem == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TrySubmitOperation(
|
||||
operations => operations.SetItemOverrideShutdown(targetEntityKey, equipmentIndex, enabled),
|
||||
"equipped-item override-shutdown");
|
||||
}
|
||||
|
||||
private void RequestThermotoggleTargetTemperature(
|
||||
EquippedItem item,
|
||||
int behaviorIndex,
|
||||
float targetTemperature)
|
||||
{
|
||||
if (!TryResolveEquippedItem(item, out var targetEntityKey, out var equipmentIndex) ||
|
||||
behaviorIndex < 0 ||
|
||||
behaviorIndex >= (item?.Behaviors?.Length ?? 0))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TrySubmitOperation(
|
||||
operations => operations.SetThermotoggleTargetTemperature(
|
||||
targetEntityKey,
|
||||
equipmentIndex,
|
||||
behaviorIndex,
|
||||
targetTemperature),
|
||||
"thermotoggle target-temperature");
|
||||
}
|
||||
|
||||
private void RequestWeaponGroupMembership(EquippedItem item, int groupIndex, bool assigned)
|
||||
{
|
||||
if (!TryResolveEquippedItem(item, out var targetEntityKey, out var equipmentIndex) ||
|
||||
groupIndex < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TrySubmitOperation(
|
||||
operations => operations.SetWeaponGroupMembership(
|
||||
targetEntityKey,
|
||||
equipmentIndex,
|
||||
groupIndex,
|
||||
assigned),
|
||||
"weapon-group membership");
|
||||
}
|
||||
|
||||
private bool TryGetRecordKeyForPresentationEntity(Entity entity, out string recordKey)
|
||||
{
|
||||
recordKey = "";
|
||||
return _presentationEntityIndex != null &&
|
||||
_presentationEntityIndex.TryGetRecordKeyForPresentationEntity(entity, out recordKey);
|
||||
}
|
||||
|
||||
private bool IsCurrentEntity(Entity entity)
|
||||
{
|
||||
if (entity == null ||
|
||||
!TryGetRecordKeyForPresentationEntity(entity, out var entityKey) ||
|
||||
string.IsNullOrWhiteSpace(entityKey) ||
|
||||
!TryResolveCurrentEntityKey(out var currentEntityKey))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return string.Equals(entityKey, currentEntityKey, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool TryResolveCurrentDockingBayRow(out AetheriaRuntimeStationDockingBayRow dockingBay)
|
||||
{
|
||||
dockingBay = null;
|
||||
var refit = StationRefitSnapshot();
|
||||
if (refit?.IsDocked != true || refit.DockingBayIndex < 0)
|
||||
return false;
|
||||
|
||||
dockingBay = (refit.DockingBays ?? Array.Empty<AetheriaRuntimeStationDockingBayRow>())
|
||||
.FirstOrDefault(row => row != null && row.DockingBayIndex == refit.DockingBayIndex);
|
||||
return dockingBay != null;
|
||||
}
|
||||
|
||||
private bool TryResolveCurrentEntityKey(out string currentEntityKey)
|
||||
{
|
||||
currentEntityKey = CurrentEntitySnapshot()?.EntityKey ?? "";
|
||||
return !string.IsNullOrWhiteSpace(currentEntityKey);
|
||||
}
|
||||
|
||||
private bool TryReadCurrentEntity(out AetheriaRuntimeCurrentEntityDocument currentEntity)
|
||||
{
|
||||
currentEntity = CurrentEntitySnapshot();
|
||||
if (currentEntity == null)
|
||||
{
|
||||
Debug.LogWarning("Failed to read Aetheria current entity for inventory ship settings.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryResolveCurrentEntity(out Entity currentEntity)
|
||||
{
|
||||
currentEntity = null;
|
||||
var currentEntityKey = CurrentEntitySnapshot()?.EntityKey ?? "";
|
||||
return _presentationEntityIndex != null &&
|
||||
!string.IsNullOrWhiteSpace(currentEntityKey) &&
|
||||
_presentationEntityIndex.TryGetPresentationEntityByRecordKey(currentEntityKey, out currentEntity);
|
||||
}
|
||||
|
||||
private bool TryResolveCurrentDockingBay(out EquippedDockingBay dockingBay)
|
||||
{
|
||||
dockingBay = null;
|
||||
var refit = StationRefitSnapshot();
|
||||
if (refit?.IsDocked != true ||
|
||||
refit.DockingBayIndex < 0 ||
|
||||
string.IsNullOrWhiteSpace(refit.DockParentEntityKey) ||
|
||||
_presentationEntityIndex == null ||
|
||||
!_presentationEntityIndex.TryGetPresentationDockingBayByRecordKey(
|
||||
refit.DockParentEntityKey,
|
||||
refit.DockingBayIndex,
|
||||
out dockingBay))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return dockingBay != null;
|
||||
}
|
||||
|
||||
private bool TryResolveEquippedItem(EquippedItem item, out string entityKey, out int equipmentIndex)
|
||||
{
|
||||
entityKey = "";
|
||||
equipmentIndex = -1;
|
||||
var entity = item?.Entity;
|
||||
if (entity?.Equipment == null ||
|
||||
!TryGetRecordKeyForPresentationEntity(entity, out entityKey))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
equipmentIndex = entity.Equipment.IndexOf(item);
|
||||
return equipmentIndex >= 0;
|
||||
}
|
||||
|
||||
private bool TrySubmitOperation(
|
||||
Action<AetheriaControl> submit,
|
||||
string label)
|
||||
{
|
||||
if (submit == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
submit(AetheriaUnityRuntimeClientProvider.Control("unity-inventory-menu"));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to send Aetheria daemon inventory menu {label} operation; operation not submitted: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCurrentEntityDocument CurrentEntitySnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.CurrentEntity.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria current entity for inventory menu: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private AetheriaRuntimeStationRefitDocument StationRefitSnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.StationRefit.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria station refit for inventory menu: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
// if (Keyboard.current.qKey.wasPressedThisFrame && _dragItem != null)
|
||||
|
|
@ -646,95 +208,4 @@ public class InventoryMenu : MonoBehaviour
|
|||
// _dragItem.Rotation = (ItemRotation) (((int) _dragItem.Rotation + 3) % 4);
|
||||
// }
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCatalogItem FindTypedInventoryItem(ItemInstance item)
|
||||
{
|
||||
return CatalogSnapshot()?.FindItem(item, x => x.ItemKey);
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCatalogSnapshot CatalogSnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.Catalog.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria runtime catalog for inventory menu: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private AetheriaRuntimePlayerSettingsDocument PlayerSettingsSnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.PlayerSettings.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria player settings for inventory menu: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private float ResolveDefaultShutdownPerformance()
|
||||
{
|
||||
var value = PlayerSettingsSnapshot()?.DefaultShutdownPerformance ?? 0.25;
|
||||
return (float)(value <= 0 ? 0.25 : value);
|
||||
}
|
||||
|
||||
private string ResolveManufacturerName(AetheriaRuntimeCatalogItem item)
|
||||
{
|
||||
return CatalogSnapshot()?.GetManufacturer(item)?.Name ?? "GameCult";
|
||||
}
|
||||
|
||||
private string FormatValue(float value)
|
||||
{
|
||||
var settings = PlayerSettingsSnapshot();
|
||||
var significantDigits = settings?.SignificantDigits ?? 3;
|
||||
var magnitude = value == 0.0f ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(value))) + 1;
|
||||
var digits = significantDigits - magnitude;
|
||||
if (digits < 0)
|
||||
digits = 0;
|
||||
|
||||
var formatted = value.ToString($"N{digits}", CultureInfo.CurrentCulture);
|
||||
var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
|
||||
var decimalSeparator = Convert.ToChar(separator);
|
||||
return formatted.Contains(separator)
|
||||
? formatted.TrimEnd('0').TrimEnd(decimalSeparator)
|
||||
: formatted;
|
||||
}
|
||||
|
||||
private string FormatTemperature(float value)
|
||||
{
|
||||
var unit = PlayerSettingsSnapshot()?.TemperatureUnit ?? nameof(TemperatureUnit.Celsius);
|
||||
if (string.Equals(unit, nameof(TemperatureUnit.Kelvin), StringComparison.OrdinalIgnoreCase))
|
||||
return $"{FormatValue(value)} K";
|
||||
if (string.Equals(unit, nameof(TemperatureUnit.Fahrenheit), StringComparison.OrdinalIgnoreCase))
|
||||
return $"{FormatValue(value * (9f / 5) - 459.67f)} F";
|
||||
|
||||
return $"{FormatValue(value - 273.15f)} C";
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (_shipSettingsSurfaceDocument != null)
|
||||
{
|
||||
AetheriaEveUnitySurfaceHost.DestroyDocument(_shipSettingsSurfaceDocument);
|
||||
_shipSettingsSurfaceDocument = null;
|
||||
}
|
||||
|
||||
if (_cargoItemDetailsSurfaceDocument != null)
|
||||
{
|
||||
AetheriaEveUnitySurfaceHost.DestroyDocument(_cargoItemDetailsSurfaceDocument);
|
||||
_cargoItemDetailsSurfaceDocument = null;
|
||||
}
|
||||
|
||||
if (_equippedItemDetailsSurfaceDocument != null)
|
||||
{
|
||||
AetheriaEveUnitySurfaceHost.DestroyDocument(_equippedItemDetailsSurfaceDocument);
|
||||
_equippedItemDetailsSurfaceDocument = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -2,16 +2,11 @@ using System;
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.EveRuntime;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Eve.Surface;
|
||||
using GameCult.Mesh;
|
||||
using Ink.Runtime;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UniRx.Triggers;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class LocalMenu : MonoBehaviour
|
||||
{
|
||||
|
|
@ -21,42 +16,18 @@ public class LocalMenu : MonoBehaviour
|
|||
public ChoicePrefab ChoicePrefab;
|
||||
|
||||
private string _currentPath;
|
||||
private LocationStory _currentLocalInkLocation;
|
||||
private LocationStory _currentLocation;
|
||||
private Story _activeStory;
|
||||
private readonly List<ActiveStoryChoice> _activeChoices = new List<ActiveStoryChoice>();
|
||||
private UIDocument _surfaceDocument;
|
||||
private readonly AetheriaEveUnitySurfaceChrome _surfaceChrome = new AetheriaEveUnitySurfaceChrome();
|
||||
private AetheriaUnityPresentationEntityIndex _presentationEntityIndex;
|
||||
private AetheriaClientState _runtimeState;
|
||||
|
||||
public void SetPresentationEntityIndex(AetheriaUnityPresentationEntityIndex presentationEntityIndex)
|
||||
{
|
||||
_presentationEntityIndex = presentationEntityIndex;
|
||||
}
|
||||
|
||||
private sealed class ActiveStoryChoice
|
||||
{
|
||||
public ActiveStoryChoice(int index, Story story, Choice choice)
|
||||
{
|
||||
Index = index;
|
||||
Story = story;
|
||||
Choice = choice;
|
||||
}
|
||||
|
||||
public int Index { get; }
|
||||
public Story Story { get; }
|
||||
public Choice Choice { get; }
|
||||
}
|
||||
private List<GameObject> _choiceInstances = new List<GameObject>();
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (!TryResolveDockedLocalInkStory(out _currentLocalInkLocation))
|
||||
if (ActionGameManager.Instance.DockedEntity is OrbitalEntity orbital)
|
||||
{
|
||||
HideStorySurface();
|
||||
return;
|
||||
_currentLocation = orbital.Story;
|
||||
_activeStory = _currentLocation.Story;
|
||||
}
|
||||
|
||||
_activeStory = _currentLocalInkLocation.Story;
|
||||
else return;
|
||||
Continue();
|
||||
}
|
||||
|
||||
|
|
@ -74,10 +45,11 @@ public class LocalMenu : MonoBehaviour
|
|||
if (!_activeStory.state.previousPointer.isNull) _currentPath = _activeStory.state.previousPointer.path.head.name;
|
||||
if(_activeStory.canContinue) _activeStory.Continue();
|
||||
if (!_activeStory.state.previousPointer.isNull) _currentPath = _activeStory.state.previousPointer.path.head.name;
|
||||
if (Output != null)
|
||||
Output.text = _activeStory.currentText;
|
||||
Output.text = _activeStory.currentText;
|
||||
|
||||
_activeChoices.Clear();
|
||||
foreach(var instance in _choiceInstances)
|
||||
Destroy(instance);
|
||||
_choiceInstances.Clear();
|
||||
|
||||
if(_activeStory.currentChoices.Any())
|
||||
{
|
||||
|
|
@ -86,7 +58,7 @@ public class LocalMenu : MonoBehaviour
|
|||
else if (!_activeStory.canContinue)
|
||||
{
|
||||
// There's no choices, but we also can't continue; indicates we hit an END
|
||||
if (_activeStory == _currentLocalInkLocation.Story)
|
||||
if (_activeStory == _currentLocation.Story)
|
||||
{
|
||||
// END inside location-based story thread, restart the story
|
||||
_activeStory.ResetState();
|
||||
|
|
@ -95,20 +67,18 @@ public class LocalMenu : MonoBehaviour
|
|||
else
|
||||
{
|
||||
// END inside quest content, switch back to location thread and present choices
|
||||
_activeStory = _currentLocalInkLocation.Story;
|
||||
_activeStory = _currentLocation.Story;
|
||||
Continue();
|
||||
}
|
||||
}
|
||||
|
||||
RenderStorySurface();
|
||||
}
|
||||
|
||||
void PresentCurrentChoices()
|
||||
{
|
||||
Debug.Log($"Current Path: \"{_currentPath}\" in {(_activeStory == _currentLocalInkLocation.Story ? "Location Story" : "Quest Story")}");
|
||||
if(!string.IsNullOrEmpty(_currentPath) && _currentLocalInkLocation.KnotQuests.ContainsKey(_currentPath))
|
||||
Debug.Log($"Current Path: \"{_currentPath}\" in {(_activeStory == _currentLocation.Story ? "Location Story" : "Quest Story")}");
|
||||
if(!string.IsNullOrEmpty(_currentPath) && _currentLocation.KnotQuests.ContainsKey(_currentPath))
|
||||
{
|
||||
foreach (var quest in _currentLocalInkLocation.KnotQuests[_currentPath])
|
||||
foreach (var quest in _currentLocation.KnotQuests[_currentPath])
|
||||
{
|
||||
if (quest.Story == _activeStory) continue; // Don't repeat choices for active injected branch
|
||||
|
||||
|
|
@ -122,140 +92,15 @@ public class LocalMenu : MonoBehaviour
|
|||
|
||||
void PresentChoice(Story story, Choice choice)
|
||||
{
|
||||
_activeChoices.Add(new ActiveStoryChoice(_activeChoices.Count, story, choice));
|
||||
}
|
||||
|
||||
private void RenderStorySurface()
|
||||
{
|
||||
if (_activeStory == null)
|
||||
return;
|
||||
|
||||
if (Output != null)
|
||||
Output.gameObject.SetActive(false);
|
||||
if (ChoiceParent != null)
|
||||
ChoiceParent.gameObject.SetActive(false);
|
||||
|
||||
_surfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
|
||||
transform,
|
||||
_surfaceDocument,
|
||||
"Aetheria Runtime Local Story Surface",
|
||||
AetheriaRuntimeLocalStorySurfaceBuilder.Build(
|
||||
ResolveLocationLabel(),
|
||||
_currentPath,
|
||||
_activeStory?.currentText ?? "",
|
||||
_activeStory?.canContinue == true,
|
||||
_activeChoices.Select(choice => new AetheriaRuntimeLocalStoryChoiceState(
|
||||
choice.Index,
|
||||
choice.Choice?.text ?? "")),
|
||||
DateTime.UtcNow.ToString("O")),
|
||||
HandleStorySurfaceCommand,
|
||||
_surfaceChrome);
|
||||
}
|
||||
|
||||
private void HandleStorySurfaceCommand(EveSurfaceCommandRequest request)
|
||||
{
|
||||
if (!AetheriaRuntimeLocalStorySurfaceCommands.TryRead(request, out var command))
|
||||
var choiceInstance = Instantiate(ChoicePrefab, ChoiceParent);
|
||||
choiceInstance.Label.text = choice.text;
|
||||
choiceInstance.Button.onClick.AddListener(() =>
|
||||
{
|
||||
Debug.LogWarning($"Unknown runtime local story command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (command.Kind)
|
||||
{
|
||||
case AetheriaRuntimeLocalStoryCommandKind.Continue:
|
||||
Continue();
|
||||
return;
|
||||
case AetheriaRuntimeLocalStoryCommandKind.Choose:
|
||||
ChooseStoryOption(command.ChoiceIndex);
|
||||
return;
|
||||
default:
|
||||
Debug.LogWarning($"Unknown runtime local story command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void ChooseStoryOption(int choiceIndex)
|
||||
{
|
||||
var selected = _activeChoices.FirstOrDefault(choice => choice.Index == choiceIndex);
|
||||
if (selected == null)
|
||||
{
|
||||
Debug.LogWarning($"Unknown runtime local story choice index: {choiceIndex}");
|
||||
return;
|
||||
}
|
||||
|
||||
_activeStory = selected.Story;
|
||||
_activeStory.ChoosePath(selected.Choice.targetPath);
|
||||
Continue();
|
||||
}
|
||||
|
||||
private string ResolveLocationLabel()
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_currentLocalInkLocation?.Name))
|
||||
return _currentLocalInkLocation.Name;
|
||||
if (!string.IsNullOrWhiteSpace(_currentLocalInkLocation?.FileName))
|
||||
return _currentLocalInkLocation.FileName;
|
||||
return "Local";
|
||||
}
|
||||
|
||||
private bool TryResolveDockedLocalInkStory(out LocationStory story)
|
||||
{
|
||||
story = null;
|
||||
var docking = CurrentDockingSnapshot();
|
||||
// Ink story execution is still a Unity-local island. The docking identity
|
||||
// comes from managed typed state; the remaining object lookup should go
|
||||
// away when local story state becomes a daemon-owned CultMesh document.
|
||||
if (_presentationEntityIndex == null ||
|
||||
docking == null ||
|
||||
!docking.IsDocked ||
|
||||
string.IsNullOrWhiteSpace(docking.DockParentEntityKey) ||
|
||||
docking.DockingBayIndex < 0 ||
|
||||
!_presentationEntityIndex.TryGetPresentationDockingBayByRecordKey(
|
||||
docking.DockParentEntityKey,
|
||||
docking.DockingBayIndex,
|
||||
out var dockingBay) ||
|
||||
dockingBay?.Entity is not OrbitalEntity { Story: { } dockedStory })
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
story = dockedStory;
|
||||
return true;
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCurrentDockingDocument CurrentDockingSnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-local-menu");
|
||||
return _runtimeState.CurrentDocking.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria current docking for local menu: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void HideStorySurface()
|
||||
{
|
||||
if (_surfaceDocument == null)
|
||||
return;
|
||||
|
||||
AetheriaEveUnitySurfaceHost.Hide(_surfaceDocument);
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
HideStorySurface();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (_surfaceDocument != null)
|
||||
{
|
||||
AetheriaEveUnitySurfaceHost.DestroyDocument(_surfaceDocument);
|
||||
_surfaceDocument = null;
|
||||
}
|
||||
_activeStory = story;
|
||||
_activeStory.ChoosePath(choice.targetPath);
|
||||
Continue();
|
||||
});
|
||||
_choiceInstances.Add(choiceInstance.gameObject);
|
||||
}
|
||||
|
||||
// Update is called once per frame
|
||||
|
|
|
|||
|
|
@ -1,13 +1,10 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Mesh;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using Unity.Mathematics;
|
||||
|
|
@ -17,6 +14,7 @@ using int2 = Unity.Mathematics.int2;
|
|||
|
||||
public class MapRenderer : MonoBehaviour
|
||||
{
|
||||
public ActionGameManager GameManager;
|
||||
public ZoneRenderer ZoneRenderer;
|
||||
public TextMeshProUGUI Title;
|
||||
public Camera MapOverlayCamera;
|
||||
|
|
@ -25,25 +23,19 @@ public class MapRenderer : MonoBehaviour
|
|||
public Camera InfluenceCamera;
|
||||
public Image OverlayDisplay;
|
||||
public Image GravityDisplay;
|
||||
public Material GravityBackdropMaterial;
|
||||
public Image TintDisplay;
|
||||
public Image InfluenceDisplay;
|
||||
public AetheriaRenderSplatLayerRenderer SplatLayerRenderer;
|
||||
public AetheriaDaemonRenderAssetCatalog AssetCatalog;
|
||||
public RectTransform MapIconRoot;
|
||||
public RawImage MapIconPrototype;
|
||||
public float Scale;
|
||||
public float2 Position;
|
||||
private AetheriaClientState _runtimeState;
|
||||
public float IconSize = 1f/128;
|
||||
|
||||
private RectTransform _rect;
|
||||
private RenderTexture _mapTexture;
|
||||
private RenderTexture _gravityTexture;
|
||||
private RenderTexture _tintTexture;
|
||||
private RenderTexture _influenceTexture;
|
||||
private int2 _size;
|
||||
private bool _init;
|
||||
private AetheriaUnityGameViewportDocuments _viewportDocuments;
|
||||
private float _nextViewportRefreshTime;
|
||||
private readonly List<RawImage> _mapIconPool = new List<RawImage>();
|
||||
|
||||
void Start()
|
||||
{
|
||||
|
|
@ -53,40 +45,30 @@ public class MapRenderer : MonoBehaviour
|
|||
private void OnEnable()
|
||||
{
|
||||
_init = true;
|
||||
SetCameraActive(MapOverlayCamera, false);
|
||||
SetCameraActive(GravityCamera, false);
|
||||
SetCameraActive(TintCamera, false);
|
||||
SetCameraActive(InfluenceCamera, false);
|
||||
if (OverlayDisplay != null)
|
||||
OverlayDisplay.gameObject.SetActive(false);
|
||||
if (GravityBackdropMaterial != null && GravityDisplay != null)
|
||||
GravityDisplay.material = GravityBackdropMaterial;
|
||||
EnsureMapIconRoot();
|
||||
SetMapIconsActive(true);
|
||||
RefreshViewportDocuments(force: true);
|
||||
MapOverlayCamera.gameObject.SetActive(true);
|
||||
GravityCamera.gameObject.SetActive(true);
|
||||
TintCamera.gameObject.SetActive(true);
|
||||
InfluenceCamera.gameObject.SetActive(true);
|
||||
Title.text = $"Zone: {GameManager.Zone.GalaxyZone.Name}";
|
||||
|
||||
// If hiding minimap asteroids, turn them back on for the map screen
|
||||
if (!ResolveShowAsteroidsInMinimap())
|
||||
if (!ActionGameManager.PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap)
|
||||
ZoneRenderer.ShowAsteroidUI = true;
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
ClearViewportCaches();
|
||||
if (_mapTexture != null)
|
||||
{
|
||||
ReleaseTextures();
|
||||
}
|
||||
SetCameraActive(MapOverlayCamera, false);
|
||||
SetCameraActive(GravityCamera, false);
|
||||
SetCameraActive(TintCamera, false);
|
||||
SetCameraActive(InfluenceCamera, false);
|
||||
if (OverlayDisplay != null)
|
||||
OverlayDisplay.gameObject.SetActive(false);
|
||||
SetMapIconsActive(false);
|
||||
MapOverlayCamera.gameObject.SetActive(false);
|
||||
GravityCamera.gameObject.SetActive(false);
|
||||
TintCamera.gameObject.SetActive(false);
|
||||
InfluenceCamera.gameObject.SetActive(false);
|
||||
|
||||
// If hiding minimap asteroids, turn them back off when leaving the map screen
|
||||
if (!ResolveShowAsteroidsInMinimap())
|
||||
if (!ActionGameManager.PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap)
|
||||
ZoneRenderer.ShowAsteroidUI = false;
|
||||
}
|
||||
|
||||
|
|
@ -94,6 +76,12 @@ public class MapRenderer : MonoBehaviour
|
|||
{
|
||||
_mapTexture.Release();
|
||||
_mapTexture = null;
|
||||
_gravityTexture.Release();
|
||||
_gravityTexture = null;
|
||||
_tintTexture.Release();
|
||||
_tintTexture = null;
|
||||
_influenceTexture.Release();
|
||||
_influenceTexture = null;
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
|
|
@ -108,230 +96,38 @@ public class MapRenderer : MonoBehaviour
|
|||
ReleaseTextures();
|
||||
}
|
||||
|
||||
_mapTexture = new RenderTexture(_size.x, _size.y, 0, RenderTextureFormat.Default);
|
||||
MapOverlayCamera.targetTexture = _mapTexture;
|
||||
OverlayDisplay.material.SetTexture("_DetailTex", _mapTexture);
|
||||
|
||||
_gravityTexture = new RenderTexture(_size.x, _size.y, 0, RenderTextureFormat.RFloat);
|
||||
GravityCamera.targetTexture = _gravityTexture;
|
||||
GravityDisplay.material.SetTexture("_DetailTex", _gravityTexture);
|
||||
|
||||
_tintTexture = new RenderTexture(_size.x / 2, _size.y / 2, 0, RenderTextureFormat.RGB111110Float);
|
||||
TintCamera.targetTexture = _tintTexture;
|
||||
TintDisplay.material.SetTexture("_DetailTex", _tintTexture);
|
||||
|
||||
_influenceTexture = new RenderTexture(_size.x, _size.y, 0, RenderTextureFormat.RFloat);
|
||||
InfluenceCamera.targetTexture = _influenceTexture;
|
||||
InfluenceDisplay.material.SetTexture("_DetailTex", _influenceTexture);
|
||||
}
|
||||
|
||||
var pos = ((Vector2) Position).Flatland(1);
|
||||
|
||||
MapOverlayCamera.transform.position = pos;
|
||||
MapOverlayCamera.orthographicSize = _size.y * Scale * .5f;
|
||||
|
||||
GravityCamera.transform.position = pos;
|
||||
GravityCamera.orthographicSize = _size.y * Scale * .5f;
|
||||
GravityDisplay.material.SetFloat("_Scale", Scale / 2);
|
||||
RefreshViewportDocuments(force: false);
|
||||
RenderSplatLayers();
|
||||
RenderMapIcons();
|
||||
}
|
||||
|
||||
private void RefreshViewportDocuments(bool force)
|
||||
{
|
||||
if (!force && Time.unscaledTime < _nextViewportRefreshTime)
|
||||
return;
|
||||
|
||||
_nextViewportRefreshTime = Time.unscaledTime + .5f;
|
||||
try
|
||||
{
|
||||
var viewport = ResolveViewportBounds();
|
||||
ClearViewportCaches();
|
||||
_viewportDocuments = AetheriaUnityRuntimeClientProvider
|
||||
.MapViewportDocuments(viewport, "unity-map-renderer");
|
||||
|
||||
var objectsViewport = _viewportDocuments?.CurrentObjectsViewport;
|
||||
var zoneName = string.IsNullOrWhiteSpace(objectsViewport?.ZoneName)
|
||||
? "Unknown"
|
||||
: objectsViewport.ZoneName;
|
||||
Title.text = $"Zone: {zoneName}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria map viewport from Verse state: {ex.Message}");
|
||||
Title.text = "Zone: Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderSplatLayers()
|
||||
{
|
||||
var renderSplatsViewport = _viewportDocuments?.CurrentRenderSplatsViewport;
|
||||
if (renderSplatsViewport == null)
|
||||
return;
|
||||
|
||||
if (SplatLayerRenderer == null)
|
||||
SplatLayerRenderer = GetComponent<AetheriaRenderSplatLayerRenderer>() ??
|
||||
gameObject.AddComponent<AetheriaRenderSplatLayerRenderer>();
|
||||
|
||||
SplatLayerRenderer.Render(renderSplatsViewport, _size.x, _size.y);
|
||||
ApplyLayerTexture(AetheriaRuntimeRenderSplatLayerKeys.GravityHeight, GravityDisplay);
|
||||
ApplyLayerTexture(AetheriaRuntimeRenderSplatLayerKeys.FogTint, TintDisplay);
|
||||
ApplyLayerTexture(AetheriaRuntimeRenderSplatLayerKeys.Influence, InfluenceDisplay);
|
||||
}
|
||||
|
||||
private void ApplyLayerTexture(string layerKey, Image display)
|
||||
{
|
||||
if (display == null ||
|
||||
SplatLayerRenderer == null ||
|
||||
!SplatLayerRenderer.TryGetTexture(layerKey, out var texture) ||
|
||||
texture == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
display.material.SetTexture("_DetailTex", texture);
|
||||
}
|
||||
|
||||
private static void SetCameraActive(Camera camera, bool active)
|
||||
{
|
||||
if (camera != null)
|
||||
camera.gameObject.SetActive(active);
|
||||
}
|
||||
|
||||
private void RenderMapIcons()
|
||||
{
|
||||
EnsureMapIconRoot();
|
||||
if (MapIconRoot == null)
|
||||
return;
|
||||
|
||||
var objects = _viewportDocuments?.CurrentObjectsViewport?.Objects ?? Array.Empty<AetheriaRuntimeViewportObject>();
|
||||
for (var i = 0; i < objects.Count; i++)
|
||||
{
|
||||
var icon = ResolveMapIcon(i);
|
||||
ApplyMapIcon(icon, objects[i]);
|
||||
}
|
||||
|
||||
for (var i = objects.Count; i < _mapIconPool.Count; i++)
|
||||
if (_mapIconPool[i] != null)
|
||||
_mapIconPool[i].gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
private RawImage ResolveMapIcon(int index)
|
||||
{
|
||||
while (_mapIconPool.Count <= index)
|
||||
{
|
||||
RawImage icon;
|
||||
if (MapIconPrototype != null)
|
||||
{
|
||||
icon = Instantiate(MapIconPrototype, MapIconRoot);
|
||||
}
|
||||
else
|
||||
{
|
||||
var go = new GameObject("Map Viewport Icon", typeof(RectTransform), typeof(CanvasRenderer), typeof(RawImage));
|
||||
go.transform.SetParent(MapIconRoot, false);
|
||||
icon = go.GetComponent<RawImage>();
|
||||
icon.texture = Texture2D.whiteTexture;
|
||||
icon.raycastTarget = false;
|
||||
}
|
||||
|
||||
_mapIconPool.Add(icon);
|
||||
}
|
||||
|
||||
return _mapIconPool[index];
|
||||
}
|
||||
|
||||
private void ApplyMapIcon(RawImage icon, AetheriaRuntimeViewportObject obj)
|
||||
{
|
||||
if (icon == null || obj == null)
|
||||
return;
|
||||
|
||||
icon.gameObject.SetActive(true);
|
||||
if (AssetCatalog != null && AssetCatalog.TryResolveTexture(obj.IconAsset, out var texture))
|
||||
icon.texture = texture;
|
||||
icon.color = ResolveIconColor(obj);
|
||||
var rectTransform = icon.rectTransform;
|
||||
var pixelSize = Mathf.Max(4f, IconSize * (obj.Controlled ? 1.25f : 1f));
|
||||
rectTransform.anchorMin = rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
|
||||
rectTransform.pivot = new Vector2(0.5f, 0.5f);
|
||||
rectTransform.sizeDelta = new Vector2(pixelSize, pixelSize);
|
||||
rectTransform.anchoredPosition = WorldToMapPosition(obj.X, obj.Y);
|
||||
rectTransform.localRotation = Quaternion.Euler(
|
||||
0,
|
||||
0,
|
||||
Mathf.Atan2((float)obj.DirectionY, (float)obj.DirectionX) * Mathf.Rad2Deg - 90f);
|
||||
}
|
||||
|
||||
private Vector2 WorldToMapPosition(double worldX, double worldY)
|
||||
{
|
||||
var viewport = _viewportDocuments?.CurrentObjectsViewport?.Viewport ?? ResolveViewportBounds();
|
||||
var minX = Math.Min(viewport.MinX, viewport.MaxX);
|
||||
var maxX = Math.Max(viewport.MinX, viewport.MaxX);
|
||||
var minY = Math.Min(viewport.MinY, viewport.MaxY);
|
||||
var maxY = Math.Max(viewport.MinY, viewport.MaxY);
|
||||
var width = Math.Max(0.0001, maxX - minX);
|
||||
var height = Math.Max(0.0001, maxY - minY);
|
||||
var rootRect = MapIconRoot != null ? MapIconRoot.rect : new Rect(0, 0, _size.x, _size.y);
|
||||
var u = (float)((worldX - minX) / width);
|
||||
var v = (float)((worldY - minY) / height);
|
||||
return new Vector2(
|
||||
(u - 0.5f) * rootRect.width,
|
||||
(v - 0.5f) * rootRect.height);
|
||||
}
|
||||
|
||||
private static Color ResolveIconColor(AetheriaRuntimeViewportObject obj)
|
||||
{
|
||||
var color = obj.Controlled
|
||||
? new Color(0.3f, 0.9f, 1.0f, 1.0f)
|
||||
: Color.HSVToRGB(frac((obj.FactionKey ?? obj.Kind ?? "").GetHashCode() * 0.0137f), 0.55f, 0.95f);
|
||||
color.a = Mathf.Clamp01(Mathf.Max(0.25f, (float)obj.Visibility));
|
||||
return color;
|
||||
}
|
||||
|
||||
private void EnsureMapIconRoot()
|
||||
{
|
||||
if (MapIconRoot != null)
|
||||
return;
|
||||
|
||||
var parent = GravityDisplay != null
|
||||
? GravityDisplay.transform.parent
|
||||
: transform;
|
||||
var go = new GameObject("Map Viewport Icons", typeof(RectTransform));
|
||||
go.transform.SetParent(parent, false);
|
||||
MapIconRoot = go.GetComponent<RectTransform>();
|
||||
MapIconRoot.anchorMin = Vector2.zero;
|
||||
MapIconRoot.anchorMax = Vector2.one;
|
||||
MapIconRoot.offsetMin = Vector2.zero;
|
||||
MapIconRoot.offsetMax = Vector2.zero;
|
||||
MapIconRoot.SetAsLastSibling();
|
||||
}
|
||||
|
||||
private void SetMapIconsActive(bool active)
|
||||
{
|
||||
if (MapIconRoot != null)
|
||||
MapIconRoot.gameObject.SetActive(active);
|
||||
}
|
||||
|
||||
private AetheriaRuntimeViewportBounds ResolveViewportBounds()
|
||||
{
|
||||
var screenHeight = _size.y <= 0 ? Math.Max(1, Screen.height) : _size.y;
|
||||
var screenWidth = _size.x <= 0 ? Math.Max(1, Screen.width) : _size.x;
|
||||
var halfHeight = screenHeight * Scale * .5f;
|
||||
var halfWidth = screenWidth * Scale * .5f;
|
||||
return new AetheriaRuntimeViewportBounds
|
||||
{
|
||||
MinX = Position.x - halfWidth,
|
||||
MinY = Position.y - halfHeight,
|
||||
MaxX = Position.x + halfWidth,
|
||||
MaxY = Position.y + halfHeight
|
||||
};
|
||||
}
|
||||
|
||||
private bool ResolveShowAsteroidsInMinimap()
|
||||
{
|
||||
try
|
||||
{
|
||||
_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-map-renderer");
|
||||
return _runtimeState.PlayerSettings.Latest()?.ShowAsteroidsInMinimap ?? false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria map graphics settings from Verse state: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearClientCaches()
|
||||
{
|
||||
ClearViewportCaches();
|
||||
}
|
||||
|
||||
private void ClearViewportCaches()
|
||||
{
|
||||
_viewportDocuments?.Dispose();
|
||||
_viewportDocuments = null;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
ClearClientCaches();
|
||||
|
||||
TintCamera.transform.position = pos;
|
||||
TintCamera.orthographicSize = _size.y * Scale * .5f;
|
||||
|
||||
InfluenceCamera.transform.position = pos;
|
||||
InfluenceCamera.orthographicSize = _size.y * Scale * .5f;
|
||||
|
||||
GameManager.ZoneRenderer.SetIconSize(IconSize * Scale);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,314 +1,69 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.EveRuntime;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Eve.Surface;
|
||||
using GameCult.Mesh;
|
||||
using UniRx.Triggers;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class MenuPanel : MonoBehaviour
|
||||
{
|
||||
private const string TabSurfaceId = "aetheria.runtime_menu.tabs";
|
||||
private const string TabCommandPrefix = "aetheria.runtime_menu.tab.";
|
||||
|
||||
[Serializable]
|
||||
private sealed class MenuTabBinding
|
||||
{
|
||||
public MenuTab Tab;
|
||||
public GameObject TabContents;
|
||||
public string Label;
|
||||
public bool RequireDock;
|
||||
}
|
||||
|
||||
public ActionGameManager GameManager;
|
||||
public RectTransform TabButtons;
|
||||
[SerializeField] private MenuTabBinding[] TabBindings = Array.Empty<MenuTabBinding>();
|
||||
public Color ActiveTabColor;
|
||||
public Color InactiveTabColor;
|
||||
|
||||
public event Action<MenuTab> TabChanged;
|
||||
|
||||
private readonly Dictionary<MenuTab, MenuTabBinding> _tabs = new Dictionary<MenuTab, MenuTabBinding>();
|
||||
private MenuTabBinding _current;
|
||||
private UIDocument _tabSurfaceDocument;
|
||||
private readonly AetheriaEveUnitySurfaceChrome _tabSurfaceChrome = new AetheriaEveUnitySurfaceChrome();
|
||||
private AetheriaClientState _runtimeState;
|
||||
private Dictionary<MenuTab, MenuTabButton> _tabs = new Dictionary<MenuTab, MenuTabButton>();
|
||||
private MenuTabButton _current;
|
||||
|
||||
public MenuTab CurrentTab { get; private set; }
|
||||
|
||||
public void ShowTab(MenuTab tab)
|
||||
{
|
||||
gameObject.SetActive(true);
|
||||
|
||||
if (!_tabs.TryGetValue(tab, out var next))
|
||||
return;
|
||||
|
||||
if (_current == next)
|
||||
{
|
||||
RenderTabSurface();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_current == _tabs[tab]) return;
|
||||
|
||||
if(_current != null)
|
||||
{
|
||||
_current.TabContents.SetActive(false);
|
||||
_current.Text.color = InactiveTabColor;
|
||||
}
|
||||
|
||||
CurrentTab = tab;
|
||||
_current = next;
|
||||
_current = _tabs[tab];
|
||||
|
||||
_current.TabContents.SetActive(true);
|
||||
RenderTabSurface();
|
||||
_current.Text.color = ActiveTabColor;
|
||||
|
||||
TabChanged?.Invoke(tab);
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (TabButtons != null)
|
||||
TabButtons.gameObject.SetActive(false);
|
||||
|
||||
RenderTabSurface();
|
||||
foreach (var tabButton in _tabs.Values)
|
||||
{
|
||||
tabButton.gameObject.SetActive(!tabButton.RequireDock || GameManager.DockedEntity != null);
|
||||
}
|
||||
_tabs[MenuTab.Local].gameObject.SetActive((GameManager.DockedEntity as OrbitalEntity)?.Story!=null);
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
foreach (var tabBinding in TabBindings)
|
||||
foreach (var tabButton in TabButtons.GetComponentsInChildren<MenuTabButton>())
|
||||
{
|
||||
if (tabBinding?.TabContents == null)
|
||||
continue;
|
||||
|
||||
tabBinding.TabContents.SetActive(false);
|
||||
_tabs[tabBinding.Tab] = tabBinding;
|
||||
tabButton.TabContents.SetActive(false);
|
||||
tabButton.Text.color = InactiveTabColor;
|
||||
_tabs.Add(tabButton.Tab, tabButton);
|
||||
tabButton.Button.onClick.AddListener(() => ShowTab(tabButton.Tab));
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
HideTabSurface();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (_tabSurfaceDocument != null)
|
||||
{
|
||||
AetheriaEveUnitySurfaceHost.DestroyDocument(_tabSurfaceDocument);
|
||||
_tabSurfaceDocument = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderTabSurface()
|
||||
{
|
||||
if (_tabs.Count == 0)
|
||||
return;
|
||||
|
||||
if (TabButtons != null)
|
||||
TabButtons.gameObject.SetActive(false);
|
||||
|
||||
_tabSurfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
|
||||
transform,
|
||||
_tabSurfaceDocument,
|
||||
"Aetheria Runtime Menu Tabs Surface",
|
||||
BuildTabSurfaceDocument(
|
||||
ToRuntimeTabKey(CurrentTab),
|
||||
ResolveVisibleTabs(),
|
||||
DateTime.UtcNow.ToString("O")),
|
||||
HandleTabSurfaceCommand,
|
||||
_tabSurfaceChrome);
|
||||
}
|
||||
|
||||
private void HandleTabSurfaceCommand(EveSurfaceCommandRequest request)
|
||||
{
|
||||
if (!TryReadTabSurfaceCommand(request, out var tabKey))
|
||||
{
|
||||
Debug.LogWarning($"Unknown runtime menu tab command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var tab in _tabs.Keys)
|
||||
{
|
||||
if (string.Equals(tabKey, ToRuntimeTabKey(tab), StringComparison.Ordinal))
|
||||
{
|
||||
ShowTab(tab);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Debug.LogWarning($"Unknown runtime menu tab command: {request?.Command}");
|
||||
}
|
||||
|
||||
private void HideTabSurface()
|
||||
{
|
||||
if (_tabSurfaceDocument == null)
|
||||
return;
|
||||
|
||||
AetheriaEveUnitySurfaceHost.Hide(_tabSurfaceDocument);
|
||||
}
|
||||
|
||||
private MenuTabBinding[] ResolveVisibleTabs()
|
||||
{
|
||||
var isDocked = TryResolveCurrentDocking(out var docking) &&
|
||||
docking.IsDocked;
|
||||
return _tabs.Values
|
||||
.Where(tabBinding => !tabBinding.RequireDock || isDocked)
|
||||
.Where(tabBinding => tabBinding.Tab != MenuTab.Local || isDocked)
|
||||
.OrderBy(tabBinding => (int)tabBinding.Tab)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private bool TryResolveCurrentDocking(out AetheriaRuntimeCurrentDockingDocument docking)
|
||||
{
|
||||
docking = null;
|
||||
try
|
||||
{
|
||||
_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-runtime-menu-tabs");
|
||||
docking = _runtimeState.CurrentDocking.Latest();
|
||||
return docking != null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria runtime docking for menu tabs: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetTabLabel(MenuTabBinding tabBinding)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(tabBinding.Label)
|
||||
? tabBinding.Tab.ToString()
|
||||
: tabBinding.Label;
|
||||
}
|
||||
|
||||
private static string ToRuntimeTabKey(MenuTab tab)
|
||||
{
|
||||
return NormalizeTabKey(tab.ToString());
|
||||
}
|
||||
|
||||
private static string NormalizeTabKey(string tabKey)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(tabKey)
|
||||
? "unknown"
|
||||
: tabKey.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static string TabCommandFor(string tabKey)
|
||||
{
|
||||
return $"{TabCommandPrefix}{NormalizeTabKey(tabKey)}";
|
||||
}
|
||||
|
||||
private static bool TryReadTabSurfaceCommand(EveSurfaceCommandRequest request, out string tabKey)
|
||||
{
|
||||
tabKey = "";
|
||||
if (request == null ||
|
||||
!string.Equals(request.SurfaceId, TabSurfaceId, StringComparison.Ordinal))
|
||||
return false;
|
||||
|
||||
var commandText = request.Operation?.OperationId ?? "";
|
||||
if (!commandText.StartsWith(TabCommandPrefix, StringComparison.Ordinal))
|
||||
return false;
|
||||
|
||||
tabKey = commandText.Substring(TabCommandPrefix.Length);
|
||||
return !string.IsNullOrWhiteSpace(tabKey);
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeSurfaceDocument BuildTabSurfaceDocument(
|
||||
string currentTabKey,
|
||||
IEnumerable<MenuTabBinding> visibleTabs,
|
||||
string updatedAtUtc)
|
||||
{
|
||||
var normalizedCurrent = NormalizeTabKey(currentTabKey);
|
||||
var tabs = (visibleTabs ?? Array.Empty<MenuTabBinding>())
|
||||
.Where(tab => tab != null)
|
||||
.OrderBy(tab => (int)tab.Tab)
|
||||
.Select(tab =>
|
||||
{
|
||||
var key = ToRuntimeTabKey(tab.Tab);
|
||||
var label = GetTabLabel(tab);
|
||||
return new
|
||||
{
|
||||
Key = key,
|
||||
Label = label,
|
||||
Selected = string.Equals(key, normalizedCurrent, StringComparison.Ordinal)
|
||||
};
|
||||
})
|
||||
.ToArray();
|
||||
|
||||
return new AetheriaRuntimeSurfaceDocument(
|
||||
providerId: "aetheria",
|
||||
providerKind: "runtime.menu",
|
||||
title: "Runtime Menu Tabs",
|
||||
version: 1,
|
||||
updatedAtUtc: updatedAtUtc ?? "",
|
||||
surface: new AetheriaRuntimeSurfaceTree(
|
||||
TabSurfaceId,
|
||||
TabSurfaceNode(
|
||||
$"{TabSurfaceId}.root",
|
||||
"surface",
|
||||
Array.Empty<(string Key, string Value)>(),
|
||||
TabSurfaceText(
|
||||
$"{TabSurfaceId}.current",
|
||||
$"Current: {normalizedCurrent}"),
|
||||
TabSurfaceButtonRow(
|
||||
$"{TabSurfaceId}.tabs",
|
||||
tabs
|
||||
.Select(tab => TabSurfaceButton(
|
||||
$"{TabSurfaceId}.{SafeSurfaceId(tab.Key)}",
|
||||
tab.Selected ? $"{tab.Label} *" : tab.Label,
|
||||
TabCommandFor(tab.Key)))
|
||||
.ToArray())),
|
||||
Array.Empty<AetheriaRuntimeSurfaceStyleToken>()),
|
||||
commands: tabs
|
||||
.Select(tab => new AetheriaRuntimeSurfaceCommandTemplate(
|
||||
TabCommandFor(tab.Key),
|
||||
tab.Label,
|
||||
AetheriaRuntimeSurfaceCommandTemplate.CultMeshTransport))
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
private static string SafeSurfaceId(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return "empty";
|
||||
|
||||
return new string(value
|
||||
.Select(character => char.IsLetterOrDigit(character) ? char.ToLowerInvariant(character) : '-')
|
||||
.ToArray()).Trim('-');
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeSurfaceComponent TabSurfaceText(string id, string value)
|
||||
{
|
||||
return TabSurfaceNode(id, "text", new[] { ("value", value ?? "") });
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeSurfaceComponent TabSurfaceButton(string id, string label, string command)
|
||||
{
|
||||
return TabSurfaceNode(id, "control.button", new[] { ("label", label ?? ""), ("command", command ?? "") });
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeSurfaceComponent TabSurfaceButtonRow(
|
||||
string id,
|
||||
params AetheriaRuntimeSurfaceComponent[] children)
|
||||
{
|
||||
return TabSurfaceNode(id, "row", Array.Empty<(string Key, string Value)>(), children);
|
||||
}
|
||||
|
||||
private static AetheriaRuntimeSurfaceComponent TabSurfaceNode(
|
||||
string id,
|
||||
string kind,
|
||||
IEnumerable<(string Key, string Value)> props,
|
||||
params AetheriaRuntimeSurfaceComponent[] children)
|
||||
{
|
||||
return new AetheriaRuntimeSurfaceComponent(
|
||||
id,
|
||||
kind,
|
||||
props.ToDictionary(prop => prop.Key, prop => prop.Value ?? "", StringComparer.Ordinal),
|
||||
children ?? Array.Empty<AetheriaRuntimeSurfaceComponent>());
|
||||
}
|
||||
|
||||
// void Start()
|
||||
// void Start()
|
||||
// {
|
||||
// ShowTab(MenuTab.Inventory);
|
||||
// }
|
||||
|
|
@ -321,4 +76,4 @@ public enum MenuTab
|
|||
Trade,
|
||||
Galaxy,
|
||||
Local
|
||||
}
|
||||
}
|
||||
19
Assets/Scripts/UI/Menu/MenuTabButton.cs
Normal file
19
Assets/Scripts/UI/Menu/MenuTabButton.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class MenuTabButton : MonoBehaviour
|
||||
{
|
||||
public GameObject TabContents;
|
||||
public Button Button;
|
||||
public MenuTab Tab;
|
||||
public TextMeshProUGUI Text;
|
||||
public bool RequireDock;
|
||||
}
|
||||
11
Assets/Scripts/UI/Menu/MenuTabButton.cs.meta
Normal file
11
Assets/Scripts/UI/Menu/MenuTabButton.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: d90317f6ecd38754fad9aee92f46b126
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -1,22 +1,21 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Eve.PluginFields;
|
||||
using GameCult.Mesh;
|
||||
using MessagePack;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
using Unity.Mathematics;
|
||||
using Random = UnityEngine.Random;
|
||||
using static Unity.Mathematics.math;
|
||||
using static Unity.Mathematics.noise;
|
||||
using Random = UnityEngine.Random;
|
||||
using float2 = Unity.Mathematics.float2;
|
||||
|
||||
public class SectorMap : MonoBehaviour
|
||||
{
|
||||
public Camera InfluenceCamera;
|
||||
public AetheriaRenderSplatRasterizer InfluenceSplatRasterizer;
|
||||
public Prototype InfluenceRendererPrototype;
|
||||
public MeshRenderer SectorRenderer;
|
||||
public Prototype ZonePrototype;
|
||||
|
|
@ -35,7 +34,6 @@ public class SectorMap : MonoBehaviour
|
|||
public Texture2D HomeIcon;
|
||||
public Prototype LegendPrototype;
|
||||
public float IconDistance = 1;
|
||||
private AetheriaClientState _runtimeState;
|
||||
public float IconBackgroundSize = 3;
|
||||
public float LabelDistance = .4f;
|
||||
public float LinkWidth;
|
||||
|
|
@ -44,42 +42,32 @@ public class SectorMap : MonoBehaviour
|
|||
public Color PlayerLocationLabelColor;
|
||||
public float PlayerLocationIconSize = 1.25f;
|
||||
|
||||
public Subject<int> ZoneClicked = new Subject<int>();
|
||||
public Subject<GalaxyZone> ZoneClicked = new Subject<GalaxyZone>();
|
||||
|
||||
private int _currentPlayerLocation = -1;
|
||||
private readonly HashSet<int> _revealedZones = new HashSet<int>();
|
||||
private readonly HashSet<(int, int)> _revealedLinks = new HashSet<(int, int)>();
|
||||
private readonly Dictionary<int, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)> _factionMaterials =
|
||||
new Dictionary<int, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)>();
|
||||
private readonly Dictionary<int, SectorZoneUI> _zoneInstances = new Dictionary<int, SectorZoneUI>();
|
||||
private readonly Queue<IEnumerable<int>> _queuedZoneReveals = new Queue<IEnumerable<int>>();
|
||||
private readonly Dictionary<int, AetheriaRuntimeSectorMapZone> _zonesByIndex =
|
||||
new Dictionary<int, AetheriaRuntimeSectorMapZone>();
|
||||
private AetheriaRuntimeSectorMapDocument _sectorMap;
|
||||
private bool _sectorMapLoaded;
|
||||
private GalaxyZone _currentPlayerLocation;
|
||||
private HashSet<GalaxyZone> _revealedZones = new HashSet<GalaxyZone>();
|
||||
private HashSet<(GalaxyZone, GalaxyZone)> _revealedLinks = new HashSet<(GalaxyZone, GalaxyZone)>();
|
||||
|
||||
public bool TryMarkPlayerLocation(int zoneIndex)
|
||||
private Dictionary<Faction, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)> _factionMaterials =
|
||||
new Dictionary<Faction, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)>();
|
||||
|
||||
private Dictionary<GalaxyZone, SectorZoneUI> _zoneInstances = new Dictionary<GalaxyZone, SectorZoneUI>();
|
||||
private Queue<IEnumerable<GalaxyZone>> _queuedZoneReveals = new Queue<IEnumerable<GalaxyZone>>();
|
||||
|
||||
public void MarkPlayerLocation(GalaxyZone zone)
|
||||
{
|
||||
EnsureSectorMapLoaded();
|
||||
if (!_zonesByIndex.ContainsKey(zoneIndex))
|
||||
return false;
|
||||
|
||||
MarkPlayerLocation(zoneIndex);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void MarkPlayerLocation(int zoneIndex)
|
||||
{
|
||||
if (_currentPlayerLocation >= 0 && _zoneInstances.TryGetValue(_currentPlayerLocation, out var previous))
|
||||
if (_currentPlayerLocation != null)
|
||||
{
|
||||
previous.Label.color = Color.white;
|
||||
previous.Label.fontStyle = FontStyles.Normal;
|
||||
previous.IconContainer.localScale = Vector3.one;
|
||||
_zoneInstances[_currentPlayerLocation].Label.color = Color.white;
|
||||
_zoneInstances[_currentPlayerLocation].Label.fontStyle = FontStyles.Normal;
|
||||
_zoneInstances[_currentPlayerLocation].IconContainer.localScale = Vector3.one;
|
||||
}
|
||||
|
||||
_currentPlayerLocation = zoneIndex;
|
||||
if (_zoneInstances.TryGetValue(_currentPlayerLocation, out var zoneUI))
|
||||
MarkPlayerLocation(zoneUI);
|
||||
_currentPlayerLocation = zone;
|
||||
if(_zoneInstances.ContainsKey(_currentPlayerLocation))
|
||||
{
|
||||
MarkPlayerLocation(_zoneInstances[_currentPlayerLocation]);
|
||||
}
|
||||
}
|
||||
|
||||
private void MarkPlayerLocation(SectorZoneUI zoneUI)
|
||||
|
|
@ -89,409 +77,268 @@ public class SectorMap : MonoBehaviour
|
|||
zoneUI.IconContainer.localScale = new Vector3(PlayerLocationIconSize, PlayerLocationIconSize, 1);
|
||||
}
|
||||
|
||||
public void QueueZoneReveal(IEnumerable<int> zoneIndices)
|
||||
public void QueueZoneReveal(IEnumerable<GalaxyZone> zones)
|
||||
{
|
||||
_queuedZoneReveals.Enqueue(zoneIndices ?? Array.Empty<int>());
|
||||
_queuedZoneReveals.Enqueue(zones);
|
||||
}
|
||||
|
||||
public void StartReveal(float linkDuration, float iconDuration)
|
||||
{
|
||||
EnsureSectorMapLoaded();
|
||||
if (_queuedZoneReveals.Count > 0)
|
||||
{
|
||||
StartCoroutine(RevealZone(_queuedZoneReveals.Dequeue(), linkDuration, iconDuration));
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerator RevealZone(IEnumerable<int> zoneIndices, float linkDuration, float iconDuration)
|
||||
public IEnumerator RevealZone(IEnumerable<GalaxyZone> zones, float linkDuration, float iconDuration)
|
||||
{
|
||||
var linksToReveal = new List<(float2 start, float2 end, Transform linkInstance, bool critical)>();
|
||||
var zoneTransforms = new List<Transform>();
|
||||
var zoneInstanceScale = ZonePrototype.transform.localScale;
|
||||
|
||||
foreach (var zoneIndex in zoneIndices ?? Array.Empty<int>())
|
||||
foreach (var zone in zones)
|
||||
{
|
||||
if (!_zonesByIndex.TryGetValue(zoneIndex, out var zone) || _revealedZones.Contains(zoneIndex))
|
||||
continue;
|
||||
|
||||
var zoneInstance = ZonePrototype.Instantiate<SectorZoneUI>();
|
||||
zoneInstance.Clickable.OnClick += (_, _, _, _) => ZoneClicked.OnNext(zone.ZoneIndex);
|
||||
if(zone.ZoneIndex == _currentPlayerLocation)
|
||||
MarkPlayerLocation(zoneInstance);
|
||||
_zoneInstances[zone.ZoneIndex] = zoneInstance;
|
||||
var zoneInstanceTransform = zoneInstance.transform;
|
||||
zoneTransforms.Add(zoneInstanceTransform);
|
||||
zoneInstanceTransform.localPosition = new Vector3((float)zone.X, (float)zone.Y);
|
||||
|
||||
if (zone.OwnerFactionIndex >= 0 && _factionMaterials.TryGetValue(zone.OwnerFactionIndex, out var ownerMaterials))
|
||||
if (!_revealedZones.Contains(zone))
|
||||
{
|
||||
zoneInstance.Primary.sharedMaterial = ownerMaterials.primaryMaterial;
|
||||
zoneInstance.Secondary.sharedMaterial = ownerMaterials.secondaryMaterial;
|
||||
}
|
||||
else
|
||||
{
|
||||
zoneInstance.Secondary.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
foreach (var link in LinksForZone(zone.ZoneIndex))
|
||||
{
|
||||
var adjacentIndex = link.FromZoneIndex == zone.ZoneIndex ? link.ToZoneIndex : link.FromZoneIndex;
|
||||
if (!_zonesByIndex.TryGetValue(adjacentIndex, out var adjacentZone) ||
|
||||
!_revealedZones.Contains(adjacentIndex) ||
|
||||
_revealedLinks.Contains((zone.ZoneIndex, adjacentIndex)) ||
|
||||
_revealedLinks.Contains((adjacentIndex, zone.ZoneIndex)))
|
||||
var zoneInstance = ZonePrototype.Instantiate<SectorZoneUI>();
|
||||
zoneInstance.Clickable.OnClick += (clickableCollider, data, ray, hit) => ZoneClicked.OnNext(zone);
|
||||
if(zone == _currentPlayerLocation)
|
||||
MarkPlayerLocation(zoneInstance);
|
||||
_zoneInstances[zone] = zoneInstance;
|
||||
var zoneInstanceTransform = zoneInstance.transform;
|
||||
zoneTransforms.Add(zoneInstanceTransform);
|
||||
zoneInstanceTransform.localPosition = new Vector3(zone.Position.x, zone.Position.y);
|
||||
if(zone.Owner != null)
|
||||
{
|
||||
continue;
|
||||
zoneInstance.Primary.sharedMaterial = _factionMaterials[zone.Owner].primaryMaterial;
|
||||
zoneInstance.Secondary.sharedMaterial = _factionMaterials[zone.Owner].secondaryMaterial;
|
||||
if(zone == ActionGameManager.CurrentGalaxy.HomeZones[zone.Owner])
|
||||
zoneInstance.Secondary.transform.localScale = Vector3.one * 4;
|
||||
}
|
||||
else
|
||||
{
|
||||
zoneInstance.Secondary.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
var linkInstance = LinkPrototype.Instantiate<Transform>();
|
||||
var critical = zone.Entrance || zone.Exit || adjacentZone.Entrance || adjacentZone.Exit;
|
||||
var start = Position(zone);
|
||||
var end = Position(adjacentZone);
|
||||
linksToReveal.Add((start, end, linkInstance, critical));
|
||||
if (zone.OwnerFactionIndex >= 0 &&
|
||||
zone.OwnerFactionIndex == adjacentZone.OwnerFactionIndex &&
|
||||
_factionMaterials.TryGetValue(zone.OwnerFactionIndex, out var factionMaterials))
|
||||
var isOnCriticalPath = ActionGameManager.CurrentGalaxy.ExitPath?.Contains(zone) ?? false;
|
||||
foreach (var adjacentZone in zone.AdjacentZones)
|
||||
{
|
||||
linkInstance.GetComponent<MeshRenderer>().sharedMaterial = factionMaterials.linkMaterial;
|
||||
// If the adjacent zone is in the set already revealed, then show the link
|
||||
if (_revealedZones.Contains(adjacentZone) &&
|
||||
!(_revealedLinks.Contains((zone, adjacentZone)) ||
|
||||
_revealedLinks.Contains((adjacentZone, zone))))
|
||||
{
|
||||
var link = LinkPrototype.Instantiate<Transform>();
|
||||
var critical = isOnCriticalPath && (ActionGameManager.CurrentGalaxy.ExitPath?.Contains(adjacentZone) ?? false);
|
||||
linksToReveal.Add((zone.Position, adjacentZone.Position, link, critical));
|
||||
if (zone.Owner != null && zone.Owner == adjacentZone.Owner)
|
||||
link.GetComponent<MeshRenderer>().sharedMaterial = _factionMaterials[zone.Owner].linkMaterial;
|
||||
|
||||
var dir = normalize(zone.Position - adjacentZone.Position);
|
||||
link.rotation = Quaternion.Euler(0,0,atan2(dir.y,dir.x) * Mathf.Rad2Deg);
|
||||
|
||||
placeLink(zone.Position, adjacentZone.Position, link, 0, critical);
|
||||
}
|
||||
}
|
||||
_revealedZones.Add(zone);
|
||||
|
||||
// Determine center of mass for adjacent zone links, used for placement of label and icons
|
||||
var linkDirection = normalize(zone.AdjacentZones
|
||||
.Aggregate(float2.zero, (v, adjacentZone) => v + normalize(adjacentZone.Position - zone.Position)));
|
||||
|
||||
var zoneText = zoneInstance.Label;
|
||||
zoneText.text = zone.Name;
|
||||
var zoneTextTransform = zoneText.GetComponent<RectTransform>();
|
||||
zoneTextTransform.pivot = new Vector2(sign(linkDirection.x)/2+.5f,sign(linkDirection.y)/2+.5f);
|
||||
zoneTextTransform.localPosition = new Vector3(-linkDirection.x * LabelDistance, -linkDirection.y * LabelDistance, -1);
|
||||
|
||||
if (zone == ActionGameManager.CurrentGalaxy.Entrance)
|
||||
{
|
||||
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
|
||||
iconInstance.material.mainTexture = EntranceIcon;
|
||||
var iconTransform = iconInstance.transform;
|
||||
iconTransform.SetParent(zoneInstanceTransform);
|
||||
iconTransform.localScale = Vector3.one;
|
||||
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
|
||||
}
|
||||
|
||||
var dir = normalize(start - end);
|
||||
linkInstance.rotation = Quaternion.Euler(0, 0, atan2(dir.y, dir.x) * Mathf.Rad2Deg);
|
||||
placeLink(start, end, linkInstance, 0, critical);
|
||||
_revealedLinks.Add((zone.ZoneIndex, adjacentIndex));
|
||||
if (zone == ActionGameManager.CurrentGalaxy.Exit)
|
||||
{
|
||||
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
|
||||
iconInstance.material.mainTexture = ExitIcon;
|
||||
var iconTransform = iconInstance.transform;
|
||||
iconTransform.SetParent(zoneInstanceTransform);
|
||||
iconTransform.localScale = Vector3.one;
|
||||
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
|
||||
}
|
||||
|
||||
var homeMega = ActionGameManager.CurrentGalaxy.HomeZones.Keys
|
||||
.FirstOrDefault(m => ActionGameManager.CurrentGalaxy.HomeZones[m] == zone);
|
||||
if (homeMega != null)
|
||||
{
|
||||
var backgroundInstance = IconBackgroundPrototype.Instantiate<MeshRenderer>();
|
||||
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
|
||||
|
||||
backgroundInstance.material.SetColor("_Color", homeMega.SecondaryColor.ToColor());
|
||||
iconInstance.material.mainTexture = HomeIcon;
|
||||
iconInstance.material.SetColor("_Color", homeMega.PrimaryColor.ToColor());
|
||||
|
||||
var backgroundTransform = backgroundInstance.transform;
|
||||
var iconTransform = iconInstance.transform;
|
||||
|
||||
backgroundTransform.SetParent(zoneInstanceTransform);
|
||||
iconTransform.SetParent(zoneInstanceTransform);
|
||||
|
||||
backgroundTransform.localScale = Vector3.one * IconBackgroundSize;
|
||||
iconTransform.localScale = Vector3.one;
|
||||
|
||||
backgroundTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance, .5f);
|
||||
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
|
||||
}
|
||||
|
||||
var bossMega = ActionGameManager.CurrentGalaxy.BossZones.Keys
|
||||
.FirstOrDefault(m => ActionGameManager.CurrentGalaxy.BossZones[m] == zone);
|
||||
if (bossMega != null)
|
||||
{
|
||||
var backgroundInstance = IconBackgroundPrototype.Instantiate<MeshRenderer>();
|
||||
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
|
||||
|
||||
backgroundInstance.material.SetColor("_Color", bossMega.SecondaryColor.ToColor());
|
||||
iconInstance.material.mainTexture = BossIcon;
|
||||
iconInstance.material.SetColor("_Color", bossMega.PrimaryColor.ToColor());
|
||||
|
||||
var backgroundTransform = backgroundInstance.transform;
|
||||
var iconTransform = iconInstance.transform;
|
||||
|
||||
backgroundTransform.SetParent(zoneInstanceTransform);
|
||||
iconTransform.SetParent(zoneInstanceTransform);
|
||||
|
||||
backgroundTransform.localScale = Vector3.one * IconBackgroundSize;
|
||||
iconTransform.localScale = Vector3.one;
|
||||
|
||||
if (homeMega != null)
|
||||
{
|
||||
backgroundTransform.localPosition = new Vector3(linkDirection.x * IconDistance, linkDirection.y * IconDistance, .5f);
|
||||
iconTransform.localPosition = new Vector3(linkDirection.x * IconDistance, linkDirection.y * IconDistance);
|
||||
}
|
||||
else
|
||||
{
|
||||
backgroundTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance, .5f);
|
||||
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_revealedZones.Add(zone.ZoneIndex);
|
||||
var linkDirection = ResolveLabelDirection(zone);
|
||||
var zoneText = zoneInstance.Label;
|
||||
zoneText.text = zone.Name;
|
||||
var zoneTextTransform = zoneText.GetComponent<RectTransform>();
|
||||
zoneTextTransform.pivot = new Vector2(sign(linkDirection.x) / 2 + .5f, sign(linkDirection.y) / 2 + .5f);
|
||||
zoneTextTransform.localPosition = new Vector3(-linkDirection.x * LabelDistance, -linkDirection.y * LabelDistance, -1);
|
||||
|
||||
if (zone.Entrance)
|
||||
AddZoneIcon(zoneInstanceTransform, EntranceIcon, linkDirection, -1);
|
||||
|
||||
if (zone.Exit)
|
||||
AddZoneIcon(zoneInstanceTransform, ExitIcon, linkDirection, zone.Entrance ? 1 : -1);
|
||||
}
|
||||
foreach (var tr in zoneTransforms) tr.gameObject.SetActive(false);
|
||||
|
||||
// Local function for animating the placement of a link
|
||||
void placeLink(float2 start, float2 end, Transform link, float t, bool critical)
|
||||
{
|
||||
var pos = lerp(start, end, t / 2);
|
||||
link.localPosition = new Vector3(pos.x, pos.y);
|
||||
link.localScale = new Vector3(length(start - end) * t, critical ? CriticalLinkWidth : LinkWidth, 1);
|
||||
|
||||
var localScale = link.localScale;
|
||||
localScale = new Vector3(length(start - end)*t, critical ? CriticalLinkWidth : LinkWidth, 1);
|
||||
link.localScale = localScale;
|
||||
}
|
||||
|
||||
var startTime = Time.time;
|
||||
while (Time.time - startTime < linkDuration)
|
||||
{
|
||||
var t = (Time.time - startTime) / linkDuration;
|
||||
foreach (var (start, end, link, critical) in linksToReveal)
|
||||
placeLink(end, start, link, t, critical);
|
||||
foreach (var (start, end, link, critical) in linksToReveal) placeLink(end, start, link, t, critical);
|
||||
|
||||
yield return null;
|
||||
}
|
||||
foreach (var (start, end, link, critical) in linksToReveal)
|
||||
placeLink(start, end, link, 1, critical);
|
||||
|
||||
foreach (var tr in zoneTransforms)
|
||||
tr.gameObject.SetActive(true);
|
||||
foreach (var (start, end, link, critical) in linksToReveal) placeLink(start, end, link, 1, critical);
|
||||
|
||||
foreach (var tr in zoneTransforms) tr.gameObject.SetActive(true);
|
||||
startTime = Time.time;
|
||||
while (Time.time - startTime < iconDuration)
|
||||
{
|
||||
var t = (Time.time - startTime) / iconDuration;
|
||||
foreach (var tr in zoneTransforms)
|
||||
tr.localScale = zoneInstanceScale * IconScaleAnimation.Evaluate(t);
|
||||
foreach (var tr in zoneTransforms) tr.localScale = zoneInstanceScale * IconScaleAnimation.Evaluate(t);
|
||||
RenderInfluence();
|
||||
|
||||
yield return null;
|
||||
}
|
||||
foreach (var tr in zoneTransforms)
|
||||
tr.localScale = zoneInstanceScale;
|
||||
foreach (var tr in zoneTransforms) tr.localScale = zoneInstanceScale;
|
||||
|
||||
StartReveal(linkDuration, iconDuration);
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
EnsureSectorMapLoaded();
|
||||
DisableLegacyInfluenceCamera();
|
||||
}
|
||||
|
||||
private void EnsureSectorMapLoaded()
|
||||
{
|
||||
_runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-sector-map");
|
||||
_sectorMap = _runtimeState.SectorMap.Latest();
|
||||
|
||||
if (_sectorMapLoaded)
|
||||
return;
|
||||
|
||||
_sectorMapLoaded = true;
|
||||
|
||||
if (_sectorMap?.Zones == null || _sectorMap.Zones.Count == 0)
|
||||
if (ActionGameManager.CurrentGalaxy == null)
|
||||
{
|
||||
gameObject.SetActive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
_zonesByIndex.Clear();
|
||||
foreach (var zone in _sectorMap.Zones)
|
||||
_zonesByIndex[zone.ZoneIndex] = zone;
|
||||
|
||||
foreach (var factionIndex in ResolveFactionIndices())
|
||||
AddFactionMaterials(factionIndex);
|
||||
|
||||
QueueZoneReveal(_sectorMap.DiscoveredZoneIndices);
|
||||
|
||||
if (_queuedZoneReveals.Count == 0)
|
||||
QueueZoneReveal(_sectorMap.Zones.Select(zone => zone.ZoneIndex));
|
||||
|
||||
if (_sectorMap.CurrentZoneIndex >= 0)
|
||||
TryMarkPlayerLocation(_sectorMap.CurrentZoneIndex);
|
||||
}
|
||||
|
||||
private void AddFactionMaterials(int factionIndex)
|
||||
{
|
||||
if (_factionMaterials.ContainsKey(factionIndex))
|
||||
return;
|
||||
|
||||
var primaryColor = ResolveFactionColor(factionIndex, secondary: false);
|
||||
var secondaryColor = ResolveFactionColor(factionIndex, secondary: true);
|
||||
var influenceTexture = new RenderTexture(1024, 1024, 0, RenderTextureFormat.RHalf);
|
||||
var influenceRenderer = InfluenceRendererPrototype.Instantiate<MeshRenderer>();
|
||||
influenceRenderer.material.mainTexture = influenceTexture;
|
||||
influenceRenderer.material.SetColor("_Color1", primaryColor);
|
||||
influenceRenderer.material.SetColor("_Color2", secondaryColor);
|
||||
influenceRenderer.material.SetFloat("_FillTilt", Random.value * PI);
|
||||
|
||||
var primary = Instantiate(ZonePrimaryMaterial);
|
||||
primary.SetColor("_Color", primaryColor * MegaPrimaryBoost);
|
||||
|
||||
var secondary = Instantiate(ZoneSecondaryMaterial);
|
||||
secondary.SetColor("_Color", secondaryColor * MegaSecondaryBoost);
|
||||
|
||||
var link = Instantiate(ZoneLinkMaterial);
|
||||
link.SetColor("_Color", primaryColor * MegaLinkBoost);
|
||||
|
||||
_factionMaterials.Add(factionIndex, (influenceRenderer, influenceTexture, primary, secondary, link));
|
||||
|
||||
var legendElement = LegendPrototype.Instantiate<LegendElement>();
|
||||
legendElement.Primary.color = primaryColor;
|
||||
legendElement.Secondary.color = secondaryColor;
|
||||
legendElement.Label.text = factionIndex < 0 ? "None" : $"F{factionIndex}";
|
||||
}
|
||||
|
||||
private IEnumerable<int> ResolveFactionIndices()
|
||||
{
|
||||
return (_sectorMap?.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
|
||||
.SelectMany(zone => (zone.FactionIndices ?? Array.Empty<int>()).Append(zone.OwnerFactionIndex))
|
||||
.Where(index => index >= 0)
|
||||
.Distinct()
|
||||
.OrderBy(index => index);
|
||||
}
|
||||
|
||||
private Color ResolveFactionColor(int factionIndex, bool secondary)
|
||||
{
|
||||
var hue = frac((factionIndex + (secondary ? 0.37f : 0f)) * 0.173f);
|
||||
return Color.HSVToRGB(hue, secondary ? 0.48f : 0.62f, secondary ? 0.72f : 0.88f);
|
||||
}
|
||||
|
||||
private IEnumerable<AetheriaRuntimeSectorMapLink> LinksForZone(int zoneIndex)
|
||||
{
|
||||
return (_sectorMap?.Links ?? Array.Empty<AetheriaRuntimeSectorMapLink>())
|
||||
.Where(link => link.FromZoneIndex == zoneIndex || link.ToZoneIndex == zoneIndex);
|
||||
}
|
||||
|
||||
private float2 ResolveLabelDirection(AetheriaRuntimeSectorMapZone zone)
|
||||
{
|
||||
var direction = float2.zero;
|
||||
foreach (var adjacentIndex in zone.AdjacentZoneIndices ?? Array.Empty<int>())
|
||||
foreach (var mega in ActionGameManager.CurrentGalaxy.Factions)
|
||||
{
|
||||
if (_zonesByIndex.TryGetValue(adjacentIndex, out var adjacent))
|
||||
direction += normalizesafe(Position(adjacent) - Position(zone));
|
||||
var influenceTexture = new RenderTexture(1024, 1024, 0, RenderTextureFormat.RHalf);
|
||||
var influenceRenderer = InfluenceRendererPrototype.Instantiate<MeshRenderer>();
|
||||
|
||||
influenceRenderer.material.mainTexture = influenceTexture;
|
||||
influenceRenderer.material.SetColor("_Color1", mega.PrimaryColor.ToColor());
|
||||
influenceRenderer.material.SetColor("_Color2", mega.SecondaryColor.ToColor());
|
||||
influenceRenderer.material.SetFloat("_FillTilt", Random.value * PI);
|
||||
|
||||
var primary = Instantiate(ZonePrimaryMaterial);
|
||||
primary.SetColor("_Color", (mega.PrimaryColor * MegaPrimaryBoost).ToColor());
|
||||
|
||||
var secondary = Instantiate(ZoneSecondaryMaterial);
|
||||
secondary.SetColor("_Color", (mega.SecondaryColor * MegaSecondaryBoost).ToColor());
|
||||
|
||||
var link = Instantiate(ZoneLinkMaterial);
|
||||
link.SetColor("_Color", (mega.PrimaryColor * MegaLinkBoost).ToColor());
|
||||
|
||||
_factionMaterials.Add(mega, (influenceRenderer, influenceTexture, primary, secondary, link));
|
||||
|
||||
var legendElement = LegendPrototype.Instantiate<LegendElement>();
|
||||
legendElement.Primary.color = mega.PrimaryColor.ToColor();
|
||||
legendElement.Secondary.color = mega.SecondaryColor.ToColor();
|
||||
legendElement.Label.text = mega.ShortName;
|
||||
}
|
||||
|
||||
return lengthsq(direction) <= 0 ? new float2(0, 1) : normalize(direction);
|
||||
}
|
||||
|
||||
private void AddZoneIcon(
|
||||
Transform zoneInstanceTransform,
|
||||
Texture2D icon,
|
||||
float2 linkDirection,
|
||||
int side)
|
||||
{
|
||||
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
|
||||
iconInstance.material.mainTexture = icon;
|
||||
var iconTransform = iconInstance.transform;
|
||||
iconTransform.SetParent(zoneInstanceTransform);
|
||||
iconTransform.localScale = Vector3.one;
|
||||
iconTransform.localPosition = new Vector3(
|
||||
side * -linkDirection.x * IconDistance,
|
||||
side * -linkDirection.y * IconDistance);
|
||||
SectorRenderer.material.SetFloat("CloudAmplitude", ActionGameManager.CurrentGalaxy.Background.CloudAmplitude);
|
||||
SectorRenderer.material.SetFloat("CloudExponent", ActionGameManager.CurrentGalaxy.Background.CloudExponent);
|
||||
SectorRenderer.material.SetFloat("NoisePosition", ActionGameManager.CurrentGalaxy.Background.NoisePosition);
|
||||
SectorRenderer.material.SetFloat("NoiseAmplitude", ActionGameManager.CurrentGalaxy.Background.NoiseAmplitude);
|
||||
SectorRenderer.material.SetFloat("NoiseOffset", ActionGameManager.CurrentGalaxy.Background.NoiseOffset);
|
||||
SectorRenderer.material.SetFloat("NoiseGain", ActionGameManager.CurrentGalaxy.Background.NoiseGain);
|
||||
SectorRenderer.material.SetFloat("NoiseLacunarity", ActionGameManager.CurrentGalaxy.Background.NoiseLacunarity);
|
||||
SectorRenderer.material.SetFloat("NoiseFrequency", ActionGameManager.CurrentGalaxy.Background.NoiseFrequency);
|
||||
}
|
||||
|
||||
private void RenderInfluence()
|
||||
{
|
||||
DisableLegacyInfluenceCamera();
|
||||
foreach (var pair in _factionMaterials)
|
||||
// Render Influence Textures
|
||||
foreach (var mega in ActionGameManager.CurrentGalaxy.Factions)
|
||||
{
|
||||
var document = BuildInfluenceSplatDocument(pair.Key);
|
||||
ResolveInfluenceSplatRasterizer().RenderLayerToTarget(
|
||||
document,
|
||||
pair.Value.influence,
|
||||
0,
|
||||
0,
|
||||
Color.clear);
|
||||
}
|
||||
}
|
||||
|
||||
private AetheriaRenderSplatRasterizer ResolveInfluenceSplatRasterizer()
|
||||
{
|
||||
if (InfluenceSplatRasterizer != null)
|
||||
return InfluenceSplatRasterizer;
|
||||
|
||||
InfluenceSplatRasterizer = GetComponent<AetheriaRenderSplatRasterizer>();
|
||||
if (InfluenceSplatRasterizer == null)
|
||||
InfluenceSplatRasterizer = gameObject.AddComponent<AetheriaRenderSplatRasterizer>();
|
||||
return InfluenceSplatRasterizer;
|
||||
}
|
||||
|
||||
private EveFieldsSplatsDocument BuildInfluenceSplatDocument(int factionIndex)
|
||||
{
|
||||
var zones = (_sectorMap?.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>()).ToArray();
|
||||
var minX = zones.Length > 0 ? zones.Min(zone => zone.X) : -1;
|
||||
var maxX = zones.Length > 0 ? zones.Max(zone => zone.X) : 1;
|
||||
var minY = zones.Length > 0 ? zones.Min(zone => zone.Y) : -1;
|
||||
var maxY = zones.Length > 0 ? zones.Max(zone => zone.Y) : 1;
|
||||
var padding = Math.Max(IconBackgroundSize * 2, 4);
|
||||
|
||||
var centerX = new List<double>();
|
||||
var centerY = new List<double>();
|
||||
var halfExtentX = new List<double>();
|
||||
var halfExtentY = new List<double>();
|
||||
var rotationCos = new List<double>();
|
||||
var rotationSin = new List<double>();
|
||||
var channel = new List<int>();
|
||||
var falloff = new List<int>();
|
||||
var valueR = new List<double>();
|
||||
var valueG = new List<double>();
|
||||
var valueB = new List<double>();
|
||||
var valueA = new List<double>();
|
||||
var sourceKey = new List<string>();
|
||||
var layerIndex = new List<int>();
|
||||
var sourceKind = new List<int>();
|
||||
var frequencyX = new List<double>();
|
||||
var frequencyY = new List<double>();
|
||||
var phaseX = new List<double>();
|
||||
var phaseY = new List<double>();
|
||||
var animationSpeed = new List<double>();
|
||||
var sourceFlags = new List<double>();
|
||||
|
||||
foreach (var zone in zones)
|
||||
{
|
||||
if (!_zoneInstances.ContainsKey(zone.ZoneIndex))
|
||||
continue;
|
||||
|
||||
var influence = ResolveZoneInfluence(zone, factionIndex);
|
||||
if (Math.Abs(influence) <= 0.0001f)
|
||||
continue;
|
||||
|
||||
centerX.Add(zone.X);
|
||||
centerY.Add(zone.Y);
|
||||
halfExtentX.Add(Math.Max(IconBackgroundSize, 1));
|
||||
halfExtentY.Add(Math.Max(IconBackgroundSize, 1));
|
||||
rotationCos.Add(1);
|
||||
rotationSin.Add(0);
|
||||
channel.Add(AetheriaRuntimeRenderSplatChannels.Influence);
|
||||
falloff.Add(AetheriaRuntimeRenderSplatFalloffs.Smooth);
|
||||
valueR.Add(influence);
|
||||
valueG.Add(influence);
|
||||
valueB.Add(influence);
|
||||
valueA.Add(1);
|
||||
sourceKey.Add($"sector-zone:{zone.ZoneIndex}:faction:{factionIndex}");
|
||||
layerIndex.Add(0);
|
||||
sourceKind.Add(AetheriaRuntimeRenderSplatSourceKinds.Constant);
|
||||
frequencyX.Add(0);
|
||||
frequencyY.Add(0);
|
||||
phaseX.Add(0);
|
||||
phaseY.Add(0);
|
||||
animationSpeed.Add(0);
|
||||
sourceFlags.Add(0);
|
||||
}
|
||||
|
||||
return new EveFieldsSplatsDocument
|
||||
{
|
||||
Schema = AetheriaRuntimeDaemonSchemas.RenderSplatsViewport,
|
||||
Viewport = new EveFieldsViewport
|
||||
foreach (var zone in ActionGameManager.CurrentGalaxy.Zones)
|
||||
{
|
||||
MinX = minX - padding,
|
||||
MinY = minY - padding,
|
||||
MaxX = maxX + padding,
|
||||
MaxY = maxY + padding
|
||||
},
|
||||
Layers = new[]
|
||||
{
|
||||
new EveFieldsSplatLayer
|
||||
if(_zoneInstances.ContainsKey(zone))
|
||||
{
|
||||
LayerKey = AetheriaRuntimeRenderSplatLayerKeys.Influence,
|
||||
DisplayName = "Sector Influence",
|
||||
Channel = AetheriaRuntimeRenderSplatChannels.Influence,
|
||||
BlendMode = AetheriaRuntimeRenderSplatBlendModes.Add,
|
||||
GraphicsFormat = "R16_SFloat"
|
||||
var instance = _zoneInstances[zone];
|
||||
var influence = 0f;
|
||||
if (zone.Factions.Length > 0)
|
||||
{
|
||||
if (zone.Factions.Contains(mega))
|
||||
{
|
||||
influence = 10;
|
||||
if (zone.Owner != mega)
|
||||
influence *= .5f;
|
||||
}
|
||||
else influence = -10;
|
||||
}
|
||||
|
||||
instance.Influence.material.SetFloat("_Depth", influence);
|
||||
}
|
||||
},
|
||||
Splats = new EveFieldsSplatSoa
|
||||
{
|
||||
Count = centerX.Count,
|
||||
CenterX = centerX,
|
||||
CenterY = centerY,
|
||||
HalfExtentX = halfExtentX,
|
||||
HalfExtentY = halfExtentY,
|
||||
RotationCos = rotationCos,
|
||||
RotationSin = rotationSin,
|
||||
Channel = channel,
|
||||
Falloff = falloff,
|
||||
ValueR = valueR,
|
||||
ValueG = valueG,
|
||||
ValueB = valueB,
|
||||
ValueA = valueA,
|
||||
SourceKey = sourceKey,
|
||||
LayerIndex = layerIndex,
|
||||
SourceKind = sourceKind,
|
||||
FrequencyX = frequencyX,
|
||||
FrequencyY = frequencyY,
|
||||
PhaseX = phaseX,
|
||||
PhaseY = phaseY,
|
||||
AnimationSpeed = animationSpeed,
|
||||
SourceFlags = sourceFlags
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static float ResolveZoneInfluence(AetheriaRuntimeSectorMapZone zone, int factionIndex)
|
||||
{
|
||||
if (zone.FactionIndices?.Count <= 0)
|
||||
return 0f;
|
||||
|
||||
if (!zone.FactionIndices.Contains(factionIndex))
|
||||
return -10f;
|
||||
|
||||
return zone.OwnerFactionIndex == factionIndex ? 10f : 5f;
|
||||
}
|
||||
|
||||
private void DisableLegacyInfluenceCamera()
|
||||
{
|
||||
if (InfluenceCamera == null)
|
||||
return;
|
||||
|
||||
InfluenceCamera.targetTexture = null;
|
||||
InfluenceCamera.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
private static float2 Position(AetheriaRuntimeSectorMapZone zone)
|
||||
{
|
||||
return new float2((float)zone.X, (float)zone.Y);
|
||||
InfluenceCamera.targetTexture = _factionMaterials[mega].influence;
|
||||
InfluenceCamera.Render();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,10 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using GameCult.Aetheria.EveRuntime;
|
||||
using GameCult.Aetheria.State.Verse;
|
||||
using GameCult.Eve.Surface;
|
||||
using GameCult.Mesh;
|
||||
using System.Linq;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
using UnityEngine.UIElements;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
using float2 = Unity.Mathematics.float2;
|
||||
|
|
@ -17,8 +12,10 @@ using float2 = Unity.Mathematics.float2;
|
|||
public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IScrollHandler
|
||||
{
|
||||
public ClickRaycaster Raycaster;
|
||||
public PropertiesPanel Properties;
|
||||
public Canvas Canvas;
|
||||
public SectorMap Map;
|
||||
public ActionGameManager GameManager;
|
||||
public Camera SectorCamera;
|
||||
public MeshRenderer SectorBackgroundRenderer;
|
||||
public float ZoomSpeed;
|
||||
|
|
@ -36,48 +33,77 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
|
|||
|
||||
private Transform _sectorBackgroundTransform;
|
||||
private Transform _sectorCameraTransform;
|
||||
private UnityEngine.UI.Image _outputImage;
|
||||
private Image _outputImage;
|
||||
private RenderTexture _outputTexture;
|
||||
private int2 _size;
|
||||
private bool _init;
|
||||
private float _aspectRatio;
|
||||
private float _sectorBackgroundDepth;
|
||||
private float _sectorCameraDepth;
|
||||
private UIDocument _zoneDetailsSurfaceDocument;
|
||||
private AetheriaClientState _runtimeState;
|
||||
private readonly AetheriaEveUnitySurfaceChrome _zoneDetailsSurfaceChrome = new AetheriaEveUnitySurfaceChrome
|
||||
{
|
||||
RootAlignItems = Align.FlexEnd,
|
||||
RootPaddingTop = 24f,
|
||||
RootPaddingRight = 24f,
|
||||
Width = 360f,
|
||||
MinWidth = 0f,
|
||||
MaxWidth = 420f,
|
||||
PaddingLeft = 18f,
|
||||
PaddingRight = 18f,
|
||||
PaddingTop = 18f,
|
||||
PaddingBottom = 18f
|
||||
};
|
||||
|
||||
private float2 _position = float2(0.5f);
|
||||
private float _viewSize = .5f;
|
||||
|
||||
private AetheriaClientState RuntimeState => _runtimeState ??= AetheriaUnityRuntimeClientProvider.RuntimeState("unity-sector-renderer");
|
||||
|
||||
void Start()
|
||||
{
|
||||
_outputImage = GetComponent<UnityEngine.UI.Image>();
|
||||
_outputImage = GetComponent<Image>();
|
||||
_sectorBackgroundTransform = SectorBackgroundRenderer.transform;
|
||||
_sectorBackgroundDepth = _sectorBackgroundTransform.position.z;
|
||||
_sectorCameraTransform = SectorCamera.transform;
|
||||
_sectorCameraDepth = _sectorCameraTransform.position.z;
|
||||
Raycaster.OnClickMiss += data =>
|
||||
{
|
||||
HideZoneDetailsSurface();
|
||||
Properties.gameObject.SetActive(false);
|
||||
};
|
||||
Map.ZoneClicked.Subscribe(zone =>
|
||||
{
|
||||
RenderZoneDetailsSurface(zone);
|
||||
Properties.gameObject.SetActive(true);
|
||||
Properties.Clear();
|
||||
Properties.Title.text = zone.Name;
|
||||
Properties.AddProperty("Owner", () => zone.Owner?.Name ?? "None");
|
||||
var otherFactions = zone.Factions
|
||||
.Where(f => f.ID != zone.Owner?.ID)
|
||||
.Select(f=>f.Name).ToArray();
|
||||
if (otherFactions.Length > 0)
|
||||
Properties.AddProperty("Factions Present", () => string.Join(", ", otherFactions));
|
||||
var density = saturate(ActionGameManager.CurrentGalaxy.Background.CloudDensity(zone.Position)/2);
|
||||
var radius = GameManager.Settings.ZoneSettings.ZoneRadius.Evaluate(density);
|
||||
var mass = GameManager.Settings.ZoneSettings.ZoneMass.Evaluate(density);
|
||||
Properties.AddProperty("Mass", () => ActionGameManager.PlayerSettings.Format(mass));
|
||||
Properties.AddProperty("Radius", () => ActionGameManager.PlayerSettings.Format(radius));
|
||||
if (zone.PackedContents == null)
|
||||
{
|
||||
Properties.AddProperty(() => "Has not been visited");
|
||||
}
|
||||
else
|
||||
{
|
||||
var planetCount = zone.PackedContents.Planets.Count(body => body is PlanetData).ToString();
|
||||
Properties.AddProperty("Planets", () => planetCount);
|
||||
|
||||
var beltCount = zone.PackedContents.Planets.Count(body => body is AsteroidBeltData).ToString();
|
||||
Properties.AddProperty("Asteroid Belts", () => beltCount);
|
||||
|
||||
var giantCount = zone.PackedContents.Planets.Count(body => body is GasGiantData && !(body is SunData)).ToString();
|
||||
Properties.AddProperty("Gas Giants", () => giantCount);
|
||||
|
||||
var starCount = zone.PackedContents.Planets.Count(body => body is SunData).ToString();
|
||||
Properties.AddProperty("Stars", () => starCount);
|
||||
|
||||
var stationCount = zone.PackedContents.Entities
|
||||
.Count(entity => ((HullData) entity.Hull.Data.Value).HullType == HullType.Station)
|
||||
.ToString();
|
||||
Properties.AddProperty("Stations", () => stationCount);
|
||||
|
||||
var turretCount = zone.PackedContents.Entities
|
||||
.Count(entity => ((HullData) entity.Hull.Data.Value).HullType == HullType.Turret)
|
||||
.ToString();
|
||||
Properties.AddProperty("Turrets", () => turretCount);
|
||||
|
||||
var shipCount = zone.PackedContents.Entities
|
||||
.Count(entity => ((HullData) entity.Hull.Data.Value).HullType == HullType.Ship)
|
||||
.ToString();
|
||||
Properties.AddProperty("Ships", () => shipCount);
|
||||
}
|
||||
});
|
||||
|
||||
// PathAnimationButton.onClick.AddListener(() =>
|
||||
|
|
@ -86,93 +112,48 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
|
|||
// });
|
||||
}
|
||||
|
||||
private void RenderZoneDetailsSurface(int zoneIndex)
|
||||
{
|
||||
var surface = ResolveZoneDetailsSurface(zoneIndex);
|
||||
if (surface == null)
|
||||
return;
|
||||
|
||||
_zoneDetailsSurfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
|
||||
transform,
|
||||
_zoneDetailsSurfaceDocument,
|
||||
"Aetheria Sector Zone Details Surface",
|
||||
surface,
|
||||
HandleZoneDetailsSurfaceCommand,
|
||||
_zoneDetailsSurfaceChrome);
|
||||
}
|
||||
|
||||
private void HandleZoneDetailsSurfaceCommand(EveSurfaceCommandRequest request)
|
||||
{
|
||||
if (!AetheriaRuntimeZoneDetailsSurfaceCommands.TryRead(request, out var command))
|
||||
{
|
||||
Debug.LogWarning($"Unknown sector-map zone details command: {request?.Command}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.Kind == AetheriaRuntimeZoneDetailsCommandKind.Close)
|
||||
{
|
||||
HideZoneDetailsSurface();
|
||||
return;
|
||||
}
|
||||
|
||||
Debug.LogWarning($"Unknown sector-map zone details command: {request?.Command}");
|
||||
}
|
||||
|
||||
private void HideZoneDetailsSurface()
|
||||
{
|
||||
if (_zoneDetailsSurfaceDocument == null)
|
||||
return;
|
||||
|
||||
AetheriaEveUnitySurfaceHost.Hide(_zoneDetailsSurfaceDocument);
|
||||
}
|
||||
|
||||
private AetheriaRuntimeSurfaceDocument ResolveZoneDetailsSurface(int zoneIndex)
|
||||
{
|
||||
if (zoneIndex < 0)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
return RuntimeState.ZoneDetailsSurface(zoneIndex).Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria sector zone details surface from managed Verse state: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// private IEnumerator AnimatePath()
|
||||
// {
|
||||
// var pathZones = ActionGameManager.CurrentSector.ExitPath;
|
||||
// LegendPanel.SetActive(false);
|
||||
// PathAnimationButton.gameObject.SetActive(false);
|
||||
//
|
||||
// var revealCount = ActionGameManager.CurrentSector.Entrance.Distance[ActionGameManager.CurrentSector.Exit];
|
||||
// Map.StartReveal(
|
||||
// PathAnimationDuration / revealCount * (LinkAnimationDuration / (IconAnimationDuration + LinkAnimationDuration)),
|
||||
// PathAnimationDuration / revealCount * (IconAnimationDuration / (IconAnimationDuration + LinkAnimationDuration)));
|
||||
// MainCamera.enabled = false;
|
||||
// SectorCamera.targetTexture = null;
|
||||
// Canvas.gameObject.SetActive(false);
|
||||
// SectorCamera.gameObject.SetActive(true);
|
||||
//
|
||||
// var pathAnimationLerp = 0f;
|
||||
// while (pathAnimationLerp < 1)
|
||||
// {
|
||||
// var currentTargetZone = pathZones[(int) (pathZones.Length * pathAnimationLerp)];
|
||||
// _position = lerp(_position, currentTargetZone.Position, PathAnimationDamping);
|
||||
// pathAnimationLerp += Time.deltaTime / (PathAnimationDuration * PathAnimationDurationPadding);
|
||||
// UpdateCamera();
|
||||
// yield return null;
|
||||
// }
|
||||
//
|
||||
// LegendPanel.SetActive(true);
|
||||
// PathAnimationButton.gameObject.SetActive(true);
|
||||
// }
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
_init = true;
|
||||
SectorCamera.gameObject.SetActive(true);
|
||||
var currentZone = ResolveCurrentZone();
|
||||
_position = currentZone == null
|
||||
? float2.zero
|
||||
: new float2((float)currentZone.PositionX, (float)currentZone.PositionY);
|
||||
_position = GameManager.Zone.GalaxyZone.Position;
|
||||
_viewSize = .25f;
|
||||
|
||||
Map.StartReveal(LinkAnimationDuration, IconAnimationDuration);
|
||||
if (currentZone != null)
|
||||
Map.TryMarkPlayerLocation(currentZone.ZoneIndex);
|
||||
}
|
||||
|
||||
private AetheriaRuntimeCurrentZoneDocument ResolveCurrentZone()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RuntimeState.CurrentZone.Latest();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogWarning($"Failed to read Aetheria sector current zone from managed Verse state: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
Map.MarkPlayerLocation(GameManager.CurrentEntity.Zone.GalaxyZone);
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
HideZoneDetailsSurface();
|
||||
if (_outputTexture != null)
|
||||
{
|
||||
_outputTexture.Release();
|
||||
|
|
@ -181,15 +162,6 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
|
|||
SectorCamera.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (_zoneDetailsSurfaceDocument != null)
|
||||
{
|
||||
AetheriaEveUnitySurfaceHost.DestroyDocument(_zoneDetailsSurfaceDocument);
|
||||
_zoneDetailsSurfaceDocument = null;
|
||||
}
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
var size = int2(Screen.width, Screen.height);
|
||||
|
|
@ -201,7 +173,7 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
|
|||
{
|
||||
_outputTexture.Release();
|
||||
}
|
||||
_outputTexture = new RenderTexture(_size.x, _size.y, 16, RenderTextureFormat.Default);
|
||||
_outputTexture = new RenderTexture(_size.x, _size.y, 0, RenderTextureFormat.Default);
|
||||
SectorCamera.targetTexture = _outputTexture;
|
||||
_outputImage.material.SetTexture("_DetailTex", _outputTexture);
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
472
Assets/Scripts/UI/Menu/TradeMenuDebug.cs
Normal file
472
Assets/Scripts/UI/Menu/TradeMenuDebug.cs
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Remoting.Contexts;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class TradeMenuDebug : MonoBehaviour
|
||||
{
|
||||
public ActionGameManager GameManager;
|
||||
public ContextMenu ContextMenu;
|
||||
public ConfirmationDialog Dialog;
|
||||
public Button NewFilterButton;
|
||||
public Prototype FilterPrototype;
|
||||
public SizeFilter MinimumSizeFilter;
|
||||
public SizeFilter MaximumSizeFilter;
|
||||
public PropertiesPanel Properties;
|
||||
public Spreadsheet Spreadsheet;
|
||||
public TextMeshProUGUI TargetCargoLabel;
|
||||
public Button FoldoutButton;
|
||||
|
||||
private EquippedCargoBay _targetCargo;
|
||||
private (ItemFilter filter, HardpointType type) _hardpointFilter;
|
||||
private (ItemFilter filter, SimpleCommodityCategory type) _commodityFilter;
|
||||
private (ItemFilter filter, CompoundCommodityCategory type) _compoundCommodityFilter;
|
||||
private List<(ItemFilter filter, Type type)> _behaviorFilters = new List<(ItemFilter filter, Type type)>();
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
_targetCargo = GameManager.DockingBay;
|
||||
TargetCargoLabel.text = "Docking Bay";
|
||||
Properties.GameManager = GameManager;
|
||||
MinimumSizeFilter.Width.onEndEdit.AddListener(_ => Populate());
|
||||
MinimumSizeFilter.Height.onEndEdit.AddListener(_ => Populate());
|
||||
MaximumSizeFilter.Width.onEndEdit.AddListener(_ => Populate());
|
||||
MaximumSizeFilter.Height.onEndEdit.AddListener(_ => Populate());
|
||||
NewFilterButton.onClick.AddListener(() =>
|
||||
{
|
||||
ContextMenu.Clear();
|
||||
IEnumerable<HardpointType> hardpointTypes = (HardpointType[]) Enum.GetValues(typeof(HardpointType));
|
||||
if (_hardpointFilter.filter != null)
|
||||
hardpointTypes = hardpointTypes.Where(x => x != _hardpointFilter.type);
|
||||
|
||||
IEnumerable<SimpleCommodityCategory> commodityTypes = (SimpleCommodityCategory[]) Enum.GetValues(typeof(SimpleCommodityCategory));
|
||||
if (_commodityFilter.filter != null)
|
||||
commodityTypes = commodityTypes.Where(x => x != _commodityFilter.type);
|
||||
|
||||
IEnumerable<CompoundCommodityCategory> compoundCommodityTypes = (CompoundCommodityCategory[]) Enum.GetValues(typeof(CompoundCommodityCategory));
|
||||
if (_compoundCommodityFilter.filter != null)
|
||||
compoundCommodityTypes = compoundCommodityTypes.Where(x => x != _compoundCommodityFilter.type);
|
||||
|
||||
ContextMenu.AddDropdown("Gear Type", hardpointTypes
|
||||
.Select<HardpointType, (string, Action, bool)>(x => (Enum.GetName(typeof(HardpointType), x), () =>
|
||||
{
|
||||
if (_hardpointFilter.filter == null)
|
||||
{
|
||||
_hardpointFilter.filter = FilterPrototype.Instantiate<ItemFilter>();
|
||||
_hardpointFilter.filter.OnDisable += () =>
|
||||
{
|
||||
_hardpointFilter.filter = null;
|
||||
Populate();
|
||||
};
|
||||
}
|
||||
if(_commodityFilter.filter != null)
|
||||
{
|
||||
_commodityFilter.filter.GetComponent<Prototype>().ReturnToPool();
|
||||
_commodityFilter.filter = null;
|
||||
}
|
||||
if(_compoundCommodityFilter.filter != null)
|
||||
{
|
||||
_compoundCommodityFilter.filter.GetComponent<Prototype>().ReturnToPool();
|
||||
_compoundCommodityFilter.filter = null;
|
||||
}
|
||||
|
||||
_hardpointFilter.filter.Label.text = $"Hardpoint: {Enum.GetName(typeof(HardpointType), x)}";
|
||||
_hardpointFilter.type = x;
|
||||
Populate();
|
||||
}, true)));
|
||||
ContextMenu.AddDropdown("Simple Commodity", commodityTypes
|
||||
.Select<SimpleCommodityCategory, (string, Action, bool)>(x => (Enum.GetName(typeof(SimpleCommodityCategory), x), () =>
|
||||
{
|
||||
if (_commodityFilter.filter == null)
|
||||
{
|
||||
_commodityFilter.filter = FilterPrototype.Instantiate<ItemFilter>();
|
||||
_commodityFilter.filter.OnDisable += () =>
|
||||
{
|
||||
_commodityFilter.filter = null;
|
||||
Populate();
|
||||
};
|
||||
}
|
||||
if(_hardpointFilter.filter != null)
|
||||
{
|
||||
_hardpointFilter.filter.GetComponent<Prototype>().ReturnToPool();
|
||||
_hardpointFilter.filter = null;
|
||||
}
|
||||
if(_compoundCommodityFilter.filter != null)
|
||||
{
|
||||
_compoundCommodityFilter.filter.GetComponent<Prototype>().ReturnToPool();
|
||||
_compoundCommodityFilter.filter = null;
|
||||
}
|
||||
|
||||
_commodityFilter.filter.Label.text = $"Hardpoint: {Enum.GetName(typeof(SimpleCommodityCategory), x)}";
|
||||
_commodityFilter.type = x;
|
||||
Populate();
|
||||
}, true)));
|
||||
ContextMenu.AddDropdown("Compound Commodity", compoundCommodityTypes
|
||||
.Select<CompoundCommodityCategory, (string, Action, bool)>(x => (Enum.GetName(typeof(CompoundCommodityCategory), x), () =>
|
||||
{
|
||||
if (_compoundCommodityFilter.filter == null)
|
||||
{
|
||||
_compoundCommodityFilter.filter = FilterPrototype.Instantiate<ItemFilter>();
|
||||
_compoundCommodityFilter.filter.OnDisable += () =>
|
||||
{
|
||||
_compoundCommodityFilter.filter = null;
|
||||
Populate();
|
||||
};
|
||||
}
|
||||
if(_hardpointFilter.filter != null)
|
||||
{
|
||||
_hardpointFilter.filter.GetComponent<Prototype>().ReturnToPool();
|
||||
_hardpointFilter.filter = null;
|
||||
}
|
||||
if(_commodityFilter.filter != null)
|
||||
{
|
||||
_commodityFilter.filter.GetComponent<Prototype>().ReturnToPool();
|
||||
_commodityFilter.filter = null;
|
||||
}
|
||||
|
||||
_compoundCommodityFilter.filter.Label.text = $"Hardpoint: {Enum.GetName(typeof(CompoundCommodityCategory), x)}";
|
||||
_compoundCommodityFilter.type = x;
|
||||
Populate();
|
||||
}, true)));
|
||||
ContextMenu.AddDropdown("Item Behavior", typeof(BehaviorData).GetAllChildClasses()
|
||||
.Where(x=> x.GetCustomAttribute<RuntimeInspectable>() != null && _behaviorFilters.All(f => f.type != x))
|
||||
.Select<Type, (string, Action, bool)>(x=> (x.Name.FormatTypeName(), () =>
|
||||
{
|
||||
var matchingType = _behaviorFilters.FirstOrDefault(y => y.type.IsAssignableFrom(x) || x.IsAssignableFrom(y.type));
|
||||
if (matchingType.filter != null) matchingType.filter.DisableButton.onClick.Invoke();
|
||||
var filter = FilterPrototype.Instantiate<ItemFilter>();
|
||||
filter.Label.text = x.Name.FormatTypeName();
|
||||
filter.OnDisable += () =>
|
||||
{
|
||||
_behaviorFilters.Remove((filter, x));
|
||||
Populate();
|
||||
};
|
||||
_behaviorFilters.Add((filter, x));
|
||||
Populate();
|
||||
}, true)));
|
||||
if(!MinimumSizeFilter.gameObject.activeSelf)
|
||||
ContextMenu.AddOption("Minimum Size",
|
||||
() =>
|
||||
{
|
||||
MinimumSizeFilter.gameObject.SetActive(true);
|
||||
MinimumSizeFilter.OnDisable += () => Populate();
|
||||
});
|
||||
if(!MaximumSizeFilter.gameObject.activeSelf)
|
||||
ContextMenu.AddOption("Maximum Size",
|
||||
() =>
|
||||
{
|
||||
MaximumSizeFilter.gameObject.SetActive(true);
|
||||
MaximumSizeFilter.OnDisable += () => Populate();
|
||||
});
|
||||
ContextMenu.Show();
|
||||
});
|
||||
Populate();
|
||||
}
|
||||
|
||||
void Populate()
|
||||
{
|
||||
var columns = new List<(string name, int size, Func<ItemData, Func<string>> output, Func<ItemData, IComparable> sortKey)>();
|
||||
|
||||
columns.Add(("Name", 3,
|
||||
data => () => data.Name,
|
||||
data => data.Name));
|
||||
if(_hardpointFilter.filter==null)
|
||||
columns.Add(("Type", 2,
|
||||
data => () =>
|
||||
{
|
||||
if (data is SimpleCommodityData s) return Enum.GetName(typeof(SimpleCommodityCategory), s.Category);
|
||||
if(data is CompoundCommodityData c) return Enum.GetName(typeof(CompoundCommodityCategory), c.Category);
|
||||
if(data is EquippableItemData e) return Enum.GetName(typeof(HardpointType), e.HardpointType);
|
||||
return "None";
|
||||
},
|
||||
data =>
|
||||
{
|
||||
if (data is SimpleCommodityData s) return (int) s.Category;
|
||||
var offset = Enum.GetValues(typeof(SimpleCommodityCategory)).Length;
|
||||
if(data is CompoundCommodityData c) return (int) c.Category + offset;
|
||||
offset += Enum.GetValues(typeof(CompoundCommodityCategory)).Length;
|
||||
if(data is EquippableItemData e) return (int) e.HardpointType + offset;
|
||||
return 0;
|
||||
}));
|
||||
columns.Add(("Mass", 1,
|
||||
data => () => ActionGameManager.PlayerSettings.Format(data.Mass),
|
||||
data => data.Mass));
|
||||
columns.Add(("Price", 1,
|
||||
data => () => data.Price.ToString("N0"),
|
||||
data => data.Price));
|
||||
columns.Add(("Size", 1,
|
||||
data => () => $"{data.Shape.Width}x{data.Shape.Height}",
|
||||
data => data.Shape.Width*data.Shape.Height));
|
||||
|
||||
var items = GameManager.ItemManager.ItemData.GetAll<ItemData>().Where(i=>i.Price!=0);
|
||||
|
||||
if (MinimumSizeFilter.gameObject.activeSelf)
|
||||
items = items.Where(i =>
|
||||
!(MinimumSizeFilter.Width.text.Length > 0 && i.Shape.Width < int.Parse(MinimumSizeFilter.Width.text) ||
|
||||
MinimumSizeFilter.Height.text.Length > 0 && i.Shape.Height < int.Parse(MinimumSizeFilter.Height.text)));
|
||||
|
||||
if (MaximumSizeFilter.gameObject.activeSelf)
|
||||
items = items.Where(i =>
|
||||
!(MaximumSizeFilter.Width.text.Length > 0 && i.Shape.Width > int.Parse(MaximumSizeFilter.Width.text) ||
|
||||
MaximumSizeFilter.Height.text.Length > 0 && i.Shape.Height > int.Parse(MaximumSizeFilter.Height.text)));
|
||||
|
||||
if(_commodityFilter.filter != null)
|
||||
items = items.Where(i => i is SimpleCommodityData s && s.Category == _commodityFilter.type);
|
||||
|
||||
if(_compoundCommodityFilter.filter != null)
|
||||
items = items.Where(i => i is CompoundCommodityData c && c.Category == _compoundCommodityFilter.type);
|
||||
|
||||
if (_hardpointFilter.filter != null)
|
||||
items = items.Where(i => i is EquippableItemData e && e.HardpointType == _hardpointFilter.type);
|
||||
|
||||
foreach (var (_, type) in _behaviorFilters)
|
||||
{
|
||||
items = items.Where(i => i is EquippableItemData e && e.Behaviors.Any(b => type.IsInstanceOfType(b)));
|
||||
|
||||
foreach (var field in type.GetFields().Where(f => f.GetCustomAttribute<RuntimeInspectable>() != null))
|
||||
{
|
||||
var fieldType = field.FieldType;
|
||||
if (fieldType == typeof(float))
|
||||
columns.Add((field.Name, 1, data =>
|
||||
{
|
||||
var behavior = ((EquippableItemData) data).Behaviors.FirstOrDefault(b => type.IsInstanceOfType(b));
|
||||
return () => ActionGameManager.PlayerSettings.Format((float) field.GetValue(behavior));
|
||||
}, data =>
|
||||
{
|
||||
var behavior = ((EquippableItemData) data).Behaviors.FirstOrDefault(b => type.IsInstanceOfType(b));
|
||||
return (float) field.GetValue(behavior);
|
||||
}));
|
||||
else if (fieldType == typeof(int))
|
||||
columns.Add((field.Name, 1, data =>
|
||||
{
|
||||
var behavior = ((EquippableItemData) data).Behaviors.FirstOrDefault(b => type.IsInstanceOfType(b));
|
||||
return () => ((int) field.GetValue(behavior)).ToString();
|
||||
}, data =>
|
||||
{
|
||||
var behavior = ((EquippableItemData) data).Behaviors.FirstOrDefault(b => type.IsInstanceOfType(b));
|
||||
return (int) field.GetValue(behavior);
|
||||
}));
|
||||
else if (fieldType == typeof(PerformanceStat))
|
||||
{
|
||||
columns.Add((field.Name, 1, data =>
|
||||
{
|
||||
var behavior = ((EquippableItemData) data).Behaviors.FirstOrDefault(b => type.IsInstanceOfType(b));
|
||||
return () => ActionGameManager.PlayerSettings.Format(((PerformanceStat) field.GetValue(behavior)).Max);
|
||||
}, data =>
|
||||
{
|
||||
var behavior = ((EquippableItemData) data).Behaviors.FirstOrDefault(b => type.IsInstanceOfType(b));
|
||||
return ((PerformanceStat) field.GetValue(behavior)).Max;
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
columns.Add(("Owned", 1,
|
||||
data => () =>
|
||||
{
|
||||
if (data is HullData)
|
||||
return GameManager.DockedEntity.Children.Count(s => s.Hull.Data.LinkID == data.ID && s is Ship {IsPlayerShip: true}).ToString();
|
||||
if(data is SimpleCommodityData)
|
||||
return (_targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0).ToString();
|
||||
return (_targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Count : 0).ToString();
|
||||
},
|
||||
data =>
|
||||
{
|
||||
if (data is HullData)
|
||||
return GameManager.DockedEntity.Children.Count(s => s.Hull.Data.LinkID == data.ID && s is Ship {IsPlayerShip: true});
|
||||
if(data is SimpleCommodityData)
|
||||
return _targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0;
|
||||
return _targetCargo.ItemsOfType.ContainsKey(data.ID) ? _targetCargo.ItemsOfType[data.ID].Count : 0;
|
||||
}));
|
||||
|
||||
Spreadsheet.ShowData(
|
||||
columns.Select(x => x.name).ToArray(),
|
||||
columns.Select(x => x.size).ToArray(),
|
||||
items.Select(i => new SpreadsheetEntryRow
|
||||
{
|
||||
Columns = columns.Select(x => new SpreadsheetEntryColumn
|
||||
{
|
||||
Output = x.output(i),
|
||||
SortKey = x.sortKey(i)
|
||||
}).ToArray(),
|
||||
OnClick = () =>
|
||||
{
|
||||
Properties.Inspect(i);
|
||||
},
|
||||
OnDoubleClick = () =>
|
||||
{
|
||||
switch (i)
|
||||
{
|
||||
case HullData h:
|
||||
Buy(h);
|
||||
break;
|
||||
case CraftedItemData c:
|
||||
Buy(c,1);
|
||||
break;
|
||||
case SimpleCommodityData s:
|
||||
Buy(s, 1);
|
||||
break;
|
||||
}
|
||||
|
||||
Populate();
|
||||
},
|
||||
OnRightClick = () =>
|
||||
{
|
||||
if (!(i is HullData))
|
||||
{
|
||||
ContextMenu.Clear();
|
||||
ContextMenu.AddOption("Buy Quantity",
|
||||
() =>
|
||||
{
|
||||
int quantity = 1;
|
||||
Dialog.Clear();
|
||||
Dialog.Title.text = $"Buying {i.Name}";
|
||||
Dialog.AddField("Quantity", () => quantity, q => quantity = min(q, GameManager.Credits/i.Price));
|
||||
Dialog.Show(() =>
|
||||
{
|
||||
switch (i)
|
||||
{
|
||||
case CraftedItemData c:
|
||||
Buy(c,quantity);
|
||||
break;
|
||||
case SimpleCommodityData s:
|
||||
Buy(s, quantity);
|
||||
break;
|
||||
}
|
||||
|
||||
Populate();
|
||||
});
|
||||
Dialog.MoveToCursor();
|
||||
});
|
||||
ContextMenu.Show();
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private void Buy(HullData data)
|
||||
{
|
||||
if (data.Price < GameManager.Credits)
|
||||
{
|
||||
var hull = GameManager.ItemManager.CreateInstance(data) as EquippableItem;
|
||||
Entity entity;
|
||||
if(data.HullType==HullType.Ship)
|
||||
entity = new Ship(GameManager.ItemManager, GameManager.Zone, hull, GameManager.Settings.GameplaySettings.DefaultEntitySettings) {IsPlayerShip = true};
|
||||
else entity = new OrbitalEntity(GameManager.ItemManager, GameManager.Zone, hull, Guid.Empty, GameManager.Settings.GameplaySettings.DefaultEntitySettings);
|
||||
entity.SetParent(GameManager.DockedEntity);
|
||||
|
||||
GameManager.Credits -= data.Price;
|
||||
}
|
||||
else
|
||||
{
|
||||
Dialog.Clear();
|
||||
Dialog.Title.text = "Unable to buy: Insufficient Credits!";
|
||||
Dialog.Show();
|
||||
Dialog.MoveToCursor();
|
||||
}
|
||||
}
|
||||
|
||||
private void Buy(CraftedItemData data, int quantity)
|
||||
{
|
||||
for (int i = 0; i < quantity; i++)
|
||||
{
|
||||
if (data.Price < GameManager.Credits)
|
||||
{
|
||||
if (_targetCargo.TryStore(GameManager.ItemManager.CreateInstance(data)))
|
||||
{
|
||||
GameManager.Credits -= data.Price;
|
||||
}
|
||||
else
|
||||
{
|
||||
Dialog.Clear();
|
||||
Dialog.Title.text = "Unable to buy: Insufficient Cargo Space!";
|
||||
Dialog.Show();
|
||||
Dialog.MoveToCursor();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Dialog.Clear();
|
||||
Dialog.Title.text = "Unable to buy: Insufficient Credits!";
|
||||
Dialog.Show();
|
||||
Dialog.MoveToCursor();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Buy(SimpleCommodityData data, int quantity)
|
||||
{
|
||||
// Up-rounded integer division from https://stackoverflow.com/a/503201
|
||||
int lots = (quantity - 1) / data.MaxStack + 1;
|
||||
int remaining = quantity;
|
||||
for (int i = 0; i < lots; i++)
|
||||
{
|
||||
int q = min(remaining, data.MaxStack);
|
||||
if (q * data.Price < GameManager.Credits)
|
||||
{
|
||||
if (_targetCargo.TryStore(GameManager.ItemManager.CreateInstance(data, q)))
|
||||
{
|
||||
GameManager.Credits -= q * data.Price;
|
||||
remaining -= q;
|
||||
}
|
||||
else
|
||||
{
|
||||
Dialog.Clear();
|
||||
Dialog.Title.text = "Unable to buy: Insufficient Cargo Space!";
|
||||
Dialog.Show();
|
||||
Dialog.MoveToCursor();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Dialog.Clear();
|
||||
Dialog.Title.text = "Unable to buy: Insufficient Credits!";
|
||||
Dialog.Show();
|
||||
Dialog.MoveToCursor();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
FoldoutButton.onClick.AddListener(() =>
|
||||
{
|
||||
ContextMenu.Clear();
|
||||
if(_targetCargo != GameManager.DockingBay)
|
||||
ContextMenu.AddOption("Docking Bay",
|
||||
() =>
|
||||
{
|
||||
_targetCargo = GameManager.DockingBay;
|
||||
TargetCargoLabel.text = "Docking Bay";
|
||||
});
|
||||
foreach (var ship in GameManager.CurrentEntity.Parent.Children.Where(e => e is Ship {IsPlayerShip: true}))
|
||||
{
|
||||
foreach (var bay in ship.CargoBays.Select((bay, index) => (bay, index)))
|
||||
ContextMenu.AddOption($"{ship.Name} Bay {bay.index}",
|
||||
() =>
|
||||
{
|
||||
_targetCargo = bay.bay;
|
||||
TargetCargoLabel.text = $"{ship.Name} Bay {bay.index}";
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
3
Assets/Scripts/UI/Menu/TradeMenuDebug.cs.meta
Normal file
3
Assets/Scripts/UI/Menu/TradeMenuDebug.cs.meta
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6eed32eb39c04a31b81e8a55685b222c
|
||||
timeCreated: 1616191013
|
||||
65
Assets/Scripts/UI/Menu/WeaponGroupAssignment.cs
Normal file
65
Assets/Scripts/UI/Menu/WeaponGroupAssignment.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
public class WeaponGroupAssignment : MonoBehaviour
|
||||
{
|
||||
public RectTransform Container;
|
||||
public WeaponGroupElement GroupPrefab;
|
||||
public Color ActiveColor;
|
||||
public Color InactiveColor;
|
||||
|
||||
Subject<(PointerEventData pointerEventData, int group)> _onBeginDrag;
|
||||
Subject<(PointerEventData pointerEventData, int group)> _onDrag;
|
||||
Subject<(PointerEventData pointerEventData, int group)> _onEndDrag;
|
||||
|
||||
public List<WeaponGroupElement> Groups { get; } = new List<WeaponGroupElement>();
|
||||
|
||||
public void Inspect(EquippedItem item)
|
||||
{
|
||||
var weapon = item.GetBehavior<Weapon>();
|
||||
if (weapon == null) throw new ArgumentException($"Attempted to inspect weapon groups on item \"{item.Data.Name}\" but no weapon is present!");
|
||||
var groupCount = ActionGameManager.Instance.Settings.GameplaySettings.WeaponGroupCount;
|
||||
for (int i = 0; i < groupCount; i++)
|
||||
{
|
||||
var i1 = i;
|
||||
bool groupContainsItem() => item.Entity.WeaponGroups[i1].items.Contains(item);
|
||||
var group = Instantiate(GroupPrefab, Container);
|
||||
Groups.Add(group);
|
||||
group.Label.text = $"G{i+1}";
|
||||
group.Label.color = groupContainsItem() ? ActiveColor : InactiveColor;
|
||||
group.Button.onClick.AddListener(() =>
|
||||
{
|
||||
if (groupContainsItem())
|
||||
{
|
||||
item.Entity.WeaponGroups[i1].items.Remove(item);
|
||||
item.Entity.WeaponGroups[i1].weapons.Remove(weapon);
|
||||
group.Label.color = InactiveColor;
|
||||
}
|
||||
else
|
||||
{
|
||||
item.Entity.WeaponGroups[i1].items.Add(item);
|
||||
item.Entity.WeaponGroups[i1].weapons.Add(weapon);
|
||||
group.Label.color = ActiveColor;
|
||||
}
|
||||
});
|
||||
|
||||
group.BeginDragTrigger.OnBeginDragAsObservable()
|
||||
.Subscribe(data => _onBeginDrag?.OnNext((data, i1)));
|
||||
group.DragTrigger.OnDragAsObservable()
|
||||
.Subscribe(data => _onDrag?.OnNext((data, i1)));
|
||||
group.EndDragTrigger.OnEndDragAsObservable()
|
||||
.Subscribe(data => _onEndDrag?.OnNext((data, i1)));
|
||||
}
|
||||
}
|
||||
|
||||
public UniRx.IObservable<(PointerEventData pointerEventData, int group)> OnBeginDragAsObservable() =>
|
||||
_onBeginDrag ?? (_onBeginDrag = new Subject<(PointerEventData pointerEventData, int group)>());
|
||||
public UniRx.IObservable<(PointerEventData pointerEventData, int group)> OnDragAsObservable() =>
|
||||
_onDrag ?? (_onDrag = new Subject<(PointerEventData pointerEventData, int group)>());
|
||||
public UniRx.IObservable<(PointerEventData pointerEventData, int group)> OnEndDragAsObservable() =>
|
||||
_onEndDrag ?? (_onEndDrag = new Subject<(PointerEventData pointerEventData, int group)>());
|
||||
}
|
||||
11
Assets/Scripts/UI/Menu/WeaponGroupAssignment.cs.meta
Normal file
11
Assets/Scripts/UI/Menu/WeaponGroupAssignment.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b9b213fc96d20d848819b8159412680c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
15
Assets/Scripts/UI/Menu/WeaponGroupElement.cs
Normal file
15
Assets/Scripts/UI/Menu/WeaponGroupElement.cs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using TMPro;
|
||||
using UniRx.Triggers;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class WeaponGroupElement : MonoBehaviour
|
||||
{
|
||||
public TextMeshProUGUI Label;
|
||||
public Button Button;
|
||||
public ObservableBeginDragTrigger BeginDragTrigger;
|
||||
public ObservableDragTrigger DragTrigger;
|
||||
public ObservableEndDragTrigger EndDragTrigger;
|
||||
}
|
||||
11
Assets/Scripts/UI/Menu/WeaponGroupElement.cs.meta
Normal file
11
Assets/Scripts/UI/Menu/WeaponGroupElement.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 27f5673ad060b834489cad765159cb84
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
89
Assets/Scripts/UI/Properties Panel/PropertiesList.cs
Normal file
89
Assets/Scripts/UI/Properties Panel/PropertiesList.cs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class PropertiesList : PropertiesPanel
|
||||
{
|
||||
public Image FoldoutIcon;
|
||||
public float FoldoutRotationDamping;
|
||||
public Button Button;
|
||||
public VerticalLayoutGroup LayoutGroup;
|
||||
public int FoldedPadding = -8;
|
||||
public int ExpandedPadding = 8;
|
||||
public event Action<bool> OnExpand;
|
||||
|
||||
private bool _expanded = false;
|
||||
private float _targetFoldoutRotation = 0;
|
||||
private float _foldoutRotation = 0;
|
||||
|
||||
public bool Expanded => _expanded;
|
||||
|
||||
public new void Awake()
|
||||
{
|
||||
Button.onClick.AddListener(ToggleExpand);
|
||||
OnPropertyAdded += go => go.SetActive(_expanded);
|
||||
//SetExpanded(true, true);
|
||||
}
|
||||
|
||||
public override void Update()
|
||||
{
|
||||
RefreshValues();
|
||||
_foldoutRotation =
|
||||
Mathf.Lerp(_foldoutRotation, _targetFoldoutRotation, FoldoutRotationDamping * Time.deltaTime);
|
||||
FoldoutIcon.transform.localRotation = Quaternion.Euler(0,0, _foldoutRotation);
|
||||
}
|
||||
|
||||
public void ToggleExpand() => SetExpanded(!_expanded, false);
|
||||
|
||||
public void SetExpanded(bool expanded, bool force)
|
||||
{
|
||||
_expanded = expanded;
|
||||
var padding = LayoutGroup.padding;
|
||||
padding = new RectOffset(padding.left, padding.right, padding.top, _expanded ? ExpandedPadding : FoldedPadding);
|
||||
LayoutGroup.padding = padding;
|
||||
foreach (var property in Properties) property.SetActive(_expanded);
|
||||
_targetFoldoutRotation = _expanded ? -90 : 0;
|
||||
if (force)
|
||||
{
|
||||
_foldoutRotation = _targetFoldoutRotation;
|
||||
FoldoutIcon.transform.localRotation = Quaternion.Euler(0,0, _foldoutRotation);
|
||||
}
|
||||
OnExpand?.Invoke(_expanded);
|
||||
}
|
||||
|
||||
// public override PropertyLabel AddProperty(string name, Func<string> read = null, Action<PointerEventData> onClick = null, bool radio = false)
|
||||
// {
|
||||
// var prop = base.AddProperty(name, read, onClick, radio);
|
||||
// prop.gameObject.SetActive(false);
|
||||
// return prop;
|
||||
// }
|
||||
//
|
||||
// public override PropertiesList AddList(string name)
|
||||
// {
|
||||
// var list = base.AddList(name);
|
||||
// list.gameObject.SetActive(false);
|
||||
// return list;
|
||||
// }
|
||||
//
|
||||
// public override RectTransform AddSection(string name)
|
||||
// {
|
||||
// var section = base.AddSection(name);
|
||||
// section.gameObject.SetActive(false);
|
||||
// return section;
|
||||
// }
|
||||
//
|
||||
// public override PropertyButton AddButton(string name, Action<PointerEventData> onClick)
|
||||
// {
|
||||
// var button = base.AddButton(name, onClick);
|
||||
// button.gameObject.SetActive(false);
|
||||
// return button;
|
||||
// }
|
||||
}
|
||||
11
Assets/Scripts/UI/Properties Panel/PropertiesList.cs.meta
Normal file
11
Assets/Scripts/UI/Properties Panel/PropertiesList.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 2544c9c8b6358c54ea58c5fb33bb48b7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
661
Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs
Normal file
661
Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
/* 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;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
using Unity.Mathematics;
|
||||
using static Unity.Mathematics.math;
|
||||
|
||||
public class PropertiesPanel : MonoBehaviour
|
||||
{
|
||||
public RectTransform Spacer;
|
||||
public DropdownMenu Dropdown;
|
||||
public TextMeshProUGUI Title;
|
||||
public RectTransform Section;
|
||||
public PropertiesList List;
|
||||
public Property Property;
|
||||
public PropertyLabel PropertyLabel;
|
||||
public AttributeProperty Attribute;
|
||||
public InputField InputField;
|
||||
public RangedFloatField RangedFloatField;
|
||||
public RangedFloatField ProgressField;
|
||||
public EnumField EnumField;
|
||||
public BoolField BoolField;
|
||||
public PropertyButton PropertyButton;
|
||||
public ButtonField ButtonField;
|
||||
public IncrementField IncrementField;
|
||||
public StatSheet StatSheet;
|
||||
public CurveField CurveField;
|
||||
public WeaponGroupAssignment WeaponGroupAssignment;
|
||||
public RectTransform Content;
|
||||
public RectTransform DragParent;
|
||||
|
||||
[HideInInspector] public ActionGameManager GameManager;
|
||||
|
||||
protected List<GameObject> Properties = new List<GameObject>();
|
||||
protected event Action RefreshPropertyValues;
|
||||
protected bool RadioSelection = false;
|
||||
|
||||
private RectTransform _dragObject;
|
||||
|
||||
|
||||
protected event Action<GameObject> OnPropertyAdded;
|
||||
protected Action OnPropertiesChanged;
|
||||
|
||||
public int Children => Properties.Count;
|
||||
|
||||
public void Awake()
|
||||
{
|
||||
OnPropertyAdded += go => go.SetActive(true);
|
||||
}
|
||||
|
||||
public virtual void Update()
|
||||
{
|
||||
RefreshValues();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
}
|
||||
|
||||
// private void OnDisable()
|
||||
// {
|
||||
// RemoveListener();
|
||||
// }
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
//RemoveListener();
|
||||
foreach(var property in Properties)
|
||||
Destroy(property);
|
||||
Title.text = "Properties";
|
||||
Properties.Clear();
|
||||
RefreshPropertyValues = null;
|
||||
RadioSelection = false;
|
||||
}
|
||||
|
||||
public RectTransform AddSpacer()
|
||||
{
|
||||
var spacer = Instantiate(Spacer, Content ?? transform);
|
||||
Properties.Add(spacer.gameObject);
|
||||
OnPropertyAdded?.Invoke(spacer.gameObject);
|
||||
return spacer;
|
||||
}
|
||||
|
||||
public RectTransform AddSection(string name)
|
||||
{
|
||||
var section = Instantiate(Section, Content ?? transform);
|
||||
section.GetComponentInChildren<TextMeshProUGUI>().text = name;
|
||||
Properties.Add(section.gameObject);
|
||||
OnPropertyAdded?.Invoke(section.gameObject);
|
||||
return section;
|
||||
}
|
||||
|
||||
public Property AddProperty(Func<string> read)
|
||||
{
|
||||
if (read == null) throw new ArgumentException("Attempted to add property with null read function!");
|
||||
|
||||
var property = Instantiate(Property, Content ?? transform);
|
||||
property.Label.text = read();
|
||||
|
||||
RefreshPropertyValues += () => property.Label.text = read();
|
||||
Properties.Add(property.gameObject);
|
||||
OnPropertyAdded?.Invoke(property.gameObject);
|
||||
return property;
|
||||
}
|
||||
|
||||
public Property AddProperty(string name, Func<string> read = null)
|
||||
{
|
||||
Property property;
|
||||
if(read != null)
|
||||
property = Instantiate(PropertyLabel, Content ?? transform);
|
||||
else
|
||||
property = Instantiate(Property, Content ?? transform);
|
||||
property.Label.text = name;
|
||||
|
||||
if (read != null)
|
||||
RefreshPropertyValues += () => ((PropertyLabel) property).Value.text = read.Invoke();
|
||||
Properties.Add(property.gameObject);
|
||||
OnPropertyAdded?.Invoke(property.gameObject);
|
||||
return property;
|
||||
}
|
||||
|
||||
public StatSheet AddStatSheet()
|
||||
{
|
||||
var sheet = Instantiate(StatSheet, Content ?? transform);
|
||||
Properties.Add(sheet.gameObject);
|
||||
OnPropertyAdded?.Invoke(sheet.gameObject);
|
||||
RefreshPropertyValues += () => sheet.RefreshValues();
|
||||
return sheet;
|
||||
}
|
||||
|
||||
public PropertiesList AddList(string name) //, IEnumerable<(string, Func<string>)> elements)
|
||||
{
|
||||
var list = Instantiate(List, Content ?? transform);
|
||||
list.GameManager = GameManager;
|
||||
list.Dropdown = Dropdown;
|
||||
list.Title.text = name;
|
||||
// foreach (var element in elements)
|
||||
// {
|
||||
// var item = Instantiate(PropertyPrefab, list);
|
||||
// item.Name.text = element.Item1;
|
||||
// item.Value.text = element.Item2();
|
||||
// item.ValueFunction = element.Item2;
|
||||
// Properties.Add(item.gameObject);
|
||||
// }
|
||||
//RefreshPropertyValues += () => list.RefreshValues();
|
||||
Properties.Add(list.gameObject);
|
||||
OnPropertyAdded?.Invoke(list.gameObject);
|
||||
return list;
|
||||
}
|
||||
|
||||
public AttributeProperty AddPersonalityProperty(PersonalityAttribute attribute, Func<float> read)
|
||||
{
|
||||
var attributeInstance = Instantiate(Attribute, Content ?? transform);
|
||||
attributeInstance.Title.text = attribute.Name;
|
||||
attributeInstance.HighLabel.text = attribute.HighName;
|
||||
attributeInstance.LowLabel.text = attribute.LowName;
|
||||
RefreshPropertyValues += () => attributeInstance.Slider.value = read();
|
||||
Properties.Add(attributeInstance.gameObject);
|
||||
OnPropertyAdded?.Invoke(attributeInstance.gameObject);
|
||||
return attributeInstance;
|
||||
}
|
||||
|
||||
public CurveField AddCurveField()
|
||||
{
|
||||
var curveInstance = Instantiate(CurveField, Content ?? transform);
|
||||
Properties.Add(curveInstance.gameObject);
|
||||
return curveInstance;
|
||||
}
|
||||
|
||||
public virtual PropertyButton AddButton(string name, Action onClick)
|
||||
{
|
||||
var button = Instantiate(PropertyButton, Content ?? transform);
|
||||
button.Label.text = name;
|
||||
button.Button.interactable = onClick != null;
|
||||
button.Button.onClick.AddListener(() => onClick());
|
||||
Properties.Add(button.gameObject);
|
||||
OnPropertyAdded?.Invoke(button.gameObject);
|
||||
return button;
|
||||
}
|
||||
|
||||
public void AddButton(string name, string label, Action onClick)
|
||||
{
|
||||
var button = Instantiate(ButtonField, Content ?? transform);
|
||||
button.Label.text = name;
|
||||
button.ButtonLabel.text = label;
|
||||
button.Button.interactable = onClick != null;
|
||||
button.Button.onClick.AddListener(() => onClick());
|
||||
Properties.Add(button.gameObject);
|
||||
OnPropertyAdded?.Invoke(button.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<string> read, Action<string> write)
|
||||
{
|
||||
var field = Instantiate(InputField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Field.contentType = TMP_InputField.ContentType.Standard;
|
||||
field.Field.onValueChanged.AddListener(val => write(val));
|
||||
// field.Field.text = read();
|
||||
RefreshPropertyValues += () =>
|
||||
{
|
||||
var s = read();
|
||||
if (field.Field.text != s)
|
||||
{
|
||||
field.Field.text = s;
|
||||
field.gameObject.SetActive(false);
|
||||
Observable.NextFrame().Subscribe(_ =>
|
||||
{
|
||||
if(field != null)
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
});
|
||||
}
|
||||
};
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<float> read, Action<float> write)
|
||||
{
|
||||
var field = Instantiate(InputField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Field.contentType = TMP_InputField.ContentType.DecimalNumber;
|
||||
field.Field.onValueChanged.AddListener(val => write(float.Parse(val)));
|
||||
RefreshPropertyValues += () =>
|
||||
{
|
||||
var s = read().ToString(CultureInfo.InvariantCulture);
|
||||
if (field.Field.text != s)
|
||||
{
|
||||
field.Field.text = s;
|
||||
field.gameObject.SetActive(false);
|
||||
Observable.NextFrame().Subscribe(_ => OnPropertyAdded?.Invoke(field.gameObject));
|
||||
}
|
||||
};
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<int> read, Action<int> write)
|
||||
{
|
||||
var field = Instantiate(InputField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Field.contentType = TMP_InputField.ContentType.IntegerNumber;
|
||||
field.Field.onValueChanged.AddListener(val => write(int.Parse(val)));
|
||||
RefreshPropertyValues += () =>
|
||||
{
|
||||
var s = read().ToString(CultureInfo.InvariantCulture);
|
||||
if (field.Field.text != s)
|
||||
{
|
||||
field.Field.text = s;
|
||||
field.gameObject.SetActive(false);
|
||||
Observable.NextFrame().Subscribe(_ => OnPropertyAdded?.Invoke(field.gameObject));
|
||||
}
|
||||
};
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddIncrementField(string name, Func<int> read, Action<int> write, Func<int> min, Func<int> max)
|
||||
{
|
||||
var field = Instantiate(IncrementField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Increment.onClick.AddListener(() => write(read() + 1));
|
||||
field.Decrement.onClick.AddListener(() => write(read() - 1));
|
||||
RefreshPropertyValues += () =>
|
||||
{
|
||||
var val = read();
|
||||
var minval = min();
|
||||
var maxval = max();
|
||||
if (val < minval || val > maxval)
|
||||
write(val = clamp(val, minval, maxval));
|
||||
field.Value.text = val.ToString(CultureInfo.InvariantCulture);
|
||||
field.Increment.interactable = val == maxval;
|
||||
field.Decrement.interactable = val == minval;
|
||||
};
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<float> read, Action<float> write, float min, float max)
|
||||
{
|
||||
var field = Instantiate(RangedFloatField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Slider.wholeNumbers = false;
|
||||
field.Slider.minValue = min;
|
||||
field.Slider.maxValue = max;
|
||||
field.Slider.onValueChanged.AddListener(val => write(val));
|
||||
RefreshPropertyValues += () => field.Slider.value = read();
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddProgressField(string name, Func<float> read)
|
||||
{
|
||||
var field = Instantiate(ProgressField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Slider.wholeNumbers = false;
|
||||
field.Slider.minValue = 0;
|
||||
field.Slider.maxValue = 1;
|
||||
//field.Slider.onValueChanged.AddListener(val => write(val));
|
||||
RefreshPropertyValues += () => field.Slider.value = read();
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<int> read, Action<int> write, int min, int max)
|
||||
{
|
||||
var field = Instantiate(RangedFloatField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Slider.wholeNumbers = true;
|
||||
field.Slider.minValue = min;
|
||||
field.Slider.maxValue = max;
|
||||
field.Slider.onValueChanged.AddListener(val => write(Mathf.RoundToInt(val)));
|
||||
RefreshPropertyValues += () => field.Slider.value = read();
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<bool> read, Action<bool> write)
|
||||
{
|
||||
var field = Instantiate(BoolField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Toggle.onValueChanged.AddListener(val => write(val));
|
||||
RefreshPropertyValues += () => field.Toggle.isOn = read();
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
public void AddField(string name, Func<int> read, Action<int> write, string[] enumOptions)
|
||||
{
|
||||
var field = Instantiate(EnumField, Content ?? transform);
|
||||
field.Label.text = name;
|
||||
field.Dropdown.onClick.AddListener(() =>
|
||||
{
|
||||
var selected = read();
|
||||
Dropdown.gameObject.SetActive(true);
|
||||
Dropdown.Clear();
|
||||
for (int i = 0; i < enumOptions.Length; i++)
|
||||
{
|
||||
var index = i;
|
||||
Dropdown.AddOption(enumOptions[i], () => write(index), index == selected);
|
||||
}
|
||||
|
||||
Dropdown.Show((RectTransform) field.Dropdown.transform);
|
||||
});
|
||||
RefreshPropertyValues += () => field.DropdownLabel.text = enumOptions[read()];
|
||||
Properties.Add(field.gameObject);
|
||||
OnPropertyAdded?.Invoke(field.gameObject);
|
||||
}
|
||||
|
||||
// public void Inspect(Entity entity)
|
||||
// {
|
||||
// Clear();
|
||||
// Title.text = entity.Name;
|
||||
// var hullData = Context.GetData(entity.Hull) as HullData;
|
||||
// AddSection(
|
||||
// hullData.HullType == HullType.Ship ? "Ship" :
|
||||
// hullData.HullType == HullType.Station ? "Station" :
|
||||
// "Platform");
|
||||
// //AddList(hullData.Name).Inspect(hull, entity);
|
||||
// //PropertiesPanel.AddProperty("Hull", () => $"{hullData.Name}");
|
||||
// AddEntityProperties(entity);
|
||||
// //cargoList.SetExpanded(false,true);
|
||||
//
|
||||
// RefreshValues();
|
||||
// }
|
||||
|
||||
// private void AddEntityProperties(Entity entity)
|
||||
// {
|
||||
// AddField("Name", () => entity.Name, name => entity.Name = name);
|
||||
// AddProperty("Mass", () => $"{entity.Mass.SignificantDigits(Context.GameplaySettings.SignificantDigits)}");
|
||||
// }
|
||||
|
||||
private void AddItemProperties(ItemInstance item)
|
||||
{
|
||||
var data = item.Data.Value;
|
||||
|
||||
AddProperty(data.Description);
|
||||
|
||||
if (item is SimpleCommodity simpleCommodity)
|
||||
AddProperty("Quantity", () => simpleCommodity.Quantity.ToString());
|
||||
|
||||
var sheet = AddStatSheet();
|
||||
var manufacturer = ActionGameManager.CultCache.Get<Faction>(data.Manufacturer);
|
||||
sheet.AddStat("Manufacturer", () => manufacturer?.Name ?? "GameCult");
|
||||
sheet.AddStat("Mass", () => ActionGameManager.PlayerSettings.Format(GameManager.ItemManager.GetMass(item)));
|
||||
|
||||
//AddProperty("Thermal Mass", () => Context.GetThermalMass(item).SignificantDigits(Context.GameplaySettings.SignificantDigits));
|
||||
}
|
||||
|
||||
private void AddEquippableItemProperties(EquippableItem item, Func<PerformanceStat, float> statValueFunction)
|
||||
{
|
||||
if (item.Durability < .01f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var gearData = GameManager.ItemManager.GetData(item);
|
||||
|
||||
var sheet = AddStatSheet();
|
||||
foreach (var behavior in gearData.Behaviors)
|
||||
{
|
||||
if (behavior is StatModifierData statMod)
|
||||
{
|
||||
sheet.AddStat($"{statMod.Stat.Target.SplitCamelCase()}:{statMod.Stat.Stat.SplitCamelCase()}", () => $"{(statMod.Type == StatModifierType.Constant ? "+" : "x")}{ActionGameManager.PlayerSettings.Format(statValueFunction(statMod.Modifier))}");
|
||||
}
|
||||
else
|
||||
{
|
||||
var type = behavior.GetType();
|
||||
if (type.GetCustomAttribute(typeof(RuntimeInspectable)) == null) continue;
|
||||
foreach (var field in type.GetFields().Where(f => f.GetCustomAttribute<RuntimeInspectable>() != null))
|
||||
{
|
||||
var fieldType = field.FieldType;
|
||||
if (fieldType == typeof(float))
|
||||
sheet.AddStat(field.Name.SplitCamelCase(), () => $"{ActionGameManager.PlayerSettings.Format((float) field.GetValue(behavior))}");
|
||||
else if (fieldType == typeof(int))
|
||||
sheet.AddStat(field.Name.SplitCamelCase(), () => $"{(int) field.GetValue(behavior)}");
|
||||
else if (fieldType == typeof(PerformanceStat))
|
||||
{
|
||||
var stat = (PerformanceStat) field.GetValue(behavior);
|
||||
sheet.AddStat(field.Name.SplitCamelCase(), () => $"{ActionGameManager.PlayerSettings.Format(statValueFunction(stat))}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (gearData.Behaviors.FirstOrDefault(b => b is WeaponData) is WeaponData weapon)
|
||||
{
|
||||
var range = AddCurveField();
|
||||
range.Show("Damage Range", weapon.DamageCurve, t => ActionGameManager.PlayerSettings.Format(lerp(statValueFunction(weapon.MinRange), statValueFunction(weapon.Range), t)));
|
||||
}
|
||||
}
|
||||
|
||||
private string GetTitle(EquippableItem item)
|
||||
{
|
||||
var data = item.Data.Value;
|
||||
var (tier, upgrades) = GameManager.ItemManager.GetTier(item);
|
||||
return
|
||||
$"<color=#{ColorUtility.ToHtmlStringRGB(tier.Color.ToColor())}>{data.Name}</color><smallcaps><size=60%> ({tier.Name}{new string('+', upgrades)})";
|
||||
}
|
||||
|
||||
public void Inspect(EquippedItem item)
|
||||
{
|
||||
Clear();
|
||||
if (item?.EquippableItem == null) return;
|
||||
|
||||
Title.text = GetTitle(item.EquippableItem);
|
||||
|
||||
AddItemProperties(item.EquippableItem);
|
||||
AddSpacer();
|
||||
|
||||
if (item.GetBehavior<Weapon>() != null)
|
||||
{
|
||||
var weaponGroups = Instantiate(WeaponGroupAssignment, Content ?? transform);
|
||||
weaponGroups.Inspect(item);
|
||||
var dragOffset = Vector2.zero;
|
||||
Transform dragObject = null;
|
||||
weaponGroups.OnBeginDragAsObservable().Subscribe(x =>
|
||||
{
|
||||
//Debug.Log($"Began dragging weapon group {x.group}");
|
||||
GameManager.BeginDrag(new WeaponGroupDragObject(x.group));
|
||||
dragObject = Instantiate(weaponGroups.Groups[x.group], DragParent, true).transform;
|
||||
dragOffset = (Vector2)dragObject.position - x.pointerEventData.position;
|
||||
});
|
||||
weaponGroups.OnDragAsObservable().Subscribe(x =>
|
||||
{
|
||||
dragObject.position = x.pointerEventData.position + dragOffset;
|
||||
});
|
||||
weaponGroups.OnEndDragAsObservable().Subscribe(x =>
|
||||
{
|
||||
//Debug.Log($"Ended dragging weapon group {x.group}");
|
||||
GameManager.EndDrag();
|
||||
Destroy(dragObject.gameObject);
|
||||
});
|
||||
Properties.Add(weaponGroups.gameObject);
|
||||
OnPropertyAdded?.Invoke(weaponGroups.gameObject);
|
||||
}
|
||||
|
||||
var gearData = GameManager.ItemManager.GetData(item.EquippableItem);
|
||||
var statusSheet = AddStatSheet();
|
||||
if (item.EquippableItem.Durability < .01f)
|
||||
statusSheet.AddStat("Durability", () => "Item Destroyed!");
|
||||
else statusSheet.AddStat("Durability", () => $"{(int)(item.EquippableItem.Durability / gearData.Durability * 100)}%");
|
||||
statusSheet.AddStat("Temperature", () => ActionGameManager.PlayerSettings.FormatTemperature(item.Temperature));
|
||||
|
||||
var heatCurve = AddCurveField();
|
||||
heatCurve.Show(
|
||||
"Thermal Performance",
|
||||
gearData.HeatPerformanceCurve,
|
||||
t => ActionGameManager.PlayerSettings.FormatTemperature(lerp(gearData.MinimumTemperature, gearData.MaximumTemperature, t)),
|
||||
true);
|
||||
RefreshPropertyValues += () => heatCurve.SetCurrent(unlerp(gearData.MinimumTemperature, gearData.MaximumTemperature, item.Temperature));
|
||||
AddEquippableItemProperties(item.EquippableItem, item.Evaluate);
|
||||
AddSpacer();
|
||||
|
||||
AddField("Override Shutdown", () => item.EquippableItem.OverrideShutdown, b => item.EquippableItem.OverrideShutdown = b);
|
||||
|
||||
foreach (var behavior in item.Behaviors)
|
||||
{
|
||||
switch (behavior)
|
||||
{
|
||||
case Thermotoggle thermotoggle when thermotoggle.ThermotoggleData.Adjustable:
|
||||
AddField("Target Temperature",
|
||||
() => thermotoggle.TargetTemperature,
|
||||
temp => thermotoggle.TargetTemperature = temp);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
RefreshValues();
|
||||
}
|
||||
|
||||
public void Inspect(ItemInstance item)
|
||||
{
|
||||
Clear();
|
||||
|
||||
AddItemProperties(item);
|
||||
|
||||
if (item is EquippableItem gear)
|
||||
{
|
||||
Title.text = GetTitle(gear);
|
||||
AddSpacer();
|
||||
var gearData = GameManager.ItemManager.GetData(gear);
|
||||
var statusSheet = AddStatSheet();
|
||||
statusSheet.AddStat("Durability", () => $"{(int)(gear.Durability / gearData.Durability * 100)}%");
|
||||
var heatCurve = AddCurveField();
|
||||
heatCurve.Show(
|
||||
"Thermal Performance",
|
||||
gearData.HeatPerformanceCurve,
|
||||
t => ActionGameManager.PlayerSettings.FormatTemperature(lerp(gearData.MinimumTemperature, gearData.MaximumTemperature, t)),
|
||||
true);
|
||||
AddEquippableItemProperties(gear, stat => GameManager.ItemManager.Evaluate(stat, gear));
|
||||
}
|
||||
|
||||
RefreshValues();
|
||||
}
|
||||
|
||||
public void Inspect(ItemData data)
|
||||
{
|
||||
AddProperty("Type", () => data.Name);
|
||||
AddProperty(data.Description).Label.fontStyle = FontStyles.Normal;
|
||||
if (data is EquippableItemData gearData)
|
||||
{
|
||||
AddProperty("Durability", () => ActionGameManager.PlayerSettings.Format(gearData.Durability));
|
||||
var sheet = AddStatSheet();
|
||||
foreach (var behavior in gearData.Behaviors)
|
||||
{
|
||||
if (behavior is StatModifierData statMod)
|
||||
{
|
||||
if(Math.Abs(statMod.Modifier.Min - statMod.Modifier.Max) < .001f)
|
||||
sheet.AddStat($"{statMod.Stat.Target}:{statMod.Stat.Stat}", () => $"{(statMod.Type == StatModifierType.Constant ? "+" : "x")}{ActionGameManager.PlayerSettings.Format(statMod.Modifier.Min)}");
|
||||
else
|
||||
sheet.AddStat($"{statMod.Stat.Target}:{statMod.Stat.Stat}", () => $"{(statMod.Type == StatModifierType.Constant ? "+" : "x")}{ActionGameManager.PlayerSettings.Format(statMod.Modifier.Min)}-{ActionGameManager.PlayerSettings.Format(statMod.Modifier.Max)}");
|
||||
}
|
||||
var type = behavior.GetType();
|
||||
if (type.GetCustomAttribute(typeof(RuntimeInspectable)) != null)
|
||||
{
|
||||
foreach (var field in type.GetFields().Where(f => f.GetCustomAttribute<RuntimeInspectable>() != null))
|
||||
{
|
||||
var fieldType = field.FieldType;
|
||||
if (fieldType == typeof(float))
|
||||
sheet.AddStat(field.Name, () => $"{ActionGameManager.PlayerSettings.Format((float) field.GetValue(behavior))}");
|
||||
else if (fieldType == typeof(int))
|
||||
sheet.AddStat(field.Name, () => $"{(int) field.GetValue(behavior)}");
|
||||
else if (fieldType == typeof(PerformanceStat))
|
||||
{
|
||||
var stat = (PerformanceStat) field.GetValue(behavior);
|
||||
if(Math.Abs(stat.Min - stat.Max) < .001f)
|
||||
sheet.AddStat(field.Name, () => $"{ActionGameManager.PlayerSettings.Format(stat.Min)}");
|
||||
else
|
||||
sheet.AddStat(field.Name, () => $"{ActionGameManager.PlayerSettings.Format(stat.Min)}-{ActionGameManager.PlayerSettings.Format(stat.Max)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Inspect(object obj, bool inspectablesOnly = false, bool readWrite = false, bool topLevel = true)
|
||||
{
|
||||
var fields = obj.GetType().GetFields();
|
||||
foreach (var field in fields)
|
||||
Inspect(obj, field, inspectablesOnly, readWrite);
|
||||
|
||||
// if(topLevel)
|
||||
// foreach (var field in _propertyFields)
|
||||
// field.transform.SetSiblingIndex(_propertyFields.IndexOf(field));
|
||||
|
||||
RefreshValues();
|
||||
}
|
||||
|
||||
public void Inspect(object obj, FieldInfo field, bool inspectablesOnly = false, bool readWrite = false)
|
||||
{
|
||||
var inspectable = field.GetCustomAttribute<InspectableAttribute>();
|
||||
if (inspectable == null && inspectablesOnly) return;
|
||||
var type = field.FieldType;
|
||||
|
||||
if (type == typeof(float))
|
||||
{
|
||||
if (readWrite)
|
||||
{
|
||||
if (inspectable is InspectableRangedFloatAttribute ranged)
|
||||
AddField(field.Name.SplitCamelCase(), () => (float) field.GetValue(obj), f => field.SetValue(obj, f),
|
||||
ranged.Min, ranged.Max);
|
||||
else
|
||||
AddField(field.Name.SplitCamelCase(), () => (float) field.GetValue(obj), f => field.SetValue(obj, f));
|
||||
} else AddProperty(field.Name.SplitCamelCase(), () => ((float) field.GetValue(obj)).ToString("0.##"));
|
||||
}
|
||||
else if (type == typeof(int))
|
||||
{
|
||||
if (readWrite)
|
||||
{
|
||||
if (inspectable is InspectableRangedIntAttribute ranged)
|
||||
AddField(field.Name.SplitCamelCase(), () => (int) field.GetValue(obj), f => field.SetValue(obj, f),
|
||||
ranged.Min, ranged.Max);
|
||||
else
|
||||
AddField(field.Name.SplitCamelCase(), () => (int) field.GetValue(obj), f => field.SetValue(obj, f));
|
||||
} else AddProperty(field.Name.SplitCamelCase(), () => ((int) field.GetValue(obj)).ToString());
|
||||
}
|
||||
else if (type.IsEnum)
|
||||
{
|
||||
if (readWrite)
|
||||
AddField(field.Name.SplitCamelCase(), () => (int) field.GetValue(obj), i => field.SetValue(obj, i),
|
||||
Enum.GetNames(field.FieldType));
|
||||
else
|
||||
AddProperty(field.Name.SplitCamelCase(), () => Enum.GetName(type, field.GetValue(obj)).SplitCamelCase());
|
||||
}
|
||||
else if (type == typeof(string))
|
||||
{
|
||||
if (readWrite)
|
||||
AddField(field.Name.SplitCamelCase(), () => (string) field.GetValue(obj), i => field.SetValue(obj, i));
|
||||
else
|
||||
AddProperty(field.Name.SplitCamelCase(), () => (string) field.GetValue(obj));
|
||||
}
|
||||
//else if (field.FieldType == typeof(Color)) Inspect(field.Name, () => (Color) field.GetValue(obj), c => field.SetValue(obj, c));
|
||||
else if (field.FieldType == typeof(bool)) AddField(field.Name, () => (bool) field.GetValue(obj), b => field.SetValue(obj, b));
|
||||
else if (type.GetCustomAttribute<InspectableAttribute>() != null)
|
||||
{
|
||||
// if(!_propertyFields.Any() || !_propertyFields.Last().gameObject.name.ToUpper().Contains("DIVIDER"))
|
||||
// _propertyFields.Add(Divider.Instantiate<Prototype>());
|
||||
var list = AddList(field.Name);
|
||||
list.Inspect(field.GetValue(obj), inspectablesOnly, readWrite, false);
|
||||
}
|
||||
else
|
||||
Debug.Log($"Field \"{field.Name}\" has unknown type {field.FieldType.Name}. No inspector was generated.");
|
||||
}
|
||||
|
||||
public void RefreshValues()
|
||||
{
|
||||
RefreshPropertyValues?.Invoke();
|
||||
}
|
||||
}
|
||||
31
Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs.meta
Normal file
31
Assets/Scripts/UI/Properties Panel/PropertiesPanel.cs.meta
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8c2bf4a7080061d42a87046c37bf0c60
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences:
|
||||
- Spacer: {instanceID: 0}
|
||||
- Dropdown: {instanceID: 0}
|
||||
- Title: {instanceID: 0}
|
||||
- Section: {instanceID: 0}
|
||||
- List: {instanceID: 0}
|
||||
- Property: {instanceID: 0}
|
||||
- PropertyLabel: {instanceID: 0}
|
||||
- Attribute: {instanceID: 0}
|
||||
- InputField: {instanceID: 0}
|
||||
- RangedFloatField: {instanceID: 0}
|
||||
- ProgressField: {instanceID: 0}
|
||||
- EnumField: {instanceID: 0}
|
||||
- BoolField: {instanceID: 0}
|
||||
- PropertyButton: {instanceID: 0}
|
||||
- ButtonField: {instanceID: 0}
|
||||
- IncrementField: {instanceID: 0}
|
||||
- StatSheet: {fileID: 3416329628306957711, guid: 4f75723ed178a084e813965e84825bd4,
|
||||
type: 3}
|
||||
- Content: {instanceID: 0}
|
||||
- SelectedChild: {instanceID: 0}
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Loading…
Reference in a new issue