diff options
author | chai <215380520@qq.com> | 2024-05-20 22:36:58 +0800 |
---|---|---|
committer | chai <215380520@qq.com> | 2024-05-20 22:36:58 +0800 |
commit | a22c505984697881f5f911a165ee022087b69e09 (patch) | |
tree | d3c030aef1ae9b8a01c889dd2902bb1e3324e72b /Thronefall_v1.0/Rewired/Rewired.Demos | |
parent | 4a4cc82d069b26bc4d4532e73860f86b211ca239 (diff) |
Diffstat (limited to 'Thronefall_v1.0/Rewired/Rewired.Demos')
19 files changed, 3744 insertions, 0 deletions
diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/Bullet.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/Bullet.cs new file mode 100644 index 0000000..bb521c8 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/Bullet.cs @@ -0,0 +1,30 @@ +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class Bullet : MonoBehaviour +{ + public float lifeTime = 3f; + + private bool die; + + private float deathTime; + + private void Start() + { + if (lifeTime > 0f) + { + deathTime = Time.time + lifeTime; + die = true; + } + } + + private void Update() + { + if (die && Time.time >= deathTime) + { + Object.Destroy(base.gameObject); + } + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/ControlRemappingDemo1.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/ControlRemappingDemo1.cs new file mode 100644 index 0000000..b0e4f51 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/ControlRemappingDemo1.cs @@ -0,0 +1,1797 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class ControlRemappingDemo1 : MonoBehaviour +{ + private class ControllerSelection + { + private int _id; + + private int _idPrev; + + private ControllerType _type; + + private ControllerType _typePrev; + + public int id + { + get + { + return _id; + } + set + { + _idPrev = _id; + _id = value; + } + } + + public ControllerType type + { + get + { + return _type; + } + set + { + _typePrev = _type; + _type = value; + } + } + + public int idPrev => _idPrev; + + public ControllerType typePrev => _typePrev; + + public bool hasSelection => _id >= 0; + + public ControllerSelection() + { + Clear(); + } + + public void Set(int id, ControllerType type) + { + this.id = id; + this.type = type; + } + + public void Clear() + { + _id = -1; + _idPrev = -1; + _type = ControllerType.Joystick; + _typePrev = ControllerType.Joystick; + } + } + + private class DialogHelper + { + public enum DialogType + { + None = 0, + JoystickConflict = 1, + ElementConflict = 2, + KeyConflict = 3, + DeleteAssignmentConfirmation = 10, + AssignElement = 11 + } + + private const float openBusyDelay = 0.25f; + + private const float closeBusyDelay = 0.1f; + + private DialogType _type; + + private bool _enabled; + + private float _busyTime; + + private bool _busyTimerRunning; + + private Action<int> drawWindowDelegate; + + private GUI.WindowFunction drawWindowFunction; + + private WindowProperties windowProperties; + + private int currentActionId; + + private Action<int, UserResponse> resultCallback; + + private float busyTimer + { + get + { + if (!_busyTimerRunning) + { + return 0f; + } + return _busyTime - Time.realtimeSinceStartup; + } + } + + public bool enabled + { + get + { + return _enabled; + } + set + { + if (value) + { + if (_type != 0) + { + StateChanged(0.25f); + } + } + else + { + _enabled = value; + _type = DialogType.None; + StateChanged(0.1f); + } + } + } + + public DialogType type + { + get + { + if (!_enabled) + { + return DialogType.None; + } + return _type; + } + set + { + if (value == DialogType.None) + { + _enabled = false; + StateChanged(0.1f); + } + else + { + _enabled = true; + StateChanged(0.25f); + } + _type = value; + } + } + + public bool busy => _busyTimerRunning; + + public DialogHelper() + { + drawWindowDelegate = DrawWindow; + drawWindowFunction = drawWindowDelegate.Invoke; + } + + public void StartModal(int queueActionId, DialogType type, WindowProperties windowProperties, Action<int, UserResponse> resultCallback) + { + StartModal(queueActionId, type, windowProperties, resultCallback, -1f); + } + + public void StartModal(int queueActionId, DialogType type, WindowProperties windowProperties, Action<int, UserResponse> resultCallback, float openBusyDelay) + { + currentActionId = queueActionId; + this.windowProperties = windowProperties; + this.type = type; + this.resultCallback = resultCallback; + if (openBusyDelay >= 0f) + { + StateChanged(openBusyDelay); + } + } + + public void Update() + { + Draw(); + UpdateTimers(); + } + + public void Draw() + { + if (_enabled) + { + bool flag = GUI.enabled; + GUI.enabled = true; + GUILayout.Window(windowProperties.windowId, windowProperties.rect, drawWindowFunction, windowProperties.title); + GUI.FocusWindow(windowProperties.windowId); + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + } + + public void DrawConfirmButton() + { + DrawConfirmButton("Confirm"); + } + + public void DrawConfirmButton(string title) + { + bool flag = GUI.enabled; + if (busy) + { + GUI.enabled = false; + } + if (GUILayout.Button(title)) + { + Confirm(UserResponse.Confirm); + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + public void DrawConfirmButton(UserResponse response) + { + DrawConfirmButton(response, "Confirm"); + } + + public void DrawConfirmButton(UserResponse response, string title) + { + bool flag = GUI.enabled; + if (busy) + { + GUI.enabled = false; + } + if (GUILayout.Button(title)) + { + Confirm(response); + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + public void DrawCancelButton() + { + DrawCancelButton("Cancel"); + } + + public void DrawCancelButton(string title) + { + bool flag = GUI.enabled; + if (busy) + { + GUI.enabled = false; + } + if (GUILayout.Button(title)) + { + Cancel(); + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + public void Confirm() + { + Confirm(UserResponse.Confirm); + } + + public void Confirm(UserResponse response) + { + resultCallback(currentActionId, response); + Close(); + } + + public void Cancel() + { + resultCallback(currentActionId, UserResponse.Cancel); + Close(); + } + + private void DrawWindow(int windowId) + { + windowProperties.windowDrawDelegate(windowProperties.title, windowProperties.message); + } + + private void UpdateTimers() + { + if (_busyTimerRunning && busyTimer <= 0f) + { + _busyTimerRunning = false; + } + } + + private void StartBusyTimer(float time) + { + _busyTime = time + Time.realtimeSinceStartup; + _busyTimerRunning = true; + } + + private void Close() + { + Reset(); + StateChanged(0.1f); + } + + private void StateChanged(float delay) + { + StartBusyTimer(delay); + } + + private void Reset() + { + _enabled = false; + _type = DialogType.None; + currentActionId = -1; + resultCallback = null; + } + + private void ResetTimers() + { + _busyTimerRunning = false; + } + + public void FullReset() + { + Reset(); + ResetTimers(); + } + } + + private abstract class QueueEntry + { + public enum State + { + Waiting, + Confirmed, + Canceled + } + + private static int uidCounter; + + public int id { get; protected set; } + + public QueueActionType queueActionType { get; protected set; } + + public State state { get; protected set; } + + public UserResponse response { get; protected set; } + + protected static int nextId + { + get + { + int result = uidCounter; + uidCounter++; + return result; + } + } + + public QueueEntry(QueueActionType queueActionType) + { + id = nextId; + this.queueActionType = queueActionType; + } + + public void Confirm(UserResponse response) + { + state = State.Confirmed; + this.response = response; + } + + public void Cancel() + { + state = State.Canceled; + } + } + + private class JoystickAssignmentChange : QueueEntry + { + public int playerId { get; private set; } + + public int joystickId { get; private set; } + + public bool assign { get; private set; } + + public JoystickAssignmentChange(int newPlayerId, int joystickId, bool assign) + : base(QueueActionType.JoystickAssignment) + { + playerId = newPlayerId; + this.joystickId = joystickId; + this.assign = assign; + } + } + + private class ElementAssignmentChange : QueueEntry + { + public ElementAssignmentChangeType changeType { get; set; } + + public InputMapper.Context context { get; private set; } + + public ElementAssignmentChange(ElementAssignmentChangeType changeType, InputMapper.Context context) + : base(QueueActionType.ElementAssignment) + { + this.changeType = changeType; + this.context = context; + } + + public ElementAssignmentChange(ElementAssignmentChange other) + : this(other.changeType, other.context.Clone()) + { + } + } + + private class FallbackJoystickIdentification : QueueEntry + { + public int joystickId { get; private set; } + + public string joystickName { get; private set; } + + public FallbackJoystickIdentification(int joystickId, string joystickName) + : base(QueueActionType.FallbackJoystickIdentification) + { + this.joystickId = joystickId; + this.joystickName = joystickName; + } + } + + private class Calibration : QueueEntry + { + public int selectedElementIdentifierId; + + public bool recording; + + public Player player { get; private set; } + + public ControllerType controllerType { get; private set; } + + public Joystick joystick { get; private set; } + + public CalibrationMap calibrationMap { get; private set; } + + public Calibration(Player player, Joystick joystick, CalibrationMap calibrationMap) + : base(QueueActionType.Calibrate) + { + this.player = player; + this.joystick = joystick; + this.calibrationMap = calibrationMap; + selectedElementIdentifierId = -1; + } + } + + private struct WindowProperties + { + public int windowId; + + public Rect rect; + + public Action<string, string> windowDrawDelegate; + + public string title; + + public string message; + } + + private enum QueueActionType + { + None, + JoystickAssignment, + ElementAssignment, + FallbackJoystickIdentification, + Calibrate + } + + private enum ElementAssignmentChangeType + { + Add, + Replace, + Remove, + ReassignOrRemove, + ConflictCheck + } + + public enum UserResponse + { + Confirm, + Cancel, + Custom1, + Custom2 + } + + private const float defaultModalWidth = 250f; + + private const float defaultModalHeight = 200f; + + private const float assignmentTimeout = 5f; + + private DialogHelper dialog; + + private InputMapper inputMapper = new InputMapper(); + + private InputMapper.ConflictFoundEventData conflictFoundEventData; + + private bool guiState; + + private bool busy; + + private bool pageGUIState; + + private Player selectedPlayer; + + private int selectedMapCategoryId; + + private ControllerSelection selectedController; + + private ControllerMap selectedMap; + + private bool showMenu; + + private bool startListening; + + private Vector2 actionScrollPos; + + private Vector2 calibrateScrollPos; + + private Queue<QueueEntry> actionQueue; + + private bool setupFinished; + + [NonSerialized] + private bool initialized; + + private bool isCompiling; + + private GUIStyle style_wordWrap; + + private GUIStyle style_centeredBox; + + private void Awake() + { + inputMapper.options.timeout = 5f; + inputMapper.options.ignoreMouseXAxis = true; + inputMapper.options.ignoreMouseYAxis = true; + Initialize(); + } + + private void OnEnable() + { + Subscribe(); + } + + private void OnDisable() + { + Unsubscribe(); + } + + private void Initialize() + { + dialog = new DialogHelper(); + actionQueue = new Queue<QueueEntry>(); + selectedController = new ControllerSelection(); + ReInput.ControllerConnectedEvent += JoystickConnected; + ReInput.ControllerPreDisconnectEvent += JoystickPreDisconnect; + ReInput.ControllerDisconnectedEvent += JoystickDisconnected; + ResetAll(); + initialized = true; + ReInput.userDataStore.Load(); + if (ReInput.unityJoystickIdentificationRequired) + { + IdentifyAllJoysticks(); + } + } + + private void Setup() + { + if (!setupFinished) + { + style_wordWrap = new GUIStyle(GUI.skin.label); + style_wordWrap.wordWrap = true; + style_centeredBox = new GUIStyle(GUI.skin.box); + style_centeredBox.alignment = TextAnchor.MiddleCenter; + setupFinished = true; + } + } + + private void Subscribe() + { + Unsubscribe(); + inputMapper.ConflictFoundEvent += OnConflictFound; + inputMapper.StoppedEvent += OnStopped; + } + + private void Unsubscribe() + { + inputMapper.RemoveAllEventListeners(); + } + + public void OnGUI() + { + if (initialized) + { + Setup(); + HandleMenuControl(); + if (!showMenu) + { + DrawInitialScreen(); + return; + } + SetGUIStateStart(); + ProcessQueue(); + DrawPage(); + ShowDialog(); + SetGUIStateEnd(); + busy = false; + } + } + + private void HandleMenuControl() + { + if (!dialog.enabled && Event.current.type == EventType.Layout && ReInput.players.GetSystemPlayer().GetButtonDown("Menu")) + { + if (showMenu) + { + ReInput.userDataStore.Save(); + Close(); + } + else + { + Open(); + } + } + } + + private void Close() + { + ClearWorkingVars(); + showMenu = false; + } + + private void Open() + { + showMenu = true; + } + + private void DrawInitialScreen() + { + ActionElementMap firstElementMapWithAction = ReInput.players.GetSystemPlayer().controllers.maps.GetFirstElementMapWithAction("Menu", skipDisabledMaps: true); + GUIContent content = ((firstElementMapWithAction == null) ? new GUIContent("There is no element assigned to open the menu!") : new GUIContent("Press " + firstElementMapWithAction.elementIdentifierName + " to open the menu.")); + GUILayout.BeginArea(GetScreenCenteredRect(300f, 50f)); + GUILayout.Box(content, style_centeredBox, GUILayout.ExpandHeight(expand: true), GUILayout.ExpandWidth(expand: true)); + GUILayout.EndArea(); + } + + private void DrawPage() + { + if (GUI.enabled != pageGUIState) + { + GUI.enabled = pageGUIState; + } + GUILayout.BeginArea(new Rect(((float)Screen.width - (float)Screen.width * 0.9f) * 0.5f, ((float)Screen.height - (float)Screen.height * 0.9f) * 0.5f, (float)Screen.width * 0.9f, (float)Screen.height * 0.9f)); + DrawPlayerSelector(); + DrawJoystickSelector(); + DrawMouseAssignment(); + DrawControllerSelector(); + DrawCalibrateButton(); + DrawMapCategories(); + actionScrollPos = GUILayout.BeginScrollView(actionScrollPos); + DrawCategoryActions(); + GUILayout.EndScrollView(); + GUILayout.EndArea(); + } + + private void DrawPlayerSelector() + { + if (ReInput.players.allPlayerCount == 0) + { + GUILayout.Label("There are no players."); + return; + } + GUILayout.Space(15f); + GUILayout.Label("Players:"); + GUILayout.BeginHorizontal(); + foreach (Player player in ReInput.players.GetPlayers(includeSystemPlayer: true)) + { + if (selectedPlayer == null) + { + selectedPlayer = player; + } + bool flag = ((player == selectedPlayer) ? true : false); + bool flag2 = GUILayout.Toggle(flag, (player.descriptiveName != string.Empty) ? player.descriptiveName : player.name, "Button", GUILayout.ExpandWidth(expand: false)); + if (flag2 != flag && flag2) + { + selectedPlayer = player; + selectedController.Clear(); + selectedMapCategoryId = -1; + } + } + GUILayout.EndHorizontal(); + } + + private void DrawMouseAssignment() + { + bool flag = GUI.enabled; + if (selectedPlayer == null) + { + GUI.enabled = false; + } + GUILayout.Space(15f); + GUILayout.Label("Assign Mouse:"); + GUILayout.BeginHorizontal(); + bool flag2 = ((selectedPlayer != null && selectedPlayer.controllers.hasMouse) ? true : false); + bool flag3 = GUILayout.Toggle(flag2, "Assign Mouse", "Button", GUILayout.ExpandWidth(expand: false)); + if (flag3 != flag2) + { + if (flag3) + { + selectedPlayer.controllers.hasMouse = true; + foreach (Player player in ReInput.players.Players) + { + if (player != selectedPlayer) + { + player.controllers.hasMouse = false; + } + } + } + else + { + selectedPlayer.controllers.hasMouse = false; + } + } + GUILayout.EndHorizontal(); + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + private void DrawJoystickSelector() + { + bool flag = GUI.enabled; + if (selectedPlayer == null) + { + GUI.enabled = false; + } + GUILayout.Space(15f); + GUILayout.Label("Assign Joysticks:"); + GUILayout.BeginHorizontal(); + bool flag2 = ((selectedPlayer == null || selectedPlayer.controllers.joystickCount == 0) ? true : false); + bool flag3 = GUILayout.Toggle(flag2, "None", "Button", GUILayout.ExpandWidth(expand: false)); + if (flag3 != flag2) + { + selectedPlayer.controllers.ClearControllersOfType(ControllerType.Joystick); + ControllerSelectionChanged(); + } + if (selectedPlayer != null) + { + foreach (Joystick joystick in ReInput.controllers.Joysticks) + { + flag2 = selectedPlayer.controllers.ContainsController(joystick); + flag3 = GUILayout.Toggle(flag2, joystick.name, "Button", GUILayout.ExpandWidth(expand: false)); + if (flag3 != flag2) + { + EnqueueAction(new JoystickAssignmentChange(selectedPlayer.id, joystick.id, flag3)); + } + } + } + GUILayout.EndHorizontal(); + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + private void DrawControllerSelector() + { + if (selectedPlayer == null) + { + return; + } + bool flag = GUI.enabled; + GUILayout.Space(15f); + GUILayout.Label("Controller to Map:"); + GUILayout.BeginHorizontal(); + if (!selectedController.hasSelection) + { + selectedController.Set(0, ControllerType.Keyboard); + ControllerSelectionChanged(); + } + bool flag2 = selectedController.type == ControllerType.Keyboard; + if (GUILayout.Toggle(flag2, "Keyboard", "Button", GUILayout.ExpandWidth(expand: false)) != flag2) + { + selectedController.Set(0, ControllerType.Keyboard); + ControllerSelectionChanged(); + } + if (!selectedPlayer.controllers.hasMouse) + { + GUI.enabled = false; + } + flag2 = selectedController.type == ControllerType.Mouse; + if (GUILayout.Toggle(flag2, "Mouse", "Button", GUILayout.ExpandWidth(expand: false)) != flag2) + { + selectedController.Set(0, ControllerType.Mouse); + ControllerSelectionChanged(); + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + foreach (Joystick joystick in selectedPlayer.controllers.Joysticks) + { + flag2 = selectedController.type == ControllerType.Joystick && selectedController.id == joystick.id; + if (GUILayout.Toggle(flag2, joystick.name, "Button", GUILayout.ExpandWidth(expand: false)) != flag2) + { + selectedController.Set(joystick.id, ControllerType.Joystick); + ControllerSelectionChanged(); + } + } + GUILayout.EndHorizontal(); + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + private void DrawCalibrateButton() + { + if (selectedPlayer == null) + { + return; + } + bool flag = GUI.enabled; + GUILayout.Space(10f); + Controller controller = (selectedController.hasSelection ? selectedPlayer.controllers.GetController(selectedController.type, selectedController.id) : null); + if (controller == null || selectedController.type != ControllerType.Joystick) + { + GUI.enabled = false; + GUILayout.Button("Select a controller to calibrate", GUILayout.ExpandWidth(expand: false)); + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + else if (GUILayout.Button("Calibrate " + controller.name, GUILayout.ExpandWidth(expand: false)) && controller is Joystick joystick) + { + CalibrationMap calibrationMap = joystick.calibrationMap; + if (calibrationMap != null) + { + EnqueueAction(new Calibration(selectedPlayer, joystick, calibrationMap)); + } + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + private void DrawMapCategories() + { + if (selectedPlayer == null || !selectedController.hasSelection) + { + return; + } + bool flag = GUI.enabled; + GUILayout.Space(15f); + GUILayout.Label("Categories:"); + GUILayout.BeginHorizontal(); + foreach (InputMapCategory userAssignableMapCategory in ReInput.mapping.UserAssignableMapCategories) + { + if (!selectedPlayer.controllers.maps.ContainsMapInCategory(selectedController.type, userAssignableMapCategory.id)) + { + GUI.enabled = false; + } + else if (selectedMapCategoryId < 0) + { + selectedMapCategoryId = userAssignableMapCategory.id; + selectedMap = selectedPlayer.controllers.maps.GetFirstMapInCategory(selectedController.type, selectedController.id, userAssignableMapCategory.id); + } + bool flag2 = ((userAssignableMapCategory.id == selectedMapCategoryId) ? true : false); + if (GUILayout.Toggle(flag2, (userAssignableMapCategory.descriptiveName != string.Empty) ? userAssignableMapCategory.descriptiveName : userAssignableMapCategory.name, "Button", GUILayout.ExpandWidth(expand: false)) != flag2) + { + selectedMapCategoryId = userAssignableMapCategory.id; + selectedMap = selectedPlayer.controllers.maps.GetFirstMapInCategory(selectedController.type, selectedController.id, userAssignableMapCategory.id); + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + GUILayout.EndHorizontal(); + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + private void DrawCategoryActions() + { + if (selectedPlayer == null || selectedMapCategoryId < 0) + { + return; + } + bool flag = GUI.enabled; + if (selectedMap == null) + { + return; + } + GUILayout.Space(15f); + GUILayout.Label("Actions:"); + InputMapCategory mapCategory = ReInput.mapping.GetMapCategory(selectedMapCategoryId); + if (mapCategory == null) + { + return; + } + InputCategory actionCategory = ReInput.mapping.GetActionCategory(mapCategory.name); + if (actionCategory == null) + { + return; + } + float width = 150f; + foreach (InputAction item in ReInput.mapping.ActionsInCategory(actionCategory.id)) + { + string text = ((item.descriptiveName != string.Empty) ? item.descriptiveName : item.name); + if (item.type == InputActionType.Button) + { + GUILayout.BeginHorizontal(); + GUILayout.Label(text, GUILayout.Width(width)); + DrawAddActionMapButton(selectedPlayer.id, item, AxisRange.Positive, selectedController, selectedMap); + foreach (ActionElementMap allMap in selectedMap.AllMaps) + { + if (allMap.actionId == item.id) + { + DrawActionAssignmentButton(selectedPlayer.id, item, AxisRange.Positive, selectedController, selectedMap, allMap); + } + } + GUILayout.EndHorizontal(); + } + else + { + if (item.type != 0) + { + continue; + } + if (selectedController.type != 0) + { + GUILayout.BeginHorizontal(); + GUILayout.Label(text, GUILayout.Width(width)); + DrawAddActionMapButton(selectedPlayer.id, item, AxisRange.Full, selectedController, selectedMap); + foreach (ActionElementMap allMap2 in selectedMap.AllMaps) + { + if (allMap2.actionId == item.id && allMap2.elementType != ControllerElementType.Button && allMap2.axisType != AxisType.Split) + { + DrawActionAssignmentButton(selectedPlayer.id, item, AxisRange.Full, selectedController, selectedMap, allMap2); + DrawInvertButton(selectedPlayer.id, item, Pole.Positive, selectedController, selectedMap, allMap2); + } + } + GUILayout.EndHorizontal(); + } + string text2 = ((item.positiveDescriptiveName != string.Empty) ? item.positiveDescriptiveName : (item.descriptiveName + " +")); + GUILayout.BeginHorizontal(); + GUILayout.Label(text2, GUILayout.Width(width)); + DrawAddActionMapButton(selectedPlayer.id, item, AxisRange.Positive, selectedController, selectedMap); + foreach (ActionElementMap allMap3 in selectedMap.AllMaps) + { + if (allMap3.actionId == item.id && allMap3.axisContribution == Pole.Positive && allMap3.axisType != AxisType.Normal) + { + DrawActionAssignmentButton(selectedPlayer.id, item, AxisRange.Positive, selectedController, selectedMap, allMap3); + } + } + GUILayout.EndHorizontal(); + string text3 = ((item.negativeDescriptiveName != string.Empty) ? item.negativeDescriptiveName : (item.descriptiveName + " -")); + GUILayout.BeginHorizontal(); + GUILayout.Label(text3, GUILayout.Width(width)); + DrawAddActionMapButton(selectedPlayer.id, item, AxisRange.Negative, selectedController, selectedMap); + foreach (ActionElementMap allMap4 in selectedMap.AllMaps) + { + if (allMap4.actionId == item.id && allMap4.axisContribution == Pole.Negative && allMap4.axisType != AxisType.Normal) + { + DrawActionAssignmentButton(selectedPlayer.id, item, AxisRange.Negative, selectedController, selectedMap, allMap4); + } + } + GUILayout.EndHorizontal(); + } + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + private void DrawActionAssignmentButton(int playerId, InputAction action, AxisRange actionRange, ControllerSelection controller, ControllerMap controllerMap, ActionElementMap elementMap) + { + if (GUILayout.Button(elementMap.elementIdentifierName, GUILayout.ExpandWidth(expand: false), GUILayout.MinWidth(30f))) + { + InputMapper.Context context = new InputMapper.Context + { + actionId = action.id, + actionRange = actionRange, + controllerMap = controllerMap, + actionElementMapToReplace = elementMap + }; + EnqueueAction(new ElementAssignmentChange(ElementAssignmentChangeType.ReassignOrRemove, context)); + startListening = true; + } + GUILayout.Space(4f); + } + + private void DrawInvertButton(int playerId, InputAction action, Pole actionAxisContribution, ControllerSelection controller, ControllerMap controllerMap, ActionElementMap elementMap) + { + bool invert = elementMap.invert; + bool flag = GUILayout.Toggle(invert, "Invert", GUILayout.ExpandWidth(expand: false)); + if (flag != invert) + { + elementMap.invert = flag; + } + GUILayout.Space(10f); + } + + private void DrawAddActionMapButton(int playerId, InputAction action, AxisRange actionRange, ControllerSelection controller, ControllerMap controllerMap) + { + if (GUILayout.Button("Add...", GUILayout.ExpandWidth(expand: false))) + { + InputMapper.Context context = new InputMapper.Context + { + actionId = action.id, + actionRange = actionRange, + controllerMap = controllerMap + }; + EnqueueAction(new ElementAssignmentChange(ElementAssignmentChangeType.Add, context)); + startListening = true; + } + GUILayout.Space(10f); + } + + private void ShowDialog() + { + dialog.Update(); + } + + private void DrawModalWindow(string title, string message) + { + if (dialog.enabled) + { + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(); + dialog.DrawConfirmButton("Okay"); + GUILayout.FlexibleSpace(); + dialog.DrawCancelButton(); + GUILayout.EndHorizontal(); + } + } + + private void DrawModalWindow_OkayOnly(string title, string message) + { + if (dialog.enabled) + { + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(); + dialog.DrawConfirmButton("Okay"); + GUILayout.EndHorizontal(); + } + } + + private void DrawElementAssignmentWindow(string title, string message) + { + if (!dialog.enabled) + { + return; + } + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.FlexibleSpace(); + if (!(actionQueue.Peek() is ElementAssignmentChange elementAssignmentChange)) + { + dialog.Cancel(); + return; + } + float num; + if (!dialog.busy) + { + if (startListening && inputMapper.status == InputMapper.Status.Idle) + { + inputMapper.Start(elementAssignmentChange.context); + startListening = false; + } + if (conflictFoundEventData != null) + { + dialog.Confirm(); + return; + } + num = inputMapper.timeRemaining; + if (num == 0f) + { + dialog.Cancel(); + return; + } + } + else + { + num = inputMapper.options.timeout; + } + GUILayout.Label("Assignment will be canceled in " + (int)Mathf.Ceil(num) + "...", style_wordWrap); + } + + private void DrawElementAssignmentProtectedConflictWindow(string title, string message) + { + if (dialog.enabled) + { + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.FlexibleSpace(); + if (!(actionQueue.Peek() is ElementAssignmentChange)) + { + dialog.Cancel(); + return; + } + GUILayout.BeginHorizontal(); + dialog.DrawConfirmButton(UserResponse.Custom1, "Add"); + GUILayout.FlexibleSpace(); + dialog.DrawCancelButton(); + GUILayout.EndHorizontal(); + } + } + + private void DrawElementAssignmentNormalConflictWindow(string title, string message) + { + if (dialog.enabled) + { + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.FlexibleSpace(); + if (!(actionQueue.Peek() is ElementAssignmentChange)) + { + dialog.Cancel(); + return; + } + GUILayout.BeginHorizontal(); + dialog.DrawConfirmButton(UserResponse.Confirm, "Replace"); + GUILayout.FlexibleSpace(); + dialog.DrawConfirmButton(UserResponse.Custom1, "Add"); + GUILayout.FlexibleSpace(); + dialog.DrawCancelButton(); + GUILayout.EndHorizontal(); + } + } + + private void DrawReassignOrRemoveElementAssignmentWindow(string title, string message) + { + if (dialog.enabled) + { + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(); + dialog.DrawConfirmButton("Reassign"); + GUILayout.FlexibleSpace(); + dialog.DrawCancelButton("Remove"); + GUILayout.EndHorizontal(); + } + } + + private void DrawFallbackJoystickIdentificationWindow(string title, string message) + { + if (!dialog.enabled) + { + return; + } + if (!(actionQueue.Peek() is FallbackJoystickIdentification fallbackJoystickIdentification)) + { + dialog.Cancel(); + return; + } + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.Label("Press any button or axis on \"" + fallbackJoystickIdentification.joystickName + "\" now.", style_wordWrap); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Skip")) + { + dialog.Cancel(); + } + else if (!dialog.busy && ReInput.controllers.SetUnityJoystickIdFromAnyButtonOrAxisPress(fallbackJoystickIdentification.joystickId, 0.8f, positiveAxesOnly: false)) + { + dialog.Confirm(); + } + } + + private void DrawCalibrationWindow(string title, string message) + { + if (!dialog.enabled) + { + return; + } + if (!(actionQueue.Peek() is Calibration calibration)) + { + dialog.Cancel(); + return; + } + GUILayout.Space(5f); + GUILayout.Label(message, style_wordWrap); + GUILayout.Space(20f); + GUILayout.BeginHorizontal(); + bool flag = GUI.enabled; + GUILayout.BeginVertical(GUILayout.Width(200f)); + calibrateScrollPos = GUILayout.BeginScrollView(calibrateScrollPos); + if (calibration.recording) + { + GUI.enabled = false; + } + IList<ControllerElementIdentifier> axisElementIdentifiers = calibration.joystick.AxisElementIdentifiers; + for (int i = 0; i < axisElementIdentifiers.Count; i++) + { + ControllerElementIdentifier controllerElementIdentifier = axisElementIdentifiers[i]; + bool flag2 = calibration.selectedElementIdentifierId == controllerElementIdentifier.id; + bool flag3 = GUILayout.Toggle(flag2, controllerElementIdentifier.name, "Button", GUILayout.ExpandWidth(expand: false)); + if (flag2 != flag3) + { + calibration.selectedElementIdentifierId = controllerElementIdentifier.id; + } + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + GUILayout.EndScrollView(); + GUILayout.EndVertical(); + GUILayout.BeginVertical(GUILayout.Width(200f)); + if (calibration.selectedElementIdentifierId >= 0) + { + float axisRawById = calibration.joystick.GetAxisRawById(calibration.selectedElementIdentifierId); + GUILayout.Label("Raw Value: " + axisRawById); + int axisIndexById = calibration.joystick.GetAxisIndexById(calibration.selectedElementIdentifierId); + AxisCalibration axis = calibration.calibrationMap.GetAxis(axisIndexById); + GUILayout.Label("Calibrated Value: " + calibration.joystick.GetAxisById(calibration.selectedElementIdentifierId)); + GUILayout.Label("Zero: " + axis.calibratedZero); + GUILayout.Label("Min: " + axis.calibratedMin); + GUILayout.Label("Max: " + axis.calibratedMax); + GUILayout.Label("Dead Zone: " + axis.deadZone); + GUILayout.Space(15f); + bool flag4 = GUILayout.Toggle(axis.enabled, "Enabled", "Button", GUILayout.ExpandWidth(expand: false)); + if (axis.enabled != flag4) + { + axis.enabled = flag4; + } + GUILayout.Space(10f); + bool flag5 = GUILayout.Toggle(calibration.recording, "Record Min/Max", "Button", GUILayout.ExpandWidth(expand: false)); + if (flag5 != calibration.recording) + { + if (flag5) + { + axis.calibratedMax = 0f; + axis.calibratedMin = 0f; + } + calibration.recording = flag5; + } + if (calibration.recording) + { + axis.calibratedMin = Mathf.Min(axis.calibratedMin, axisRawById, axis.calibratedMin); + axis.calibratedMax = Mathf.Max(axis.calibratedMax, axisRawById, axis.calibratedMax); + GUI.enabled = false; + } + if (GUILayout.Button("Set Zero", GUILayout.ExpandWidth(expand: false))) + { + axis.calibratedZero = axisRawById; + } + if (GUILayout.Button("Set Dead Zone", GUILayout.ExpandWidth(expand: false))) + { + axis.deadZone = axisRawById; + } + bool flag6 = GUILayout.Toggle(axis.invert, "Invert", "Button", GUILayout.ExpandWidth(expand: false)); + if (axis.invert != flag6) + { + axis.invert = flag6; + } + GUILayout.Space(10f); + if (GUILayout.Button("Reset", GUILayout.ExpandWidth(expand: false))) + { + axis.Reset(); + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + else + { + GUILayout.Label("Select an axis to begin."); + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + if (calibration.recording) + { + GUI.enabled = false; + } + if (GUILayout.Button("Close")) + { + calibrateScrollPos = default(Vector2); + dialog.Confirm(); + } + if (GUI.enabled != flag) + { + GUI.enabled = flag; + } + } + + private void DialogResultCallback(int queueActionId, UserResponse response) + { + foreach (QueueEntry item in actionQueue) + { + if (item.id == queueActionId) + { + if (response != UserResponse.Cancel) + { + item.Confirm(response); + } + else + { + item.Cancel(); + } + break; + } + } + } + + private Rect GetScreenCenteredRect(float width, float height) + { + return new Rect((float)Screen.width * 0.5f - width * 0.5f, (float)((double)Screen.height * 0.5 - (double)(height * 0.5f)), width, height); + } + + private void EnqueueAction(QueueEntry entry) + { + if (entry != null) + { + busy = true; + GUI.enabled = false; + actionQueue.Enqueue(entry); + } + } + + private void ProcessQueue() + { + if (dialog.enabled || busy || actionQueue.Count == 0) + { + return; + } + while (actionQueue.Count > 0) + { + QueueEntry queueEntry = actionQueue.Peek(); + bool flag = false; + switch (queueEntry.queueActionType) + { + case QueueActionType.JoystickAssignment: + flag = ProcessJoystickAssignmentChange((JoystickAssignmentChange)queueEntry); + break; + case QueueActionType.ElementAssignment: + flag = ProcessElementAssignmentChange((ElementAssignmentChange)queueEntry); + break; + case QueueActionType.FallbackJoystickIdentification: + flag = ProcessFallbackJoystickIdentification((FallbackJoystickIdentification)queueEntry); + break; + case QueueActionType.Calibrate: + flag = ProcessCalibration((Calibration)queueEntry); + break; + } + if (flag) + { + actionQueue.Dequeue(); + continue; + } + break; + } + } + + private bool ProcessJoystickAssignmentChange(JoystickAssignmentChange entry) + { + if (entry.state == QueueEntry.State.Canceled) + { + return true; + } + Player player = ReInput.players.GetPlayer(entry.playerId); + if (player == null) + { + return true; + } + if (!entry.assign) + { + player.controllers.RemoveController(ControllerType.Joystick, entry.joystickId); + ControllerSelectionChanged(); + return true; + } + if (player.controllers.ContainsController(ControllerType.Joystick, entry.joystickId)) + { + return true; + } + if (!ReInput.controllers.IsJoystickAssigned(entry.joystickId) || entry.state == QueueEntry.State.Confirmed) + { + player.controllers.AddController(ControllerType.Joystick, entry.joystickId, removeFromOtherPlayers: true); + ControllerSelectionChanged(); + return true; + } + dialog.StartModal(entry.id, DialogHelper.DialogType.JoystickConflict, new WindowProperties + { + title = "Joystick Reassignment", + message = "This joystick is already assigned to another player. Do you want to reassign this joystick to " + player.descriptiveName + "?", + rect = GetScreenCenteredRect(250f, 200f), + windowDrawDelegate = DrawModalWindow + }, DialogResultCallback); + return false; + } + + private bool ProcessElementAssignmentChange(ElementAssignmentChange entry) + { + switch (entry.changeType) + { + case ElementAssignmentChangeType.ReassignOrRemove: + return ProcessRemoveOrReassignElementAssignment(entry); + case ElementAssignmentChangeType.Remove: + return ProcessRemoveElementAssignment(entry); + case ElementAssignmentChangeType.Add: + case ElementAssignmentChangeType.Replace: + return ProcessAddOrReplaceElementAssignment(entry); + case ElementAssignmentChangeType.ConflictCheck: + return ProcessElementAssignmentConflictCheck(entry); + default: + throw new NotImplementedException(); + } + } + + private bool ProcessRemoveOrReassignElementAssignment(ElementAssignmentChange entry) + { + if (entry.context.controllerMap == null) + { + return true; + } + if (entry.state == QueueEntry.State.Canceled) + { + ElementAssignmentChange elementAssignmentChange = new ElementAssignmentChange(entry); + elementAssignmentChange.changeType = ElementAssignmentChangeType.Remove; + actionQueue.Enqueue(elementAssignmentChange); + return true; + } + if (entry.state == QueueEntry.State.Confirmed) + { + ElementAssignmentChange elementAssignmentChange2 = new ElementAssignmentChange(entry); + elementAssignmentChange2.changeType = ElementAssignmentChangeType.Replace; + actionQueue.Enqueue(elementAssignmentChange2); + return true; + } + dialog.StartModal(entry.id, DialogHelper.DialogType.AssignElement, new WindowProperties + { + title = "Reassign or Remove", + message = "Do you want to reassign or remove this assignment?", + rect = GetScreenCenteredRect(250f, 200f), + windowDrawDelegate = DrawReassignOrRemoveElementAssignmentWindow + }, DialogResultCallback); + return false; + } + + private bool ProcessRemoveElementAssignment(ElementAssignmentChange entry) + { + if (entry.context.controllerMap == null) + { + return true; + } + if (entry.state == QueueEntry.State.Canceled) + { + return true; + } + if (entry.state == QueueEntry.State.Confirmed) + { + entry.context.controllerMap.DeleteElementMap(entry.context.actionElementMapToReplace.id); + return true; + } + dialog.StartModal(entry.id, DialogHelper.DialogType.DeleteAssignmentConfirmation, new WindowProperties + { + title = "Remove Assignment", + message = "Are you sure you want to remove this assignment?", + rect = GetScreenCenteredRect(250f, 200f), + windowDrawDelegate = DrawModalWindow + }, DialogResultCallback); + return false; + } + + private bool ProcessAddOrReplaceElementAssignment(ElementAssignmentChange entry) + { + if (entry.state == QueueEntry.State.Canceled) + { + inputMapper.Stop(); + return true; + } + if (entry.state == QueueEntry.State.Confirmed) + { + if (Event.current.type != EventType.Layout) + { + return false; + } + if (conflictFoundEventData != null) + { + ElementAssignmentChange elementAssignmentChange = new ElementAssignmentChange(entry); + elementAssignmentChange.changeType = ElementAssignmentChangeType.ConflictCheck; + actionQueue.Enqueue(elementAssignmentChange); + } + return true; + } + string text; + if (entry.context.controllerMap.controllerType != 0) + { + text = ((entry.context.controllerMap.controllerType != ControllerType.Mouse) ? "Press any button or axis to assign it to this action." : "Press any mouse button or axis to assign it to this action.\n\nTo assign mouse movement axes, move the mouse quickly in the direction you want mapped to the action. Slow movements will be ignored."); + } + else + { + text = ((Application.platform != 0 && Application.platform != RuntimePlatform.OSXPlayer) ? "Press any key to assign it to this action. You may also use the modifier keys Control, Alt, and Shift. If you wish to assign a modifier key itself to this action, press and hold the key for 1 second." : "Press any key to assign it to this action. You may also use the modifier keys Command, Control, Alt, and Shift. If you wish to assign a modifier key itself to this action, press and hold the key for 1 second."); + if (Application.isEditor) + { + text += "\n\nNOTE: Some modifier key combinations will not work in the Unity Editor, but they will work in a game build."; + } + } + dialog.StartModal(entry.id, DialogHelper.DialogType.AssignElement, new WindowProperties + { + title = "Assign", + message = text, + rect = GetScreenCenteredRect(250f, 200f), + windowDrawDelegate = DrawElementAssignmentWindow + }, DialogResultCallback); + return false; + } + + private bool ProcessElementAssignmentConflictCheck(ElementAssignmentChange entry) + { + if (entry.context.controllerMap == null) + { + return true; + } + if (entry.state == QueueEntry.State.Canceled) + { + inputMapper.Stop(); + return true; + } + if (conflictFoundEventData == null) + { + return true; + } + if (entry.state == QueueEntry.State.Confirmed) + { + if (entry.response == UserResponse.Confirm) + { + conflictFoundEventData.responseCallback(InputMapper.ConflictResponse.Replace); + } + else + { + if (entry.response != UserResponse.Custom1) + { + throw new NotImplementedException(); + } + conflictFoundEventData.responseCallback(InputMapper.ConflictResponse.Add); + } + return true; + } + if (conflictFoundEventData.isProtected) + { + string message = conflictFoundEventData.assignment.elementDisplayName + " is already in use and is protected from reassignment. You cannot remove the protected assignment, but you can still assign the action to this element. If you do so, the element will trigger multiple actions when activated."; + dialog.StartModal(entry.id, DialogHelper.DialogType.AssignElement, new WindowProperties + { + title = "Assignment Conflict", + message = message, + rect = GetScreenCenteredRect(250f, 200f), + windowDrawDelegate = DrawElementAssignmentProtectedConflictWindow + }, DialogResultCallback); + } + else + { + string message2 = conflictFoundEventData.assignment.elementDisplayName + " is already in use. You may replace the other conflicting assignments, add this assignment anyway which will leave multiple actions assigned to this element, or cancel this assignment."; + dialog.StartModal(entry.id, DialogHelper.DialogType.AssignElement, new WindowProperties + { + title = "Assignment Conflict", + message = message2, + rect = GetScreenCenteredRect(250f, 200f), + windowDrawDelegate = DrawElementAssignmentNormalConflictWindow + }, DialogResultCallback); + } + return false; + } + + private bool ProcessFallbackJoystickIdentification(FallbackJoystickIdentification entry) + { + if (entry.state == QueueEntry.State.Canceled) + { + return true; + } + if (entry.state == QueueEntry.State.Confirmed) + { + return true; + } + dialog.StartModal(entry.id, DialogHelper.DialogType.JoystickConflict, new WindowProperties + { + title = "Joystick Identification Required", + message = "A joystick has been attached or removed. You will need to identify each joystick by pressing a button on the controller listed below:", + rect = GetScreenCenteredRect(250f, 200f), + windowDrawDelegate = DrawFallbackJoystickIdentificationWindow + }, DialogResultCallback, 1f); + return false; + } + + private bool ProcessCalibration(Calibration entry) + { + if (entry.state == QueueEntry.State.Canceled) + { + return true; + } + if (entry.state == QueueEntry.State.Confirmed) + { + return true; + } + dialog.StartModal(entry.id, DialogHelper.DialogType.JoystickConflict, new WindowProperties + { + title = "Calibrate Controller", + message = "Select an axis to calibrate on the " + entry.joystick.name + ".", + rect = GetScreenCenteredRect(450f, 480f), + windowDrawDelegate = DrawCalibrationWindow + }, DialogResultCallback); + return false; + } + + private void PlayerSelectionChanged() + { + ClearControllerSelection(); + } + + private void ControllerSelectionChanged() + { + ClearMapSelection(); + } + + private void ClearControllerSelection() + { + selectedController.Clear(); + ClearMapSelection(); + } + + private void ClearMapSelection() + { + selectedMapCategoryId = -1; + selectedMap = null; + } + + private void ResetAll() + { + ClearWorkingVars(); + initialized = false; + showMenu = false; + } + + private void ClearWorkingVars() + { + selectedPlayer = null; + ClearMapSelection(); + selectedController.Clear(); + actionScrollPos = default(Vector2); + dialog.FullReset(); + actionQueue.Clear(); + busy = false; + startListening = false; + conflictFoundEventData = null; + inputMapper.Stop(); + } + + private void SetGUIStateStart() + { + guiState = true; + if (busy) + { + guiState = false; + } + pageGUIState = guiState && !busy && !dialog.enabled && !dialog.busy; + if (GUI.enabled != guiState) + { + GUI.enabled = guiState; + } + } + + private void SetGUIStateEnd() + { + guiState = true; + if (!GUI.enabled) + { + GUI.enabled = guiState; + } + } + + private void JoystickConnected(ControllerStatusChangedEventArgs args) + { + if (ReInput.controllers.IsControllerAssigned(args.controllerType, args.controllerId)) + { + foreach (Player allPlayer in ReInput.players.AllPlayers) + { + if (allPlayer.controllers.ContainsController(args.controllerType, args.controllerId)) + { + ReInput.userDataStore.LoadControllerData(allPlayer.id, args.controllerType, args.controllerId); + } + } + } + else + { + ReInput.userDataStore.LoadControllerData(args.controllerType, args.controllerId); + } + if (ReInput.unityJoystickIdentificationRequired) + { + IdentifyAllJoysticks(); + } + } + + private void JoystickPreDisconnect(ControllerStatusChangedEventArgs args) + { + if (selectedController.hasSelection && args.controllerType == selectedController.type && args.controllerId == selectedController.id) + { + ClearControllerSelection(); + } + if (!showMenu) + { + return; + } + if (ReInput.controllers.IsControllerAssigned(args.controllerType, args.controllerId)) + { + foreach (Player allPlayer in ReInput.players.AllPlayers) + { + if (allPlayer.controllers.ContainsController(args.controllerType, args.controllerId)) + { + ReInput.userDataStore.SaveControllerData(allPlayer.id, args.controllerType, args.controllerId); + } + } + return; + } + ReInput.userDataStore.SaveControllerData(args.controllerType, args.controllerId); + } + + private void JoystickDisconnected(ControllerStatusChangedEventArgs args) + { + if (showMenu) + { + ClearWorkingVars(); + } + if (ReInput.unityJoystickIdentificationRequired) + { + IdentifyAllJoysticks(); + } + } + + private void OnConflictFound(InputMapper.ConflictFoundEventData data) + { + conflictFoundEventData = data; + } + + private void OnStopped(InputMapper.StoppedEventData data) + { + conflictFoundEventData = null; + } + + public void IdentifyAllJoysticks() + { + if (ReInput.controllers.joystickCount == 0) + { + return; + } + ClearWorkingVars(); + Open(); + foreach (Joystick joystick in ReInput.controllers.Joysticks) + { + actionQueue.Enqueue(new FallbackJoystickIdentification(joystick.id, joystick.name)); + } + } + + protected void CheckRecompile() + { + } + + private void RecompileWindow(int windowId) + { + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllerDemo.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllerDemo.cs new file mode 100644 index 0000000..2c67e86 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllerDemo.cs @@ -0,0 +1,144 @@ +using System; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class CustomControllerDemo : MonoBehaviour +{ + public int playerId; + + public string controllerTag; + + public bool useUpdateCallbacks; + + private int buttonCount; + + private int axisCount; + + private float[] axisValues; + + private bool[] buttonValues; + + private TouchJoystickExample[] joysticks; + + private TouchButtonExample[] buttons; + + private CustomController controller; + + [NonSerialized] + private bool initialized; + + private void Awake() + { + ScreenOrientation screenOrientation = ScreenOrientation.LandscapeLeft; + if (SystemInfo.deviceType == DeviceType.Handheld && Screen.orientation != screenOrientation) + { + Screen.orientation = screenOrientation; + } + Initialize(); + } + + private void Initialize() + { + ReInput.InputSourceUpdateEvent += OnInputSourceUpdate; + joysticks = GetComponentsInChildren<TouchJoystickExample>(); + buttons = GetComponentsInChildren<TouchButtonExample>(); + axisCount = joysticks.Length * 2; + buttonCount = buttons.Length; + axisValues = new float[axisCount]; + buttonValues = new bool[buttonCount]; + Player player = ReInput.players.GetPlayer(playerId); + controller = player.controllers.GetControllerWithTag<CustomController>(controllerTag); + if (controller == null) + { + Debug.LogError("A matching controller was not found for tag \"" + controllerTag + "\""); + } + if (controller.buttonCount != buttonValues.Length || controller.axisCount != axisValues.Length) + { + Debug.LogError("Controller has wrong number of elements!"); + } + if (useUpdateCallbacks && controller != null) + { + controller.SetAxisUpdateCallback(GetAxisValueCallback); + controller.SetButtonUpdateCallback(GetButtonValueCallback); + } + initialized = true; + } + + private void Update() + { + if (ReInput.isReady && !initialized) + { + Initialize(); + } + } + + private void OnInputSourceUpdate() + { + GetSourceAxisValues(); + GetSourceButtonValues(); + if (!useUpdateCallbacks) + { + SetControllerAxisValues(); + SetControllerButtonValues(); + } + } + + private void GetSourceAxisValues() + { + for (int i = 0; i < axisValues.Length; i++) + { + if (i % 2 != 0) + { + axisValues[i] = joysticks[i / 2].position.y; + } + else + { + axisValues[i] = joysticks[i / 2].position.x; + } + } + } + + private void GetSourceButtonValues() + { + for (int i = 0; i < buttonValues.Length; i++) + { + buttonValues[i] = buttons[i].isPressed; + } + } + + private void SetControllerAxisValues() + { + for (int i = 0; i < axisValues.Length; i++) + { + controller.SetAxisValue(i, axisValues[i]); + } + } + + private void SetControllerButtonValues() + { + for (int i = 0; i < buttonValues.Length; i++) + { + controller.SetButtonValue(i, buttonValues[i]); + } + } + + private float GetAxisValueCallback(int index) + { + if (index >= axisValues.Length) + { + return 0f; + } + return axisValues[index]; + } + + private bool GetButtonValueCallback(int index) + { + if (index >= buttonValues.Length) + { + return false; + } + return buttonValues[index]; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllerDemo_Player.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllerDemo_Player.cs new file mode 100644 index 0000000..7c4346a --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllerDemo_Player.cs @@ -0,0 +1,58 @@ +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +[RequireComponent(typeof(CharacterController))] +public class CustomControllerDemo_Player : MonoBehaviour +{ + public int playerId; + + public float speed = 1f; + + public float bulletSpeed = 20f; + + public GameObject bulletPrefab; + + private Player _player; + + private CharacterController cc; + + private Player player + { + get + { + if (_player == null) + { + _player = ReInput.players.GetPlayer(playerId); + } + return _player; + } + } + + private void Awake() + { + cc = GetComponent<CharacterController>(); + } + + private void Update() + { + if (ReInput.isReady) + { + Vector2 vector = new Vector2(player.GetAxis("Move Horizontal"), player.GetAxis("Move Vertical")); + cc.Move(vector * speed * Time.deltaTime); + if (player.GetButtonDown("Fire")) + { + Vector3 vector2 = Vector3.Scale(new Vector3(1f, 0f, 0f), base.transform.right); + Object.Instantiate(bulletPrefab, base.transform.position + vector2, Quaternion.identity).GetComponent<Rigidbody>().velocity = new Vector3(bulletSpeed * base.transform.right.x, 0f, 0f); + } + if (player.GetButtonDown("Change Color")) + { + Renderer component = GetComponent<Renderer>(); + Material material = component.material; + material.color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1f); + component.material = material; + } + } + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllersTiltDemo.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllersTiltDemo.cs new file mode 100644 index 0000000..d24caf2 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/CustomControllersTiltDemo.cs @@ -0,0 +1,47 @@ +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class CustomControllersTiltDemo : MonoBehaviour +{ + public Transform target; + + public float speed = 10f; + + private CustomController controller; + + private Player player; + + private void Awake() + { + Screen.orientation = ScreenOrientation.LandscapeLeft; + player = ReInput.players.GetPlayer(0); + ReInput.InputSourceUpdateEvent += OnInputUpdate; + controller = (CustomController)player.controllers.GetControllerWithTag(ControllerType.Custom, "TiltController"); + } + + private void Update() + { + if (!(target == null)) + { + Vector3 zero = Vector3.zero; + zero.y = player.GetAxis("Tilt Vertical"); + zero.x = player.GetAxis("Tilt Horizontal"); + if (zero.sqrMagnitude > 1f) + { + zero.Normalize(); + } + zero *= Time.deltaTime; + target.Translate(zero * speed); + } + } + + private void OnInputUpdate() + { + Vector3 acceleration = Input.acceleration; + controller.SetAxisValue(0, acceleration.x); + controller.SetAxisValue(1, acceleration.y); + controller.SetAxisValue(2, acceleration.z); + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/DualShock4SpecialFeaturesExample.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/DualShock4SpecialFeaturesExample.cs new file mode 100644 index 0000000..838b779 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/DualShock4SpecialFeaturesExample.cs @@ -0,0 +1,219 @@ +using System.Collections.Generic; +using Rewired.ControllerExtensions; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class DualShock4SpecialFeaturesExample : MonoBehaviour +{ + private class Touch + { + public GameObject go; + + public int touchId = -1; + } + + private const int maxTouches = 2; + + public int playerId; + + public Transform touchpadTransform; + + public GameObject lightObject; + + public Transform accelerometerTransform; + + private List<Touch> touches; + + private Queue<Touch> unusedTouches; + + private bool isFlashing; + + private GUIStyle textStyle; + + private Player player => ReInput.players.GetPlayer(playerId); + + private void Awake() + { + InitializeTouchObjects(); + } + + private void Update() + { + if (!ReInput.isReady) + { + return; + } + IDualShock4Extension firstDS = GetFirstDS4(player); + if (firstDS != null) + { + base.transform.rotation = firstDS.GetOrientation(); + HandleTouchpad(firstDS); + Vector3 accelerometerValue = firstDS.GetAccelerometerValue(); + accelerometerTransform.LookAt(accelerometerTransform.position + accelerometerValue); + } + if (player.GetButtonDown("CycleLight")) + { + SetRandomLightColor(); + } + if (player.GetButtonDown("ResetOrientation")) + { + ResetOrientation(); + } + if (player.GetButtonDown("ToggleLightFlash")) + { + if (isFlashing) + { + StopLightFlash(); + } + else + { + StartLightFlash(); + } + isFlashing = !isFlashing; + } + if (player.GetButtonDown("VibrateLeft")) + { + firstDS.SetVibration(0, 1f, 1f); + } + if (player.GetButtonDown("VibrateRight")) + { + firstDS.SetVibration(1, 1f, 1f); + } + } + + private void OnGUI() + { + if (textStyle == null) + { + textStyle = new GUIStyle(GUI.skin.label); + textStyle.fontSize = 20; + textStyle.wordWrap = true; + } + if (GetFirstDS4(player) != null) + { + GUILayout.BeginArea(new Rect(200f, 100f, (float)Screen.width - 400f, (float)Screen.height - 200f)); + GUILayout.Label("Rotate the Dual Shock 4 to see the model rotate in sync.", textStyle); + GUILayout.Label("Touch the touchpad to see them appear on the model.", textStyle); + ActionElementMap firstElementMapWithAction = player.controllers.maps.GetFirstElementMapWithAction(ControllerType.Joystick, "ResetOrientation", skipDisabledMaps: true); + if (firstElementMapWithAction != null) + { + GUILayout.Label("Press " + firstElementMapWithAction.elementIdentifierName + " to reset the orientation. Hold the gamepad facing the screen with sticks pointing up and press the button.", textStyle); + } + firstElementMapWithAction = player.controllers.maps.GetFirstElementMapWithAction(ControllerType.Joystick, "CycleLight", skipDisabledMaps: true); + if (firstElementMapWithAction != null) + { + GUILayout.Label("Press " + firstElementMapWithAction.elementIdentifierName + " to change the light color.", textStyle); + } + firstElementMapWithAction = player.controllers.maps.GetFirstElementMapWithAction(ControllerType.Joystick, "ToggleLightFlash", skipDisabledMaps: true); + if (firstElementMapWithAction != null) + { + GUILayout.Label("Press " + firstElementMapWithAction.elementIdentifierName + " to start or stop the light flashing.", textStyle); + } + firstElementMapWithAction = player.controllers.maps.GetFirstElementMapWithAction(ControllerType.Joystick, "VibrateLeft", skipDisabledMaps: true); + if (firstElementMapWithAction != null) + { + GUILayout.Label("Press " + firstElementMapWithAction.elementIdentifierName + " vibrate the left motor.", textStyle); + } + firstElementMapWithAction = player.controllers.maps.GetFirstElementMapWithAction(ControllerType.Joystick, "VibrateRight", skipDisabledMaps: true); + if (firstElementMapWithAction != null) + { + GUILayout.Label("Press " + firstElementMapWithAction.elementIdentifierName + " vibrate the right motor.", textStyle); + } + GUILayout.EndArea(); + } + } + + private void ResetOrientation() + { + GetFirstDS4(player)?.ResetOrientation(); + } + + private void SetRandomLightColor() + { + IDualShock4Extension firstDS = GetFirstDS4(player); + if (firstDS != null) + { + Color color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1f); + firstDS.SetLightColor(color); + lightObject.GetComponent<MeshRenderer>().material.color = color; + } + } + + private void StartLightFlash() + { + if (GetFirstDS4(player) is DualShock4Extension dualShock4Extension) + { + dualShock4Extension.SetLightFlash(0.5f, 0.5f); + } + } + + private void StopLightFlash() + { + if (GetFirstDS4(player) is DualShock4Extension dualShock4Extension) + { + dualShock4Extension.StopLightFlash(); + } + } + + private IDualShock4Extension GetFirstDS4(Player player) + { + foreach (Joystick joystick in player.controllers.Joysticks) + { + IDualShock4Extension extension = joystick.GetExtension<IDualShock4Extension>(); + if (extension != null) + { + return extension; + } + } + return null; + } + + private void InitializeTouchObjects() + { + touches = new List<Touch>(2); + unusedTouches = new Queue<Touch>(2); + for (int i = 0; i < 2; i++) + { + Touch touch = new Touch(); + touch.go = GameObject.CreatePrimitive(PrimitiveType.Sphere); + touch.go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); + touch.go.transform.SetParent(touchpadTransform, worldPositionStays: true); + touch.go.GetComponent<MeshRenderer>().material.color = ((i == 0) ? Color.red : Color.green); + touch.go.SetActive(value: false); + unusedTouches.Enqueue(touch); + } + } + + private void HandleTouchpad(IDualShock4Extension ds4) + { + for (int num = touches.Count - 1; num >= 0; num--) + { + Touch touch = touches[num]; + if (!ds4.IsTouchingByTouchId(touch.touchId)) + { + touch.go.SetActive(value: false); + unusedTouches.Enqueue(touch); + touches.RemoveAt(num); + } + } + for (int i = 0; i < ds4.maxTouches; i++) + { + if (ds4.IsTouching(i)) + { + int touchId = ds4.GetTouchId(i); + Touch touch2 = touches.Find((Touch x) => x.touchId == touchId); + if (touch2 == null) + { + touch2 = unusedTouches.Dequeue(); + touches.Add(touch2); + } + touch2.touchId = touchId; + touch2.go.SetActive(value: true); + ds4.GetTouchPosition(i, out var position); + touch2.go.transform.localPosition = new Vector3(position.x - 0.5f, 0.5f + touch2.go.transform.localScale.y * 0.5f, position.y - 0.5f); + } + } + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/EightPlayersExample_Player.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/EightPlayersExample_Player.cs new file mode 100644 index 0000000..0ce56e1 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/EightPlayersExample_Player.cs @@ -0,0 +1,71 @@ +using System; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +[RequireComponent(typeof(CharacterController))] +public class EightPlayersExample_Player : MonoBehaviour +{ + public int playerId; + + public float moveSpeed = 3f; + + public float bulletSpeed = 15f; + + public GameObject bulletPrefab; + + private Player player; + + private CharacterController cc; + + private Vector3 moveVector; + + private bool fire; + + [NonSerialized] + private bool initialized; + + private void Awake() + { + cc = GetComponent<CharacterController>(); + } + + private void Initialize() + { + player = ReInput.players.GetPlayer(playerId); + initialized = true; + } + + private void Update() + { + if (ReInput.isReady) + { + if (!initialized) + { + Initialize(); + } + GetInput(); + ProcessInput(); + } + } + + private void GetInput() + { + moveVector.x = player.GetAxis("Move Horizontal"); + moveVector.y = player.GetAxis("Move Vertical"); + fire = player.GetButtonDown("Fire"); + } + + private void ProcessInput() + { + if (moveVector.x != 0f || moveVector.y != 0f) + { + cc.Move(moveVector * moveSpeed * Time.deltaTime); + } + if (fire) + { + UnityEngine.Object.Instantiate(bulletPrefab, base.transform.position + base.transform.right, base.transform.rotation).GetComponent<Rigidbody>().AddForce(base.transform.right * bulletSpeed, ForceMode.VelocityChange); + } + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/FallbackJoystickIdentificationDemo.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/FallbackJoystickIdentificationDemo.cs new file mode 100644 index 0000000..3213b71 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/FallbackJoystickIdentificationDemo.cs @@ -0,0 +1,114 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class FallbackJoystickIdentificationDemo : MonoBehaviour +{ + private const float windowWidth = 250f; + + private const float windowHeight = 250f; + + private const float inputDelay = 1f; + + private bool identifyRequired; + + private Queue<Joystick> joysticksToIdentify; + + private float nextInputAllowedTime; + + private GUIStyle style; + + private void Awake() + { + if (ReInput.unityJoystickIdentificationRequired) + { + ReInput.ControllerConnectedEvent += JoystickConnected; + ReInput.ControllerDisconnectedEvent += JoystickDisconnected; + IdentifyAllJoysticks(); + } + } + + private void JoystickConnected(ControllerStatusChangedEventArgs args) + { + IdentifyAllJoysticks(); + } + + private void JoystickDisconnected(ControllerStatusChangedEventArgs args) + { + IdentifyAllJoysticks(); + } + + public void IdentifyAllJoysticks() + { + Reset(); + if (ReInput.controllers.joystickCount != 0) + { + Joystick[] joysticks = ReInput.controllers.GetJoysticks(); + if (joysticks != null) + { + identifyRequired = true; + joysticksToIdentify = new Queue<Joystick>(joysticks); + SetInputDelay(); + } + } + } + + private void SetInputDelay() + { + nextInputAllowedTime = Time.time + 1f; + } + + private void OnGUI() + { + if (!identifyRequired) + { + return; + } + if (joysticksToIdentify == null || joysticksToIdentify.Count == 0) + { + Reset(); + return; + } + Rect screenRect = new Rect((float)Screen.width * 0.5f - 125f, (float)Screen.height * 0.5f - 125f, 250f, 250f); + GUILayout.Window(0, screenRect, DrawDialogWindow, "Joystick Identification Required"); + GUI.FocusWindow(0); + if (!(Time.time < nextInputAllowedTime) && ReInput.controllers.SetUnityJoystickIdFromAnyButtonOrAxisPress(joysticksToIdentify.Peek().id, 0.8f, positiveAxesOnly: false)) + { + joysticksToIdentify.Dequeue(); + SetInputDelay(); + if (joysticksToIdentify.Count == 0) + { + Reset(); + } + } + } + + private void DrawDialogWindow(int windowId) + { + if (identifyRequired) + { + if (style == null) + { + style = new GUIStyle(GUI.skin.label); + style.wordWrap = true; + } + GUILayout.Space(15f); + GUILayout.Label("A joystick has been attached or removed. You will need to identify each joystick by pressing a button on the controller listed below:", style); + Joystick joystick = joysticksToIdentify.Peek(); + GUILayout.Label("Press any button on \"" + joystick.name + "\" now.", style); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Skip")) + { + joysticksToIdentify.Dequeue(); + } + } + } + + private void Reset() + { + joysticksToIdentify = null; + identifyRequired = false; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/PlayerMouseSpriteExample.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/PlayerMouseSpriteExample.cs new file mode 100644 index 0000000..194fb5d --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/PlayerMouseSpriteExample.cs @@ -0,0 +1,116 @@ +using System; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class PlayerMouseSpriteExample : MonoBehaviour +{ + [Tooltip("The Player that will control the mouse")] + public int playerId; + + [Tooltip("The Rewired Action used for the mouse horizontal axis.")] + public string horizontalAction = "MouseX"; + + [Tooltip("The Rewired Action used for the mouse vertical axis.")] + public string verticalAction = "MouseY"; + + [Tooltip("The Rewired Action used for the mouse wheel axis.")] + public string wheelAction = "MouseWheel"; + + [Tooltip("The Rewired Action used for the mouse left button.")] + public string leftButtonAction = "MouseLeftButton"; + + [Tooltip("The Rewired Action used for the mouse right button.")] + public string rightButtonAction = "MouseRightButton"; + + [Tooltip("The Rewired Action used for the mouse middle button.")] + public string middleButtonAction = "MouseMiddleButton"; + + [Tooltip("The distance from the camera that the pointer will be drawn.")] + public float distanceFromCamera = 1f; + + [Tooltip("The scale of the sprite pointer.")] + public float spriteScale = 0.05f; + + [Tooltip("The pointer prefab.")] + public GameObject pointerPrefab; + + [Tooltip("The click effect prefab.")] + public GameObject clickEffectPrefab; + + [Tooltip("Should the hardware pointer be hidden?")] + public bool hideHardwarePointer = true; + + [NonSerialized] + private GameObject pointer; + + [NonSerialized] + private PlayerMouse mouse; + + private void Awake() + { + pointer = UnityEngine.Object.Instantiate(pointerPrefab); + pointer.transform.localScale = new Vector3(spriteScale, spriteScale, spriteScale); + if (hideHardwarePointer) + { + Cursor.visible = false; + } + mouse = PlayerMouse.Factory.Create(); + mouse.playerId = playerId; + mouse.xAxis.actionName = horizontalAction; + mouse.yAxis.actionName = verticalAction; + mouse.wheel.yAxis.actionName = wheelAction; + mouse.leftButton.actionName = leftButtonAction; + mouse.rightButton.actionName = rightButtonAction; + mouse.middleButton.actionName = middleButtonAction; + mouse.pointerSpeed = 1f; + mouse.wheel.yAxis.repeatRate = 5f; + mouse.screenPosition = new Vector2((float)Screen.width * 0.5f, (float)Screen.height * 0.5f); + mouse.ScreenPositionChangedEvent += OnScreenPositionChanged; + OnScreenPositionChanged(mouse.screenPosition); + } + + private void Update() + { + if (ReInput.isReady) + { + pointer.transform.Rotate(Vector3.forward, mouse.wheel.yAxis.value * 20f); + if (mouse.leftButton.justPressed) + { + CreateClickEffect(new Color(0f, 1f, 0f, 1f)); + } + if (mouse.rightButton.justPressed) + { + CreateClickEffect(new Color(1f, 0f, 0f, 1f)); + } + if (mouse.middleButton.justPressed) + { + CreateClickEffect(new Color(1f, 1f, 0f, 1f)); + } + } + } + + private void OnDestroy() + { + if (ReInput.isReady) + { + mouse.ScreenPositionChangedEvent -= OnScreenPositionChanged; + } + } + + private void CreateClickEffect(Color color) + { + GameObject obj = UnityEngine.Object.Instantiate(clickEffectPrefab); + obj.transform.localScale = new Vector3(spriteScale, spriteScale, spriteScale); + obj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(mouse.screenPosition.x, mouse.screenPosition.y, distanceFromCamera)); + obj.GetComponentInChildren<SpriteRenderer>().color = color; + UnityEngine.Object.Destroy(obj, 0.5f); + } + + private void OnScreenPositionChanged(Vector2 position) + { + Vector3 position2 = Camera.main.ScreenToWorldPoint(new Vector3(position.x, position.y, distanceFromCamera)); + pointer.transform.position = position2; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/PlayerPointerEventHandlerExample.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/PlayerPointerEventHandlerExample.cs new file mode 100644 index 0000000..dde8871 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/PlayerPointerEventHandlerExample.cs @@ -0,0 +1,138 @@ +using System.Collections.Generic; +using System.Text; +using Rewired.Integration.UnityUI; +using UnityEngine; +using UnityEngine.EventSystems; +using UnityEngine.UI; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public sealed class PlayerPointerEventHandlerExample : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler, IPointerUpHandler, IPointerDownHandler, IPointerClickHandler, IScrollHandler, IBeginDragHandler, IDragHandler, IEndDragHandler +{ + public Text text; + + private const int logLength = 10; + + private List<string> log = new List<string>(); + + private void Log(string o) + { + log.Add(o); + if (log.Count > 10) + { + log.RemoveAt(0); + } + } + + private void Update() + { + if (!(text != null)) + { + return; + } + StringBuilder stringBuilder = new StringBuilder(); + foreach (string item in log) + { + stringBuilder.AppendLine(item); + } + text.text = stringBuilder.ToString(); + } + + public void OnPointerEnter(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnPointerEnter: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData)); + } + } + + public void OnPointerExit(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnPointerExit: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData)); + } + } + + public void OnPointerUp(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnPointerUp: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData) + ", Button Index = " + playerPointerEventData.buttonIndex); + } + } + + public void OnPointerDown(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnPointerDown: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData) + ", Button Index = " + playerPointerEventData.buttonIndex); + } + } + + public void OnPointerClick(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnPointerClick: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData) + ", Button Index = " + playerPointerEventData.buttonIndex); + } + } + + public void OnScroll(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnScroll: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData)); + } + } + + public void OnBeginDrag(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnBeginDrag: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData) + ", Button Index = " + playerPointerEventData.buttonIndex); + } + } + + public void OnDrag(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnDrag: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData) + ", Button Index = " + playerPointerEventData.buttonIndex); + } + } + + public void OnEndDrag(PointerEventData eventData) + { + if (eventData is PlayerPointerEventData) + { + PlayerPointerEventData playerPointerEventData = (PlayerPointerEventData)eventData; + Log("OnEndDrag: Player = " + playerPointerEventData.playerId + ", Pointer Index = " + playerPointerEventData.inputSourceIndex + ", Source = " + GetSourceName(playerPointerEventData) + ", Button Index = " + playerPointerEventData.buttonIndex); + } + } + + private static string GetSourceName(PlayerPointerEventData playerEventData) + { + if (playerEventData.sourceType == PointerEventType.Mouse) + { + if (playerEventData.mouseSource is Behaviour) + { + return (playerEventData.mouseSource as Behaviour).name; + } + } + else if (playerEventData.sourceType == PointerEventType.Touch && playerEventData.touchSource is Behaviour) + { + return (playerEventData.touchSource as Behaviour).name; + } + return null; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/PressAnyButtonToJoinExample_Assigner.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/PressAnyButtonToJoinExample_Assigner.cs new file mode 100644 index 0000000..83c25e8 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/PressAnyButtonToJoinExample_Assigner.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class PressAnyButtonToJoinExample_Assigner : MonoBehaviour +{ + private void Update() + { + if (ReInput.isReady) + { + AssignJoysticksToPlayers(); + } + } + + private void AssignJoysticksToPlayers() + { + IList<Joystick> joysticks = ReInput.controllers.Joysticks; + for (int i = 0; i < joysticks.Count; i++) + { + Joystick joystick = joysticks[i]; + if (!ReInput.controllers.IsControllerAssigned(joystick.type, joystick.id) && joystick.GetAnyButtonDown()) + { + Player player = FindPlayerWithoutJoystick(); + if (player == null) + { + return; + } + player.controllers.AddController(joystick, removeFromOtherPlayers: false); + } + } + if (DoAllPlayersHaveJoysticks()) + { + ReInput.configuration.autoAssignJoysticks = true; + base.enabled = false; + } + } + + private Player FindPlayerWithoutJoystick() + { + IList<Player> players = ReInput.players.Players; + for (int i = 0; i < players.Count; i++) + { + if (players[i].controllers.joystickCount <= 0) + { + return players[i]; + } + } + return null; + } + + private bool DoAllPlayersHaveJoysticks() + { + return FindPlayerWithoutJoystick() == null; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/PressAnyButtonToJoinExample_GamePlayer.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/PressAnyButtonToJoinExample_GamePlayer.cs new file mode 100644 index 0000000..a0466ce --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/PressAnyButtonToJoinExample_GamePlayer.cs @@ -0,0 +1,67 @@ +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +[RequireComponent(typeof(CharacterController))] +public class PressAnyButtonToJoinExample_GamePlayer : MonoBehaviour +{ + public int playerId; + + public float moveSpeed = 3f; + + public float bulletSpeed = 15f; + + public GameObject bulletPrefab; + + private CharacterController cc; + + private Vector3 moveVector; + + private bool fire; + + private Player player + { + get + { + if (!ReInput.isReady) + { + return null; + } + return ReInput.players.GetPlayer(playerId); + } + } + + private void OnEnable() + { + cc = GetComponent<CharacterController>(); + } + + private void Update() + { + if (ReInput.isReady && player != null) + { + GetInput(); + ProcessInput(); + } + } + + private void GetInput() + { + moveVector.x = player.GetAxis("Move Horizontal"); + moveVector.y = player.GetAxis("Move Vertical"); + fire = player.GetButtonDown("Fire"); + } + + private void ProcessInput() + { + if (moveVector.x != 0f || moveVector.y != 0f) + { + cc.Move(moveVector * moveSpeed * Time.deltaTime); + } + if (fire) + { + Object.Instantiate(bulletPrefab, base.transform.position + base.transform.right, base.transform.rotation).GetComponent<Rigidbody>().AddForce(base.transform.right * bulletSpeed, ForceMode.VelocityChange); + } + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/PressStartToJoinExample_Assigner.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/PressStartToJoinExample_Assigner.cs new file mode 100644 index 0000000..6b23589 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/PressStartToJoinExample_Assigner.cs @@ -0,0 +1,87 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class PressStartToJoinExample_Assigner : MonoBehaviour +{ + private class PlayerMap + { + public int rewiredPlayerId; + + public int gamePlayerId; + + public PlayerMap(int rewiredPlayerId, int gamePlayerId) + { + this.rewiredPlayerId = rewiredPlayerId; + this.gamePlayerId = gamePlayerId; + } + } + + private static PressStartToJoinExample_Assigner instance; + + public int maxPlayers = 4; + + private List<PlayerMap> playerMap; + + private int gamePlayerIdCounter; + + public static Player GetRewiredPlayer(int gamePlayerId) + { + if (!ReInput.isReady) + { + return null; + } + if (instance == null) + { + Debug.LogError("Not initialized. Do you have a PressStartToJoinPlayerSelector in your scehe?"); + return null; + } + for (int i = 0; i < instance.playerMap.Count; i++) + { + if (instance.playerMap[i].gamePlayerId == gamePlayerId) + { + return ReInput.players.GetPlayer(instance.playerMap[i].rewiredPlayerId); + } + } + return null; + } + + private void Awake() + { + playerMap = new List<PlayerMap>(); + instance = this; + } + + private void Update() + { + for (int i = 0; i < ReInput.players.playerCount; i++) + { + if (ReInput.players.GetPlayer(i).GetButtonDown("JoinGame")) + { + AssignNextPlayer(i); + } + } + } + + private void AssignNextPlayer(int rewiredPlayerId) + { + if (playerMap.Count >= maxPlayers) + { + Debug.LogError("Max player limit already reached!"); + return; + } + int nextGamePlayerId = GetNextGamePlayerId(); + playerMap.Add(new PlayerMap(rewiredPlayerId, nextGamePlayerId)); + Player player = ReInput.players.GetPlayer(rewiredPlayerId); + player.controllers.maps.SetMapsEnabled(state: false, "Assignment"); + player.controllers.maps.SetMapsEnabled(state: true, "Default"); + Debug.Log("Added Rewired Player id " + rewiredPlayerId + " to game player " + nextGamePlayerId); + } + + private int GetNextGamePlayerId() + { + return gamePlayerIdCounter++; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/PressStartToJoinExample_GamePlayer.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/PressStartToJoinExample_GamePlayer.cs new file mode 100644 index 0000000..04ee6c4 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/PressStartToJoinExample_GamePlayer.cs @@ -0,0 +1,57 @@ +using UnityEngine; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +[RequireComponent(typeof(CharacterController))] +public class PressStartToJoinExample_GamePlayer : MonoBehaviour +{ + public int gamePlayerId; + + public float moveSpeed = 3f; + + public float bulletSpeed = 15f; + + public GameObject bulletPrefab; + + private CharacterController cc; + + private Vector3 moveVector; + + private bool fire; + + private Player player => PressStartToJoinExample_Assigner.GetRewiredPlayer(gamePlayerId); + + private void OnEnable() + { + cc = GetComponent<CharacterController>(); + } + + private void Update() + { + if (ReInput.isReady && player != null) + { + GetInput(); + ProcessInput(); + } + } + + private void GetInput() + { + moveVector.x = player.GetAxis("Move Horizontal"); + moveVector.y = player.GetAxis("Move Vertical"); + fire = player.GetButtonDown("Fire"); + } + + private void ProcessInput() + { + if (moveVector.x != 0f || moveVector.y != 0f) + { + cc.Move(moveVector * moveSpeed * Time.deltaTime); + } + if (fire) + { + Object.Instantiate(bulletPrefab, base.transform.position + base.transform.right, base.transform.rotation).GetComponent<Rigidbody>().AddForce(base.transform.right * bulletSpeed, ForceMode.VelocityChange); + } + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/SimpleCombinedKeyboardMouseRemapping.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/SimpleCombinedKeyboardMouseRemapping.cs new file mode 100644 index 0000000..3a2544b --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/SimpleCombinedKeyboardMouseRemapping.cs @@ -0,0 +1,225 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class SimpleCombinedKeyboardMouseRemapping : MonoBehaviour +{ + private class Row + { + public InputAction action; + + public AxisRange actionRange; + + public Button button; + + public Text text; + } + + private struct TargetMapping + { + public ControllerMap controllerMap; + + public int actionElementMapId; + } + + private const string category = "Default"; + + private const string layout = "Default"; + + private const string uiCategory = "UI"; + + private InputMapper inputMapper_keyboard = new InputMapper(); + + private InputMapper inputMapper_mouse = new InputMapper(); + + public GameObject buttonPrefab; + + public GameObject textPrefab; + + public RectTransform fieldGroupTransform; + + public RectTransform actionGroupTransform; + + public Text controllerNameUIText; + + public Text statusUIText; + + private List<Row> rows = new List<Row>(); + + private TargetMapping _replaceTargetMapping; + + private Player player => ReInput.players.GetPlayer(0); + + private void OnEnable() + { + if (ReInput.isReady) + { + inputMapper_keyboard.options.timeout = 5f; + inputMapper_mouse.options.timeout = 5f; + inputMapper_mouse.options.ignoreMouseXAxis = true; + inputMapper_mouse.options.ignoreMouseYAxis = true; + inputMapper_keyboard.options.allowButtonsOnFullAxisAssignment = false; + inputMapper_mouse.options.allowButtonsOnFullAxisAssignment = false; + inputMapper_keyboard.InputMappedEvent += OnInputMapped; + inputMapper_keyboard.StoppedEvent += OnStopped; + inputMapper_mouse.InputMappedEvent += OnInputMapped; + inputMapper_mouse.StoppedEvent += OnStopped; + InitializeUI(); + } + } + + private void OnDisable() + { + inputMapper_keyboard.Stop(); + inputMapper_mouse.Stop(); + inputMapper_keyboard.RemoveAllEventListeners(); + inputMapper_mouse.RemoveAllEventListeners(); + } + + private void RedrawUI() + { + controllerNameUIText.text = "Keyboard/Mouse"; + for (int i = 0; i < rows.Count; i++) + { + Row row = rows[i]; + InputAction action = rows[i].action; + string text = string.Empty; + int actionElementMapId = -1; + for (int j = 0; j < 2; j++) + { + ControllerType controllerType = ((j != 0) ? ControllerType.Mouse : ControllerType.Keyboard); + foreach (ActionElementMap item in player.controllers.maps.GetMap(controllerType, 0, "Default", "Default").ElementMapsWithAction(action.id)) + { + if (item.ShowInField(row.actionRange)) + { + text = item.elementIdentifierName; + actionElementMapId = item.id; + break; + } + } + if (actionElementMapId >= 0) + { + break; + } + } + row.text.text = text; + row.button.onClick.RemoveAllListeners(); + int index = i; + row.button.onClick.AddListener(delegate + { + OnInputFieldClicked(index, actionElementMapId); + }); + } + } + + private void ClearUI() + { + controllerNameUIText.text = string.Empty; + for (int i = 0; i < rows.Count; i++) + { + rows[i].text.text = string.Empty; + } + } + + private void InitializeUI() + { + foreach (Transform item in actionGroupTransform) + { + Object.Destroy(item.gameObject); + } + foreach (Transform item2 in fieldGroupTransform) + { + Object.Destroy(item2.gameObject); + } + foreach (InputAction item3 in ReInput.mapping.ActionsInCategory("Default")) + { + if (item3.type == InputActionType.Axis) + { + CreateUIRow(item3, AxisRange.Full, item3.descriptiveName); + CreateUIRow(item3, AxisRange.Positive, (!string.IsNullOrEmpty(item3.positiveDescriptiveName)) ? item3.positiveDescriptiveName : (item3.descriptiveName + " +")); + CreateUIRow(item3, AxisRange.Negative, (!string.IsNullOrEmpty(item3.negativeDescriptiveName)) ? item3.negativeDescriptiveName : (item3.descriptiveName + " -")); + } + else if (item3.type == InputActionType.Button) + { + CreateUIRow(item3, AxisRange.Positive, item3.descriptiveName); + } + } + RedrawUI(); + } + + private void CreateUIRow(InputAction action, AxisRange actionRange, string label) + { + GameObject obj = Object.Instantiate(textPrefab); + obj.transform.SetParent(actionGroupTransform); + obj.transform.SetAsLastSibling(); + obj.GetComponent<Text>().text = label; + GameObject gameObject = Object.Instantiate(buttonPrefab); + gameObject.transform.SetParent(fieldGroupTransform); + gameObject.transform.SetAsLastSibling(); + rows.Add(new Row + { + action = action, + actionRange = actionRange, + button = gameObject.GetComponent<Button>(), + text = gameObject.GetComponentInChildren<Text>() + }); + } + + private void OnInputFieldClicked(int index, int actionElementMapToReplaceId) + { + if (index >= 0 && index < rows.Count) + { + ControllerMap map = player.controllers.maps.GetMap(ControllerType.Keyboard, 0, "Default", "Default"); + ControllerMap map2 = player.controllers.maps.GetMap(ControllerType.Mouse, 0, "Default", "Default"); + ControllerMap controllerMap = (map.ContainsElementMap(actionElementMapToReplaceId) ? map : ((!map2.ContainsElementMap(actionElementMapToReplaceId)) ? null : map2)); + _replaceTargetMapping = new TargetMapping + { + actionElementMapId = actionElementMapToReplaceId, + controllerMap = controllerMap + }; + StartCoroutine(StartListeningDelayed(index, map, map2, actionElementMapToReplaceId)); + } + } + + private IEnumerator StartListeningDelayed(int index, ControllerMap keyboardMap, ControllerMap mouseMap, int actionElementMapToReplaceId) + { + yield return new WaitForSeconds(0.1f); + inputMapper_keyboard.Start(new InputMapper.Context + { + actionId = rows[index].action.id, + controllerMap = keyboardMap, + actionRange = rows[index].actionRange, + actionElementMapToReplace = keyboardMap.GetElementMap(actionElementMapToReplaceId) + }); + inputMapper_mouse.Start(new InputMapper.Context + { + actionId = rows[index].action.id, + controllerMap = mouseMap, + actionRange = rows[index].actionRange, + actionElementMapToReplace = mouseMap.GetElementMap(actionElementMapToReplaceId) + }); + player.controllers.maps.SetMapsEnabled(state: false, "UI"); + statusUIText.text = "Listening..."; + } + + private void OnInputMapped(InputMapper.InputMappedEventData data) + { + inputMapper_keyboard.Stop(); + inputMapper_mouse.Stop(); + if (_replaceTargetMapping.controllerMap != null && data.actionElementMap.controllerMap != _replaceTargetMapping.controllerMap) + { + _replaceTargetMapping.controllerMap.DeleteElementMap(_replaceTargetMapping.actionElementMapId); + } + RedrawUI(); + } + + private void OnStopped(InputMapper.StoppedEventData data) + { + statusUIText.text = string.Empty; + player.controllers.maps.SetMapsEnabled(state: true, "UI"); + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/SimpleControlRemapping.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/SimpleControlRemapping.cs new file mode 100644 index 0000000..386ebe7 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/SimpleControlRemapping.cs @@ -0,0 +1,257 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +public class SimpleControlRemapping : MonoBehaviour +{ + private class Row + { + public InputAction action; + + public AxisRange actionRange; + + public Button button; + + public Text text; + } + + private const string category = "Default"; + + private const string layout = "Default"; + + private const string uiCategory = "UI"; + + private InputMapper inputMapper = new InputMapper(); + + public GameObject buttonPrefab; + + public GameObject textPrefab; + + public RectTransform fieldGroupTransform; + + public RectTransform actionGroupTransform; + + public Text controllerNameUIText; + + public Text statusUIText; + + private ControllerType selectedControllerType; + + private int selectedControllerId; + + private List<Row> rows = new List<Row>(); + + private Player player => ReInput.players.GetPlayer(0); + + private ControllerMap controllerMap + { + get + { + if (controller == null) + { + return null; + } + return player.controllers.maps.GetMap(controller.type, controller.id, "Default", "Default"); + } + } + + private Controller controller => player.controllers.GetController(selectedControllerType, selectedControllerId); + + private void OnEnable() + { + if (ReInput.isReady) + { + inputMapper.options.timeout = 5f; + inputMapper.options.ignoreMouseXAxis = true; + inputMapper.options.ignoreMouseYAxis = true; + ReInput.ControllerConnectedEvent += OnControllerChanged; + ReInput.ControllerDisconnectedEvent += OnControllerChanged; + inputMapper.InputMappedEvent += OnInputMapped; + inputMapper.StoppedEvent += OnStopped; + InitializeUI(); + } + } + + private void OnDisable() + { + inputMapper.Stop(); + inputMapper.RemoveAllEventListeners(); + ReInput.ControllerConnectedEvent -= OnControllerChanged; + ReInput.ControllerDisconnectedEvent -= OnControllerChanged; + } + + private void RedrawUI() + { + if (controller == null) + { + ClearUI(); + return; + } + controllerNameUIText.text = controller.name; + for (int i = 0; i < rows.Count; i++) + { + Row row = rows[i]; + InputAction action = rows[i].action; + string text = string.Empty; + int actionElementMapId = -1; + foreach (ActionElementMap item in controllerMap.ElementMapsWithAction(action.id)) + { + if (item.ShowInField(row.actionRange)) + { + text = item.elementIdentifierName; + actionElementMapId = item.id; + break; + } + } + row.text.text = text; + row.button.onClick.RemoveAllListeners(); + int index = i; + row.button.onClick.AddListener(delegate + { + OnInputFieldClicked(index, actionElementMapId); + }); + } + } + + private void ClearUI() + { + if (selectedControllerType == ControllerType.Joystick) + { + controllerNameUIText.text = "No joysticks attached"; + } + else + { + controllerNameUIText.text = string.Empty; + } + for (int i = 0; i < rows.Count; i++) + { + rows[i].text.text = string.Empty; + } + } + + private void InitializeUI() + { + foreach (Transform item in actionGroupTransform) + { + Object.Destroy(item.gameObject); + } + foreach (Transform item2 in fieldGroupTransform) + { + Object.Destroy(item2.gameObject); + } + foreach (InputAction item3 in ReInput.mapping.ActionsInCategory("Default")) + { + if (item3.type == InputActionType.Axis) + { + CreateUIRow(item3, AxisRange.Full, item3.descriptiveName); + CreateUIRow(item3, AxisRange.Positive, (!string.IsNullOrEmpty(item3.positiveDescriptiveName)) ? item3.positiveDescriptiveName : (item3.descriptiveName + " +")); + CreateUIRow(item3, AxisRange.Negative, (!string.IsNullOrEmpty(item3.negativeDescriptiveName)) ? item3.negativeDescriptiveName : (item3.descriptiveName + " -")); + } + else if (item3.type == InputActionType.Button) + { + CreateUIRow(item3, AxisRange.Positive, item3.descriptiveName); + } + } + RedrawUI(); + } + + private void CreateUIRow(InputAction action, AxisRange actionRange, string label) + { + GameObject obj = Object.Instantiate(textPrefab); + obj.transform.SetParent(actionGroupTransform); + obj.transform.SetAsLastSibling(); + obj.GetComponent<Text>().text = label; + GameObject gameObject = Object.Instantiate(buttonPrefab); + gameObject.transform.SetParent(fieldGroupTransform); + gameObject.transform.SetAsLastSibling(); + rows.Add(new Row + { + action = action, + actionRange = actionRange, + button = gameObject.GetComponent<Button>(), + text = gameObject.GetComponentInChildren<Text>() + }); + } + + private void SetSelectedController(ControllerType controllerType) + { + bool flag = false; + if (controllerType != selectedControllerType) + { + selectedControllerType = controllerType; + flag = true; + } + int num = selectedControllerId; + if (selectedControllerType == ControllerType.Joystick) + { + if (player.controllers.joystickCount > 0) + { + selectedControllerId = player.controllers.Joysticks[0].id; + } + else + { + selectedControllerId = -1; + } + } + else + { + selectedControllerId = 0; + } + if (selectedControllerId != num) + { + flag = true; + } + if (flag) + { + inputMapper.Stop(); + RedrawUI(); + } + } + + public void OnControllerSelected(int controllerType) + { + SetSelectedController((ControllerType)controllerType); + } + + private void OnInputFieldClicked(int index, int actionElementMapToReplaceId) + { + if (index >= 0 && index < rows.Count && controller != null) + { + StartCoroutine(StartListeningDelayed(index, actionElementMapToReplaceId)); + } + } + + private IEnumerator StartListeningDelayed(int index, int actionElementMapToReplaceId) + { + yield return new WaitForSeconds(0.1f); + inputMapper.Start(new InputMapper.Context + { + actionId = rows[index].action.id, + controllerMap = controllerMap, + actionRange = rows[index].actionRange, + actionElementMapToReplace = controllerMap.GetElementMap(actionElementMapToReplaceId) + }); + player.controllers.maps.SetMapsEnabled(state: false, "UI"); + statusUIText.text = "Listening..."; + } + + private void OnControllerChanged(ControllerStatusChangedEventArgs args) + { + SetSelectedController(selectedControllerType); + } + + private void OnInputMapped(InputMapper.InputMappedEventData data) + { + RedrawUI(); + } + + private void OnStopped(InputMapper.StoppedEventData data) + { + statusUIText.text = string.Empty; + player.controllers.maps.SetMapsEnabled(state: true, "UI"); + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/TouchButtonExample.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/TouchButtonExample.cs new file mode 100644 index 0000000..af6edad --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/TouchButtonExample.cs @@ -0,0 +1,52 @@ +using UnityEngine; +using UnityEngine.EventSystems; +using UnityEngine.UI; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +[RequireComponent(typeof(Image))] +public class TouchButtonExample : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler +{ + public bool allowMouseControl = true; + + public bool isPressed { get; private set; } + + private void Awake() + { + if (SystemInfo.deviceType == DeviceType.Handheld) + { + allowMouseControl = false; + } + } + + private void Restart() + { + isPressed = false; + } + + void IPointerDownHandler.OnPointerDown(PointerEventData eventData) + { + if (allowMouseControl || !IsMousePointerId(eventData.pointerId)) + { + isPressed = true; + } + } + + void IPointerUpHandler.OnPointerUp(PointerEventData eventData) + { + if (allowMouseControl || !IsMousePointerId(eventData.pointerId)) + { + isPressed = false; + } + } + + private static bool IsMousePointerId(int id) + { + if (id != -1 && id != -2) + { + return id == -3; + } + return true; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/TouchJoystickExample.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/TouchJoystickExample.cs new file mode 100644 index 0000000..f05af89 --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/TouchJoystickExample.cs @@ -0,0 +1,110 @@ +using System; +using UnityEngine; +using UnityEngine.EventSystems; +using UnityEngine.UI; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +[RequireComponent(typeof(Image))] +public class TouchJoystickExample : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler, IDragHandler +{ + public bool allowMouseControl = true; + + public int radius = 50; + + private Vector2 origAnchoredPosition; + + private Vector3 origWorldPosition; + + private Vector2 origScreenResolution; + + private ScreenOrientation origScreenOrientation; + + [NonSerialized] + private bool hasFinger; + + [NonSerialized] + private int lastFingerId; + + public Vector2 position { get; private set; } + + private void Start() + { + if (SystemInfo.deviceType == DeviceType.Handheld) + { + allowMouseControl = false; + } + StoreOrigValues(); + } + + private void Update() + { + if ((float)Screen.width != origScreenResolution.x || (float)Screen.height != origScreenResolution.y || Screen.orientation != origScreenOrientation) + { + Restart(); + StoreOrigValues(); + } + } + + private void Restart() + { + hasFinger = false; + (base.transform as RectTransform).anchoredPosition = origAnchoredPosition; + position = Vector2.zero; + } + + private void StoreOrigValues() + { + origAnchoredPosition = (base.transform as RectTransform).anchoredPosition; + origWorldPosition = base.transform.position; + origScreenResolution = new Vector2(Screen.width, Screen.height); + origScreenOrientation = Screen.orientation; + } + + private void UpdateValue(Vector3 value) + { + Vector3 vector = origWorldPosition - value; + vector.y = 0f - vector.y; + vector /= (float)radius; + position = new Vector2(0f - vector.x, vector.y); + } + + void IPointerDownHandler.OnPointerDown(PointerEventData eventData) + { + if (!hasFinger && (allowMouseControl || !IsMousePointerId(eventData.pointerId))) + { + hasFinger = true; + lastFingerId = eventData.pointerId; + } + } + + void IPointerUpHandler.OnPointerUp(PointerEventData eventData) + { + if (eventData.pointerId == lastFingerId && (allowMouseControl || !IsMousePointerId(eventData.pointerId))) + { + Restart(); + } + } + + void IDragHandler.OnDrag(PointerEventData eventData) + { + if (hasFinger && eventData.pointerId == lastFingerId) + { + Vector3 vector = new Vector3(eventData.position.x - origWorldPosition.x, eventData.position.y - origWorldPosition.y); + vector = Vector3.ClampMagnitude(vector, radius); + Vector3 value = origWorldPosition + vector; + base.transform.position = value; + UpdateValue(value); + } + } + + private static bool IsMousePointerId(int id) + { + if (id != -1 && id != -2) + { + return id == -3; + } + return true; + } +} diff --git a/Thronefall_v1.0/Rewired/Rewired.Demos/UIPointer.cs b/Thronefall_v1.0/Rewired/Rewired.Demos/UIPointer.cs new file mode 100644 index 0000000..c65fdae --- /dev/null +++ b/Thronefall_v1.0/Rewired/Rewired.Demos/UIPointer.cs @@ -0,0 +1,98 @@ +using UnityEngine; +using UnityEngine.EventSystems; +using UnityEngine.UI; + +namespace Rewired.Demos; + +[AddComponentMenu("")] +[RequireComponent(typeof(RectTransform))] +public sealed class UIPointer : UIBehaviour +{ + [Tooltip("Should the hardware pointer be hidden?")] + [SerializeField] + private bool _hideHardwarePointer = true; + + [Tooltip("Sets the pointer to the last sibling in the parent hierarchy. Do not enable this on multiple UIPointers under the same parent transform or they will constantly fight each other for dominance.")] + [SerializeField] + private bool _autoSort = true; + + private Canvas _canvas; + + public bool autoSort + { + get + { + return _autoSort; + } + set + { + if (value != _autoSort) + { + _autoSort = value; + if (value) + { + base.transform.SetAsLastSibling(); + } + } + } + } + + protected override void Awake() + { + base.Awake(); + Graphic[] componentsInChildren = GetComponentsInChildren<Graphic>(); + for (int i = 0; i < componentsInChildren.Length; i++) + { + componentsInChildren[i].raycastTarget = false; + } + if (_hideHardwarePointer) + { + Cursor.visible = false; + } + if (_autoSort) + { + base.transform.SetAsLastSibling(); + } + GetDependencies(); + } + + private void Update() + { + if (_autoSort && base.transform.GetSiblingIndex() < base.transform.parent.childCount - 1) + { + base.transform.SetAsLastSibling(); + } + } + + protected override void OnTransformParentChanged() + { + base.OnTransformParentChanged(); + GetDependencies(); + } + + protected override void OnCanvasGroupChanged() + { + base.OnCanvasGroupChanged(); + GetDependencies(); + } + + public void OnScreenPositionChanged(Vector2 screenPosition) + { + if (!(_canvas == null)) + { + Camera cam = null; + RenderMode renderMode = _canvas.renderMode; + if (renderMode != 0 && (uint)(renderMode - 1) <= 1u) + { + cam = _canvas.worldCamera; + } + RectTransformUtility.ScreenPointToLocalPointInRectangle(base.transform.parent as RectTransform, screenPosition, cam, out var localPoint); + base.transform.localPosition = new Vector3(localPoint.x, localPoint.y, base.transform.localPosition.z); + } + } + + private void GetDependencies() + { + _canvas = base.transform.root.GetComponentInChildren<Canvas>(); + } +} |